file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
grabbing.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use glutin::{Event, ElementState}; mod support; #[cfg(target_os = "android")] android_start!(main); fn main()
}, Event::Closed => break, a @ Event::MouseMoved(_, _) => { println!("{:?}", a); }, _ => (), } context.draw_frame((0.0, 1.0, 0.0, 1.0)); let _ = window.swap_buffers(); } }
{ let window = glutin::WindowBuilder::new().build().unwrap(); window.set_title("glutin - Cursor grabbing test"); let _ = unsafe { window.make_current() }; let context = support::load(&window); let mut grabbed = false; for event in window.wait_events() { match event { Event::KeyboardInput(ElementState::Pressed, _, _) => { if grabbed { grabbed = false; window.set_cursor_state(glutin::CursorState::Normal) .ok().expect("could not ungrab mouse cursor"); } else { grabbed = true; window.set_cursor_state(glutin::CursorState::Grab) .ok().expect("could not grab mouse cursor"); }
identifier_body
grabbing.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use glutin::{Event, ElementState}; mod support; #[cfg(target_os = "android")] android_start!(main); fn
() { let window = glutin::WindowBuilder::new().build().unwrap(); window.set_title("glutin - Cursor grabbing test"); let _ = unsafe { window.make_current() }; let context = support::load(&window); let mut grabbed = false; for event in window.wait_events() { match event { Event::KeyboardInput(ElementState::Pressed, _, _) => { if grabbed { grabbed = false; window.set_cursor_state(glutin::CursorState::Normal) .ok().expect("could not ungrab mouse cursor"); } else { grabbed = true; window.set_cursor_state(glutin::CursorState::Grab) .ok().expect("could not grab mouse cursor"); } }, Event::Closed => break, a @ Event::MouseMoved(_, _) => { println!("{:?}", a); }, _ => (), } context.draw_frame((0.0, 1.0, 0.0, 1.0)); let _ = window.swap_buffers(); } }
main
identifier_name
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn
() { let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(), ..something }; Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: f(), b: b() }; Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { // Comment a: foo(), /* Comment */ // Comment b: bar(), /* Comment */ }; Foo { a: Bar, b: f() }; Quux { x: if cond { bar(); }, y: baz(), }; Baz { x: yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, z: zzzzz, /* test */ }; A { // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit // amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante // hendrerit. Donec et mollis dolor. first: item(), // Praesent et diam eget libero egestas mattis sit amet vitae augue. // Nam tincidunt congue enim, ut porta lorem lacinia consectetur. second: Item, }; Diagram { // o This graph demonstrates how // / \ significant whitespace is // o o preserved. // /|\ \ // o o o o graph: G, } }
main
identifier_name
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn main() { let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(), ..something }; Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: f(), b: b() }; Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { // Comment a: foo(), /* Comment */ // Comment b: bar(), /* Comment */ }; Foo { a: Bar, b: f() }; Quux { x: if cond
, y: baz(), }; Baz { x: yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, z: zzzzz, /* test */ }; A { // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit // amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante // hendrerit. Donec et mollis dolor. first: item(), // Praesent et diam eget libero egestas mattis sit amet vitae augue. // Nam tincidunt congue enim, ut porta lorem lacinia consectetur. second: Item, }; Diagram { // o This graph demonstrates how // / \ significant whitespace is // o o preserved. // /|\ \ // o o o o graph: G, } }
{ bar(); }
conditional_block
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn main() { let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(), ..something }; Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: f(), b: b() }; Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { // Comment
// Comment b: bar(), /* Comment */ }; Foo { a: Bar, b: f() }; Quux { x: if cond { bar(); }, y: baz(), }; Baz { x: yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, z: zzzzz, /* test */ }; A { // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit // amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante // hendrerit. Donec et mollis dolor. first: item(), // Praesent et diam eget libero egestas mattis sit amet vitae augue. // Nam tincidunt congue enim, ut porta lorem lacinia consectetur. second: Item, }; Diagram { // o This graph demonstrates how // / \ significant whitespace is // o o preserved. // /|\ \ // o o o o graph: G, } }
a: foo(), /* Comment */
random_line_split
struct_lits_visual.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-struct_lit_style: Visual // rustfmt-error_on_line_overflow: false // Struct literal expressions. fn main()
Quux { x: if cond { bar(); }, y: baz(), }; Baz { x: yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, z: zzzzz, /* test */ }; A { // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit // amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante // hendrerit. Donec et mollis dolor. first: item(), // Praesent et diam eget libero egestas mattis sit amet vitae augue. // Nam tincidunt congue enim, ut porta lorem lacinia consectetur. second: Item, }; Diagram { // o This graph demonstrates how // / \ significant whitespace is // o o preserved. // /|\ \ // o o o o graph: G, } }
{ let x = Bar; // Comment let y = Foo { a: x }; Foo { a: foo(), // comment // comment b: bar(), ..something }; Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: f(), b: b() }; Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { // Comment a: foo(), /* Comment */ // Comment b: bar(), /* Comment */ }; Foo { a: Bar, b: f() };
identifier_body
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; pub mod ram; pub mod emu; pub mod system; /// Copy as much memory as possible from `src` to `dest`. pub fn copy_memory(src: &[u8], dest: &mut [u8]) { for x in 0.. { if (x >= src.len()) || (x >= dest.len()) { break } dest[x] = src[x] } } fn swap_word(src: Word) -> Word { let src = src as u32; let src = (src >> 24) | ((src >> 8) & 0xff00) | ((src << 8) & 0xff0000) | ((src << 24) & 0xff000000); src as Word } fn
(a: Word, b: Word, c: Word) -> (Word, bool, bool) { let sa = a as i64; let sb = b as i64; let sc = c as i64; let ua = (a as u32) as u64; let ub = (b as u32) as u64; let uc = (c as u32) as u64; let us = ua.wrapping_add(ub).wrapping_add(uc); let ss = sa.wrapping_add(sb).wrapping_add(sc); let result = us as u32; (result as i32, (result as u64)!= us, ((result as i32) as i64)!= ss) } pub trait Memory { fn read(&self, _addr: u64, _dest: &mut [u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn write(&self, _addr: u64, _src: &[u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn read_u8(&self, addr: u64) -> Result<u8> { let mut data = [0u8]; try!(self.read(addr, &mut data)); Ok(data[0]) } fn read_u16(&self, addr: u64) -> Result<u16> { let mut data = [0u8;2]; try!(self.read(addr, &mut data)); Ok((data[0] as u16) | ((data[1] as u16) << 8)) } fn read_u32(&self, addr: u64) -> Result<u32> { let mut data = [0u8;4]; try!(self.read(addr, &mut data)); Ok((data[0] as u32) | ((data[1] as u32) << 8) | ((data[2] as u32) << 16) | ((data[3] as u32) << 24)) } fn write_u8(&self, addr: u64, val: u8) -> Result<()> { self.write(addr, &[val]) } fn write_u16(&self, addr: u64, val: u16) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8]) } fn write_u32(&self, addr: u64, val: u32) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8, ((val >> 16) & 0xff) as u8, ((val >> 24) & 0xff) as u8]) } } pub trait System { type Memory: Memory; fn memory(&self) -> &Self::Memory; }
adc32
identifier_name
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; pub mod ram; pub mod emu; pub mod system; /// Copy as much memory as possible from `src` to `dest`. pub fn copy_memory(src: &[u8], dest: &mut [u8]) { for x in 0.. { if (x >= src.len()) || (x >= dest.len()) { break } dest[x] = src[x] } } fn swap_word(src: Word) -> Word { let src = src as u32; let src = (src >> 24) | ((src >> 8) & 0xff00) | ((src << 8) & 0xff0000) | ((src << 24) & 0xff000000); src as Word } fn adc32(a: Word, b: Word, c: Word) -> (Word, bool, bool) { let sa = a as i64; let sb = b as i64; let sc = c as i64; let ua = (a as u32) as u64; let ub = (b as u32) as u64; let uc = (c as u32) as u64; let us = ua.wrapping_add(ub).wrapping_add(uc); let ss = sa.wrapping_add(sb).wrapping_add(sc); let result = us as u32; (result as i32, (result as u64)!= us, ((result as i32) as i64)!= ss) } pub trait Memory { fn read(&self, _addr: u64, _dest: &mut [u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn write(&self, _addr: u64, _src: &[u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn read_u8(&self, addr: u64) -> Result<u8> { let mut data = [0u8]; try!(self.read(addr, &mut data)); Ok(data[0]) } fn read_u16(&self, addr: u64) -> Result<u16> { let mut data = [0u8;2]; try!(self.read(addr, &mut data)); Ok((data[0] as u16) | ((data[1] as u16) << 8)) } fn read_u32(&self, addr: u64) -> Result<u32> { let mut data = [0u8;4]; try!(self.read(addr, &mut data)); Ok((data[0] as u32) | ((data[1] as u32) << 8) | ((data[2] as u32) << 16) | ((data[3] as u32) << 24)) } fn write_u8(&self, addr: u64, val: u8) -> Result<()> { self.write(addr, &[val]) } fn write_u16(&self, addr: u64, val: u16) -> Result<()>
fn write_u32(&self, addr: u64, val: u32) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8, ((val >> 16) & 0xff) as u8, ((val >> 24) & 0xff) as u8]) } } pub trait System { type Memory: Memory; fn memory(&self) -> &Self::Memory; }
{ self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8]) }
identifier_body
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; pub mod ram; pub mod emu; pub mod system; /// Copy as much memory as possible from `src` to `dest`. pub fn copy_memory(src: &[u8], dest: &mut [u8]) { for x in 0.. { if (x >= src.len()) || (x >= dest.len())
dest[x] = src[x] } } fn swap_word(src: Word) -> Word { let src = src as u32; let src = (src >> 24) | ((src >> 8) & 0xff00) | ((src << 8) & 0xff0000) | ((src << 24) & 0xff000000); src as Word } fn adc32(a: Word, b: Word, c: Word) -> (Word, bool, bool) { let sa = a as i64; let sb = b as i64; let sc = c as i64; let ua = (a as u32) as u64; let ub = (b as u32) as u64; let uc = (c as u32) as u64; let us = ua.wrapping_add(ub).wrapping_add(uc); let ss = sa.wrapping_add(sb).wrapping_add(sc); let result = us as u32; (result as i32, (result as u64)!= us, ((result as i32) as i64)!= ss) } pub trait Memory { fn read(&self, _addr: u64, _dest: &mut [u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn write(&self, _addr: u64, _src: &[u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn read_u8(&self, addr: u64) -> Result<u8> { let mut data = [0u8]; try!(self.read(addr, &mut data)); Ok(data[0]) } fn read_u16(&self, addr: u64) -> Result<u16> { let mut data = [0u8;2]; try!(self.read(addr, &mut data)); Ok((data[0] as u16) | ((data[1] as u16) << 8)) } fn read_u32(&self, addr: u64) -> Result<u32> { let mut data = [0u8;4]; try!(self.read(addr, &mut data)); Ok((data[0] as u32) | ((data[1] as u32) << 8) | ((data[2] as u32) << 16) | ((data[3] as u32) << 24)) } fn write_u8(&self, addr: u64, val: u8) -> Result<()> { self.write(addr, &[val]) } fn write_u16(&self, addr: u64, val: u16) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8]) } fn write_u32(&self, addr: u64, val: u32) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8, ((val >> 16) & 0xff) as u8, ((val >> 24) & 0xff) as u8]) } } pub trait System { type Memory: Memory; fn memory(&self) -> &Self::Memory; }
{ break }
conditional_block
mod.rs
//! A'simple' ARM emulator. //! //! At the moment the emulator only has support for a handful of THUMB-2 instructions /// and no ARM-mode support. use super::*; pub use self::memory_tree::MemoryTree; pub use self::ram::RAM; pub use self::emu::SimpleEmulator; pub use self::system::SimpleSystem; pub mod memory_tree; pub mod ram; pub mod emu; pub mod system; /// Copy as much memory as possible from `src` to `dest`. pub fn copy_memory(src: &[u8], dest: &mut [u8]) { for x in 0.. { if (x >= src.len()) || (x >= dest.len()) { break } dest[x] = src[x] } } fn swap_word(src: Word) -> Word { let src = src as u32; let src = (src >> 24) | ((src >> 8) & 0xff00) | ((src << 8) & 0xff0000) | ((src << 24) & 0xff000000); src as Word } fn adc32(a: Word, b: Word, c: Word) -> (Word, bool, bool) { let sa = a as i64; let sb = b as i64; let sc = c as i64; let ua = (a as u32) as u64; let ub = (b as u32) as u64; let uc = (c as u32) as u64; let us = ua.wrapping_add(ub).wrapping_add(uc); let ss = sa.wrapping_add(sb).wrapping_add(sc); let result = us as u32; (result as i32, (result as u64)!= us, ((result as i32) as i64)!= ss) } pub trait Memory { fn read(&self, _addr: u64, _dest: &mut [u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn write(&self, _addr: u64, _src: &[u8]) -> Result<()> { Err(Error::Unknown(format!("not implemented"))) } fn read_u8(&self, addr: u64) -> Result<u8> { let mut data = [0u8]; try!(self.read(addr, &mut data)); Ok(data[0]) } fn read_u16(&self, addr: u64) -> Result<u16> {
try!(self.read(addr, &mut data)); Ok((data[0] as u16) | ((data[1] as u16) << 8)) } fn read_u32(&self, addr: u64) -> Result<u32> { let mut data = [0u8;4]; try!(self.read(addr, &mut data)); Ok((data[0] as u32) | ((data[1] as u32) << 8) | ((data[2] as u32) << 16) | ((data[3] as u32) << 24)) } fn write_u8(&self, addr: u64, val: u8) -> Result<()> { self.write(addr, &[val]) } fn write_u16(&self, addr: u64, val: u16) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8]) } fn write_u32(&self, addr: u64, val: u32) -> Result<()> { self.write(addr, &[(val & 0xff) as u8, ((val >> 8) & 0xff) as u8, ((val >> 16) & 0xff) as u8, ((val >> 24) & 0xff) as u8]) } } pub trait System { type Memory: Memory; fn memory(&self) -> &Self::Memory; }
let mut data = [0u8;2];
random_line_split
result_try.rs
use std::io::prelude::*; use std::fs::File; type Result<T> = std::result::Result<T, String>; // Setup to make this work. Create two files with some info. Ignore the // return values because we don't care about them here. fn setup() { File::create("a") .and_then(|mut file| file.write_all(b"grape")) .unwrap(); File::create("b") .and_then(|mut file| file.write_all(b"fruit")) .unwrap(); } // Get the data from each file with the data stored in a `Result`. fn get_data(path: &str) -> Result<String> { File::open(path) .map_err(|err| err.to_string()) .and_then(|mut file| { let mut contents = String::new(); // Read the data into `contents`. file.read_to_string(&mut contents) .map_err(|err| err.to_string()) // Ignore the output `read_to_string` returns and return `contents`.
// Concat the contents of the two files together into a new `Result`. fn concat(a: &str, b: &str) -> Result<String> { let (data_a, data_b) = (get_data(a), get_data(b)); data_a.and_then(|a| // Return `Ok` when both `a` and `b` are `Ok`. Otherwise return // whichever has the first `Err`. data_b.and_then(|b| Ok(a + &b)) ) } fn main() { setup(); match concat("a", "b") { Ok(n) => println!("{}", n), Err(e) => println!("Error: {}", e), } }
.map(|_| contents) }) }
random_line_split
result_try.rs
use std::io::prelude::*; use std::fs::File; type Result<T> = std::result::Result<T, String>; // Setup to make this work. Create two files with some info. Ignore the // return values because we don't care about them here. fn setup() { File::create("a") .and_then(|mut file| file.write_all(b"grape")) .unwrap(); File::create("b") .and_then(|mut file| file.write_all(b"fruit")) .unwrap(); } // Get the data from each file with the data stored in a `Result`. fn get_data(path: &str) -> Result<String> { File::open(path) .map_err(|err| err.to_string()) .and_then(|mut file| { let mut contents = String::new(); // Read the data into `contents`. file.read_to_string(&mut contents) .map_err(|err| err.to_string()) // Ignore the output `read_to_string` returns and return `contents`. .map(|_| contents) }) } // Concat the contents of the two files together into a new `Result`. fn concat(a: &str, b: &str) -> Result<String> { let (data_a, data_b) = (get_data(a), get_data(b)); data_a.and_then(|a| // Return `Ok` when both `a` and `b` are `Ok`. Otherwise return // whichever has the first `Err`. data_b.and_then(|b| Ok(a + &b)) ) } fn main()
{ setup(); match concat("a", "b") { Ok(n) => println!("{}", n), Err(e) => println!("Error: {}", e), } }
identifier_body
result_try.rs
use std::io::prelude::*; use std::fs::File; type Result<T> = std::result::Result<T, String>; // Setup to make this work. Create two files with some info. Ignore the // return values because we don't care about them here. fn setup() { File::create("a") .and_then(|mut file| file.write_all(b"grape")) .unwrap(); File::create("b") .and_then(|mut file| file.write_all(b"fruit")) .unwrap(); } // Get the data from each file with the data stored in a `Result`. fn get_data(path: &str) -> Result<String> { File::open(path) .map_err(|err| err.to_string()) .and_then(|mut file| { let mut contents = String::new(); // Read the data into `contents`. file.read_to_string(&mut contents) .map_err(|err| err.to_string()) // Ignore the output `read_to_string` returns and return `contents`. .map(|_| contents) }) } // Concat the contents of the two files together into a new `Result`. fn concat(a: &str, b: &str) -> Result<String> { let (data_a, data_b) = (get_data(a), get_data(b)); data_a.and_then(|a| // Return `Ok` when both `a` and `b` are `Ok`. Otherwise return // whichever has the first `Err`. data_b.and_then(|b| Ok(a + &b)) ) } fn
() { setup(); match concat("a", "b") { Ok(n) => println!("{}", n), Err(e) => println!("Error: {}", e), } }
main
identifier_name
lib.rs
// Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![deny(rust_2018_idioms)] #![allow(clippy::type_complexity, clippy::new_without_default)] #![recursion_limit = "256"] #[macro_use] extern crate async_trait; #[macro_use] extern crate clap; #[macro_use] extern crate counted_array; #[cfg(feature = "jsonwebtoken")] use jsonwebtoken as jwt; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[cfg(feature = "rouille")] #[macro_use(router)] extern crate rouille; #[macro_use] extern crate serde_derive; // To get macros in scope, this has to be first. #[cfg(test)] #[macro_use] mod test; #[macro_use] pub mod errors; #[cfg(feature = "azure")] mod azure; mod cache; mod client; mod cmdline; mod commands; mod compiler; pub mod config; pub mod dist; mod jobserver; pub mod lru_disk_cache; mod mock_command; mod protocol; pub mod server; #[cfg(feature = "simple-s3")] mod simples3; #[doc(hidden)] pub mod util; use std::env; const LOGGING_ENV: &str = "SCCACHE_LOG"; pub fn main() { init_logging(); std::process::exit(match cmdline::parse() { Ok(cmd) => match commands::run_command(cmd) { Ok(s) => s, Err(e) => { eprintln!("sccache: error: {}", e); for e in e.chain().skip(1) { eprintln!("sccache: caused by: {}", e); } 2 } }, Err(e) => { println!("sccache: {}", e); for e in e.chain().skip(1) {
println!(); 1 } }); } fn init_logging() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!("Failed to initalize logging: {:?}", e), } } }
println!("sccache: caused by: {}", e); } cmdline::get_app().print_help().unwrap();
random_line_split
lib.rs
// Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![deny(rust_2018_idioms)] #![allow(clippy::type_complexity, clippy::new_without_default)] #![recursion_limit = "256"] #[macro_use] extern crate async_trait; #[macro_use] extern crate clap; #[macro_use] extern crate counted_array; #[cfg(feature = "jsonwebtoken")] use jsonwebtoken as jwt; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[cfg(feature = "rouille")] #[macro_use(router)] extern crate rouille; #[macro_use] extern crate serde_derive; // To get macros in scope, this has to be first. #[cfg(test)] #[macro_use] mod test; #[macro_use] pub mod errors; #[cfg(feature = "azure")] mod azure; mod cache; mod client; mod cmdline; mod commands; mod compiler; pub mod config; pub mod dist; mod jobserver; pub mod lru_disk_cache; mod mock_command; mod protocol; pub mod server; #[cfg(feature = "simple-s3")] mod simples3; #[doc(hidden)] pub mod util; use std::env; const LOGGING_ENV: &str = "SCCACHE_LOG"; pub fn main() { init_logging(); std::process::exit(match cmdline::parse() { Ok(cmd) => match commands::run_command(cmd) { Ok(s) => s, Err(e) => { eprintln!("sccache: error: {}", e); for e in e.chain().skip(1) { eprintln!("sccache: caused by: {}", e); } 2 } }, Err(e) => { println!("sccache: {}", e); for e in e.chain().skip(1) { println!("sccache: caused by: {}", e); } cmdline::get_app().print_help().unwrap(); println!(); 1 } }); } fn
() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!("Failed to initalize logging: {:?}", e), } } }
init_logging
identifier_name
lib.rs
// Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![deny(rust_2018_idioms)] #![allow(clippy::type_complexity, clippy::new_without_default)] #![recursion_limit = "256"] #[macro_use] extern crate async_trait; #[macro_use] extern crate clap; #[macro_use] extern crate counted_array; #[cfg(feature = "jsonwebtoken")] use jsonwebtoken as jwt; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[cfg(feature = "rouille")] #[macro_use(router)] extern crate rouille; #[macro_use] extern crate serde_derive; // To get macros in scope, this has to be first. #[cfg(test)] #[macro_use] mod test; #[macro_use] pub mod errors; #[cfg(feature = "azure")] mod azure; mod cache; mod client; mod cmdline; mod commands; mod compiler; pub mod config; pub mod dist; mod jobserver; pub mod lru_disk_cache; mod mock_command; mod protocol; pub mod server; #[cfg(feature = "simple-s3")] mod simples3; #[doc(hidden)] pub mod util; use std::env; const LOGGING_ENV: &str = "SCCACHE_LOG"; pub fn main() { init_logging(); std::process::exit(match cmdline::parse() { Ok(cmd) => match commands::run_command(cmd) { Ok(s) => s, Err(e) =>
}, Err(e) => { println!("sccache: {}", e); for e in e.chain().skip(1) { println!("sccache: caused by: {}", e); } cmdline::get_app().print_help().unwrap(); println!(); 1 } }); } fn init_logging() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!("Failed to initalize logging: {:?}", e), } } }
{ eprintln!("sccache: error: {}", e); for e in e.chain().skip(1) { eprintln!("sccache: caused by: {}", e); } 2 }
conditional_block
lib.rs
// Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![deny(rust_2018_idioms)] #![allow(clippy::type_complexity, clippy::new_without_default)] #![recursion_limit = "256"] #[macro_use] extern crate async_trait; #[macro_use] extern crate clap; #[macro_use] extern crate counted_array; #[cfg(feature = "jsonwebtoken")] use jsonwebtoken as jwt; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[cfg(feature = "rouille")] #[macro_use(router)] extern crate rouille; #[macro_use] extern crate serde_derive; // To get macros in scope, this has to be first. #[cfg(test)] #[macro_use] mod test; #[macro_use] pub mod errors; #[cfg(feature = "azure")] mod azure; mod cache; mod client; mod cmdline; mod commands; mod compiler; pub mod config; pub mod dist; mod jobserver; pub mod lru_disk_cache; mod mock_command; mod protocol; pub mod server; #[cfg(feature = "simple-s3")] mod simples3; #[doc(hidden)] pub mod util; use std::env; const LOGGING_ENV: &str = "SCCACHE_LOG"; pub fn main() { init_logging(); std::process::exit(match cmdline::parse() { Ok(cmd) => match commands::run_command(cmd) { Ok(s) => s, Err(e) => { eprintln!("sccache: error: {}", e); for e in e.chain().skip(1) { eprintln!("sccache: caused by: {}", e); } 2 } }, Err(e) => { println!("sccache: {}", e); for e in e.chain().skip(1) { println!("sccache: caused by: {}", e); } cmdline::get_app().print_help().unwrap(); println!(); 1 } }); } fn init_logging()
{ if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!("Failed to initalize logging: {:?}", e), } } }
identifier_body
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str}; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut visitor_count: int = 0; fn
() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}]...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection unsafe { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } }, None => () } let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } } }
main
identifier_name
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str}; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut visitor_count: int = 0; fn main() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}]...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection unsafe { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) =>
, None => () } }, None => () } let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } } }
{println(format!("Received connection from: [{:s}]", pn.to_str()));}
conditional_block
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str}; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut visitor_count: int = 0; fn main()
None => () } let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } } }
{ let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}] ...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection unsafe { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } },
identifier_body
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. //
// Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::io::*; use std::io::net::ip::{SocketAddr}; use std::{str}; static IP: &'static str = "127.0.0.1"; static PORT: int = 4414; static mut visitor_count: int = 0; fn main() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}]...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection unsafe { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } }, None => () } let mut buf = [0,..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype!html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } } }
// University of Virginia - cs4414 Spring 2014
random_line_split
bin.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors //
// 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![forbid(unsafe_code)] #![deny( non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] #[macro_use] extern crate libimagrt; simple_imag_application_binary!(libimaglinkcmd, ImagLink);
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version
random_line_split
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend(){ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a); } #[allow(unused_must_use)] fn
() { println!("There are {:?} available backends", get_backend_count().unwrap()); let available = get_available_backends().unwrap(); if available.contains(&Backend::AF_BACKEND_CPU){ println!("Evaluating CPU Backend..."); let err = set_backend(Backend::AF_BACKEND_CPU); println!("There are {} CPU compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_CUDA){ println!("Evaluating CUDA Backend..."); let err = set_backend(Backend::AF_BACKEND_CUDA); println!("There are {} CUDA compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CUDA backend error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL); println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e), }; } }
main
identifier_name
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend(){ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a); } #[allow(unused_must_use)] fn main() { println!("There are {:?} available backends", get_backend_count().unwrap()); let available = get_available_backends().unwrap(); if available.contains(&Backend::AF_BACKEND_CPU)
if available.contains(&Backend::AF_BACKEND_CUDA){ println!("Evaluating CUDA Backend..."); let err = set_backend(Backend::AF_BACKEND_CUDA); println!("There are {} CUDA compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CUDA backend error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL); println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e), }; } }
{ println!("Evaluating CPU Backend..."); let err = set_backend(Backend::AF_BACKEND_CPU); println!("There are {} CPU compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; }
conditional_block
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend()
#[allow(unused_must_use)] fn main() { println!("There are {:?} available backends", get_backend_count().unwrap()); let available = get_available_backends().unwrap(); if available.contains(&Backend::AF_BACKEND_CPU){ println!("Evaluating CPU Backend..."); let err = set_backend(Backend::AF_BACKEND_CPU); println!("There are {} CPU compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_CUDA){ println!("Evaluating CUDA Backend..."); let err = set_backend(Backend::AF_BACKEND_CUDA); println!("There are {} CUDA compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CUDA backend error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL); println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e), }; } }
{ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a); }
identifier_body
unified.rs
extern crate arrayfire as af; use af::*; #[allow(unused_must_use)] fn test_backend(){ info(); let num_rows: u64 = 10; let num_cols: u64 = 10; let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); println!("Create a 10-by-10 matrix of random floats on the compute device"); let a = match randu(dims, Aftype::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a); } #[allow(unused_must_use)] fn main() { println!("There are {:?} available backends", get_backend_count().unwrap()); let available = get_available_backends().unwrap(); if available.contains(&Backend::AF_BACKEND_CPU){ println!("Evaluating CPU Backend..."); let err = set_backend(Backend::AF_BACKEND_CPU); println!("There are {} CPU compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_CUDA){ println!("Evaluating CUDA Backend..."); let err = set_backend(Backend::AF_BACKEND_CUDA); println!("There are {} CUDA compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CUDA backend error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL);
}; } }
println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e),
random_line_split
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32,..8*16] = [0x00FF0000,..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32) { SCREEN_WIDTH = width; SCREEN_HEIGHT= height; sgash::init(); /* For the following magic values, see * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html */ // 800x600 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html if (SCREEN_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); } pub unsafe fn write_char(c: char, address: *mut u32) { volatile_store(address, c as u32); } pub unsafe fn scrollup() { let mut i = CURSOR_HEIGHT*SCREEN_WIDTH; while i < (SCREEN_WIDTH*SCREEN_HEIGHT) { *((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32); i += 1; } i = 4*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT { scrollup(); } let font_offset = (c as u8) - 0x20; let map = font::bitmaps[font_offset]; let mut i = -1; let mut j = 0; let mut addr = START_ADDR + 4*(CURSOR_X + /*CURSOR_WIDTH +*/ 1 + SCREEN_WIDTH*CURSOR_Y + CURSOR_HEIGHT*SCREEN_WIDTH); while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } } pub unsafe fn paint(color: u32) { let mut i = 0; while i < SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR as u32 + i*4) as *mut u32) = color; i+=1; } } pub unsafe fn fill_bg() { paint(BG_COLOR); } #[allow(dead_code)] pub unsafe fn read(addr: u32) -> u32 { *(addr as *mut u32) } pub unsafe fn ws(addr: u32, value: u32) { *(addr as *mut u32) = *(addr as *mut u32) | value; } #[allow(dead_code)] pub unsafe fn
(addr: u32, value: u32) { *(addr as *mut u32) = value; } pub unsafe fn set_fg(color: u32) { FG_COLOR = color; } pub unsafe fn set_bg(color: u32) { BG_COLOR = color; } pub unsafe fn set_cursor_color(color: u32) { CURSOR_COLOR = color; }
wh
identifier_name
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32,..8*16] = [0x00FF0000,..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32) { SCREEN_WIDTH = width; SCREEN_HEIGHT= height; sgash::init(); /* For the following magic values, see * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html */ // 800x600 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html if (SCREEN_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); } pub unsafe fn write_char(c: char, address: *mut u32) { volatile_store(address, c as u32); } pub unsafe fn scrollup() { let mut i = CURSOR_HEIGHT*SCREEN_WIDTH; while i < (SCREEN_WIDTH*SCREEN_HEIGHT) { *((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32); i += 1; } i = 4*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT { scrollup(); } let font_offset = (c as u8) - 0x20; let map = font::bitmaps[font_offset]; let mut i = -1; let mut j = 0; let mut addr = START_ADDR + 4*(CURSOR_X + /*CURSOR_WIDTH +*/ 1 + SCREEN_WIDTH*CURSOR_Y + CURSOR_HEIGHT*SCREEN_WIDTH); while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } }
while i < SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR as u32 + i*4) as *mut u32) = color; i+=1; } } pub unsafe fn fill_bg() { paint(BG_COLOR); } #[allow(dead_code)] pub unsafe fn read(addr: u32) -> u32 { *(addr as *mut u32) } pub unsafe fn ws(addr: u32, value: u32) { *(addr as *mut u32) = *(addr as *mut u32) | value; } #[allow(dead_code)] pub unsafe fn wh(addr: u32, value: u32) { *(addr as *mut u32) = value; } pub unsafe fn set_fg(color: u32) { FG_COLOR = color; } pub unsafe fn set_bg(color: u32) { BG_COLOR = color; } pub unsafe fn set_cursor_color(color: u32) { CURSOR_COLOR = color; }
pub unsafe fn paint(color: u32) { let mut i = 0;
random_line_split
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32,..8*16] = [0x00FF0000,..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32) { SCREEN_WIDTH = width; SCREEN_HEIGHT= height; sgash::init(); /* For the following magic values, see * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html */ // 800x600 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html if (SCREEN_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); } pub unsafe fn write_char(c: char, address: *mut u32) { volatile_store(address, c as u32); } pub unsafe fn scrollup() { let mut i = CURSOR_HEIGHT*SCREEN_WIDTH; while i < (SCREEN_WIDTH*SCREEN_HEIGHT) { *((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32); i += 1; } i = 4*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT
let font_offset = (c as u8) - 0x20; let map = font::bitmaps[font_offset]; let mut i = -1; let mut j = 0; let mut addr = START_ADDR + 4*(CURSOR_X + /*CURSOR_WIDTH +*/ 1 + SCREEN_WIDTH*CURSOR_Y + CURSOR_HEIGHT*SCREEN_WIDTH); while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } } pub unsafe fn paint(color: u32) { let mut i = 0; while i < SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR as u32 + i*4) as *mut u32) = color; i+=1; } } pub unsafe fn fill_bg() { paint(BG_COLOR); } #[allow(dead_code)] pub unsafe fn read(addr: u32) -> u32 { *(addr as *mut u32) } pub unsafe fn ws(addr: u32, value: u32) { *(addr as *mut u32) = *(addr as *mut u32) | value; } #[allow(dead_code)] pub unsafe fn wh(addr: u32, value: u32) { *(addr as *mut u32) = value; } pub unsafe fn set_fg(color: u32) { FG_COLOR = color; } pub unsafe fn set_bg(color: u32) { BG_COLOR = color; } pub unsafe fn set_cursor_color(color: u32) { CURSOR_COLOR = color; }
{ scrollup(); }
conditional_block
mod.rs
/* io::mod.rs */ use core::mem::volatile_store; use kernel::sgash; mod font; /* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */ pub static UART0: *mut u32 = 0x101f1000 as *mut u32; pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32; #[allow(dead_code)] pub static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32,..8*16] = [0x00FF0000,..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32)
/* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); } pub unsafe fn write_char(c: char, address: *mut u32) { volatile_store(address, c as u32); } pub unsafe fn scrollup() { let mut i = CURSOR_HEIGHT*SCREEN_WIDTH; while i < (SCREEN_WIDTH*SCREEN_HEIGHT) { *((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32); i += 1; } i = 4*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT { scrollup(); } let font_offset = (c as u8) - 0x20; let map = font::bitmaps[font_offset]; let mut i = -1; let mut j = 0; let mut addr = START_ADDR + 4*(CURSOR_X + /*CURSOR_WIDTH +*/ 1 + SCREEN_WIDTH*CURSOR_Y + CURSOR_HEIGHT*SCREEN_WIDTH); while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } } pub unsafe fn paint(color: u32) { let mut i = 0; while i < SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR as u32 + i*4) as *mut u32) = color; i+=1; } } pub unsafe fn fill_bg() { paint(BG_COLOR); } #[allow(dead_code)] pub unsafe fn read(addr: u32) -> u32 { *(addr as *mut u32) } pub unsafe fn ws(addr: u32, value: u32) { *(addr as *mut u32) = *(addr as *mut u32) | value; } #[allow(dead_code)] pub unsafe fn wh(addr: u32, value: u32) { *(addr as *mut u32) = value; } pub unsafe fn set_fg(color: u32) { FG_COLOR = color; } pub unsafe fn set_bg(color: u32) { BG_COLOR = color; } pub unsafe fn set_cursor_color(color: u32) { CURSOR_COLOR = color; }
{ SCREEN_WIDTH = width; SCREEN_HEIGHT= height; sgash::init(); /* For the following magic values, see * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html */ // 800x600 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html if (SCREEN_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR);
identifier_body
rec-align-u64.rs
// run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // ignore-wasm32-bare seems unimportant to test // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type with the questionable alignment #[derive(Debug)] struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "emscripten", target_os = "freebsd", target_os = "fuchsia",
target_os = "netbsd", target_os = "openbsd", target_os = "solaris", target_os = "vxworks"))] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> usize { 4 } pub fn size() -> usize { 12 } } #[cfg(not(target_arch = "x86"))] pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } #[cfg(target_env = "sgx")] mod m { #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } #[cfg(target_os = "windows")] mod m { pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; let y = format!("{:?}", x); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
target_os = "linux", target_os = "macos",
random_line_split
rec-align-u64.rs
// run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // ignore-wasm32-bare seems unimportant to test // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type with the questionable alignment #[derive(Debug)] struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "emscripten", target_os = "freebsd", target_os = "fuchsia", target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris", target_os = "vxworks"))] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> usize { 4 } pub fn size() -> usize { 12 } } #[cfg(not(target_arch = "x86"))] pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } #[cfg(target_env = "sgx")] mod m { #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> usize { 8 } pub fn
() -> usize { 16 } } } #[cfg(target_os = "windows")] mod m { pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; let y = format!("{:?}", x); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
size
identifier_name
rec-align-u64.rs
// run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // ignore-wasm32-bare seems unimportant to test // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type with the questionable alignment #[derive(Debug)] struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "emscripten", target_os = "freebsd", target_os = "fuchsia", target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris", target_os = "vxworks"))] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> usize { 4 } pub fn size() -> usize { 12 } } #[cfg(not(target_arch = "x86"))] pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } #[cfg(target_env = "sgx")] mod m { #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> usize
pub fn size() -> usize { 16 } } } #[cfg(target_os = "windows")] mod m { pub mod m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; let y = format!("{:?}", x); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
{ 8 }
identifier_body
accept_ranges.rs
use std::fmt::{self, Display}; use std::str::FromStr; header! { #[doc="`Accept-Ranges` header, defined in"] #[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"] #[doc=""] #[doc="The `Accept-Ranges` header field allows a server to indicate that it"] #[doc="supports range requests for the target resource."] #[doc=""] #[doc="# ABNF"] #[doc="```plain"] #[doc="Accept-Ranges = acceptable-ranges"] #[doc="acceptable-ranges = 1#range-unit / \"none\""] #[doc=""] #[doc="# Example values"] #[doc="* `bytes`"] #[doc="* `none`"] #[doc="* `unknown-unit`"] #[doc="```"] #[doc=""] #[doc="# Examples"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"] #[doc="```"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::None]));"] #[doc="```"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set("] #[doc=" AcceptRanges(vec!["] #[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"] #[doc=" RangeUnit::Bytes,"] #[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"] #[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"] #[doc=" ])"] #[doc=");"] #[doc="```"] (AcceptRanges, "Accept-Ranges") => (RangeUnit)+ test_acccept_ranges { test_header!(test1, vec![b"bytes"]); test_header!(test2, vec![b"none"]); test_header!(test3, vec![b"unknown-unit"]); test_header!(test4, vec![b"bytes, unknown-unit"]); } } /// Range Units, described in [RFC7233](http://tools.ietf.org/html/rfc7233#section-2) /// /// A representation can be partitioned into subranges according to /// various structural units, depending on the structure inherent in the /// representation's media type. /// /// # ABNF /// ```plain /// range-unit = bytes-unit / other-range-unit /// bytes-unit = "bytes" /// other-range-unit = token /// ``` #[derive(Clone, Debug, Eq, PartialEq)] pub enum
{ /// Indicating byte-range requests are supported. Bytes, /// Reserved as keyword, indicating no ranges are supported. None, /// The given range unit is not registered at IANA. Unregistered(String), } impl FromStr for RangeUnit { type Err = ::Error; fn from_str(s: &str) -> ::Result<Self> { match s { "bytes" => Ok(RangeUnit::Bytes), "none" => Ok(RangeUnit::None), // FIXME: Check if s is really a Token _ => Ok(RangeUnit::Unregistered(s.to_owned())), } } } impl Display for RangeUnit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RangeUnit::Bytes => f.write_str("bytes"), RangeUnit::None => f.write_str("none"), RangeUnit::Unregistered(ref x) => f.write_str(&x), } } }
RangeUnit
identifier_name
accept_ranges.rs
use std::fmt::{self, Display}; use std::str::FromStr; header! { #[doc="`Accept-Ranges` header, defined in"] #[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"] #[doc=""] #[doc="The `Accept-Ranges` header field allows a server to indicate that it"] #[doc="supports range requests for the target resource."] #[doc=""] #[doc="# ABNF"] #[doc="```plain"] #[doc="Accept-Ranges = acceptable-ranges"] #[doc="acceptable-ranges = 1#range-unit / \"none\""] #[doc=""] #[doc="# Example values"] #[doc="* `bytes`"] #[doc="* `none`"] #[doc="* `unknown-unit`"] #[doc="```"] #[doc=""] #[doc="# Examples"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"] #[doc="```"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::None]));"] #[doc="```"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set("] #[doc=" AcceptRanges(vec!["] #[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"] #[doc=" RangeUnit::Bytes,"] #[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"] #[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"] #[doc=" ])"] #[doc=");"] #[doc="```"] (AcceptRanges, "Accept-Ranges") => (RangeUnit)+ test_acccept_ranges { test_header!(test1, vec![b"bytes"]); test_header!(test2, vec![b"none"]); test_header!(test3, vec![b"unknown-unit"]); test_header!(test4, vec![b"bytes, unknown-unit"]); } } /// Range Units, described in [RFC7233](http://tools.ietf.org/html/rfc7233#section-2) /// /// A representation can be partitioned into subranges according to /// various structural units, depending on the structure inherent in the /// representation's media type. /// /// # ABNF /// ```plain /// range-unit = bytes-unit / other-range-unit /// bytes-unit = "bytes" /// other-range-unit = token /// ``` #[derive(Clone, Debug, Eq, PartialEq)] pub enum RangeUnit { /// Indicating byte-range requests are supported. Bytes, /// Reserved as keyword, indicating no ranges are supported. None, /// The given range unit is not registered at IANA. Unregistered(String), } impl FromStr for RangeUnit { type Err = ::Error; fn from_str(s: &str) -> ::Result<Self>
} impl Display for RangeUnit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RangeUnit::Bytes => f.write_str("bytes"), RangeUnit::None => f.write_str("none"), RangeUnit::Unregistered(ref x) => f.write_str(&x), } } }
{ match s { "bytes" => Ok(RangeUnit::Bytes), "none" => Ok(RangeUnit::None), // FIXME: Check if s is really a Token _ => Ok(RangeUnit::Unregistered(s.to_owned())), } }
identifier_body
accept_ranges.rs
use std::fmt::{self, Display}; use std::str::FromStr; header! { #[doc="`Accept-Ranges` header, defined in"] #[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"] #[doc=""] #[doc="The `Accept-Ranges` header field allows a server to indicate that it"] #[doc="supports range requests for the target resource."] #[doc=""] #[doc="# ABNF"] #[doc="```plain"] #[doc="Accept-Ranges = acceptable-ranges"] #[doc="acceptable-ranges = 1#range-unit / \"none\""] #[doc=""] #[doc="# Example values"] #[doc="* `bytes`"] #[doc="* `none`"] #[doc="* `unknown-unit`"] #[doc="```"] #[doc=""] #[doc="# Examples"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"] #[doc="```"]
#[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::None]));"] #[doc="```"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set("] #[doc=" AcceptRanges(vec!["] #[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"] #[doc=" RangeUnit::Bytes,"] #[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"] #[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"] #[doc=" ])"] #[doc=");"] #[doc="```"] (AcceptRanges, "Accept-Ranges") => (RangeUnit)+ test_acccept_ranges { test_header!(test1, vec![b"bytes"]); test_header!(test2, vec![b"none"]); test_header!(test3, vec![b"unknown-unit"]); test_header!(test4, vec![b"bytes, unknown-unit"]); } } /// Range Units, described in [RFC7233](http://tools.ietf.org/html/rfc7233#section-2) /// /// A representation can be partitioned into subranges according to /// various structural units, depending on the structure inherent in the /// representation's media type. /// /// # ABNF /// ```plain /// range-unit = bytes-unit / other-range-unit /// bytes-unit = "bytes" /// other-range-unit = token /// ``` #[derive(Clone, Debug, Eq, PartialEq)] pub enum RangeUnit { /// Indicating byte-range requests are supported. Bytes, /// Reserved as keyword, indicating no ranges are supported. None, /// The given range unit is not registered at IANA. Unregistered(String), } impl FromStr for RangeUnit { type Err = ::Error; fn from_str(s: &str) -> ::Result<Self> { match s { "bytes" => Ok(RangeUnit::Bytes), "none" => Ok(RangeUnit::None), // FIXME: Check if s is really a Token _ => Ok(RangeUnit::Unregistered(s.to_owned())), } } } impl Display for RangeUnit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RangeUnit::Bytes => f.write_str("bytes"), RangeUnit::None => f.write_str("none"), RangeUnit::Unregistered(ref x) => f.write_str(&x), } } }
#[doc="```"]
random_line_split
chunks.rs
use std::sync::{Arc, Mutex}; use simple_parallel; use state::LSystem; use super::{LProcessor, SimpleProcessor}; /// Parallel processor dividing a state into chunks to be individually iterated /// within a pool of threads. pub struct
{ /// The number of symbols per full chunk. chunk_size: usize, /// The thread pool. pool: simple_parallel::Pool, } impl ChunksProcessor { /// Try and create a new 'ChunksProcessor' instance with the given parameters. /// Typical values: /// - max_tasks : number of CPU logical cores /// - chunks_size : between 100_000 and 1_000_000 symbols per chunk pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> { if max_tasks == 0 { Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})", max_tasks)) } else if chunks_size == 0 { Err(format!("ChunksProcessor::new : invalid chunks size ({})", chunks_size)) } else { Ok(ChunksProcessor { chunk_size: chunks_size, pool: simple_parallel::Pool::new(max_tasks), }) } } } impl<S> LProcessor<S> for ChunksProcessor where S: Clone + Eq + Send + Sync { // TODO : better error handling... fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> { // Set-up let mut vec: Vec<Vec<S>> = Vec::new(); let state_len = lsystem.state().len(); if state_len == 0 { return Err(format!("cannot iterate an empty state")); } let rem = state_len % self.chunk_size; let chunks_number = state_len / self.chunk_size + match rem { 0 => 0, _ => 1, }; for _ in 0..chunks_number { vec.push(Vec::new()); } let sub_states = Arc::new(Mutex::new(vec)); // Chunks processing let rules = lsystem.rules().clone(); let errors = Mutex::new(String::new()); let chunks_iter = lsystem.state().chunks(self.chunk_size); self.pool .for_(chunks_iter.enumerate(), |(n, chunk)| { let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) { Ok(v) => v, Err(why) => { let mut error_lock = errors.lock().unwrap(); *error_lock = format!("{}\n{}", *error_lock, why); Vec::new() } }; let mut chunk_data = sub_states.lock().unwrap(); chunk_data[n] = result; }); // Error handling let error_lock = errors.lock().unwrap(); if!error_lock.is_empty() { return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock)); } // Final assembling let mut new_state_size = 0usize; let mut new_state: Vec<S> = Vec::new(); let data = sub_states.lock().unwrap(); for n in 0..chunks_number { let chunk_iterated = &data[n]; new_state_size = match new_state_size.checked_add(chunk_iterated.len()) { Some(v) => v, None => { return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \ for for Vec")) } }; new_state.extend(chunk_iterated.iter().cloned()); } Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1))) } } #[cfg(test)] mod test { use rules::HashMapRules; use state::{LSystem, new_rules_value}; use interpret::TurtleCommand; use process::{LProcessor, ChunksProcessor}; #[test] fn chunks_processing() { let mut rules = HashMapRules::new(); // algae rules rules.set_str('A', "AB", TurtleCommand::None); rules.set_str('B', "A", TurtleCommand::None); let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]; let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules)); let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap(); for n in 0..expected_sizes.len() { assert_eq!(lsystem.iteration(), n as u64); assert_eq!(lsystem.state().len(), expected_sizes[n]); lsystem = processor.iterate(&lsystem).ok().unwrap(); } } }
ChunksProcessor
identifier_name
chunks.rs
use std::sync::{Arc, Mutex}; use simple_parallel; use state::LSystem; use super::{LProcessor, SimpleProcessor}; /// Parallel processor dividing a state into chunks to be individually iterated /// within a pool of threads. pub struct ChunksProcessor { /// The number of symbols per full chunk. chunk_size: usize, /// The thread pool. pool: simple_parallel::Pool, } impl ChunksProcessor { /// Try and create a new 'ChunksProcessor' instance with the given parameters. /// Typical values: /// - max_tasks : number of CPU logical cores /// - chunks_size : between 100_000 and 1_000_000 symbols per chunk pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> { if max_tasks == 0 { Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})", max_tasks)) } else if chunks_size == 0 { Err(format!("ChunksProcessor::new : invalid chunks size ({})", chunks_size)) } else { Ok(ChunksProcessor { chunk_size: chunks_size, pool: simple_parallel::Pool::new(max_tasks), }) }
where S: Clone + Eq + Send + Sync { // TODO : better error handling... fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> { // Set-up let mut vec: Vec<Vec<S>> = Vec::new(); let state_len = lsystem.state().len(); if state_len == 0 { return Err(format!("cannot iterate an empty state")); } let rem = state_len % self.chunk_size; let chunks_number = state_len / self.chunk_size + match rem { 0 => 0, _ => 1, }; for _ in 0..chunks_number { vec.push(Vec::new()); } let sub_states = Arc::new(Mutex::new(vec)); // Chunks processing let rules = lsystem.rules().clone(); let errors = Mutex::new(String::new()); let chunks_iter = lsystem.state().chunks(self.chunk_size); self.pool .for_(chunks_iter.enumerate(), |(n, chunk)| { let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) { Ok(v) => v, Err(why) => { let mut error_lock = errors.lock().unwrap(); *error_lock = format!("{}\n{}", *error_lock, why); Vec::new() } }; let mut chunk_data = sub_states.lock().unwrap(); chunk_data[n] = result; }); // Error handling let error_lock = errors.lock().unwrap(); if!error_lock.is_empty() { return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock)); } // Final assembling let mut new_state_size = 0usize; let mut new_state: Vec<S> = Vec::new(); let data = sub_states.lock().unwrap(); for n in 0..chunks_number { let chunk_iterated = &data[n]; new_state_size = match new_state_size.checked_add(chunk_iterated.len()) { Some(v) => v, None => { return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \ for for Vec")) } }; new_state.extend(chunk_iterated.iter().cloned()); } Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1))) } } #[cfg(test)] mod test { use rules::HashMapRules; use state::{LSystem, new_rules_value}; use interpret::TurtleCommand; use process::{LProcessor, ChunksProcessor}; #[test] fn chunks_processing() { let mut rules = HashMapRules::new(); // algae rules rules.set_str('A', "AB", TurtleCommand::None); rules.set_str('B', "A", TurtleCommand::None); let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]; let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules)); let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap(); for n in 0..expected_sizes.len() { assert_eq!(lsystem.iteration(), n as u64); assert_eq!(lsystem.state().len(), expected_sizes[n]); lsystem = processor.iterate(&lsystem).ok().unwrap(); } } }
} } impl<S> LProcessor<S> for ChunksProcessor
random_line_split
chunks.rs
use std::sync::{Arc, Mutex}; use simple_parallel; use state::LSystem; use super::{LProcessor, SimpleProcessor}; /// Parallel processor dividing a state into chunks to be individually iterated /// within a pool of threads. pub struct ChunksProcessor { /// The number of symbols per full chunk. chunk_size: usize, /// The thread pool. pool: simple_parallel::Pool, } impl ChunksProcessor { /// Try and create a new 'ChunksProcessor' instance with the given parameters. /// Typical values: /// - max_tasks : number of CPU logical cores /// - chunks_size : between 100_000 and 1_000_000 symbols per chunk pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> { if max_tasks == 0 { Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})", max_tasks)) } else if chunks_size == 0 { Err(format!("ChunksProcessor::new : invalid chunks size ({})", chunks_size)) } else { Ok(ChunksProcessor { chunk_size: chunks_size, pool: simple_parallel::Pool::new(max_tasks), }) } } } impl<S> LProcessor<S> for ChunksProcessor where S: Clone + Eq + Send + Sync { // TODO : better error handling... fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> { // Set-up let mut vec: Vec<Vec<S>> = Vec::new(); let state_len = lsystem.state().len(); if state_len == 0 { return Err(format!("cannot iterate an empty state")); } let rem = state_len % self.chunk_size; let chunks_number = state_len / self.chunk_size + match rem { 0 => 0, _ => 1, }; for _ in 0..chunks_number { vec.push(Vec::new()); } let sub_states = Arc::new(Mutex::new(vec)); // Chunks processing let rules = lsystem.rules().clone(); let errors = Mutex::new(String::new()); let chunks_iter = lsystem.state().chunks(self.chunk_size); self.pool .for_(chunks_iter.enumerate(), |(n, chunk)| { let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) { Ok(v) => v, Err(why) => { let mut error_lock = errors.lock().unwrap(); *error_lock = format!("{}\n{}", *error_lock, why); Vec::new() } }; let mut chunk_data = sub_states.lock().unwrap(); chunk_data[n] = result; }); // Error handling let error_lock = errors.lock().unwrap(); if!error_lock.is_empty() { return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock)); } // Final assembling let mut new_state_size = 0usize; let mut new_state: Vec<S> = Vec::new(); let data = sub_states.lock().unwrap(); for n in 0..chunks_number { let chunk_iterated = &data[n]; new_state_size = match new_state_size.checked_add(chunk_iterated.len()) { Some(v) => v, None => { return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \ for for Vec")) } }; new_state.extend(chunk_iterated.iter().cloned()); } Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1))) } } #[cfg(test)] mod test { use rules::HashMapRules; use state::{LSystem, new_rules_value}; use interpret::TurtleCommand; use process::{LProcessor, ChunksProcessor}; #[test] fn chunks_processing()
}
{ let mut rules = HashMapRules::new(); // algae rules rules.set_str('A', "AB", TurtleCommand::None); rules.set_str('B', "A", TurtleCommand::None); let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]; let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules)); let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap(); for n in 0..expected_sizes.len() { assert_eq!(lsystem.iteration(), n as u64); assert_eq!(lsystem.state().len(), expected_sizes[n]); lsystem = processor.iterate(&lsystem).ok().unwrap(); } }
identifier_body
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to be allocated //! on the heap. //! //! ## Undefined //! The undefined type is a type with exactly one value: `undefined`. //! It is the value of any unassigned variable. //! //! ## Null //! The null type if also a type with exactly one value: `null`. //! //! ## Boolean //! The boolean type has exactly two values: `true` and `false`. //! //! ## String //! The string type is defined by the spec to be the set of //! all finite sequences of 16-bit integers. Unlike Rust strings, //! ECMAScript strings can be indexed, which returns the n-th //! 16-bit integer that composes this string. //! //! When a string contains textual data, it's assumed by the //! implementation and the spec that each 16-bit integer is a //! valid UTF-16 code unit. //! //! ## Number //! The number type is defined by the spec as a 64-bit floating //! point number. As such, there exist many ways to represent a //! floating point `NaN`, as well as exactly one `Infinity` and //! `-Infinity`. //! //! ECMAScript acknowledges the existence of both a positive //! zero and negative zero. //! //! Some ECMAScript operations work on 32-bit integers explicitly. //! In this case, the implementation will convert a Number value //! into an integer using the internal *ToInt32* and *ToUInt32* conversion //! functions to convert the numeric value. //! //! ## Object //! You could write books about this type, so I'll keep this brief. //! An object is a collection of properties. Every property is one //! of three types: //! * A **named data property**, which associates a *name* with an //! ECMAScript language value and a set of attributes. //! * A **named accessor property**, which associates a *name* with //! one or two *acessor functions* (getter/setter), along with a //! set of attributes. //! * An **internal property**, which isn't exposed to ECMAScript and //! is used for specification and implementation purposes. pub mod object; pub mod activation; pub mod property; pub mod function; use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace}; use std::vec::IntoIter; use std::default::Default; //pub use self::object::Object; //pub use self::activation::Activation; pub type RootedValue = RootedPtr<Value>; #[derive(Copy, Clone)] pub enum Value { // `undefined`, the sentinel of ECMAScript Undefined, // `null`, the value of the null object Null, // numbers Number(heap::NumberPtr), // booleans Boolean(heap::BooleanPtr), // strings String(heap::StringPtr), // objects Object(heap::ObjectPtr), } impl ToHeapObject for Value { fn to_heap_object(&self) -> Option<HeapObject> { match *self { Value::Null | Value::Undefined => None, Value::Number(ptr) => ptr.to_heap_object(), Value::Boolean(ptr) => ptr.to_heap_object(), Value::String(ptr) => ptr.to_heap_object(), Value::Object(ptr) => ptr.to_heap_object(), } } } impl Trace for Value { fn trace(&self) -> IntoIter<HeapObject> { if let Some(heap_obj) = self.to_heap_object() { heap_obj.trace() } else { vec![].into_iter() } } } impl Default for Value { fn default() -> Value { Value::Undefined } } impl Value { pub fn undefined() -> Value { Value::Undefined } pub fn
() -> Value { Value::Null } pub fn number(ptr: heap::NumberPtr) -> Value { Value::Number(ptr) } pub fn boolean(ptr: heap::BooleanPtr) -> Value { Value::Boolean(ptr) } pub fn string(ptr: heap::StringPtr) -> Value { Value::String(ptr) } pub fn object(ptr: heap::ObjectPtr) -> Value { Value::Object(ptr) } pub fn is_undefined(&self) -> bool { if let Value::Undefined = *self { true } else { false } } pub fn is_null(&self) -> bool { if let Value::Null = *self { true } else { false } } pub fn is_string(&self) -> bool { if let Value::String(_) = *self { true } else { false } } pub fn is_object(&self) -> bool { if let Value::Object(_) = *self { true } else { false } } pub fn unwrap_object(&self) -> heap::ObjectPtr { if let Value::Object(ptr) = *self { return ptr; } panic!("unwrap_object called on non-object value"); } pub fn same_value(&self, _: Value) -> bool { // TODO unimplemented!() } } pub trait IntoRootedValue { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue; } macro_rules! into_rooted_value_impl { ($rooted_ty:ty, $name:path) => { impl IntoRootedValue for $rooted_ty { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue { let ptr = self.into_inner(); heap.root_value($name(ptr)) } } } } into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean); into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number); into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object); into_rooted_value_impl!(heap::RootedStringPtr, Value::String); #[derive(Debug)] pub struct Exception; pub type EvalResult<T> = Result<T, Exception>; pub type EvalValue = Result<RootedValue, Exception>;
null
identifier_name
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to be allocated //! on the heap. //! //! ## Undefined //! The undefined type is a type with exactly one value: `undefined`. //! It is the value of any unassigned variable. //! //! ## Null //! The null type if also a type with exactly one value: `null`. //! //! ## Boolean //! The boolean type has exactly two values: `true` and `false`. //! //! ## String //! The string type is defined by the spec to be the set of //! all finite sequences of 16-bit integers. Unlike Rust strings, //! ECMAScript strings can be indexed, which returns the n-th //! 16-bit integer that composes this string. //! //! When a string contains textual data, it's assumed by the //! implementation and the spec that each 16-bit integer is a //! valid UTF-16 code unit. //! //! ## Number //! The number type is defined by the spec as a 64-bit floating //! point number. As such, there exist many ways to represent a //! floating point `NaN`, as well as exactly one `Infinity` and //! `-Infinity`. //! //! ECMAScript acknowledges the existence of both a positive //! zero and negative zero. //! //! Some ECMAScript operations work on 32-bit integers explicitly. //! In this case, the implementation will convert a Number value //! into an integer using the internal *ToInt32* and *ToUInt32* conversion //! functions to convert the numeric value. //! //! ## Object //! You could write books about this type, so I'll keep this brief. //! An object is a collection of properties. Every property is one //! of three types: //! * A **named data property**, which associates a *name* with an //! ECMAScript language value and a set of attributes. //! * A **named accessor property**, which associates a *name* with //! one or two *acessor functions* (getter/setter), along with a //! set of attributes. //! * An **internal property**, which isn't exposed to ECMAScript and //! is used for specification and implementation purposes. pub mod object; pub mod activation; pub mod property; pub mod function; use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace}; use std::vec::IntoIter; use std::default::Default; //pub use self::object::Object; //pub use self::activation::Activation; pub type RootedValue = RootedPtr<Value>; #[derive(Copy, Clone)] pub enum Value { // `undefined`, the sentinel of ECMAScript Undefined, // `null`, the value of the null object Null, // numbers Number(heap::NumberPtr), // booleans Boolean(heap::BooleanPtr), // strings String(heap::StringPtr), // objects Object(heap::ObjectPtr), } impl ToHeapObject for Value { fn to_heap_object(&self) -> Option<HeapObject> { match *self { Value::Null | Value::Undefined => None, Value::Number(ptr) => ptr.to_heap_object(), Value::Boolean(ptr) => ptr.to_heap_object(), Value::String(ptr) => ptr.to_heap_object(), Value::Object(ptr) => ptr.to_heap_object(), } } } impl Trace for Value { fn trace(&self) -> IntoIter<HeapObject> { if let Some(heap_obj) = self.to_heap_object() { heap_obj.trace() } else { vec![].into_iter() } } } impl Default for Value { fn default() -> Value
} impl Value { pub fn undefined() -> Value { Value::Undefined } pub fn null() -> Value { Value::Null } pub fn number(ptr: heap::NumberPtr) -> Value { Value::Number(ptr) } pub fn boolean(ptr: heap::BooleanPtr) -> Value { Value::Boolean(ptr) } pub fn string(ptr: heap::StringPtr) -> Value { Value::String(ptr) } pub fn object(ptr: heap::ObjectPtr) -> Value { Value::Object(ptr) } pub fn is_undefined(&self) -> bool { if let Value::Undefined = *self { true } else { false } } pub fn is_null(&self) -> bool { if let Value::Null = *self { true } else { false } } pub fn is_string(&self) -> bool { if let Value::String(_) = *self { true } else { false } } pub fn is_object(&self) -> bool { if let Value::Object(_) = *self { true } else { false } } pub fn unwrap_object(&self) -> heap::ObjectPtr { if let Value::Object(ptr) = *self { return ptr; } panic!("unwrap_object called on non-object value"); } pub fn same_value(&self, _: Value) -> bool { // TODO unimplemented!() } } pub trait IntoRootedValue { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue; } macro_rules! into_rooted_value_impl { ($rooted_ty:ty, $name:path) => { impl IntoRootedValue for $rooted_ty { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue { let ptr = self.into_inner(); heap.root_value($name(ptr)) } } } } into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean); into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number); into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object); into_rooted_value_impl!(heap::RootedStringPtr, Value::String); #[derive(Debug)] pub struct Exception; pub type EvalResult<T> = Result<T, Exception>; pub type EvalValue = Result<RootedValue, Exception>;
{ Value::Undefined }
identifier_body
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to be allocated //! on the heap. //! //! ## Undefined //! The undefined type is a type with exactly one value: `undefined`. //! It is the value of any unassigned variable. //! //! ## Null //! The null type if also a type with exactly one value: `null`. //! //! ## Boolean //! The boolean type has exactly two values: `true` and `false`. //! //! ## String //! The string type is defined by the spec to be the set of //! all finite sequences of 16-bit integers. Unlike Rust strings, //! ECMAScript strings can be indexed, which returns the n-th //! 16-bit integer that composes this string. //! //! When a string contains textual data, it's assumed by the //! implementation and the spec that each 16-bit integer is a //! valid UTF-16 code unit. //! //! ## Number //! The number type is defined by the spec as a 64-bit floating //! point number. As such, there exist many ways to represent a //! floating point `NaN`, as well as exactly one `Infinity` and //! `-Infinity`. //! //! ECMAScript acknowledges the existence of both a positive //! zero and negative zero. //! //! Some ECMAScript operations work on 32-bit integers explicitly. //! In this case, the implementation will convert a Number value //! into an integer using the internal *ToInt32* and *ToUInt32* conversion //! functions to convert the numeric value. //! //! ## Object //! You could write books about this type, so I'll keep this brief. //! An object is a collection of properties. Every property is one //! of three types: //! * A **named data property**, which associates a *name* with an //! ECMAScript language value and a set of attributes. //! * A **named accessor property**, which associates a *name* with //! one or two *acessor functions* (getter/setter), along with a //! set of attributes. //! * An **internal property**, which isn't exposed to ECMAScript and //! is used for specification and implementation purposes. pub mod object; pub mod activation; pub mod property; pub mod function; use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace}; use std::vec::IntoIter; use std::default::Default; //pub use self::object::Object; //pub use self::activation::Activation; pub type RootedValue = RootedPtr<Value>; #[derive(Copy, Clone)] pub enum Value { // `undefined`, the sentinel of ECMAScript Undefined, // `null`, the value of the null object Null, // numbers Number(heap::NumberPtr), // booleans Boolean(heap::BooleanPtr), // strings String(heap::StringPtr), // objects Object(heap::ObjectPtr), } impl ToHeapObject for Value { fn to_heap_object(&self) -> Option<HeapObject> { match *self { Value::Null | Value::Undefined => None, Value::Number(ptr) => ptr.to_heap_object(), Value::Boolean(ptr) => ptr.to_heap_object(), Value::String(ptr) => ptr.to_heap_object(), Value::Object(ptr) => ptr.to_heap_object(), } } } impl Trace for Value { fn trace(&self) -> IntoIter<HeapObject> { if let Some(heap_obj) = self.to_heap_object() { heap_obj.trace()
} else { vec![].into_iter() } } } impl Default for Value { fn default() -> Value { Value::Undefined } } impl Value { pub fn undefined() -> Value { Value::Undefined } pub fn null() -> Value { Value::Null } pub fn number(ptr: heap::NumberPtr) -> Value { Value::Number(ptr) } pub fn boolean(ptr: heap::BooleanPtr) -> Value { Value::Boolean(ptr) } pub fn string(ptr: heap::StringPtr) -> Value { Value::String(ptr) } pub fn object(ptr: heap::ObjectPtr) -> Value { Value::Object(ptr) } pub fn is_undefined(&self) -> bool { if let Value::Undefined = *self { true } else { false } } pub fn is_null(&self) -> bool { if let Value::Null = *self { true } else { false } } pub fn is_string(&self) -> bool { if let Value::String(_) = *self { true } else { false } } pub fn is_object(&self) -> bool { if let Value::Object(_) = *self { true } else { false } } pub fn unwrap_object(&self) -> heap::ObjectPtr { if let Value::Object(ptr) = *self { return ptr; } panic!("unwrap_object called on non-object value"); } pub fn same_value(&self, _: Value) -> bool { // TODO unimplemented!() } } pub trait IntoRootedValue { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue; } macro_rules! into_rooted_value_impl { ($rooted_ty:ty, $name:path) => { impl IntoRootedValue for $rooted_ty { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue { let ptr = self.into_inner(); heap.root_value($name(ptr)) } } } } into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean); into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number); into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object); into_rooted_value_impl!(heap::RootedStringPtr, Value::String); #[derive(Debug)] pub struct Exception; pub type EvalResult<T> = Result<T, Exception>; pub type EvalValue = Result<RootedValue, Exception>;
random_line_split
mod.rs
//! This module contains type definition for ECMAScript values. //! According to the ECMA-262 specification, there are six "types" //! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`, //! and `Object`. Four of these are value types and do not need //! heap allocation, while `String` and `Object` have to be allocated //! on the heap. //! //! ## Undefined //! The undefined type is a type with exactly one value: `undefined`. //! It is the value of any unassigned variable. //! //! ## Null //! The null type if also a type with exactly one value: `null`. //! //! ## Boolean //! The boolean type has exactly two values: `true` and `false`. //! //! ## String //! The string type is defined by the spec to be the set of //! all finite sequences of 16-bit integers. Unlike Rust strings, //! ECMAScript strings can be indexed, which returns the n-th //! 16-bit integer that composes this string. //! //! When a string contains textual data, it's assumed by the //! implementation and the spec that each 16-bit integer is a //! valid UTF-16 code unit. //! //! ## Number //! The number type is defined by the spec as a 64-bit floating //! point number. As such, there exist many ways to represent a //! floating point `NaN`, as well as exactly one `Infinity` and //! `-Infinity`. //! //! ECMAScript acknowledges the existence of both a positive //! zero and negative zero. //! //! Some ECMAScript operations work on 32-bit integers explicitly. //! In this case, the implementation will convert a Number value //! into an integer using the internal *ToInt32* and *ToUInt32* conversion //! functions to convert the numeric value. //! //! ## Object //! You could write books about this type, so I'll keep this brief. //! An object is a collection of properties. Every property is one //! of three types: //! * A **named data property**, which associates a *name* with an //! ECMAScript language value and a set of attributes. //! * A **named accessor property**, which associates a *name* with //! one or two *acessor functions* (getter/setter), along with a //! set of attributes. //! * An **internal property**, which isn't exposed to ECMAScript and //! is used for specification and implementation purposes. pub mod object; pub mod activation; pub mod property; pub mod function; use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace}; use std::vec::IntoIter; use std::default::Default; //pub use self::object::Object; //pub use self::activation::Activation; pub type RootedValue = RootedPtr<Value>; #[derive(Copy, Clone)] pub enum Value { // `undefined`, the sentinel of ECMAScript Undefined, // `null`, the value of the null object Null, // numbers Number(heap::NumberPtr), // booleans Boolean(heap::BooleanPtr), // strings String(heap::StringPtr), // objects Object(heap::ObjectPtr), } impl ToHeapObject for Value { fn to_heap_object(&self) -> Option<HeapObject> { match *self { Value::Null | Value::Undefined => None, Value::Number(ptr) => ptr.to_heap_object(), Value::Boolean(ptr) => ptr.to_heap_object(), Value::String(ptr) => ptr.to_heap_object(), Value::Object(ptr) => ptr.to_heap_object(), } } } impl Trace for Value { fn trace(&self) -> IntoIter<HeapObject> { if let Some(heap_obj) = self.to_heap_object() { heap_obj.trace() } else
} } impl Default for Value { fn default() -> Value { Value::Undefined } } impl Value { pub fn undefined() -> Value { Value::Undefined } pub fn null() -> Value { Value::Null } pub fn number(ptr: heap::NumberPtr) -> Value { Value::Number(ptr) } pub fn boolean(ptr: heap::BooleanPtr) -> Value { Value::Boolean(ptr) } pub fn string(ptr: heap::StringPtr) -> Value { Value::String(ptr) } pub fn object(ptr: heap::ObjectPtr) -> Value { Value::Object(ptr) } pub fn is_undefined(&self) -> bool { if let Value::Undefined = *self { true } else { false } } pub fn is_null(&self) -> bool { if let Value::Null = *self { true } else { false } } pub fn is_string(&self) -> bool { if let Value::String(_) = *self { true } else { false } } pub fn is_object(&self) -> bool { if let Value::Object(_) = *self { true } else { false } } pub fn unwrap_object(&self) -> heap::ObjectPtr { if let Value::Object(ptr) = *self { return ptr; } panic!("unwrap_object called on non-object value"); } pub fn same_value(&self, _: Value) -> bool { // TODO unimplemented!() } } pub trait IntoRootedValue { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue; } macro_rules! into_rooted_value_impl { ($rooted_ty:ty, $name:path) => { impl IntoRootedValue for $rooted_ty { fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue { let ptr = self.into_inner(); heap.root_value($name(ptr)) } } } } into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean); into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number); into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object); into_rooted_value_impl!(heap::RootedStringPtr, Value::String); #[derive(Debug)] pub struct Exception; pub type EvalResult<T> = Result<T, Exception>; pub type EvalValue = Result<RootedValue, Exception>;
{ vec![].into_iter() }
conditional_block
compiled.rs
_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok", "dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin", "cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling", "no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs", "return_does_clr_eol"]; pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines", "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal", "width_status_line", "num_labels", "label_height", "label_width", "max_attributes", "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity", "dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size", "micro_line_size", "number_of_pins", "output_res_char", "output_res_line", "output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons", "bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay", "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"]; pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return", "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos", "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home", "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right", "cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line", "dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode", "enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode", "enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode", "enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode", "exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode", "exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string", "init_2string", "init_3string", "init_file", "insert_character", "insert_line", "insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl", "key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3", "key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il", "key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab", "key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3", "lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline", "pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index", "parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor", "pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char", "reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor", "row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab", "set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1", "key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm", "key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character", "xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close", "key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find", "key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options", "key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace", "key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel", "key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send", "key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft", "key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint", "key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend", "key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16", "key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24", "key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32", "key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40", "key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48", "key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56", "key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol", "clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock", "display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone", "quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair", "orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground", "set_background", "change_char_pitch", "change_line_pitch", "change_res_horz", "change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality", "enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality", "enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode", "enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode", "exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode", "exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right", "micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro", "parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin", "set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image", "stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin", "set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return", "color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band", "set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode", "enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape", "alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode", "enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes", "set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs", "other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner", "acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline", "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"]; pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear", "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_", "khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_", "_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln", "rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true pub fn parse(file: &mut io::Reader, longnames: bool) -> Result<Box<TermInfo>, String> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ) let bnames; let snames; let nnames; if longnames { bnames = boolfnames; snames = stringfnames; nnames = numfnames; } else { bnames = boolnames; snames = stringnames; nnames = numnames; } // Check magic number let magic = try!(file.read_le_u16()); if magic!= 0x011A { return Err(format!("invalid magic number: expected {:x}, found {:x}", 0x011Au, magic as uint)); } let names_bytes = try!(file.read_le_i16()) as int; let bools_bytes = try!(file.read_le_i16()) as int; let numbers_count = try!(file.read_le_i16()) as int; let string_offsets_count = try!(file.read_le_i16()) as int; let string_table_bytes = try!(file.read_le_i16()) as int; assert!(names_bytes > 0); if (bools_bytes as uint) > boolnames.len() { return Err("incompatible file: more booleans than \ expected".to_string()); } if (numbers_count as uint) > numnames.len() { return Err("incompatible file: more numbers than \ expected".to_string()); } if (string_offsets_count as uint) > stringnames.len() { return Err("incompatible file: more string offsets than \ expected".to_string()); } // don't read NUL let bytes = try!(file.read_exact(names_bytes as uint - 1)); let names_str = match String::from_utf8(bytes) { Ok(s) => s, Err(_) => return Err("input not utf-8".to_string()), }; let term_names: Vec<String> = names_str.as_slice() .split('|') .map(|s| s.to_string()) .collect(); try!(file.read_byte()); // consume NUL let mut bools_map = HashMap::new(); if bools_bytes!= 0 { for i in range(0, bools_bytes) { let b = try!(file.read_byte()); if b == 1 { bools_map.insert(bnames[i as uint].to_string(), true); } } } if (bools_bytes + names_bytes) % 2 == 1 { try!(file.read_byte()); // compensate for padding } let mut numbers_map = HashMap::new(); if numbers_count!= 0 { for i in range(0, numbers_count) { let n = try!(file.read_le_u16()); if n!= 0xFFFF { numbers_map.insert(nnames[i as uint].to_string(), n); } } } let mut string_map = HashMap::new(); if string_offsets_count!= 0 { let mut string_offsets = Vec::with_capacity(10); for _ in range(0, string_offsets_count) { string_offsets.push(try!(file.read_le_u16())); } let string_table = try!(file.read_exact(string_table_bytes as uint)); if string_table.len()!= string_table_bytes as uint { return Err("error: hit EOF before end of string \ table".to_string()); } for (i, v) in string_offsets.iter().enumerate() { let offset = *v; if offset == 0xFFFF { // non-entry continue; } let name = if snames[i] == "_" { stringfnames[i] } else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct string_map.insert(name.to_string(), Vec::new()); continue; } // Find the offset of the NUL we want to go to let nulpos = string_table[offset as uint.. string_table_bytes as uint] .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_string(), string_table[offset as uint.. offset as uint + len].to_vec()) }, None => { return Err("invalid file: missing NUL in \ string_table".to_string()); } }; } } // And that's all there is to it Ok(box TermInfo { names: term_names, bools: bools_map, numbers: numbers_map, strings: string_map }) } /// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> Box<TermInfo>
{ let mut strings = HashMap::new(); strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec()); strings.insert("bold".to_string(), b"\x1B[1m".to_vec()); strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec()); strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec()); box TermInfo { names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version bools: HashMap::new(), numbers: HashMap::new(), strings: strings } }
identifier_body
compiled.rs
Info; // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable. pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin", "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type", "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above", "memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok", "dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin", "cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling", "no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs", "return_does_clr_eol"]; pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines", "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal", "width_status_line", "num_labels", "label_height", "label_width", "max_attributes", "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity", "dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size", "micro_line_size", "number_of_pins", "output_res_char", "output_res_line", "output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons", "bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay", "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"]; pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return", "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos", "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home", "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right", "cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line", "dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode", "enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode", "enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode", "enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode", "exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode", "exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string", "init_2string", "init_3string", "init_file", "insert_character", "insert_line", "insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl", "key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3", "key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il", "key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab", "key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3", "lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline", "pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index", "parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor", "pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char", "reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor", "row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab", "set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1", "key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm", "key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character", "xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close", "key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find", "key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options", "key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace", "key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel", "key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send", "key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft", "key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint", "key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend", "key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16", "key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24", "key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32", "key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40", "key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48", "key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56", "key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol", "clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock", "display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone", "quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair", "orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground", "set_background", "change_char_pitch", "change_line_pitch", "change_res_horz", "change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality", "enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality", "enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode", "enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode", "exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode", "exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right", "micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro", "parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin", "set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return", "color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band", "set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode", "enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape", "alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode", "enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes", "set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs", "other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner", "acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline", "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"]; pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear", "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_", "khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_", "_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln", "rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true pub fn parse(file: &mut io::Reader, longnames: bool) -> Result<Box<TermInfo>, String> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ) let bnames; let snames; let nnames; if longnames { bnames = boolfnames; snames = stringfnames; nnames = numfnames; } else { bnames = boolnames; snames = stringnames; nnames = numnames; } // Check magic number let magic = try!(file.read_le_u16()); if magic!= 0x011A { return Err(format!("invalid magic number: expected {:x}, found {:x}", 0x011Au, magic as uint)); } let names_bytes = try!(file.read_le_i16()) as int; let bools_bytes = try!(file.read_le_i16()) as int; let numbers_count = try!(file.read_le_i16()) as int; let string_offsets_count = try!(file.read_le_i16()) as int; let string_table_bytes = try!(file.read_le_i16()) as int; assert!(names_bytes > 0); if (bools_bytes as uint) > boolnames.len() { return Err("incompatible file: more booleans than \ expected".to_string()); } if (numbers_count as uint) > numnames.len() { return Err("incompatible file: more numbers than \ expected".to_string()); } if (string_offsets_count as uint) > stringnames.len() { return Err("incompatible file: more string offsets than \ expected".to_string()); } // don't read NUL let bytes = try!(file.read_exact(names_bytes as uint - 1)); let names_str = match String::from_utf8(bytes) { Ok(s) => s, Err(_) => return Err("input not utf-8".to_string()), }; let term_names: Vec<String> = names_str.as_slice() .split('|') .map(|s| s.to_string()) .collect(); try!(file.read_byte()); // consume NUL let mut bools_map = HashMap::new(); if bools_bytes!= 0 { for i in range(0, bools_bytes) { let b = try!(file.read_byte()); if b == 1 { bools_map.insert(bnames[i as uint].to_string(), true); } } } if (bools_bytes + names_bytes) % 2 == 1 { try!(file.read_byte()); // compensate for padding } let mut numbers_map = HashMap::new(); if numbers_count!= 0 { for i in range(0, numbers_count) { let n = try!(file.read_le_u16()); if n!= 0xFFFF { numbers_map.insert(nnames[i as uint].to_string(), n); } } } let mut string_map = HashMap::new(); if string_offsets_count!= 0 { let mut string_offsets = Vec::with_capacity(10); for _ in range(0, string_offsets_count) { string_offsets.push(try!(file.read_le_u16())); } let string_table = try!(file.read_exact(string_table_bytes as uint)); if string_table.len()!= string_table_bytes as uint { return Err("error: hit EOF before end of string \ table".to_string()); } for (i, v) in string_offsets.iter().enumerate() { let offset = *v; if offset == 0xFFFF { // non-entry continue; } let name = if snames[i] == "_" { stringfnames[i] } else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct string_map.insert(name.to_string(), Vec::new()); continue; } // Find the offset of the NUL we want to go to let nulpos = string_table[offset as uint.. string_table_bytes as uint] .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_string(), string_table[offset as uint.. offset as uint + len].to_vec()) }, None => { return Err("invalid file: missing NUL in \ string_table".to_string()); } }; } } // And that's all there is to it Ok(box TermInfo { names: term_names, bools: bools_map, numbers: numbers_map, strings: string_map }) } /// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> Box<TermInfo> { let mut strings = HashMap::new(); strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec()); strings.insert("bold".to_string(), b"\x1B[1m".to_vec()); strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec()); strings.insert("set
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
random_line_split
compiled.rs
_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff", "prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region", "can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch", "cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin", "cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling", "no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs", "return_does_clr_eol"]; pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"]; pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines", "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal", "width_status_line", "num_labels", "label_height", "label_width", "max_attributes", "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity", "dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size", "micro_line_size", "number_of_pins", "output_res_char", "output_res_line", "output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons", "bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay", "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"]; pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"]; pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return", "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos", "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home", "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right", "cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line", "dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode", "enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode", "enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode", "enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode", "exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode", "exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string", "init_2string", "init_3string", "init_file", "insert_character", "insert_line", "insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl", "key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3", "key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il", "key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab", "key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3", "lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline", "pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index", "parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor", "pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char", "reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor", "row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab", "set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1", "key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm", "key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character", "xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close", "key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find", "key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options", "key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace", "key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel", "key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send", "key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft", "key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint", "key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend", "key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16", "key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24", "key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32", "key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40", "key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48", "key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56", "key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol", "clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock", "display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone", "quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair", "orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground", "set_background", "change_char_pitch", "change_line_pitch", "change_res_horz", "change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality", "enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality", "enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode", "enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode", "exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode", "exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right", "micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro", "parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin", "set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin", "set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image", "stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr", "zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse", "set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init", "set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin", "set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return", "color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band", "set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode", "enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape", "alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode", "enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes", "set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs", "other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner", "acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline", "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"]; pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear", "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_", "khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_", "_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey", "pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p", "rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln", "rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_", "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu", "box1"]; /// Parse a compiled terminfo entry, using long capability names if `longnames` is true pub fn parse(file: &mut io::Reader, longnames: bool) -> Result<Box<TermInfo>, String> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ) let bnames; let snames; let nnames; if longnames { bnames = boolfnames; snames = stringfnames; nnames = numfnames; } else { bnames = boolnames; snames = stringnames; nnames = numnames; } // Check magic number let magic = try!(file.read_le_u16()); if magic!= 0x011A { return Err(format!("invalid magic number: expected {:x}, found {:x}", 0x011Au, magic as uint)); } let names_bytes = try!(file.read_le_i16()) as int; let bools_bytes = try!(file.read_le_i16()) as int; let numbers_count = try!(file.read_le_i16()) as int; let string_offsets_count = try!(file.read_le_i16()) as int; let string_table_bytes = try!(file.read_le_i16()) as int; assert!(names_bytes > 0); if (bools_bytes as uint) > boolnames.len() { return Err("incompatible file: more booleans than \ expected".to_string()); } if (numbers_count as uint) > numnames.len() { return Err("incompatible file: more numbers than \ expected".to_string()); } if (string_offsets_count as uint) > stringnames.len() { return Err("incompatible file: more string offsets than \ expected".to_string()); } // don't read NUL let bytes = try!(file.read_exact(names_bytes as uint - 1)); let names_str = match String::from_utf8(bytes) { Ok(s) => s, Err(_) => return Err("input not utf-8".to_string()), }; let term_names: Vec<String> = names_str.as_slice() .split('|') .map(|s| s.to_string()) .collect(); try!(file.read_byte()); // consume NUL let mut bools_map = HashMap::new(); if bools_bytes!= 0 { for i in range(0, bools_bytes) { let b = try!(file.read_byte()); if b == 1 { bools_map.insert(bnames[i as uint].to_string(), true); } } } if (bools_bytes + names_bytes) % 2 == 1 { try!(file.read_byte()); // compensate for padding } let mut numbers_map = HashMap::new(); if numbers_count!= 0 { for i in range(0, numbers_count) { let n = try!(file.read_le_u16()); if n!= 0xFFFF { numbers_map.insert(nnames[i as uint].to_string(), n); } } } let mut string_map = HashMap::new(); if string_offsets_count!= 0 { let mut string_offsets = Vec::with_capacity(10); for _ in range(0, string_offsets_count) { string_offsets.push(try!(file.read_le_u16())); } let string_table = try!(file.read_exact(string_table_bytes as uint)); if string_table.len()!= string_table_bytes as uint { return Err("error: hit EOF before end of string \ table".to_string()); } for (i, v) in string_offsets.iter().enumerate() { let offset = *v; if offset == 0xFFFF { // non-entry continue; } let name = if snames[i] == "_" { stringfnames[i] } else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct string_map.insert(name.to_string(), Vec::new()); continue; } // Find the offset of the NUL we want to go to let nulpos = string_table[offset as uint.. string_table_bytes as uint] .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_string(), string_table[offset as uint.. offset as uint + len].to_vec()) }, None => { return Err("invalid file: missing NUL in \ string_table".to_string()); } }; } } // And that's all there is to it Ok(box TermInfo { names: term_names, bools: bools_map, numbers: numbers_map, strings: string_map }) } /// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> Box<TermInfo> { let mut strings = HashMap::new(); strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec()); strings.insert("bold".to_string(), b"\x1B[1m".to_vec()); strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec()); strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec()); box TermInfo { names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version bools: HashMap::new(), numbers: HashMap::new(), strings: strings } } #[cfg(test)] mod test { use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames}; #[test] fn
test_veclens
identifier_name
overflowing_mul.rs
use num::arithmetic::traits::{OverflowingMul, OverflowingMulAssign}; macro_rules! impl_overflowing_mul { ($t:ident) => { impl OverflowingMul<$t> for $t { type Output = $t; #[inline] fn overflowing_mul(self, other: $t) -> ($t, bool) { $t::overflowing_mul(self, other) } }
/// Replaces `self` with `self * other`. /// /// Returns a boolean indicating whether an arithmetic overflow would occur. If an /// overflow would have occurred, then the wrapped value is assigned. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::overflowing_mul` module. #[inline] fn overflowing_mul_assign(&mut self, other: $t) -> bool { let (result, overflow) = self.overflowing_mul(other); *self = result; overflow } } }; } apply_to_primitive_ints!(impl_overflowing_mul);
impl OverflowingMulAssign<$t> for $t {
random_line_split
main.rs
#![feature(plugin)] #![allow(dead_code)] #![allow(unused_variables)] // error-chain can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate chrono; extern crate markdown; extern crate liquid; extern crate walkdir; extern crate rustc_serialize; extern crate docopt; extern crate inotify; extern crate git2; extern crate url; use std::collections::HashMap; use std::io::prelude::*; use std::io::BufReader; use std::fs::{self, File, OpenOptions}; use std::sync::mpsc::channel; use std::thread; use std::process::Command; use std::default::Default; use std::path::PathBuf; use walkdir::WalkDir; use liquid::Renderable; use liquid::Context; use liquid::Value; use docopt::Docopt; mod logger; mod post; mod site; mod cmdline; #[macro_use] mod new_blog; use logger::*; use post::*; use site::*; use cmdline::{NOT_SILICA_SITE, USAGE}; use new_blog::{create_new_site, exists_config, create_new_post}; mod errors { // Create the Error, ErrorKind, ResultExt, and Result types error_chain! { } } use errors::*; #[derive(Debug, RustcDecodable)] struct Args { cmd_site: bool, cmd_post: bool, cmd_publish: bool, cmd_serve: bool, flag_draft: bool, flag_version: bool, flag_help: bool, arg_sname: Vec<String>, arg_pname: Vec<String>, } #[derive(Debug)] pub enum State { Metadata, Content, WeGood, MarkdownParseError, NotValidSite, IOError, } enum SilicaParseError { ConfigFile, NotASite, Other, } fn watch() { let site = Site::new(); let (tx, rx) = channel(); thread::spawn(move || { site.watch_changes(tx.clone()); }); println!("Watching for changes"); match rx.recv().unwrap() { Events::Modified => { let _ = publish("./"); serve() } _ => println!("I got nothing"), } } fn serve() { if!exists_config("./config.toml") { return log_err(NOT_SILICA_SITE); } Command::new("pkill") .arg("python") .output() .unwrap_or_else(|e| panic!("failed to run Web Server: {}", e)); let mut child = Command::new("python") .arg("-m") .arg("http.server") .spawn() .unwrap_or_else(|e| panic!("failed to run Web Server: {}", e)); // watch for file event changes // this calls the site's watch_changes method which spawns another thread and receives a // a signal of file changes, back to main thread, and on receiving the main thread // does a match and calls the serve publish command again, which restarts the server. watch(); let ecode = child.wait() .unwrap_or_else(|e| panic!("failed to wait on child: {}", e)); println!("Child Exited with {:?}", ecode); } // TODO decouple roles here maybe? fn publish(base: &str) -> Result<()> { assert_valid_site!(); let mut config_map = HashMap::new(); let mut posts: Vec<Post> = vec![]; let mut path_post = PathBuf::new(); path_post.push(base); path_post.push("content"); path_post.push("posts"); let mut site = Site::new(); let has_md_ext = |ext: &walkdir::DirEntry| ext.path().extension().unwrap() == "md"; // TODO use this when we have better idea on basic properties of a Silica Site let _site_configs = || -> Result<HashMap<String, String>> { let lines = BufReader::new(File::open("./silica.toml").unwrap()).lines(); for line in lines { let line_content = line.unwrap(); let v: Vec<&str> = line_content.split("=").collect(); if v.len() == 2 { config_map.insert(v[0].trim().to_owned(), v[1].trim().to_owned()); } } Ok(config_map) }; for entry in WalkDir::new(path_post) { let entry = entry.unwrap(); if!entry.path().is_dir() && has_md_ext(&entry) { let current_file = entry.path().to_str().unwrap(); match File::open(current_file) { Ok(ref mut f) => { log_info(&format!("Processing {:?}", current_file)); let mut md_string = String::new(); let _ = f.read_to_string(&mut md_string); match parse_md(md_string) { Ok(post) => posts.push(post), Err(_) => bail!("Markdown Parse Error") } } Err(_) => bail!("Markdown Parse Error"), } } else { log_warn("Some non-markdown files discovered"); } } site.posts(posts); match fs::metadata("./build") { Ok(_) => log_warn("Exists: Ignoring folder creation"), Err(_) => {let _ = fs::create_dir("./build");} } let mut index_page = String::new(); index_page.push_str("./build/"); index_page.push_str("index.html"); match File::create(&index_page) { Ok(mut buffer) => { let mut site_template = OpenOptions::new().read(true).open("../base/base_theme.html").unwrap(); let mut base_theme_buff: Vec<u8> = Vec::new(); site_template.read_to_end(&mut base_theme_buff).unwrap(); let base_theme_buff = String::from_utf8(base_theme_buff).unwrap(); let _ = buffer.write_all((&base_theme_buff[..]).as_bytes()); let mut liquid_posts = vec![]; if let Some(ref posts) = *site.get_posts() { for p in posts { liquid_posts.push(Value::Str(p.get_content())) } } let template = liquid::parse(&base_theme_buff, Default::default()).unwrap(); let mut cx = Context::new(); cx.set_val("posts", Value::Array(liquid_posts)); let output = template.render(&mut cx).unwrap().unwrap(); let mut output_slice = output.as_bytes(); let _ = buffer.write_all(&mut output_slice); } Err(_) => bail!("Error transpiling markdown to HTML") } Ok(()) } fn process_cmd(args: &Args) -> Result<()> { if args.cmd_site { create_new_site(args.arg_sname.first().unwrap()) } else if args.cmd_post { let mut as_draft: bool = false; if args.flag_draft { as_draft = true; } let post_name = args.arg_pname[0].clone(); let _ = create_new_post(&post_name, as_draft); } else if args.cmd_publish { match publish("./") { Err(what) => bail!("Something's wrong: {:?}", what), Ok(_) => { log_info("Your shiny new site lives in `build` folder.\nHave a great day."); } } } else if args.cmd_serve { serve() } else if args.flag_help { println!("{}", USAGE); } Ok(()) } // The entry point for silica. Parses command line arguments and acts accordingly fn main() { let args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if let Err(ref e) = process_cmd(&args) { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg); } ::std::process::exit(1); } } #[cfg(test)] mod test { use {bootstrap, init_post}; #[test] fn
() { use std::path::Path; use std::fs; let site_dir = Path::new("./blog"); let site_config_file = Path::new("./blog/config.toml"); bootstrap("blog"); assert_eq!(true, site_dir.is_dir()); assert_eq!(true, site_config_file.exists()); fs::remove_dir_all("./blog").unwrap(); } #[test] fn test_init_post() { use std::path::Path; use std::fs; init_post("intro.md", false); let post_md = Path::new("./intro.md"); assert_eq!(true, post_md.exists()); fs::remove_file("./intro.md").unwrap(); } }
test_create_site
identifier_name
main.rs
#![feature(plugin)] #![allow(dead_code)] #![allow(unused_variables)] // error-chain can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate chrono; extern crate markdown; extern crate liquid; extern crate walkdir; extern crate rustc_serialize; extern crate docopt; extern crate inotify; extern crate git2; extern crate url; use std::collections::HashMap; use std::io::prelude::*; use std::io::BufReader; use std::fs::{self, File, OpenOptions}; use std::sync::mpsc::channel; use std::thread; use std::process::Command; use std::default::Default; use std::path::PathBuf; use walkdir::WalkDir; use liquid::Renderable; use liquid::Context; use liquid::Value; use docopt::Docopt; mod logger; mod post; mod site; mod cmdline; #[macro_use] mod new_blog; use logger::*; use post::*; use site::*; use cmdline::{NOT_SILICA_SITE, USAGE}; use new_blog::{create_new_site, exists_config, create_new_post}; mod errors { // Create the Error, ErrorKind, ResultExt, and Result types error_chain! { } } use errors::*; #[derive(Debug, RustcDecodable)] struct Args { cmd_site: bool, cmd_post: bool, cmd_publish: bool, cmd_serve: bool, flag_draft: bool, flag_version: bool, flag_help: bool, arg_sname: Vec<String>, arg_pname: Vec<String>, } #[derive(Debug)]
Metadata, Content, WeGood, MarkdownParseError, NotValidSite, IOError, } enum SilicaParseError { ConfigFile, NotASite, Other, } fn watch() { let site = Site::new(); let (tx, rx) = channel(); thread::spawn(move || { site.watch_changes(tx.clone()); }); println!("Watching for changes"); match rx.recv().unwrap() { Events::Modified => { let _ = publish("./"); serve() } _ => println!("I got nothing"), } } fn serve() { if!exists_config("./config.toml") { return log_err(NOT_SILICA_SITE); } Command::new("pkill") .arg("python") .output() .unwrap_or_else(|e| panic!("failed to run Web Server: {}", e)); let mut child = Command::new("python") .arg("-m") .arg("http.server") .spawn() .unwrap_or_else(|e| panic!("failed to run Web Server: {}", e)); // watch for file event changes // this calls the site's watch_changes method which spawns another thread and receives a // a signal of file changes, back to main thread, and on receiving the main thread // does a match and calls the serve publish command again, which restarts the server. watch(); let ecode = child.wait() .unwrap_or_else(|e| panic!("failed to wait on child: {}", e)); println!("Child Exited with {:?}", ecode); } // TODO decouple roles here maybe? fn publish(base: &str) -> Result<()> { assert_valid_site!(); let mut config_map = HashMap::new(); let mut posts: Vec<Post> = vec![]; let mut path_post = PathBuf::new(); path_post.push(base); path_post.push("content"); path_post.push("posts"); let mut site = Site::new(); let has_md_ext = |ext: &walkdir::DirEntry| ext.path().extension().unwrap() == "md"; // TODO use this when we have better idea on basic properties of a Silica Site let _site_configs = || -> Result<HashMap<String, String>> { let lines = BufReader::new(File::open("./silica.toml").unwrap()).lines(); for line in lines { let line_content = line.unwrap(); let v: Vec<&str> = line_content.split("=").collect(); if v.len() == 2 { config_map.insert(v[0].trim().to_owned(), v[1].trim().to_owned()); } } Ok(config_map) }; for entry in WalkDir::new(path_post) { let entry = entry.unwrap(); if!entry.path().is_dir() && has_md_ext(&entry) { let current_file = entry.path().to_str().unwrap(); match File::open(current_file) { Ok(ref mut f) => { log_info(&format!("Processing {:?}", current_file)); let mut md_string = String::new(); let _ = f.read_to_string(&mut md_string); match parse_md(md_string) { Ok(post) => posts.push(post), Err(_) => bail!("Markdown Parse Error") } } Err(_) => bail!("Markdown Parse Error"), } } else { log_warn("Some non-markdown files discovered"); } } site.posts(posts); match fs::metadata("./build") { Ok(_) => log_warn("Exists: Ignoring folder creation"), Err(_) => {let _ = fs::create_dir("./build");} } let mut index_page = String::new(); index_page.push_str("./build/"); index_page.push_str("index.html"); match File::create(&index_page) { Ok(mut buffer) => { let mut site_template = OpenOptions::new().read(true).open("../base/base_theme.html").unwrap(); let mut base_theme_buff: Vec<u8> = Vec::new(); site_template.read_to_end(&mut base_theme_buff).unwrap(); let base_theme_buff = String::from_utf8(base_theme_buff).unwrap(); let _ = buffer.write_all((&base_theme_buff[..]).as_bytes()); let mut liquid_posts = vec![]; if let Some(ref posts) = *site.get_posts() { for p in posts { liquid_posts.push(Value::Str(p.get_content())) } } let template = liquid::parse(&base_theme_buff, Default::default()).unwrap(); let mut cx = Context::new(); cx.set_val("posts", Value::Array(liquid_posts)); let output = template.render(&mut cx).unwrap().unwrap(); let mut output_slice = output.as_bytes(); let _ = buffer.write_all(&mut output_slice); } Err(_) => bail!("Error transpiling markdown to HTML") } Ok(()) } fn process_cmd(args: &Args) -> Result<()> { if args.cmd_site { create_new_site(args.arg_sname.first().unwrap()) } else if args.cmd_post { let mut as_draft: bool = false; if args.flag_draft { as_draft = true; } let post_name = args.arg_pname[0].clone(); let _ = create_new_post(&post_name, as_draft); } else if args.cmd_publish { match publish("./") { Err(what) => bail!("Something's wrong: {:?}", what), Ok(_) => { log_info("Your shiny new site lives in `build` folder.\nHave a great day."); } } } else if args.cmd_serve { serve() } else if args.flag_help { println!("{}", USAGE); } Ok(()) } // The entry point for silica. Parses command line arguments and acts accordingly fn main() { let args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if let Err(ref e) = process_cmd(&args) { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg); } ::std::process::exit(1); } } #[cfg(test)] mod test { use {bootstrap, init_post}; #[test] fn test_create_site() { use std::path::Path; use std::fs; let site_dir = Path::new("./blog"); let site_config_file = Path::new("./blog/config.toml"); bootstrap("blog"); assert_eq!(true, site_dir.is_dir()); assert_eq!(true, site_config_file.exists()); fs::remove_dir_all("./blog").unwrap(); } #[test] fn test_init_post() { use std::path::Path; use std::fs; init_post("intro.md", false); let post_md = Path::new("./intro.md"); assert_eq!(true, post_md.exists()); fs::remove_file("./intro.md").unwrap(); } }
pub enum State {
random_line_split
main.rs
#![feature(plugin)] #![allow(dead_code)] #![allow(unused_variables)] // error-chain can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate chrono; extern crate markdown; extern crate liquid; extern crate walkdir; extern crate rustc_serialize; extern crate docopt; extern crate inotify; extern crate git2; extern crate url; use std::collections::HashMap; use std::io::prelude::*; use std::io::BufReader; use std::fs::{self, File, OpenOptions}; use std::sync::mpsc::channel; use std::thread; use std::process::Command; use std::default::Default; use std::path::PathBuf; use walkdir::WalkDir; use liquid::Renderable; use liquid::Context; use liquid::Value; use docopt::Docopt; mod logger; mod post; mod site; mod cmdline; #[macro_use] mod new_blog; use logger::*; use post::*; use site::*; use cmdline::{NOT_SILICA_SITE, USAGE}; use new_blog::{create_new_site, exists_config, create_new_post}; mod errors { // Create the Error, ErrorKind, ResultExt, and Result types error_chain! { } } use errors::*; #[derive(Debug, RustcDecodable)] struct Args { cmd_site: bool, cmd_post: bool, cmd_publish: bool, cmd_serve: bool, flag_draft: bool, flag_version: bool, flag_help: bool, arg_sname: Vec<String>, arg_pname: Vec<String>, } #[derive(Debug)] pub enum State { Metadata, Content, WeGood, MarkdownParseError, NotValidSite, IOError, } enum SilicaParseError { ConfigFile, NotASite, Other, } fn watch() { let site = Site::new(); let (tx, rx) = channel(); thread::spawn(move || { site.watch_changes(tx.clone()); }); println!("Watching for changes"); match rx.recv().unwrap() { Events::Modified => { let _ = publish("./"); serve() } _ => println!("I got nothing"), } } fn serve() { if!exists_config("./config.toml") { return log_err(NOT_SILICA_SITE); } Command::new("pkill") .arg("python") .output() .unwrap_or_else(|e| panic!("failed to run Web Server: {}", e)); let mut child = Command::new("python") .arg("-m") .arg("http.server") .spawn() .unwrap_or_else(|e| panic!("failed to run Web Server: {}", e)); // watch for file event changes // this calls the site's watch_changes method which spawns another thread and receives a // a signal of file changes, back to main thread, and on receiving the main thread // does a match and calls the serve publish command again, which restarts the server. watch(); let ecode = child.wait() .unwrap_or_else(|e| panic!("failed to wait on child: {}", e)); println!("Child Exited with {:?}", ecode); } // TODO decouple roles here maybe? fn publish(base: &str) -> Result<()> { assert_valid_site!(); let mut config_map = HashMap::new(); let mut posts: Vec<Post> = vec![]; let mut path_post = PathBuf::new(); path_post.push(base); path_post.push("content"); path_post.push("posts"); let mut site = Site::new(); let has_md_ext = |ext: &walkdir::DirEntry| ext.path().extension().unwrap() == "md"; // TODO use this when we have better idea on basic properties of a Silica Site let _site_configs = || -> Result<HashMap<String, String>> { let lines = BufReader::new(File::open("./silica.toml").unwrap()).lines(); for line in lines { let line_content = line.unwrap(); let v: Vec<&str> = line_content.split("=").collect(); if v.len() == 2 { config_map.insert(v[0].trim().to_owned(), v[1].trim().to_owned()); } } Ok(config_map) }; for entry in WalkDir::new(path_post) { let entry = entry.unwrap(); if!entry.path().is_dir() && has_md_ext(&entry) { let current_file = entry.path().to_str().unwrap(); match File::open(current_file) { Ok(ref mut f) => { log_info(&format!("Processing {:?}", current_file)); let mut md_string = String::new(); let _ = f.read_to_string(&mut md_string); match parse_md(md_string) { Ok(post) => posts.push(post), Err(_) => bail!("Markdown Parse Error") } } Err(_) => bail!("Markdown Parse Error"), } } else { log_warn("Some non-markdown files discovered"); } } site.posts(posts); match fs::metadata("./build") { Ok(_) => log_warn("Exists: Ignoring folder creation"), Err(_) => {let _ = fs::create_dir("./build");} } let mut index_page = String::new(); index_page.push_str("./build/"); index_page.push_str("index.html"); match File::create(&index_page) { Ok(mut buffer) => { let mut site_template = OpenOptions::new().read(true).open("../base/base_theme.html").unwrap(); let mut base_theme_buff: Vec<u8> = Vec::new(); site_template.read_to_end(&mut base_theme_buff).unwrap(); let base_theme_buff = String::from_utf8(base_theme_buff).unwrap(); let _ = buffer.write_all((&base_theme_buff[..]).as_bytes()); let mut liquid_posts = vec![]; if let Some(ref posts) = *site.get_posts() { for p in posts { liquid_posts.push(Value::Str(p.get_content())) } } let template = liquid::parse(&base_theme_buff, Default::default()).unwrap(); let mut cx = Context::new(); cx.set_val("posts", Value::Array(liquid_posts)); let output = template.render(&mut cx).unwrap().unwrap(); let mut output_slice = output.as_bytes(); let _ = buffer.write_all(&mut output_slice); } Err(_) => bail!("Error transpiling markdown to HTML") } Ok(()) } fn process_cmd(args: &Args) -> Result<()> { if args.cmd_site { create_new_site(args.arg_sname.first().unwrap()) } else if args.cmd_post { let mut as_draft: bool = false; if args.flag_draft { as_draft = true; } let post_name = args.arg_pname[0].clone(); let _ = create_new_post(&post_name, as_draft); } else if args.cmd_publish { match publish("./") { Err(what) => bail!("Something's wrong: {:?}", what), Ok(_) => { log_info("Your shiny new site lives in `build` folder.\nHave a great day."); } } } else if args.cmd_serve { serve() } else if args.flag_help
Ok(()) } // The entry point for silica. Parses command line arguments and acts accordingly fn main() { let args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if let Err(ref e) = process_cmd(&args) { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg); } ::std::process::exit(1); } } #[cfg(test)] mod test { use {bootstrap, init_post}; #[test] fn test_create_site() { use std::path::Path; use std::fs; let site_dir = Path::new("./blog"); let site_config_file = Path::new("./blog/config.toml"); bootstrap("blog"); assert_eq!(true, site_dir.is_dir()); assert_eq!(true, site_config_file.exists()); fs::remove_dir_all("./blog").unwrap(); } #[test] fn test_init_post() { use std::path::Path; use std::fs; init_post("intro.md", false); let post_md = Path::new("./intro.md"); assert_eq!(true, post_md.exists()); fs::remove_file("./intro.md").unwrap(); } }
{ println!("{}", USAGE); }
conditional_block
rustdoc.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Rustdoc - The Rust documentation generator #[link(name = "rustdoc", vers = "0.8-pre", uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412", url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")]; #[comment = "The Rust documentation generator"]; #[license = "MIT/ASL2"]; #[crate_type = "lib"]; #[allow(non_implicitly_copyable_typarams)]; extern mod extra; extern mod rustc; extern mod syntax; use std::io; use std::os; use config::Config; use doc::Item; use doc::ItemUtils; pub mod pass; pub mod config; pub mod parse; pub mod extract; pub mod attr_parser; pub mod doc; pub mod markdown_index_pass; pub mod markdown_pass; pub mod markdown_writer; pub mod fold; pub mod path_pass; pub mod attr_pass; pub mod tystr_pass; pub mod prune_hidden_pass; pub mod desc_to_brief_pass; pub mod text_pass; pub mod unindent_pass; pub mod trim_pass; pub mod astsrv; pub mod demo; pub mod sort_pass; pub mod sort_item_name_pass; pub mod sort_item_type_pass; pub mod page_pass; pub mod sectionalize_pass; pub mod escape_pass; pub mod prune_private_pass; pub mod util; pub fn main() { let args = os::args(); if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) { config::usage(); return; } let config = match config::parse_config(args) { Ok(config) => config, Err(err) =>
}; run(config); } /// Runs rustdoc over the given file fn run(config: Config) { let source_file = copy config.input_crate; // Create an AST service from the source code do astsrv::from_file(source_file.to_str()) |srv| { // Just time how long it takes for the AST to become available do time(~"wait_ast") { do astsrv::exec(srv.clone()) |_ctxt| { } }; // Extract the initial doc tree from the AST. This contains // just names and node ids. let doc = time(~"extract", || { let default_name = copy source_file; extract::from_srv(srv.clone(), default_name.to_str()) }); // Refine and publish the document pass::run_passes(srv, doc, ~[ // Generate type and signature strings tystr_pass::mk_pass(), // Record the full paths to various nodes path_pass::mk_pass(), // Extract the docs attributes and attach them to doc nodes attr_pass::mk_pass(), // Perform various text escaping escape_pass::mk_pass(), // Remove things marked doc(hidden) prune_hidden_pass::mk_pass(), // Remove things that are private prune_private_pass::mk_pass(), // Extract brief documentation from the full descriptions desc_to_brief_pass::mk_pass(), // Massage the text to remove extra indentation unindent_pass::mk_pass(), // Split text into multiple sections according to headers sectionalize_pass::mk_pass(), // Trim extra spaces from text trim_pass::mk_pass(), // Sort items by name sort_item_name_pass::mk_pass(), // Sort items again by kind sort_item_type_pass::mk_pass(), // Create indexes appropriate for markdown markdown_index_pass::mk_pass(copy config), // Break the document into pages if required by the // output format page_pass::mk_pass(config.output_style), // Render markdown_pass::mk_pass( markdown_writer::make_writer_factory(copy config) ) ]); } } pub fn time<T>(what: ~str, f: &fn() -> T) -> T { let start = extra::time::precise_time_s(); let rv = f(); let end = extra::time::precise_time_s(); info!("time: %3.3f s %s", end - start, what); rv }
{ io::println(fmt!("error: %s", err)); return; }
conditional_block
rustdoc.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Rustdoc - The Rust documentation generator #[link(name = "rustdoc", vers = "0.8-pre", uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412", url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")]; #[comment = "The Rust documentation generator"]; #[license = "MIT/ASL2"]; #[crate_type = "lib"]; #[allow(non_implicitly_copyable_typarams)]; extern mod extra; extern mod rustc; extern mod syntax; use std::io; use std::os; use config::Config; use doc::Item; use doc::ItemUtils; pub mod pass; pub mod config; pub mod parse; pub mod extract; pub mod attr_parser; pub mod doc; pub mod markdown_index_pass; pub mod markdown_pass; pub mod markdown_writer; pub mod fold; pub mod path_pass; pub mod attr_pass; pub mod tystr_pass; pub mod prune_hidden_pass; pub mod desc_to_brief_pass; pub mod text_pass; pub mod unindent_pass; pub mod trim_pass; pub mod astsrv; pub mod demo; pub mod sort_pass; pub mod sort_item_name_pass; pub mod sort_item_type_pass; pub mod page_pass; pub mod sectionalize_pass; pub mod escape_pass; pub mod prune_private_pass; pub mod util; pub fn main() { let args = os::args(); if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) { config::usage(); return; } let config = match config::parse_config(args) { Ok(config) => config, Err(err) => { io::println(fmt!("error: %s", err)); return; } }; run(config); } /// Runs rustdoc over the given file fn run(config: Config)
pass::run_passes(srv, doc, ~[ // Generate type and signature strings tystr_pass::mk_pass(), // Record the full paths to various nodes path_pass::mk_pass(), // Extract the docs attributes and attach them to doc nodes attr_pass::mk_pass(), // Perform various text escaping escape_pass::mk_pass(), // Remove things marked doc(hidden) prune_hidden_pass::mk_pass(), // Remove things that are private prune_private_pass::mk_pass(), // Extract brief documentation from the full descriptions desc_to_brief_pass::mk_pass(), // Massage the text to remove extra indentation unindent_pass::mk_pass(), // Split text into multiple sections according to headers sectionalize_pass::mk_pass(), // Trim extra spaces from text trim_pass::mk_pass(), // Sort items by name sort_item_name_pass::mk_pass(), // Sort items again by kind sort_item_type_pass::mk_pass(), // Create indexes appropriate for markdown markdown_index_pass::mk_pass(copy config), // Break the document into pages if required by the // output format page_pass::mk_pass(config.output_style), // Render markdown_pass::mk_pass( markdown_writer::make_writer_factory(copy config) ) ]); } } pub fn time<T>(what: ~str, f: &fn() -> T) -> T { let start = extra::time::precise_time_s(); let rv = f(); let end = extra::time::precise_time_s(); info!("time: %3.3f s %s", end - start, what); rv }
{ let source_file = copy config.input_crate; // Create an AST service from the source code do astsrv::from_file(source_file.to_str()) |srv| { // Just time how long it takes for the AST to become available do time(~"wait_ast") { do astsrv::exec(srv.clone()) |_ctxt| { } }; // Extract the initial doc tree from the AST. This contains // just names and node ids. let doc = time(~"extract", || { let default_name = copy source_file; extract::from_srv(srv.clone(), default_name.to_str()) }); // Refine and publish the document
identifier_body
rustdoc.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Rustdoc - The Rust documentation generator #[link(name = "rustdoc", vers = "0.8-pre", uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412", url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")]; #[comment = "The Rust documentation generator"]; #[license = "MIT/ASL2"]; #[crate_type = "lib"]; #[allow(non_implicitly_copyable_typarams)]; extern mod extra; extern mod rustc; extern mod syntax; use std::io; use std::os; use config::Config; use doc::Item; use doc::ItemUtils; pub mod pass; pub mod config; pub mod parse; pub mod extract; pub mod attr_parser; pub mod doc; pub mod markdown_index_pass; pub mod markdown_pass; pub mod markdown_writer; pub mod fold; pub mod path_pass; pub mod attr_pass; pub mod tystr_pass; pub mod prune_hidden_pass; pub mod desc_to_brief_pass; pub mod text_pass; pub mod unindent_pass; pub mod trim_pass; pub mod astsrv; pub mod demo; pub mod sort_pass; pub mod sort_item_name_pass; pub mod sort_item_type_pass; pub mod page_pass; pub mod sectionalize_pass; pub mod escape_pass; pub mod prune_private_pass; pub mod util; pub fn main() { let args = os::args(); if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) { config::usage(); return; } let config = match config::parse_config(args) { Ok(config) => config, Err(err) => { io::println(fmt!("error: %s", err)); return; } }; run(config); } /// Runs rustdoc over the given file fn
(config: Config) { let source_file = copy config.input_crate; // Create an AST service from the source code do astsrv::from_file(source_file.to_str()) |srv| { // Just time how long it takes for the AST to become available do time(~"wait_ast") { do astsrv::exec(srv.clone()) |_ctxt| { } }; // Extract the initial doc tree from the AST. This contains // just names and node ids. let doc = time(~"extract", || { let default_name = copy source_file; extract::from_srv(srv.clone(), default_name.to_str()) }); // Refine and publish the document pass::run_passes(srv, doc, ~[ // Generate type and signature strings tystr_pass::mk_pass(), // Record the full paths to various nodes path_pass::mk_pass(), // Extract the docs attributes and attach them to doc nodes attr_pass::mk_pass(), // Perform various text escaping escape_pass::mk_pass(), // Remove things marked doc(hidden) prune_hidden_pass::mk_pass(), // Remove things that are private prune_private_pass::mk_pass(), // Extract brief documentation from the full descriptions desc_to_brief_pass::mk_pass(), // Massage the text to remove extra indentation unindent_pass::mk_pass(), // Split text into multiple sections according to headers sectionalize_pass::mk_pass(), // Trim extra spaces from text trim_pass::mk_pass(), // Sort items by name sort_item_name_pass::mk_pass(), // Sort items again by kind sort_item_type_pass::mk_pass(), // Create indexes appropriate for markdown markdown_index_pass::mk_pass(copy config), // Break the document into pages if required by the // output format page_pass::mk_pass(config.output_style), // Render markdown_pass::mk_pass( markdown_writer::make_writer_factory(copy config) ) ]); } } pub fn time<T>(what: ~str, f: &fn() -> T) -> T { let start = extra::time::precise_time_s(); let rv = f(); let end = extra::time::precise_time_s(); info!("time: %3.3f s %s", end - start, what); rv }
run
identifier_name
rustdoc.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Rustdoc - The Rust documentation generator #[link(name = "rustdoc", vers = "0.8-pre", uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412", url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")]; #[comment = "The Rust documentation generator"]; #[license = "MIT/ASL2"]; #[crate_type = "lib"]; #[allow(non_implicitly_copyable_typarams)]; extern mod extra; extern mod rustc; extern mod syntax; use std::io; use std::os; use config::Config; use doc::Item; use doc::ItemUtils; pub mod pass; pub mod config; pub mod parse; pub mod extract; pub mod attr_parser; pub mod doc; pub mod markdown_index_pass; pub mod markdown_pass; pub mod markdown_writer; pub mod fold; pub mod path_pass; pub mod attr_pass; pub mod tystr_pass; pub mod prune_hidden_pass; pub mod desc_to_brief_pass; pub mod text_pass; pub mod unindent_pass; pub mod trim_pass; pub mod astsrv; pub mod demo; pub mod sort_pass; pub mod sort_item_name_pass; pub mod sort_item_type_pass; pub mod page_pass; pub mod sectionalize_pass; pub mod escape_pass; pub mod prune_private_pass; pub mod util; pub fn main() {
config::usage(); return; } let config = match config::parse_config(args) { Ok(config) => config, Err(err) => { io::println(fmt!("error: %s", err)); return; } }; run(config); } /// Runs rustdoc over the given file fn run(config: Config) { let source_file = copy config.input_crate; // Create an AST service from the source code do astsrv::from_file(source_file.to_str()) |srv| { // Just time how long it takes for the AST to become available do time(~"wait_ast") { do astsrv::exec(srv.clone()) |_ctxt| { } }; // Extract the initial doc tree from the AST. This contains // just names and node ids. let doc = time(~"extract", || { let default_name = copy source_file; extract::from_srv(srv.clone(), default_name.to_str()) }); // Refine and publish the document pass::run_passes(srv, doc, ~[ // Generate type and signature strings tystr_pass::mk_pass(), // Record the full paths to various nodes path_pass::mk_pass(), // Extract the docs attributes and attach them to doc nodes attr_pass::mk_pass(), // Perform various text escaping escape_pass::mk_pass(), // Remove things marked doc(hidden) prune_hidden_pass::mk_pass(), // Remove things that are private prune_private_pass::mk_pass(), // Extract brief documentation from the full descriptions desc_to_brief_pass::mk_pass(), // Massage the text to remove extra indentation unindent_pass::mk_pass(), // Split text into multiple sections according to headers sectionalize_pass::mk_pass(), // Trim extra spaces from text trim_pass::mk_pass(), // Sort items by name sort_item_name_pass::mk_pass(), // Sort items again by kind sort_item_type_pass::mk_pass(), // Create indexes appropriate for markdown markdown_index_pass::mk_pass(copy config), // Break the document into pages if required by the // output format page_pass::mk_pass(config.output_style), // Render markdown_pass::mk_pass( markdown_writer::make_writer_factory(copy config) ) ]); } } pub fn time<T>(what: ~str, f: &fn() -> T) -> T { let start = extra::time::precise_time_s(); let rv = f(); let end = extra::time::precise_time_s(); info!("time: %3.3f s %s", end - start, what); rv }
let args = os::args(); if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) {
random_line_split
rgb24.rs
#[derive(Clone, Copy, Debug)] pub struct Rgb24 { pub red: u8, pub green: u8, pub blue: u8, } impl Rgb24 { pub fn new(red: u8, green: u8, blue: u8) -> Self { Rgb24 { red: red, green: green, blue: blue, } } pub fn
(self) -> u8 { self.red } pub fn green(self) -> u8 { self.green } pub fn blue(self) -> u8 { self.blue } } pub mod colours { use super::*; pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 }; pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0 }; pub const BLUE: Rgb24 = Rgb24 { red: 0, green: 0, blue: 255 }; }
red
identifier_name
rgb24.rs
#[derive(Clone, Copy, Debug)] pub struct Rgb24 { pub red: u8, pub green: u8, pub blue: u8, } impl Rgb24 { pub fn new(red: u8, green: u8, blue: u8) -> Self { Rgb24 { red: red, green: green, blue: blue, } } pub fn red(self) -> u8 { self.red } pub fn green(self) -> u8
pub fn blue(self) -> u8 { self.blue } } pub mod colours { use super::*; pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 }; pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0 }; pub const BLUE: Rgb24 = Rgb24 { red: 0, green: 0, blue: 255 }; }
{ self.green }
identifier_body
userscripts.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlheadelement::HTMLHeadElement; use crate::dom::node::document_from_node; use js::jsval::UndefinedValue; use servo_config::opts; use std::fs::{read_dir, File}; use std::io::Read; use std::path::PathBuf; pub fn load_script(head: &HTMLHeadElement)
for file in files { let mut f = File::open(&file).unwrap(); let mut contents = vec![]; f.read_to_end(&mut contents).unwrap(); let script_text = String::from_utf8_lossy(&contents); win.upcast::<GlobalScope>() .evaluate_script_on_global_with_result( &script_text, &file.to_string_lossy(), rval.handle_mut(), 1, ); } })); }
{ let path_str = match opts::get().userscripts.clone() { Some(p) => p, None => return, }; let doc = document_from_node(head); let win = Trusted::new(doc.window()); doc.add_delayed_task(task!(UserScriptExecute: move || { let win = win.root(); let cx = win.get_cx(); rooted!(in(cx) let mut rval = UndefinedValue()); let path = PathBuf::from(&path_str); let mut files = read_dir(&path) .expect("Bad path passed to --userscripts") .filter_map(|e| e.ok()) .map(|e| e.path()) .collect::<Vec<_>>(); files.sort();
identifier_body
userscripts.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlheadelement::HTMLHeadElement; use crate::dom::node::document_from_node; use js::jsval::UndefinedValue; use servo_config::opts; use std::fs::{read_dir, File}; use std::io::Read; use std::path::PathBuf; pub fn load_script(head: &HTMLHeadElement) { let path_str = match opts::get().userscripts.clone() { Some(p) => p, None => return, }; let doc = document_from_node(head); let win = Trusted::new(doc.window()); doc.add_delayed_task(task!(UserScriptExecute: move || { let win = win.root(); let cx = win.get_cx(); rooted!(in(cx) let mut rval = UndefinedValue()); let path = PathBuf::from(&path_str); let mut files = read_dir(&path) .expect("Bad path passed to --userscripts") .filter_map(|e| e.ok()) .map(|e| e.path()) .collect::<Vec<_>>(); files.sort(); for file in files { let mut f = File::open(&file).unwrap(); let mut contents = vec![]; f.read_to_end(&mut contents).unwrap(); let script_text = String::from_utf8_lossy(&contents); win.upcast::<GlobalScope>()
&file.to_string_lossy(), rval.handle_mut(), 1, ); } })); }
.evaluate_script_on_global_with_result( &script_text,
random_line_split
userscripts.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlheadelement::HTMLHeadElement; use crate::dom::node::document_from_node; use js::jsval::UndefinedValue; use servo_config::opts; use std::fs::{read_dir, File}; use std::io::Read; use std::path::PathBuf; pub fn
(head: &HTMLHeadElement) { let path_str = match opts::get().userscripts.clone() { Some(p) => p, None => return, }; let doc = document_from_node(head); let win = Trusted::new(doc.window()); doc.add_delayed_task(task!(UserScriptExecute: move || { let win = win.root(); let cx = win.get_cx(); rooted!(in(cx) let mut rval = UndefinedValue()); let path = PathBuf::from(&path_str); let mut files = read_dir(&path) .expect("Bad path passed to --userscripts") .filter_map(|e| e.ok()) .map(|e| e.path()) .collect::<Vec<_>>(); files.sort(); for file in files { let mut f = File::open(&file).unwrap(); let mut contents = vec![]; f.read_to_end(&mut contents).unwrap(); let script_text = String::from_utf8_lossy(&contents); win.upcast::<GlobalScope>() .evaluate_script_on_global_with_result( &script_text, &file.to_string_lossy(), rval.handle_mut(), 1, ); } })); }
load_script
identifier_name
walker.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::fs::{self, DirEntry, Metadata}; use std::io; use std::path::{Path, PathBuf}; use anyhow::Result; use thiserror::Error; use pathmatcher::{DirectoryMatch, Matcher}; use types::path::ParseError; use types::{RepoPath, RepoPathBuf}; #[derive(Error, Debug)] pub enum WalkError { #[error("invalid file name encoding '{0}'")] FsUtf8Error(String), #[error("IO error at '{0}': {1}")] IOError(RepoPathBuf, #[source] io::Error), #[error("path error at '{0}': {1}")] RepoPathError(String, #[source] ParseError), #[error("invalid file type at '{0}'")] InvalidFileType(RepoPathBuf), #[error("invalid mtime for '{0}': {1}")] InvalidMTime(RepoPathBuf, #[source] anyhow::Error), } impl WalkError { pub fn filename(&self) -> String { match self { WalkError::FsUtf8Error(path) => path.to_string(), WalkError::IOError(path, _) => path.to_string(), WalkError::RepoPathError(path, _) => path.to_string(), WalkError::InvalidFileType(path) => path.to_string(), WalkError::InvalidMTime(path, _) => path.to_string(), } } pub fn message(&self) -> String { match self { WalkError::FsUtf8Error(_) => "invalid file name encoding".to_string(), WalkError::IOError(_, error) => error.to_string(), WalkError::RepoPathError(_, error) => error.to_string(), WalkError::InvalidFileType(_) => "invalid file type".to_string(), WalkError::InvalidMTime(_, error) => format!("invalid mtime - {}", error.to_string()), } } } pub enum WalkEntry { File(RepoPathBuf, Metadata), Directory(RepoPathBuf), } impl AsRef<RepoPath> for WalkEntry { fn as_ref(&self) -> &RepoPath { match self { WalkEntry::File(f, _) => f, WalkEntry::Directory(d) => d, } } } /// Walker traverses the working copy, starting at the root of the repo,
dir_matches: Vec<RepoPathBuf>, results: Vec<Result<WalkEntry>>, matcher: M, include_directories: bool, } impl<M> Walker<M> where M: Matcher, { pub fn new(root: PathBuf, matcher: M, include_directories: bool) -> Result<Self> { let mut dir_matches = vec![]; if matcher.matches_directory(&RepoPathBuf::new())?!= DirectoryMatch::Nothing { dir_matches.push(RepoPathBuf::new()); } let walker = Walker { root, dir_matches, results: Vec::new(), matcher, include_directories, }; Ok(walker) } fn match_entry(&mut self, next_dir: &RepoPathBuf, entry: DirEntry) -> Result<()> { // It'd be nice to move all this conversion noise to a function, but having it here saves // us from allocating filename repeatedly. let filename = entry.file_name(); let filename = filename.to_str().ok_or(WalkError::FsUtf8Error( filename.to_string_lossy().into_owned(), ))?; let filename = RepoPath::from_str(filename) .map_err(|e| WalkError::RepoPathError(filename.to_owned(), e))?; let filetype = entry .file_type() .map_err(|e| WalkError::IOError(filename.to_owned(), e))?; let mut candidate_path = next_dir.clone(); candidate_path.push(filename); if filetype.is_file() || filetype.is_symlink() { if self.matcher.matches_file(candidate_path.as_repo_path())? { self.results .push(Ok(WalkEntry::File(candidate_path, entry.metadata()?))); } } else if filetype.is_dir() { if filename.as_str()!= ".hg" && self .matcher .matches_directory(candidate_path.as_repo_path())? != DirectoryMatch::Nothing { self.dir_matches.push(candidate_path); } } else if self.matcher.matches_file(candidate_path.as_repo_path())? { return Err(WalkError::InvalidFileType(filename.to_owned()).into()); } Ok(()) } /// Lazy traversal to find matching files fn walk(&mut self) -> Result<()> { while self.results.is_empty() &&!self.dir_matches.is_empty() { let next_dir = self.dir_matches.pop().unwrap(); if self.include_directories { self.results .push(Ok(WalkEntry::Directory(next_dir.clone()))); } let abs_next_dir = self.root.join(next_dir.as_str()); // Don't process the directory if it contains a.hg directory, unless it's the root. if next_dir.is_empty() ||!Path::exists(&abs_next_dir.join(".hg")) { for entry in fs::read_dir(abs_next_dir) .map_err(|e| WalkError::IOError(next_dir.clone(), e))? { let entry = entry.map_err(|e| WalkError::IOError(next_dir.clone(), e))?; if let Err(e) = self.match_entry(&next_dir, entry) { self.results.push(Err(e)); } } } } Ok(()) } } impl<M> Iterator for Walker<M> where M: Matcher, { type Item = Result<WalkEntry>; fn next(&mut self) -> Option<Self::Item> { match self.walk() { Err(e) => Some(Err(e)), Ok(()) => self.results.pop(), } } } #[cfg(test)] mod tests { use super::*; use std::fs::{create_dir_all, OpenOptions}; use std::path::PathBuf; use tempfile::tempdir; use pathmatcher::{AlwaysMatcher, NeverMatcher}; fn create_directory( directories: &std::vec::Vec<&str>, files: &std::vec::Vec<&str>, ) -> Result<tempfile::TempDir> { let root = tempdir()?; for dir in directories { create_dir_all(root.path().join(dir))?; } for file in files { let path = root.path().join(file); OpenOptions::new() .create(true) .write(true) .open(path.as_path())?; } Ok(root) } #[test] fn test_walker() -> Result<()> { let directories = vec!["dirA", "dirB/dirC/dirD"]; let files = vec!["dirA/a.txt", "dirA/b.txt", "dirB/dirC/dirD/c.txt"]; let root_dir = create_directory(&directories, &files)?; let root_path = PathBuf::from(root_dir.path()); let walker = Walker::new(root_path, AlwaysMatcher::new(), false)?; let walked_files: Result<Vec<_>> = walker.collect(); let walked_files = walked_files?; assert_eq!(walked_files.len(), 3); for file in walked_files { assert!(files.contains(&file.as_ref().to_string().as_str())); } Ok(()) } #[test] fn test_match_nothing() -> Result<()> { let directories = vec!["dirA"]; let files = vec!["dirA/a.txt", "b.txt"]; let root_dir = create_directory(&directories, &files)?; let root_path = PathBuf::from(root_dir.path()); let walker = Walker::new(root_path, NeverMatcher::new(), false)?; let walked_files: Vec<_> = walker.collect(); assert!(walked_files.is_empty()); Ok(()) } }
/// finding files matched by matcher pub struct Walker<M> { root: PathBuf,
random_line_split
walker.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::fs::{self, DirEntry, Metadata}; use std::io; use std::path::{Path, PathBuf}; use anyhow::Result; use thiserror::Error; use pathmatcher::{DirectoryMatch, Matcher}; use types::path::ParseError; use types::{RepoPath, RepoPathBuf}; #[derive(Error, Debug)] pub enum WalkError { #[error("invalid file name encoding '{0}'")] FsUtf8Error(String), #[error("IO error at '{0}': {1}")] IOError(RepoPathBuf, #[source] io::Error), #[error("path error at '{0}': {1}")] RepoPathError(String, #[source] ParseError), #[error("invalid file type at '{0}'")] InvalidFileType(RepoPathBuf), #[error("invalid mtime for '{0}': {1}")] InvalidMTime(RepoPathBuf, #[source] anyhow::Error), } impl WalkError { pub fn filename(&self) -> String { match self { WalkError::FsUtf8Error(path) => path.to_string(), WalkError::IOError(path, _) => path.to_string(), WalkError::RepoPathError(path, _) => path.to_string(), WalkError::InvalidFileType(path) => path.to_string(), WalkError::InvalidMTime(path, _) => path.to_string(), } } pub fn message(&self) -> String { match self { WalkError::FsUtf8Error(_) => "invalid file name encoding".to_string(), WalkError::IOError(_, error) => error.to_string(), WalkError::RepoPathError(_, error) => error.to_string(), WalkError::InvalidFileType(_) => "invalid file type".to_string(), WalkError::InvalidMTime(_, error) => format!("invalid mtime - {}", error.to_string()), } } } pub enum WalkEntry { File(RepoPathBuf, Metadata), Directory(RepoPathBuf), } impl AsRef<RepoPath> for WalkEntry { fn as_ref(&self) -> &RepoPath { match self { WalkEntry::File(f, _) => f, WalkEntry::Directory(d) => d, } } } /// Walker traverses the working copy, starting at the root of the repo, /// finding files matched by matcher pub struct Walker<M> { root: PathBuf, dir_matches: Vec<RepoPathBuf>, results: Vec<Result<WalkEntry>>, matcher: M, include_directories: bool, } impl<M> Walker<M> where M: Matcher, { pub fn new(root: PathBuf, matcher: M, include_directories: bool) -> Result<Self> { let mut dir_matches = vec![]; if matcher.matches_directory(&RepoPathBuf::new())?!= DirectoryMatch::Nothing { dir_matches.push(RepoPathBuf::new()); } let walker = Walker { root, dir_matches, results: Vec::new(), matcher, include_directories, }; Ok(walker) } fn match_entry(&mut self, next_dir: &RepoPathBuf, entry: DirEntry) -> Result<()> { // It'd be nice to move all this conversion noise to a function, but having it here saves // us from allocating filename repeatedly. let filename = entry.file_name(); let filename = filename.to_str().ok_or(WalkError::FsUtf8Error( filename.to_string_lossy().into_owned(), ))?; let filename = RepoPath::from_str(filename) .map_err(|e| WalkError::RepoPathError(filename.to_owned(), e))?; let filetype = entry .file_type() .map_err(|e| WalkError::IOError(filename.to_owned(), e))?; let mut candidate_path = next_dir.clone(); candidate_path.push(filename); if filetype.is_file() || filetype.is_symlink() { if self.matcher.matches_file(candidate_path.as_repo_path())? { self.results .push(Ok(WalkEntry::File(candidate_path, entry.metadata()?))); } } else if filetype.is_dir() { if filename.as_str()!= ".hg" && self .matcher .matches_directory(candidate_path.as_repo_path())? != DirectoryMatch::Nothing { self.dir_matches.push(candidate_path); } } else if self.matcher.matches_file(candidate_path.as_repo_path())? { return Err(WalkError::InvalidFileType(filename.to_owned()).into()); } Ok(()) } /// Lazy traversal to find matching files fn walk(&mut self) -> Result<()> { while self.results.is_empty() &&!self.dir_matches.is_empty() { let next_dir = self.dir_matches.pop().unwrap(); if self.include_directories { self.results .push(Ok(WalkEntry::Directory(next_dir.clone()))); } let abs_next_dir = self.root.join(next_dir.as_str()); // Don't process the directory if it contains a.hg directory, unless it's the root. if next_dir.is_empty() ||!Path::exists(&abs_next_dir.join(".hg")) { for entry in fs::read_dir(abs_next_dir) .map_err(|e| WalkError::IOError(next_dir.clone(), e))? { let entry = entry.map_err(|e| WalkError::IOError(next_dir.clone(), e))?; if let Err(e) = self.match_entry(&next_dir, entry) { self.results.push(Err(e)); } } } } Ok(()) } } impl<M> Iterator for Walker<M> where M: Matcher, { type Item = Result<WalkEntry>; fn
(&mut self) -> Option<Self::Item> { match self.walk() { Err(e) => Some(Err(e)), Ok(()) => self.results.pop(), } } } #[cfg(test)] mod tests { use super::*; use std::fs::{create_dir_all, OpenOptions}; use std::path::PathBuf; use tempfile::tempdir; use pathmatcher::{AlwaysMatcher, NeverMatcher}; fn create_directory( directories: &std::vec::Vec<&str>, files: &std::vec::Vec<&str>, ) -> Result<tempfile::TempDir> { let root = tempdir()?; for dir in directories { create_dir_all(root.path().join(dir))?; } for file in files { let path = root.path().join(file); OpenOptions::new() .create(true) .write(true) .open(path.as_path())?; } Ok(root) } #[test] fn test_walker() -> Result<()> { let directories = vec!["dirA", "dirB/dirC/dirD"]; let files = vec!["dirA/a.txt", "dirA/b.txt", "dirB/dirC/dirD/c.txt"]; let root_dir = create_directory(&directories, &files)?; let root_path = PathBuf::from(root_dir.path()); let walker = Walker::new(root_path, AlwaysMatcher::new(), false)?; let walked_files: Result<Vec<_>> = walker.collect(); let walked_files = walked_files?; assert_eq!(walked_files.len(), 3); for file in walked_files { assert!(files.contains(&file.as_ref().to_string().as_str())); } Ok(()) } #[test] fn test_match_nothing() -> Result<()> { let directories = vec!["dirA"]; let files = vec!["dirA/a.txt", "b.txt"]; let root_dir = create_directory(&directories, &files)?; let root_path = PathBuf::from(root_dir.path()); let walker = Walker::new(root_path, NeverMatcher::new(), false)?; let walked_files: Vec<_> = walker.collect(); assert!(walked_files.is_empty()); Ok(()) } }
next
identifier_name
walker.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::fs::{self, DirEntry, Metadata}; use std::io; use std::path::{Path, PathBuf}; use anyhow::Result; use thiserror::Error; use pathmatcher::{DirectoryMatch, Matcher}; use types::path::ParseError; use types::{RepoPath, RepoPathBuf}; #[derive(Error, Debug)] pub enum WalkError { #[error("invalid file name encoding '{0}'")] FsUtf8Error(String), #[error("IO error at '{0}': {1}")] IOError(RepoPathBuf, #[source] io::Error), #[error("path error at '{0}': {1}")] RepoPathError(String, #[source] ParseError), #[error("invalid file type at '{0}'")] InvalidFileType(RepoPathBuf), #[error("invalid mtime for '{0}': {1}")] InvalidMTime(RepoPathBuf, #[source] anyhow::Error), } impl WalkError { pub fn filename(&self) -> String { match self { WalkError::FsUtf8Error(path) => path.to_string(), WalkError::IOError(path, _) => path.to_string(), WalkError::RepoPathError(path, _) => path.to_string(), WalkError::InvalidFileType(path) => path.to_string(), WalkError::InvalidMTime(path, _) => path.to_string(), } } pub fn message(&self) -> String { match self { WalkError::FsUtf8Error(_) => "invalid file name encoding".to_string(), WalkError::IOError(_, error) => error.to_string(), WalkError::RepoPathError(_, error) => error.to_string(), WalkError::InvalidFileType(_) => "invalid file type".to_string(), WalkError::InvalidMTime(_, error) => format!("invalid mtime - {}", error.to_string()), } } } pub enum WalkEntry { File(RepoPathBuf, Metadata), Directory(RepoPathBuf), } impl AsRef<RepoPath> for WalkEntry { fn as_ref(&self) -> &RepoPath { match self { WalkEntry::File(f, _) => f, WalkEntry::Directory(d) => d, } } } /// Walker traverses the working copy, starting at the root of the repo, /// finding files matched by matcher pub struct Walker<M> { root: PathBuf, dir_matches: Vec<RepoPathBuf>, results: Vec<Result<WalkEntry>>, matcher: M, include_directories: bool, } impl<M> Walker<M> where M: Matcher, { pub fn new(root: PathBuf, matcher: M, include_directories: bool) -> Result<Self>
fn match_entry(&mut self, next_dir: &RepoPathBuf, entry: DirEntry) -> Result<()> { // It'd be nice to move all this conversion noise to a function, but having it here saves // us from allocating filename repeatedly. let filename = entry.file_name(); let filename = filename.to_str().ok_or(WalkError::FsUtf8Error( filename.to_string_lossy().into_owned(), ))?; let filename = RepoPath::from_str(filename) .map_err(|e| WalkError::RepoPathError(filename.to_owned(), e))?; let filetype = entry .file_type() .map_err(|e| WalkError::IOError(filename.to_owned(), e))?; let mut candidate_path = next_dir.clone(); candidate_path.push(filename); if filetype.is_file() || filetype.is_symlink() { if self.matcher.matches_file(candidate_path.as_repo_path())? { self.results .push(Ok(WalkEntry::File(candidate_path, entry.metadata()?))); } } else if filetype.is_dir() { if filename.as_str()!= ".hg" && self .matcher .matches_directory(candidate_path.as_repo_path())? != DirectoryMatch::Nothing { self.dir_matches.push(candidate_path); } } else if self.matcher.matches_file(candidate_path.as_repo_path())? { return Err(WalkError::InvalidFileType(filename.to_owned()).into()); } Ok(()) } /// Lazy traversal to find matching files fn walk(&mut self) -> Result<()> { while self.results.is_empty() &&!self.dir_matches.is_empty() { let next_dir = self.dir_matches.pop().unwrap(); if self.include_directories { self.results .push(Ok(WalkEntry::Directory(next_dir.clone()))); } let abs_next_dir = self.root.join(next_dir.as_str()); // Don't process the directory if it contains a.hg directory, unless it's the root. if next_dir.is_empty() ||!Path::exists(&abs_next_dir.join(".hg")) { for entry in fs::read_dir(abs_next_dir) .map_err(|e| WalkError::IOError(next_dir.clone(), e))? { let entry = entry.map_err(|e| WalkError::IOError(next_dir.clone(), e))?; if let Err(e) = self.match_entry(&next_dir, entry) { self.results.push(Err(e)); } } } } Ok(()) } } impl<M> Iterator for Walker<M> where M: Matcher, { type Item = Result<WalkEntry>; fn next(&mut self) -> Option<Self::Item> { match self.walk() { Err(e) => Some(Err(e)), Ok(()) => self.results.pop(), } } } #[cfg(test)] mod tests { use super::*; use std::fs::{create_dir_all, OpenOptions}; use std::path::PathBuf; use tempfile::tempdir; use pathmatcher::{AlwaysMatcher, NeverMatcher}; fn create_directory( directories: &std::vec::Vec<&str>, files: &std::vec::Vec<&str>, ) -> Result<tempfile::TempDir> { let root = tempdir()?; for dir in directories { create_dir_all(root.path().join(dir))?; } for file in files { let path = root.path().join(file); OpenOptions::new() .create(true) .write(true) .open(path.as_path())?; } Ok(root) } #[test] fn test_walker() -> Result<()> { let directories = vec!["dirA", "dirB/dirC/dirD"]; let files = vec!["dirA/a.txt", "dirA/b.txt", "dirB/dirC/dirD/c.txt"]; let root_dir = create_directory(&directories, &files)?; let root_path = PathBuf::from(root_dir.path()); let walker = Walker::new(root_path, AlwaysMatcher::new(), false)?; let walked_files: Result<Vec<_>> = walker.collect(); let walked_files = walked_files?; assert_eq!(walked_files.len(), 3); for file in walked_files { assert!(files.contains(&file.as_ref().to_string().as_str())); } Ok(()) } #[test] fn test_match_nothing() -> Result<()> { let directories = vec!["dirA"]; let files = vec!["dirA/a.txt", "b.txt"]; let root_dir = create_directory(&directories, &files)?; let root_path = PathBuf::from(root_dir.path()); let walker = Walker::new(root_path, NeverMatcher::new(), false)?; let walked_files: Vec<_> = walker.collect(); assert!(walked_files.is_empty()); Ok(()) } }
{ let mut dir_matches = vec![]; if matcher.matches_directory(&RepoPathBuf::new())? != DirectoryMatch::Nothing { dir_matches.push(RepoPathBuf::new()); } let walker = Walker { root, dir_matches, results: Vec::new(), matcher, include_directories, }; Ok(walker) }
identifier_body
issue-8498.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn main()
assert!(**z == 7); } None => () } }
{ match &[(box 5,box 7)] { ps => { let (ref y, _) = ps[0]; assert!(**y == 5); } } match Some(&[(box 5,)]) { Some(ps) => { let (ref y,) = ps[0]; assert!(**y == 5); } None => () } match Some(&[(box 5,box 7)]) { Some(ps) => { let (ref y, ref z) = ps[0]; assert!(**y == 5);
identifier_body
issue-8498.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn main() { match &[(box 5,box 7)] { ps => { let (ref y, _) = ps[0]; assert!(**y == 5); } } match Some(&[(box 5,)]) { Some(ps) => { let (ref y,) = ps[0]; assert!(**y == 5); } None => () } match Some(&[(box 5,box 7)]) { Some(ps) => { let (ref y, ref z) = ps[0]; assert!(**y == 5);
}
assert!(**z == 7); } None => () }
random_line_split
issue-8498.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn
() { match &[(box 5,box 7)] { ps => { let (ref y, _) = ps[0]; assert!(**y == 5); } } match Some(&[(box 5,)]) { Some(ps) => { let (ref y,) = ps[0]; assert!(**y == 5); } None => () } match Some(&[(box 5,box 7)]) { Some(ps) => { let (ref y, ref z) = ps[0]; assert!(**y == 5); assert!(**z == 7); } None => () } }
main
identifier_name
json.rs
#![cfg(feature = "alloc")] #[macro_use] extern crate nom; extern crate jemallocator; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{Err, IResult, Offset, error::{VerboseError, VerboseErrorKind}}; use nom::{ character::complete::alphanumeric1 as alphanumeric, bytes::complete::{take_while, tag}, multi::separated_listc, branch::alt, sequence::{preceded, terminated}, error::context }; use nom::character::complete::char; use nom::number::complete::recognize_float; use nom::error::{ErrorKind,ParseError}; use std::str; use std::iter::repeat; use std::collections::HashMap; #[derive(Debug, PartialEq)] pub enum JsonValue { Str(String), Boolean(bool), Num(f64), Array(Vec<JsonValue>), Object(HashMap<String, JsonValue>), } fn sp<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { let chars = " \t\r\n"; take_while(move |c| chars.contains(c))(i) } fn float<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, f64, E> { flat_map!(i, recognize_float, parse_to!(f64)) } fn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { escaped!(i, call!(alphanumeric), '\\', one_of!("\"n\\")) } fn string<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { //delimitedc(i, char('\"'), parse_str, char('\"')) let (i, _) = char('\"')(i)?; //context("string", |i| terminatedc(i, parse_str, char('\"')))(i) context("string", terminated(parse_str, char('\"')))(i) }
|i| tag("false")(i).map(|(i,_)| (i, false)), |i| tag("true")(i).map(|(i,_)| (i, true)) ))(input) /* match tag::<&'static str, &'a str, E>("false")(i) { Ok((i, _)) => Ok((i, false)), Err(_) => tag("true")(i).map(|(i,_)| (i, true)) } */ } fn array<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, Vec<JsonValue>, E> { let (i, _) = char('[')(i)?; /*context( "array", |i| terminatedc(i, |i| separated_listc(i, |i| precededc(i, sp, char(',')), value), |i| precededc(i, sp, char(']'))) )(i)*/ context( "array", terminated( |i| separated_listc(i, preceded(sp, char(',')), value), preceded(sp, char(']'))) )(i) } fn key_value<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, (&'a str, JsonValue), E> { separated_pair!(i, preceded!(sp, string), preceded!(sp, char!(':')), value) } fn hash<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, HashMap<String, JsonValue>, E> { let (i, _) = char('{')(i)?; context( "map", terminated( |i| map!(i, separated_list!(preceded!(sp, char!(',')), key_value), |tuple_vec| tuple_vec .into_iter() .map(|(k, v)| (String::from(k), v)) .collect() ), preceded(sp, char('}'))) )(i) /* map!(i, delimited!( char!('{'), separated_list!(preceded!(sp, char!(',')), key_value), preceded!(sp, char!('}')) ), |tuple_vec| tuple_vec .into_iter() .map(|(k, v)| (String::from(k), v)) .collect() ) */ } fn value<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> { preceded!(i, sp, alt!( hash => { |h| JsonValue::Object(h) } | array => { |v| JsonValue::Array(v) } | string => { |s| JsonValue::Str(String::from(s)) } | float => { |f| JsonValue::Num(f) } | boolean => { |b| JsonValue::Boolean(b) } )) } fn root<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> { delimited!(i, sp, alt( ( |input| hash(input).map(|(i,h)| (i, JsonValue::Object(h))), |input| array(input).map(|(i,v)| (i, JsonValue::Array(v))) ) ), /*alt!( hash => { |h| JsonValue::Object(h) } | array => { |v| JsonValue::Array(v) } ),*/ not!(complete!(sp))) } fn convert_error(input: &str, e: VerboseError<&str>) -> String { let lines: Vec<_> = input.lines().map(String::from).collect(); //println!("lines: {:#?}", lines); let mut result = String::new(); for (i, (substring, kind)) in e.errors.iter().enumerate() { let mut offset = input.offset(substring); let mut line = 0; let mut column = 0; for (j,l) in lines.iter().enumerate() { if offset <= l.len() { line = j; column = offset; break; } else { offset = offset - l.len(); } } match kind { VerboseErrorKind::Char(c) => { result += &format!("{}: at line {}:\n", i, line); result += &lines[line]; result += "\n"; if column > 0 { result += &repeat(' ').take(column-1).collect::<String>(); } result += "^\n"; result += &format!("expected '{}', found {}\n\n", c, substring.chars().next().unwrap()); }, VerboseErrorKind::Context(s) => { result += &format!("{}: at line {}, in {}:\n", i, line, s); result += &lines[line]; result += "\n"; if column > 0 { result += &repeat(' ').take(column -1).collect::<String>(); } result += "^\n\n"; } _ => {} } } result } fn main() { let data = " { \"a\"\t: 42, \"b\": [ \"x\", \"y\", 12 ], \"c\": { 1\"hello\" : \"world\" } } "; println!("will try to parse:\n\n**********\n{}\n**********\n", data); println!("basic errors - `root::<(&str, ErrorKind)>(data)`:\n{:#?}\n", root::<(&str, ErrorKind)>(data)); println!("parsed verbose: {:#?}", root::<VerboseError<&str>>(data)); match root::<VerboseError<&str>>(data) { Err(Err::Error(e)) | Err(Err::Failure(e)) => { println!("verbose errors - `root::<VerboseError>(data)`:\n{}", convert_error(data, e)); }, _ => panic!(), } }
fn boolean<'a, E: ParseError<&'a str>>(input: &'a str) ->IResult<&'a str, bool, E> { alt( (
random_line_split
json.rs
#![cfg(feature = "alloc")] #[macro_use] extern crate nom; extern crate jemallocator; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{Err, IResult, Offset, error::{VerboseError, VerboseErrorKind}}; use nom::{ character::complete::alphanumeric1 as alphanumeric, bytes::complete::{take_while, tag}, multi::separated_listc, branch::alt, sequence::{preceded, terminated}, error::context }; use nom::character::complete::char; use nom::number::complete::recognize_float; use nom::error::{ErrorKind,ParseError}; use std::str; use std::iter::repeat; use std::collections::HashMap; #[derive(Debug, PartialEq)] pub enum JsonValue { Str(String), Boolean(bool), Num(f64), Array(Vec<JsonValue>), Object(HashMap<String, JsonValue>), } fn sp<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { let chars = " \t\r\n"; take_while(move |c| chars.contains(c))(i) } fn float<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, f64, E> { flat_map!(i, recognize_float, parse_to!(f64)) } fn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E>
fn string<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { //delimitedc(i, char('\"'), parse_str, char('\"')) let (i, _) = char('\"')(i)?; //context("string", |i| terminatedc(i, parse_str, char('\"')))(i) context("string", terminated(parse_str, char('\"')))(i) } fn boolean<'a, E: ParseError<&'a str>>(input: &'a str) ->IResult<&'a str, bool, E> { alt( ( |i| tag("false")(i).map(|(i,_)| (i, false)), |i| tag("true")(i).map(|(i,_)| (i, true)) ))(input) /* match tag::<&'static str, &'a str, E>("false")(i) { Ok((i, _)) => Ok((i, false)), Err(_) => tag("true")(i).map(|(i,_)| (i, true)) } */ } fn array<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, Vec<JsonValue>, E> { let (i, _) = char('[')(i)?; /*context( "array", |i| terminatedc(i, |i| separated_listc(i, |i| precededc(i, sp, char(',')), value), |i| precededc(i, sp, char(']'))) )(i)*/ context( "array", terminated( |i| separated_listc(i, preceded(sp, char(',')), value), preceded(sp, char(']'))) )(i) } fn key_value<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, (&'a str, JsonValue), E> { separated_pair!(i, preceded!(sp, string), preceded!(sp, char!(':')), value) } fn hash<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, HashMap<String, JsonValue>, E> { let (i, _) = char('{')(i)?; context( "map", terminated( |i| map!(i, separated_list!(preceded!(sp, char!(',')), key_value), |tuple_vec| tuple_vec .into_iter() .map(|(k, v)| (String::from(k), v)) .collect() ), preceded(sp, char('}'))) )(i) /* map!(i, delimited!( char!('{'), separated_list!(preceded!(sp, char!(',')), key_value), preceded!(sp, char!('}')) ), |tuple_vec| tuple_vec .into_iter() .map(|(k, v)| (String::from(k), v)) .collect() ) */ } fn value<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> { preceded!(i, sp, alt!( hash => { |h| JsonValue::Object(h) } | array => { |v| JsonValue::Array(v) } | string => { |s| JsonValue::Str(String::from(s)) } | float => { |f| JsonValue::Num(f) } | boolean => { |b| JsonValue::Boolean(b) } )) } fn root<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> { delimited!(i, sp, alt( ( |input| hash(input).map(|(i,h)| (i, JsonValue::Object(h))), |input| array(input).map(|(i,v)| (i, JsonValue::Array(v))) ) ), /*alt!( hash => { |h| JsonValue::Object(h) } | array => { |v| JsonValue::Array(v) } ),*/ not!(complete!(sp))) } fn convert_error(input: &str, e: VerboseError<&str>) -> String { let lines: Vec<_> = input.lines().map(String::from).collect(); //println!("lines: {:#?}", lines); let mut result = String::new(); for (i, (substring, kind)) in e.errors.iter().enumerate() { let mut offset = input.offset(substring); let mut line = 0; let mut column = 0; for (j,l) in lines.iter().enumerate() { if offset <= l.len() { line = j; column = offset; break; } else { offset = offset - l.len(); } } match kind { VerboseErrorKind::Char(c) => { result += &format!("{}: at line {}:\n", i, line); result += &lines[line]; result += "\n"; if column > 0 { result += &repeat(' ').take(column-1).collect::<String>(); } result += "^\n"; result += &format!("expected '{}', found {}\n\n", c, substring.chars().next().unwrap()); }, VerboseErrorKind::Context(s) => { result += &format!("{}: at line {}, in {}:\n", i, line, s); result += &lines[line]; result += "\n"; if column > 0 { result += &repeat(' ').take(column -1).collect::<String>(); } result += "^\n\n"; } _ => {} } } result } fn main() { let data = " { \"a\"\t: 42, \"b\": [ \"x\", \"y\", 12 ], \"c\": { 1\"hello\" : \"world\" } } "; println!("will try to parse:\n\n**********\n{}\n**********\n", data); println!("basic errors - `root::<(&str, ErrorKind)>(data)`:\n{:#?}\n", root::<(&str, ErrorKind)>(data)); println!("parsed verbose: {:#?}", root::<VerboseError<&str>>(data)); match root::<VerboseError<&str>>(data) { Err(Err::Error(e)) | Err(Err::Failure(e)) => { println!("verbose errors - `root::<VerboseError>(data)`:\n{}", convert_error(data, e)); }, _ => panic!(), } }
{ escaped!(i, call!(alphanumeric), '\\', one_of!("\"n\\")) }
identifier_body
json.rs
#![cfg(feature = "alloc")] #[macro_use] extern crate nom; extern crate jemallocator; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{Err, IResult, Offset, error::{VerboseError, VerboseErrorKind}}; use nom::{ character::complete::alphanumeric1 as alphanumeric, bytes::complete::{take_while, tag}, multi::separated_listc, branch::alt, sequence::{preceded, terminated}, error::context }; use nom::character::complete::char; use nom::number::complete::recognize_float; use nom::error::{ErrorKind,ParseError}; use std::str; use std::iter::repeat; use std::collections::HashMap; #[derive(Debug, PartialEq)] pub enum JsonValue { Str(String), Boolean(bool), Num(f64), Array(Vec<JsonValue>), Object(HashMap<String, JsonValue>), } fn sp<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { let chars = " \t\r\n"; take_while(move |c| chars.contains(c))(i) } fn
<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, f64, E> { flat_map!(i, recognize_float, parse_to!(f64)) } fn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { escaped!(i, call!(alphanumeric), '\\', one_of!("\"n\\")) } fn string<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> { //delimitedc(i, char('\"'), parse_str, char('\"')) let (i, _) = char('\"')(i)?; //context("string", |i| terminatedc(i, parse_str, char('\"')))(i) context("string", terminated(parse_str, char('\"')))(i) } fn boolean<'a, E: ParseError<&'a str>>(input: &'a str) ->IResult<&'a str, bool, E> { alt( ( |i| tag("false")(i).map(|(i,_)| (i, false)), |i| tag("true")(i).map(|(i,_)| (i, true)) ))(input) /* match tag::<&'static str, &'a str, E>("false")(i) { Ok((i, _)) => Ok((i, false)), Err(_) => tag("true")(i).map(|(i,_)| (i, true)) } */ } fn array<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, Vec<JsonValue>, E> { let (i, _) = char('[')(i)?; /*context( "array", |i| terminatedc(i, |i| separated_listc(i, |i| precededc(i, sp, char(',')), value), |i| precededc(i, sp, char(']'))) )(i)*/ context( "array", terminated( |i| separated_listc(i, preceded(sp, char(',')), value), preceded(sp, char(']'))) )(i) } fn key_value<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, (&'a str, JsonValue), E> { separated_pair!(i, preceded!(sp, string), preceded!(sp, char!(':')), value) } fn hash<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, HashMap<String, JsonValue>, E> { let (i, _) = char('{')(i)?; context( "map", terminated( |i| map!(i, separated_list!(preceded!(sp, char!(',')), key_value), |tuple_vec| tuple_vec .into_iter() .map(|(k, v)| (String::from(k), v)) .collect() ), preceded(sp, char('}'))) )(i) /* map!(i, delimited!( char!('{'), separated_list!(preceded!(sp, char!(',')), key_value), preceded!(sp, char!('}')) ), |tuple_vec| tuple_vec .into_iter() .map(|(k, v)| (String::from(k), v)) .collect() ) */ } fn value<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> { preceded!(i, sp, alt!( hash => { |h| JsonValue::Object(h) } | array => { |v| JsonValue::Array(v) } | string => { |s| JsonValue::Str(String::from(s)) } | float => { |f| JsonValue::Num(f) } | boolean => { |b| JsonValue::Boolean(b) } )) } fn root<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> { delimited!(i, sp, alt( ( |input| hash(input).map(|(i,h)| (i, JsonValue::Object(h))), |input| array(input).map(|(i,v)| (i, JsonValue::Array(v))) ) ), /*alt!( hash => { |h| JsonValue::Object(h) } | array => { |v| JsonValue::Array(v) } ),*/ not!(complete!(sp))) } fn convert_error(input: &str, e: VerboseError<&str>) -> String { let lines: Vec<_> = input.lines().map(String::from).collect(); //println!("lines: {:#?}", lines); let mut result = String::new(); for (i, (substring, kind)) in e.errors.iter().enumerate() { let mut offset = input.offset(substring); let mut line = 0; let mut column = 0; for (j,l) in lines.iter().enumerate() { if offset <= l.len() { line = j; column = offset; break; } else { offset = offset - l.len(); } } match kind { VerboseErrorKind::Char(c) => { result += &format!("{}: at line {}:\n", i, line); result += &lines[line]; result += "\n"; if column > 0 { result += &repeat(' ').take(column-1).collect::<String>(); } result += "^\n"; result += &format!("expected '{}', found {}\n\n", c, substring.chars().next().unwrap()); }, VerboseErrorKind::Context(s) => { result += &format!("{}: at line {}, in {}:\n", i, line, s); result += &lines[line]; result += "\n"; if column > 0 { result += &repeat(' ').take(column -1).collect::<String>(); } result += "^\n\n"; } _ => {} } } result } fn main() { let data = " { \"a\"\t: 42, \"b\": [ \"x\", \"y\", 12 ], \"c\": { 1\"hello\" : \"world\" } } "; println!("will try to parse:\n\n**********\n{}\n**********\n", data); println!("basic errors - `root::<(&str, ErrorKind)>(data)`:\n{:#?}\n", root::<(&str, ErrorKind)>(data)); println!("parsed verbose: {:#?}", root::<VerboseError<&str>>(data)); match root::<VerboseError<&str>>(data) { Err(Err::Error(e)) | Err(Err::Failure(e)) => { println!("verbose errors - `root::<VerboseError>(data)`:\n{}", convert_error(data, e)); }, _ => panic!(), } }
float
identifier_name
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0; for x in min_x..=max_x { for y in min_y..=max_y { let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n { count += 1; } } } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b()
{ let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
identifier_body
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0; for x in min_x..=max_x { for y in min_y..=max_y { let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n
} } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
{ count += 1; }
conditional_block
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0;
let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n { count += 1; } } } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
for x in min_x..=max_x { for y in min_y..=max_y {
random_line_split
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0; for x in min_x..=max_x { for y in min_y..=max_y { let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n { count += 1; } } } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn
() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
test_06b
identifier_name
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) } ClusterBootstrapped(cluster_id: u64) { display("cluster {} is already bootstrapped", cluster_id) } ClusterNotBootstrapped(cluster_id: u64) { display("cluster {} is not bootstrapped", cluster_id) } Incompatible { display("feature is not supported in other cluster components") } Grpc(err: grpcio::Error) { from() cause(err) display("{}", err) } Other(err: Box<dyn error::Error + Sync + Send>) { from() cause(err.as_ref()) display("unknown error {:?}", err) } RegionNotFound(key: Vec<u8>) { display("region is not found for key {}", &log_wrappers::Value::key(key)) } StoreTombstone(msg: String) { display("store is tombstone {:?}", msg) } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode
}
{ match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCOMPATIBLE, Error::Grpc(_) => error_code::pd::GRPC, Error::RegionNotFound(_) => error_code::pd::REGION_NOT_FOUND, Error::StoreTombstone(_) => error_code::pd::STORE_TOMBSTONE, Error::Other(_) => error_code::pd::UNKNOWN, } }
identifier_body
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) } ClusterBootstrapped(cluster_id: u64) { display("cluster {} is already bootstrapped", cluster_id) } ClusterNotBootstrapped(cluster_id: u64) { display("cluster {} is not bootstrapped", cluster_id) } Incompatible { display("feature is not supported in other cluster components") } Grpc(err: grpcio::Error) { from() cause(err) display("{}", err) } Other(err: Box<dyn error::Error + Sync + Send>) { from() cause(err.as_ref()) display("unknown error {:?}", err) } RegionNotFound(key: Vec<u8>) { display("region is not found for key {}", &log_wrappers::Value::key(key)) } StoreTombstone(msg: String) { display("store is tombstone {:?}", msg) } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn
(&self) -> ErrorCode { match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCOMPATIBLE, Error::Grpc(_) => error_code::pd::GRPC, Error::RegionNotFound(_) => error_code::pd::REGION_NOT_FOUND, Error::StoreTombstone(_) => error_code::pd::STORE_TOMBSTONE, Error::Other(_) => error_code::pd::UNKNOWN, } } }
error_code
identifier_name
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) } ClusterBootstrapped(cluster_id: u64) { display("cluster {} is already bootstrapped", cluster_id) } ClusterNotBootstrapped(cluster_id: u64) { display("cluster {} is not bootstrapped", cluster_id) } Incompatible { display("feature is not supported in other cluster components") } Grpc(err: grpcio::Error) { from() cause(err) display("{}", err) }
display("unknown error {:?}", err) } RegionNotFound(key: Vec<u8>) { display("region is not found for key {}", &log_wrappers::Value::key(key)) } StoreTombstone(msg: String) { display("store is tombstone {:?}", msg) } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode { match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCOMPATIBLE, Error::Grpc(_) => error_code::pd::GRPC, Error::RegionNotFound(_) => error_code::pd::REGION_NOT_FOUND, Error::StoreTombstone(_) => error_code::pd::STORE_TOMBSTONE, Error::Other(_) => error_code::pd::UNKNOWN, } } }
Other(err: Box<dyn error::Error + Sync + Send>) { from() cause(err.as_ref())
random_line_split
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap(); display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> { self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn
(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value { 0 } else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error> { // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame; Ok(()) } }
init_display
identifier_name
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap();
self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn init_display(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value { 0 } else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error> { // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame; Ok(()) } }
display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> {
random_line_split
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap(); display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> { self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn init_display(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value { 0 } else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error>
Ok(()) } }
{ // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame;
identifier_body
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap(); display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> { self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn init_display(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value
else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error> { // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame; Ok(()) } }
{ 0 }
conditional_block
scancode.rs
// Copyright 2014 The sdl2-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // SDL_scancode.h #[repr(C)] pub enum SDL_Scancode { SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, SDL_SCANCODE_NONUSHASH = 50, SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68,
SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, SDL_SCANCODE_APPLICATION = 101, SDL_SCANCODE_POWER = 102, SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, SDL_SCANCODE_LANG2 = 145, SDL_SCANCODE_LANG3 = 146, SDL_SCANCODE_LANG4 = 147, SDL_SCANCODE_LANG5 = 148, SDL_SCANCODE_LANG6 = 149, SDL_SCANCODE_LANG7 = 150, SDL_SCANCODE_LANG8 = 151, SDL_SCANCODE_LANG9 = 152, SDL_SCANCODE_ALTERASE = 153, SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, SDL_SCANCODE_LGUI = 227, SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, SDL_SCANCODE_RGUI = 231, SDL_SCANCODE_MODE = 257, SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, SDL_NUM_SCANCODES = 512, }
SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72,
random_line_split
scancode.rs
// Copyright 2014 The sdl2-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // SDL_scancode.h #[repr(C)] pub enum
{ SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, SDL_SCANCODE_NONUSHASH = 50, SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, SDL_SCANCODE_APPLICATION = 101, SDL_SCANCODE_POWER = 102, SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, SDL_SCANCODE_LANG2 = 145, SDL_SCANCODE_LANG3 = 146, SDL_SCANCODE_LANG4 = 147, SDL_SCANCODE_LANG5 = 148, SDL_SCANCODE_LANG6 = 149, SDL_SCANCODE_LANG7 = 150, SDL_SCANCODE_LANG8 = 151, SDL_SCANCODE_LANG9 = 152, SDL_SCANCODE_ALTERASE = 153, SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, SDL_SCANCODE_LGUI = 227, SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, SDL_SCANCODE_RGUI = 231, SDL_SCANCODE_MODE = 257, SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, SDL_NUM_SCANCODES = 512, }
SDL_Scancode
identifier_name
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the /// visual representation of text on screen in a way that does not correspond to their on /// memory representation. /// /// ### Explanation /// /// The unicode characters `\u{202A}`, `\u{202B}`, `\u{202D}`, `\u{202E}`, `\u{2066}`, /// `\u{2067}`, `\u{2068}`, `\u{202C}` and `\u{2069}` make the flow of text on screen change /// its direction on software that supports these codepoints. This makes the text "abc" display /// as "cba" on screen. By leveraging software that supports these, people can write specially /// crafted literals that make the surrounding code seem like it's performing one action, when /// in reality it is performing another. Because of this, we proactively lint against their /// presence to avoid surprises. /// /// ### Example /// /// ```rust,compile_fail /// #![deny(text_direction_codepoint_in_literal)] /// fn main() { /// println!("{:?}", '‮'); /// } /// ``` /// /// {{produces}} /// pub TEXT_DIRECTION_CODEPOINT_IN_LITERAL, Deny, "detect special Unicode codepoints that affect the visual representation of text on screen, \ changing the direction in which text flows", } declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]); impl HiddenUnicodeCodepoints { fn li
&self, cx: &EarlyContext<'_>, text: Symbol, span: Span, padding: u32, point_at_inner_spans: bool, label: &str, ) { // Obtain the `Span`s for each of the forbidden chars. let spans: Vec<_> = text .as_str() .char_indices() .filter_map(|(i, c)| { TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| { let lo = span.lo() + BytePos(i as u32 + padding); (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32))) }) }) .collect(); cx.struct_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, |lint| { let mut err = lint.build(&format!( "unicode codepoint changing visible direction of text present in {}", label )); let (an, s) = match spans.len() { 1 => ("an ", ""), _ => ("", "s"), }; err.span_label( span, &format!( "this {} contains {}invisible unicode text flow control codepoint{}", label, an, s, ), ); if point_at_inner_spans { for (c, span) in &spans { err.span_label(*span, format!("{:?}", c)); } } err.note( "these kind of unicode codepoints change the way text flows on applications that \ support them, but can cause confusion because they change the order of \ characters on the screen", ); if point_at_inner_spans &&!spans.is_empty() { err.multipart_suggestion_with_style( "if their presence wasn't intentional, you can remove them", spans.iter().map(|(_, span)| (*span, "".to_string())).collect(), Applicability::MachineApplicable, SuggestionStyle::HideCodeAlways, ); err.multipart_suggestion( "if you want to keep them but make them visible in your source code, you can \ escape them", spans .into_iter() .map(|(c, span)| { let c = format!("{:?}", c); (span, c[1..c.len() - 1].to_string()) }) .collect(), Applicability::MachineApplicable, ); } else { // FIXME: in other suggestions we've reversed the inner spans of doc comments. We // should do the same here to provide the same good suggestions as we do for // literals above. err.note("if their presence wasn't intentional, you can remove them"); err.note(&format!( "if you want to keep them but make them visible in your source code, you can \ escape them: {}", spans .into_iter() .map(|(c, _)| { format!("{:?}", c) }) .collect::<Vec<String>>() .join(", "), )); } err.emit(); }); } } impl EarlyLintPass for HiddenUnicodeCodepoints { fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { if let ast::AttrKind::DocComment(_, comment) = attr.kind { if contains_text_flow_control_chars(&comment.as_str()) { self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment"); } } } fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { // byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString` let (text, span, padding) = match &expr.kind { ast::ExprKind::Lit(ast::Lit { token, kind, span }) => { let text = token.symbol; if!contains_text_flow_control_chars(&text.as_str()) { return; } let padding = match kind { // account for `"` or `'` ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1, // account for `r###"` ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2, _ => return, }; (text, span, padding) } _ => return, }; self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal"); } }
nt_text_direction_codepoint(
identifier_name
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the /// visual representation of text on screen in a way that does not correspond to their on /// memory representation. /// /// ### Explanation /// /// The unicode characters `\u{202A}`, `\u{202B}`, `\u{202D}`, `\u{202E}`, `\u{2066}`, /// `\u{2067}`, `\u{2068}`, `\u{202C}` and `\u{2069}` make the flow of text on screen change /// its direction on software that supports these codepoints. This makes the text "abc" display /// as "cba" on screen. By leveraging software that supports these, people can write specially /// crafted literals that make the surrounding code seem like it's performing one action, when /// in reality it is performing another. Because of this, we proactively lint against their /// presence to avoid surprises. /// /// ### Example /// /// ```rust,compile_fail /// #![deny(text_direction_codepoint_in_literal)] /// fn main() { /// println!("{:?}", '‮'); /// } /// ``` /// /// {{produces}} /// pub TEXT_DIRECTION_CODEPOINT_IN_LITERAL, Deny, "detect special Unicode codepoints that affect the visual representation of text on screen, \ changing the direction in which text flows", } declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]); impl HiddenUnicodeCodepoints { fn lint_text_direction_codepoint( &self, cx: &EarlyContext<'_>, text: Symbol, span: Span, padding: u32, point_at_inner_spans: bool, label: &str, ) { // Obtain the `Span`s for each of the forbidden chars. let spans: Vec<_> = text .as_str() .char_indices() .filter_map(|(i, c)| { TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| { let lo = span.lo() + BytePos(i as u32 + padding); (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32))) }) }) .collect(); cx.struct_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, |lint| { let mut err = lint.build(&format!( "unicode codepoint changing visible direction of text present in {}", label )); let (an, s) = match spans.len() { 1 => ("an ", ""), _ => ("", "s"), }; err.span_label( span, &format!( "this {} contains {}invisible unicode text flow control codepoint{}", label, an, s, ), ); if point_at_inner_spans { for (c, span) in &spans { err.span_label(*span, format!("{:?}", c)); } } err.note( "these kind of unicode codepoints change the way text flows on applications that \ support them, but can cause confusion because they change the order of \ characters on the screen", ); if point_at_inner_spans &&!spans.is_empty() { err.multipart_suggestion_with_style( "if their presence wasn't intentional, you can remove them", spans.iter().map(|(_, span)| (*span, "".to_string())).collect(), Applicability::MachineApplicable, SuggestionStyle::HideCodeAlways, ); err.multipart_suggestion( "if you want to keep them but make them visible in your source code, you can \ escape them", spans .into_iter() .map(|(c, span)| { let c = format!("{:?}", c); (span, c[1..c.len() - 1].to_string()) }) .collect(), Applicability::MachineApplicable, ); } else { // FIXME: in other suggestions we've reversed the inner spans of doc comments. We // should do the same here to provide the same good suggestions as we do for // literals above. err.note("if their presence wasn't intentional, you can remove them"); err.note(&format!( "if you want to keep them but make them visible in your source code, you can \ escape them: {}", spans .into_iter() .map(|(c, _)| { format!("{:?}", c) }) .collect::<Vec<String>>() .join(", "), )); } err.emit(); }); } } impl EarlyLintPass for HiddenUnicodeCodepoints { fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { if let ast::AttrKind::DocComment(_, comment) = attr.kind { if contains_text_flow_control_chars(&comment.as_str()) { self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment"); } } } fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
}
// byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString` let (text, span, padding) = match &expr.kind { ast::ExprKind::Lit(ast::Lit { token, kind, span }) => { let text = token.symbol; if !contains_text_flow_control_chars(&text.as_str()) { return; } let padding = match kind { // account for `"` or `'` ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1, // account for `r###"` ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2, _ => return, }; (text, span, padding) } _ => return, }; self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal"); }
identifier_body
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the /// visual representation of text on screen in a way that does not correspond to their on /// memory representation. /// /// ### Explanation /// /// The unicode characters `\u{202A}`, `\u{202B}`, `\u{202D}`, `\u{202E}`, `\u{2066}`, /// `\u{2067}`, `\u{2068}`, `\u{202C}` and `\u{2069}` make the flow of text on screen change /// its direction on software that supports these codepoints. This makes the text "abc" display /// as "cba" on screen. By leveraging software that supports these, people can write specially /// crafted literals that make the surrounding code seem like it's performing one action, when /// in reality it is performing another. Because of this, we proactively lint against their /// presence to avoid surprises. /// /// ### Example /// /// ```rust,compile_fail /// #![deny(text_direction_codepoint_in_literal)] /// fn main() { /// println!("{:?}", '‮'); /// } /// ``` /// /// {{produces}} /// pub TEXT_DIRECTION_CODEPOINT_IN_LITERAL, Deny, "detect special Unicode codepoints that affect the visual representation of text on screen, \ changing the direction in which text flows", } declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]); impl HiddenUnicodeCodepoints { fn lint_text_direction_codepoint( &self, cx: &EarlyContext<'_>, text: Symbol, span: Span, padding: u32, point_at_inner_spans: bool, label: &str, ) { // Obtain the `Span`s for each of the forbidden chars. let spans: Vec<_> = text .as_str() .char_indices() .filter_map(|(i, c)| { TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| { let lo = span.lo() + BytePos(i as u32 + padding); (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32))) }) }) .collect(); cx.struct_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, |lint| { let mut err = lint.build(&format!( "unicode codepoint changing visible direction of text present in {}", label )); let (an, s) = match spans.len() { 1 => ("an ", ""), _ => ("", "s"), }; err.span_label( span, &format!( "this {} contains {}invisible unicode text flow control codepoint{}", label, an, s, ), ); if point_at_inner_spans { for (c, span) in &spans { err.span_label(*span, format!("{:?}", c)); } } err.note( "these kind of unicode codepoints change the way text flows on applications that \ support them, but can cause confusion because they change the order of \ characters on the screen", ); if point_at_inner_spans &&!spans.is_empty() { err.multipart_suggestion_with_style( "if their presence wasn't intentional, you can remove them",
err.multipart_suggestion( "if you want to keep them but make them visible in your source code, you can \ escape them", spans .into_iter() .map(|(c, span)| { let c = format!("{:?}", c); (span, c[1..c.len() - 1].to_string()) }) .collect(), Applicability::MachineApplicable, ); } else { // FIXME: in other suggestions we've reversed the inner spans of doc comments. We // should do the same here to provide the same good suggestions as we do for // literals above. err.note("if their presence wasn't intentional, you can remove them"); err.note(&format!( "if you want to keep them but make them visible in your source code, you can \ escape them: {}", spans .into_iter() .map(|(c, _)| { format!("{:?}", c) }) .collect::<Vec<String>>() .join(", "), )); } err.emit(); }); } } impl EarlyLintPass for HiddenUnicodeCodepoints { fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { if let ast::AttrKind::DocComment(_, comment) = attr.kind { if contains_text_flow_control_chars(&comment.as_str()) { self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment"); } } } fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { // byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString` let (text, span, padding) = match &expr.kind { ast::ExprKind::Lit(ast::Lit { token, kind, span }) => { let text = token.symbol; if!contains_text_flow_control_chars(&text.as_str()) { return; } let padding = match kind { // account for `"` or `'` ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1, // account for `r###"` ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2, _ => return, }; (text, span, padding) } _ => return, }; self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal"); } }
spans.iter().map(|(_, span)| (*span, "".to_string())).collect(), Applicability::MachineApplicable, SuggestionStyle::HideCodeAlways, );
random_line_split
htmltextareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{AttributeHandlers, HTMLTextAreaElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLTextAreaElement { htmlelement: HTMLElement, } impl HTMLTextAreaElementDerived for EventTarget { fn is_htmltextareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTextAreaElementTypeId)) } } impl HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited(HTMLTextAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTextAreaElement>
} impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type fn Type(self) -> DOMString { "textarea".to_string() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLTextAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ let element = HTMLTextAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTextAreaElementBinding::Wrap) }
identifier_body
htmltextareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{AttributeHandlers, HTMLTextAreaElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLTextAreaElement { htmlelement: HTMLElement, } impl HTMLTextAreaElementDerived for EventTarget { fn is_htmltextareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTextAreaElementTypeId)) } } impl HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited(HTMLTextAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTextAreaElement> { let element = HTMLTextAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTextAreaElementBinding::Wrap) } } impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type fn Type(self) -> DOMString { "textarea".to_string() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn
(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLTextAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
after_set_attr
identifier_name
htmltextareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{AttributeHandlers, HTMLTextAreaElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLTextAreaElement { htmlelement: HTMLElement, } impl HTMLTextAreaElementDerived for EventTarget { fn is_htmltextareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTextAreaElementTypeId)) } } impl HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited(HTMLTextAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTextAreaElement> { let element = HTMLTextAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTextAreaElementBinding::Wrap) } } impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type fn Type(self) -> DOMString { "textarea".to_string() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => {
} } fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLTextAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
node.set_disabled_state(true); node.set_enabled_state(false); }, _ => ()
random_line_split
shootout-ackermann.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::os; fn ack(m: int, n: int) -> int { if m == 0 { return n + 1 } else { if n == 0 { return ack(m - 1, 1); } else { return ack(m - 1, ack(m, n - 1)); } } } fn
() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); }
main
identifier_name
shootout-ackermann.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::os; fn ack(m: int, n: int) -> int { if m == 0 { return n + 1 } else { if n == 0
else { return ack(m - 1, ack(m, n - 1)); } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); }
{ return ack(m - 1, 1); }
conditional_block
shootout-ackermann.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::os; fn ack(m: int, n: int) -> int {
if m == 0 { return n + 1 } else { if n == 0 { return ack(m - 1, 1); } else { return ack(m - 1, ack(m, n - 1)); } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); }
random_line_split
shootout-ackermann.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::os; fn ack(m: int, n: int) -> int { if m == 0 { return n + 1 } else { if n == 0 { return ack(m - 1, 1); } else { return ack(m - 1, ack(m, n - 1)); } } } fn main()
{ let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); }
identifier_body
print_queue_resolvers.rs
use async_graphql::{ ID, Context, FieldResult, }; // use eyre::{ // eyre, // // Result, // Context as _, // }; use printspool_json_store::{ Record, JsonRow }; use crate::{ PrintQueue, part::Part, // package::Package, }; #[derive(async_graphql::InputObject, Default)] struct PrintQueuePartsInput { /// Include the prints that are currently in the queue or actively printing (default: true) #[graphql(default = true)] include_queued: bool, /// Include the print history of parts that have completed all of their prints (default: false) #[graphql(default = false)] include_finished: bool, /// Include starred prints regardless of whether they are in the queue or finished /// (default: false) #[graphql(default = false)] include_starred: bool, } #[async_graphql::Object] impl PrintQueue { async fn id(&self) -> ID { (&self.id).into() } async fn name<'ctx>(&self) -> &String
async fn parts<'ctx>( &self, ctx: &'ctx Context<'_>, // id: Option<ID>, input: Option<PrintQueuePartsInput>, ) -> FieldResult<Vec<Part>> { let db: &crate::Db = ctx.data()?; let input = input.unwrap_or(PrintQueuePartsInput { include_queued: true, include_finished: false, include_starred: false, }); let parts = sqlx::query_as!( JsonRow, r#" SELECT parts.props FROM parts INNER JOIN packages ON packages.id = parts.package_id AND packages.print_queue_id = $1 LEFT OUTER JOIN tasks ON tasks.part_id = parts.id AND tasks.status = 'finished' WHERE parts.deleted_at IS NULL AND (tasks.id IS NULL OR tasks.status IS NOT NULL) GROUP BY parts.id, parts.quantity, packages.quantity, packages.starred HAVING ( $2 IS TRUE AND parts.quantity * packages.quantity > COUNT(tasks.id) ) OR ( $3 IS TRUE AND parts.quantity * packages.quantity <= COUNT(tasks.id) ) OR ( $4 IS TRUE AND packages.starred ) ORDER BY parts.position "#, self.id, input.include_queued, input.include_finished, input.include_starred, ) .fetch_all(db) .await?; let parts = Part::from_rows(parts)?; Ok(parts) } }
{ &self.name }
identifier_body
print_queue_resolvers.rs
use async_graphql::{ ID, Context, FieldResult, }; // use eyre::{ // eyre, // // Result, // Context as _, // }; use printspool_json_store::{ Record, JsonRow }; use crate::{ PrintQueue, part::Part, // package::Package, }; #[derive(async_graphql::InputObject, Default)] struct PrintQueuePartsInput { /// Include the prints that are currently in the queue or actively printing (default: true) #[graphql(default = true)] include_queued: bool, /// Include the print history of parts that have completed all of their prints (default: false) #[graphql(default = false)] include_finished: bool, /// Include starred prints regardless of whether they are in the queue or finished /// (default: false) #[graphql(default = false)] include_starred: bool, } #[async_graphql::Object] impl PrintQueue { async fn id(&self) -> ID { (&self.id).into() } async fn name<'ctx>(&self) -> &String { &self.name } async fn
<'ctx>( &self, ctx: &'ctx Context<'_>, // id: Option<ID>, input: Option<PrintQueuePartsInput>, ) -> FieldResult<Vec<Part>> { let db: &crate::Db = ctx.data()?; let input = input.unwrap_or(PrintQueuePartsInput { include_queued: true, include_finished: false, include_starred: false, }); let parts = sqlx::query_as!( JsonRow, r#" SELECT parts.props FROM parts INNER JOIN packages ON packages.id = parts.package_id AND packages.print_queue_id = $1 LEFT OUTER JOIN tasks ON tasks.part_id = parts.id AND tasks.status = 'finished' WHERE parts.deleted_at IS NULL AND (tasks.id IS NULL OR tasks.status IS NOT NULL) GROUP BY parts.id, parts.quantity, packages.quantity, packages.starred HAVING ( $2 IS TRUE AND parts.quantity * packages.quantity > COUNT(tasks.id) ) OR ( $3 IS TRUE AND parts.quantity * packages.quantity <= COUNT(tasks.id) ) OR ( $4 IS TRUE AND packages.starred ) ORDER BY parts.position "#, self.id, input.include_queued, input.include_finished, input.include_starred, ) .fetch_all(db) .await?; let parts = Part::from_rows(parts)?; Ok(parts) } }
parts
identifier_name
print_queue_resolvers.rs
use async_graphql::{ ID, Context, FieldResult, }; // use eyre::{ // eyre, // // Result, // Context as _, // }; use printspool_json_store::{ Record, JsonRow }; use crate::{ PrintQueue, part::Part, // package::Package, }; #[derive(async_graphql::InputObject, Default)] struct PrintQueuePartsInput { /// Include the prints that are currently in the queue or actively printing (default: true) #[graphql(default = true)] include_queued: bool, /// Include the print history of parts that have completed all of their prints (default: false) #[graphql(default = false)] include_finished: bool, /// Include starred prints regardless of whether they are in the queue or finished /// (default: false) #[graphql(default = false)] include_starred: bool, }
impl PrintQueue { async fn id(&self) -> ID { (&self.id).into() } async fn name<'ctx>(&self) -> &String { &self.name } async fn parts<'ctx>( &self, ctx: &'ctx Context<'_>, // id: Option<ID>, input: Option<PrintQueuePartsInput>, ) -> FieldResult<Vec<Part>> { let db: &crate::Db = ctx.data()?; let input = input.unwrap_or(PrintQueuePartsInput { include_queued: true, include_finished: false, include_starred: false, }); let parts = sqlx::query_as!( JsonRow, r#" SELECT parts.props FROM parts INNER JOIN packages ON packages.id = parts.package_id AND packages.print_queue_id = $1 LEFT OUTER JOIN tasks ON tasks.part_id = parts.id AND tasks.status = 'finished' WHERE parts.deleted_at IS NULL AND (tasks.id IS NULL OR tasks.status IS NOT NULL) GROUP BY parts.id, parts.quantity, packages.quantity, packages.starred HAVING ( $2 IS TRUE AND parts.quantity * packages.quantity > COUNT(tasks.id) ) OR ( $3 IS TRUE AND parts.quantity * packages.quantity <= COUNT(tasks.id) ) OR ( $4 IS TRUE AND packages.starred ) ORDER BY parts.position "#, self.id, input.include_queued, input.include_finished, input.include_starred, ) .fetch_all(db) .await?; let parts = Part::from_rows(parts)?; Ok(parts) } }
#[async_graphql::Object]
random_line_split
cargo.rs
extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; // Write the Docopt usage string. const USAGE: &'static str = " Rust's package manager Usage: cargo <command> [<args>...] cargo [options] Options: -h, --help Display this message -V, --version Print version info and exit --list List installed commands -v, --verbose Use verbose output Some common cargo commands are: build Compile the current project clean Remove the target directory doc Build this project's and its dependencies' documentation new Create a new cargo project run Build and execute src/main.rs test Run the tests bench Run the benchmarks update Update dependencies listed in Cargo.lock See 'cargo help <command>' for more information on a specific command. "; #[derive(Debug, RustcDecodable)] struct Args { arg_command: Option<Command>, arg_args: Vec<String>, flag_list: bool, flag_verbose: bool, } #[derive(Debug, RustcDecodable)] enum Command { Build, Clean, Doc, New, Run, Test, Bench, Update, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.options_first(true).decode())
.unwrap_or_else(|e| e.exit()); println!("{:?}", args); }
random_line_split
cargo.rs
extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; // Write the Docopt usage string. const USAGE: &'static str = " Rust's package manager Usage: cargo <command> [<args>...] cargo [options] Options: -h, --help Display this message -V, --version Print version info and exit --list List installed commands -v, --verbose Use verbose output Some common cargo commands are: build Compile the current project clean Remove the target directory doc Build this project's and its dependencies' documentation new Create a new cargo project run Build and execute src/main.rs test Run the tests bench Run the benchmarks update Update dependencies listed in Cargo.lock See 'cargo help <command>' for more information on a specific command. "; #[derive(Debug, RustcDecodable)] struct Args { arg_command: Option<Command>, arg_args: Vec<String>, flag_list: bool, flag_verbose: bool, } #[derive(Debug, RustcDecodable)] enum Command { Build, Clean, Doc, New, Run, Test, Bench, Update, } fn
() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.options_first(true).decode()) .unwrap_or_else(|e| e.exit()); println!("{:?}", args); }
main
identifier_name
sha.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use core::cell::Cell; use core::mem; use crate::hil::digest::{DigestEngine, DigestMode, DigestError}; use kernel::common::cells::VolatileCell; use super::keymgr::{KEYMGR0_REGS, Registers}; #[allow(unused)] enum ShaTrigMask { Go = 0x1, Reset = 0x2, Step = 0x4, Stop = 0x8, } #[allow(unused)] enum ShaCfgEnMask { BigEndian = 0x01, Sha1 = 0x02, BusError = 0x08, Livestream = 0x10, Hmac = 0x20, IntEnDone = 0x1_0000, IntMaskDone = 0x2_0000, } pub struct ShaEngine { regs: *mut Registers, current_mode: Cell<Option<DigestMode>>, } enum CertificateMask { CertBits = 0x3f, // Bits 0:5 Enable = 0x40, // 1 << 6 //CheckOnly = 0x80, // 1 << 7 } impl ShaEngine { const unsafe fn new(regs: *mut Registers) -> ShaEngine
pub fn handle_interrupt(&self, _nvic: u32) { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); } } pub static mut KEYMGR0_SHA: ShaEngine = unsafe { ShaEngine::new(KEYMGR0_REGS) }; const HMAC_KEY_SIZE_BYTES: usize = 32; const HMAC_KEY_SIZE_WORDS: usize = HMAC_KEY_SIZE_BYTES / 4; impl DigestEngine for ShaEngine { fn initialize(&self, mode: DigestMode) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status // Compile-time check for DigestMode exhaustiveness match mode { DigestMode::Sha1 | DigestMode::Sha256 | DigestMode::Sha256Hmac => (), }; self.current_mode.set(Some(mode)); regs.trig.set(ShaTrigMask::Stop as u32); let mut flags = ShaCfgEnMask::Livestream as u32 | ShaCfgEnMask::IntEnDone as u32; match mode { DigestMode::Sha1 => flags |= ShaCfgEnMask::Sha1 as u32, DigestMode::Sha256 => (), DigestMode::Sha256Hmac => flags |= ShaCfgEnMask::Hmac as u32, } regs.cfg_en.set(flags); regs.trig.set(ShaTrigMask::Go as u32); Ok(()) } fn initialize_hmac(&self, key: &[u8]) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status self.current_mode.set(Some(DigestMode::Sha256Hmac)); if key.len() < HMAC_KEY_SIZE_BYTES { print!("Key too small: {}\n", key.len()); return Err(DigestError::BufferTooSmall(HMAC_KEY_SIZE_BYTES)); } for i in 0..HMAC_KEY_SIZE_WORDS { let word: u32 = (key[4 * i + 0] as u32) << 0 | (key[4 * i + 1] as u32) << 8 | (key[4 * i + 2] as u32) << 16 | (key[4 * i + 3] as u32) << 24; regs.key_w[i].set(word); } let flags = ShaCfgEnMask::Livestream as u32 | ShaCfgEnMask::IntEnDone as u32 | ShaCfgEnMask::Hmac as u32; regs.cfg_en.set(flags); regs.trig.set(ShaTrigMask::Go as u32); return Ok(()); } fn initialize_certificate(&self, certificate_id: u32) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status regs.use_cert.set(certificate_id & CertificateMask::CertBits as u32 | CertificateMask::Enable as u32); regs.cfg_en.set(ShaCfgEnMask::IntEnDone as u32); regs.trig.set(ShaTrigMask::Go as u32); Ok(()) } fn update(&self, data: &[u8]) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; if self.current_mode.get().is_none() { print!("ERROR: SHA::update called but engine not initialized!\n"); return Err(DigestError::NotConfigured); } let fifo_u8: &VolatileCell<u8> = unsafe { mem::transmute(&regs.input_fifo) }; // TODO(yuriks): Feed FIFO word at a time when possible for b in data { fifo_u8.set(*b); } Ok(data.len()) } fn finalize(&self, output: &mut [u8]) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; let expected_output_size = match self.current_mode.get() { None => return Err(DigestError::NotConfigured), Some(mode) => mode.output_size(), }; if output.len() < expected_output_size { return Err(DigestError::BufferTooSmall(expected_output_size)); } // Tell hardware we're done streaming and then wait for the // hash calculation to finish. regs.itop.set(0); regs.trig.set(ShaTrigMask::Stop as u32); while regs.itop.get() == 0 {} for i in 0..(expected_output_size / 4) { let word = regs.sts_h[i].get(); output[i * 4 + 0] = (word >> 0) as u8; output[i * 4 + 1] = (word >> 8) as u8; output[i * 4 + 2] = (word >> 16) as u8; output[i * 4 + 3] = (word >> 24) as u8; } regs.itop.set(0); Ok(expected_output_size) } // Finalize withtout seeing the result; this is used for certificates // (hidden secret generation) fn finalize_hidden(&self) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); regs.trig.set(ShaTrigMask::Stop as u32); while regs.itop.get() == 0 {} regs.itop.set(0); Ok(0) } }
{ ShaEngine { regs: regs, current_mode: Cell::new(None), } }
identifier_body
sha.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use core::cell::Cell; use core::mem; use crate::hil::digest::{DigestEngine, DigestMode, DigestError}; use kernel::common::cells::VolatileCell; use super::keymgr::{KEYMGR0_REGS, Registers}; #[allow(unused)] enum ShaTrigMask { Go = 0x1, Reset = 0x2, Step = 0x4, Stop = 0x8, } #[allow(unused)] enum ShaCfgEnMask { BigEndian = 0x01, Sha1 = 0x02, BusError = 0x08, Livestream = 0x10, Hmac = 0x20, IntEnDone = 0x1_0000, IntMaskDone = 0x2_0000, } pub struct ShaEngine { regs: *mut Registers, current_mode: Cell<Option<DigestMode>>, } enum CertificateMask { CertBits = 0x3f, // Bits 0:5 Enable = 0x40, // 1 << 6 //CheckOnly = 0x80, // 1 << 7 } impl ShaEngine { const unsafe fn
(regs: *mut Registers) -> ShaEngine { ShaEngine { regs: regs, current_mode: Cell::new(None), } } pub fn handle_interrupt(&self, _nvic: u32) { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); } } pub static mut KEYMGR0_SHA: ShaEngine = unsafe { ShaEngine::new(KEYMGR0_REGS) }; const HMAC_KEY_SIZE_BYTES: usize = 32; const HMAC_KEY_SIZE_WORDS: usize = HMAC_KEY_SIZE_BYTES / 4; impl DigestEngine for ShaEngine { fn initialize(&self, mode: DigestMode) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status // Compile-time check for DigestMode exhaustiveness match mode { DigestMode::Sha1 | DigestMode::Sha256 | DigestMode::Sha256Hmac => (), }; self.current_mode.set(Some(mode)); regs.trig.set(ShaTrigMask::Stop as u32); let mut flags = ShaCfgEnMask::Livestream as u32 | ShaCfgEnMask::IntEnDone as u32; match mode { DigestMode::Sha1 => flags |= ShaCfgEnMask::Sha1 as u32, DigestMode::Sha256 => (), DigestMode::Sha256Hmac => flags |= ShaCfgEnMask::Hmac as u32, } regs.cfg_en.set(flags); regs.trig.set(ShaTrigMask::Go as u32); Ok(()) } fn initialize_hmac(&self, key: &[u8]) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status self.current_mode.set(Some(DigestMode::Sha256Hmac)); if key.len() < HMAC_KEY_SIZE_BYTES { print!("Key too small: {}\n", key.len()); return Err(DigestError::BufferTooSmall(HMAC_KEY_SIZE_BYTES)); } for i in 0..HMAC_KEY_SIZE_WORDS { let word: u32 = (key[4 * i + 0] as u32) << 0 | (key[4 * i + 1] as u32) << 8 | (key[4 * i + 2] as u32) << 16 | (key[4 * i + 3] as u32) << 24; regs.key_w[i].set(word); } let flags = ShaCfgEnMask::Livestream as u32 | ShaCfgEnMask::IntEnDone as u32 | ShaCfgEnMask::Hmac as u32; regs.cfg_en.set(flags); regs.trig.set(ShaTrigMask::Go as u32); return Ok(()); } fn initialize_certificate(&self, certificate_id: u32) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status regs.use_cert.set(certificate_id & CertificateMask::CertBits as u32 | CertificateMask::Enable as u32); regs.cfg_en.set(ShaCfgEnMask::IntEnDone as u32); regs.trig.set(ShaTrigMask::Go as u32); Ok(()) } fn update(&self, data: &[u8]) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; if self.current_mode.get().is_none() { print!("ERROR: SHA::update called but engine not initialized!\n"); return Err(DigestError::NotConfigured); } let fifo_u8: &VolatileCell<u8> = unsafe { mem::transmute(&regs.input_fifo) }; // TODO(yuriks): Feed FIFO word at a time when possible for b in data { fifo_u8.set(*b); } Ok(data.len()) } fn finalize(&self, output: &mut [u8]) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; let expected_output_size = match self.current_mode.get() { None => return Err(DigestError::NotConfigured), Some(mode) => mode.output_size(), }; if output.len() < expected_output_size { return Err(DigestError::BufferTooSmall(expected_output_size)); } // Tell hardware we're done streaming and then wait for the // hash calculation to finish. regs.itop.set(0); regs.trig.set(ShaTrigMask::Stop as u32); while regs.itop.get() == 0 {} for i in 0..(expected_output_size / 4) { let word = regs.sts_h[i].get(); output[i * 4 + 0] = (word >> 0) as u8; output[i * 4 + 1] = (word >> 8) as u8; output[i * 4 + 2] = (word >> 16) as u8; output[i * 4 + 3] = (word >> 24) as u8; } regs.itop.set(0); Ok(expected_output_size) } // Finalize withtout seeing the result; this is used for certificates // (hidden secret generation) fn finalize_hidden(&self) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); regs.trig.set(ShaTrigMask::Stop as u32); while regs.itop.get() == 0 {} regs.itop.set(0); Ok(0) } }
new
identifier_name
sha.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use core::cell::Cell; use core::mem; use crate::hil::digest::{DigestEngine, DigestMode, DigestError}; use kernel::common::cells::VolatileCell; use super::keymgr::{KEYMGR0_REGS, Registers}; #[allow(unused)] enum ShaTrigMask { Go = 0x1, Reset = 0x2, Step = 0x4, Stop = 0x8, } #[allow(unused)] enum ShaCfgEnMask { BigEndian = 0x01, Sha1 = 0x02, BusError = 0x08, Livestream = 0x10, Hmac = 0x20, IntEnDone = 0x1_0000, IntMaskDone = 0x2_0000, } pub struct ShaEngine { regs: *mut Registers, current_mode: Cell<Option<DigestMode>>, } enum CertificateMask { CertBits = 0x3f, // Bits 0:5 Enable = 0x40, // 1 << 6 //CheckOnly = 0x80, // 1 << 7 } impl ShaEngine { const unsafe fn new(regs: *mut Registers) -> ShaEngine { ShaEngine { regs: regs, current_mode: Cell::new(None), } } pub fn handle_interrupt(&self, _nvic: u32) { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); } } pub static mut KEYMGR0_SHA: ShaEngine = unsafe { ShaEngine::new(KEYMGR0_REGS) }; const HMAC_KEY_SIZE_BYTES: usize = 32; const HMAC_KEY_SIZE_WORDS: usize = HMAC_KEY_SIZE_BYTES / 4; impl DigestEngine for ShaEngine { fn initialize(&self, mode: DigestMode) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status // Compile-time check for DigestMode exhaustiveness match mode { DigestMode::Sha1 | DigestMode::Sha256 | DigestMode::Sha256Hmac => (), }; self.current_mode.set(Some(mode)); regs.trig.set(ShaTrigMask::Stop as u32);
DigestMode::Sha1 => flags |= ShaCfgEnMask::Sha1 as u32, DigestMode::Sha256 => (), DigestMode::Sha256Hmac => flags |= ShaCfgEnMask::Hmac as u32, } regs.cfg_en.set(flags); regs.trig.set(ShaTrigMask::Go as u32); Ok(()) } fn initialize_hmac(&self, key: &[u8]) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status self.current_mode.set(Some(DigestMode::Sha256Hmac)); if key.len() < HMAC_KEY_SIZE_BYTES { print!("Key too small: {}\n", key.len()); return Err(DigestError::BufferTooSmall(HMAC_KEY_SIZE_BYTES)); } for i in 0..HMAC_KEY_SIZE_WORDS { let word: u32 = (key[4 * i + 0] as u32) << 0 | (key[4 * i + 1] as u32) << 8 | (key[4 * i + 2] as u32) << 16 | (key[4 * i + 3] as u32) << 24; regs.key_w[i].set(word); } let flags = ShaCfgEnMask::Livestream as u32 | ShaCfgEnMask::IntEnDone as u32 | ShaCfgEnMask::Hmac as u32; regs.cfg_en.set(flags); regs.trig.set(ShaTrigMask::Go as u32); return Ok(()); } fn initialize_certificate(&self, certificate_id: u32) -> Result<(), DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); // clear status regs.use_cert.set(certificate_id & CertificateMask::CertBits as u32 | CertificateMask::Enable as u32); regs.cfg_en.set(ShaCfgEnMask::IntEnDone as u32); regs.trig.set(ShaTrigMask::Go as u32); Ok(()) } fn update(&self, data: &[u8]) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; if self.current_mode.get().is_none() { print!("ERROR: SHA::update called but engine not initialized!\n"); return Err(DigestError::NotConfigured); } let fifo_u8: &VolatileCell<u8> = unsafe { mem::transmute(&regs.input_fifo) }; // TODO(yuriks): Feed FIFO word at a time when possible for b in data { fifo_u8.set(*b); } Ok(data.len()) } fn finalize(&self, output: &mut [u8]) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; let expected_output_size = match self.current_mode.get() { None => return Err(DigestError::NotConfigured), Some(mode) => mode.output_size(), }; if output.len() < expected_output_size { return Err(DigestError::BufferTooSmall(expected_output_size)); } // Tell hardware we're done streaming and then wait for the // hash calculation to finish. regs.itop.set(0); regs.trig.set(ShaTrigMask::Stop as u32); while regs.itop.get() == 0 {} for i in 0..(expected_output_size / 4) { let word = regs.sts_h[i].get(); output[i * 4 + 0] = (word >> 0) as u8; output[i * 4 + 1] = (word >> 8) as u8; output[i * 4 + 2] = (word >> 16) as u8; output[i * 4 + 3] = (word >> 24) as u8; } regs.itop.set(0); Ok(expected_output_size) } // Finalize withtout seeing the result; this is used for certificates // (hidden secret generation) fn finalize_hidden(&self) -> Result<usize, DigestError> { let ref regs = unsafe { &*self.regs }.sha; regs.itop.set(0); regs.trig.set(ShaTrigMask::Stop as u32); while regs.itop.get() == 0 {} regs.itop.set(0); Ok(0) } }
let mut flags = ShaCfgEnMask::Livestream as u32 | ShaCfgEnMask::IntEnDone as u32; match mode {
random_line_split
script.rs
use std::fmt; use std::str::FromStr; use super::lang_mapping; use crate::error::Error; use crate::Lang; #[cfg(feature = "enum-map")] use enum_map::Enum; /// Represents a writing system (Latin, Cyrillic, Arabic, etc). #[cfg_attr(feature = "enum-map", derive(Enum))] #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum Script { // Keep this in alphabetic order (for C bindings) Arabic, Bengali, Cyrillic, Devanagari, Ethiopic, Georgian, Greek, Gujarati, Gurmukhi, Hangul, Hebrew, Hiragana, Kannada, Katakana, Khmer, Latin, Malayalam, Mandarin, Myanmar, Oriya, Sinhala, Tamil, Telugu, Thai, } // Array of all existing Script values. const VALUES: [Script; 24] = [ Script::Arabic, Script::Bengali, Script::Cyrillic, Script::Devanagari, Script::Ethiopic, Script::Georgian, Script::Greek, Script::Gujarati, Script::Gurmukhi, Script::Hangul, Script::Hebrew, Script::Hiragana, Script::Kannada, Script::Katakana, Script::Khmer, Script::Latin, Script::Malayalam, Script::Mandarin, Script::Myanmar, Script::Oriya, Script::Sinhala, Script::Tamil, Script::Telugu, Script::Thai, ]; impl Script { /// Get all existing scripts. /// /// # Example /// ``` /// use whatlang::Script; /// for script in Script::all() { /// println!("{}", script); /// } /// ``` pub fn all() -> &'static [Script] { &VALUES } pub fn name(&self) -> &str { match *self { Script::Latin => "Latin", Script::Cyrillic => "Cyrillic", Script::Arabic => "Arabic", Script::Devanagari => "Devanagari", Script::Hiragana => "Hiragana", Script::Katakana => "Katakana", Script::Ethiopic => "Ethiopic", Script::Hebrew => "Hebrew", Script::Bengali => "Bengali", Script::Georgian => "Georgian", Script::Mandarin => "Mandarin", Script::Hangul => "Hangul", Script::Greek => "Greek", Script::Kannada => "Kannada", Script::Tamil => "Tamil", Script::Thai => "Thai", Script::Gujarati => "Gujarati", Script::Gurmukhi => "Gurmukhi", Script::Telugu => "Telugu", Script::Malayalam => "Malayalam", Script::Oriya => "Oriya", Script::Myanmar => "Myanmar", Script::Sinhala => "Sinhala", Script::Khmer => "Khmer", } } pub fn langs(&self) -> &[Lang] { lang_mapping::script_langs(*self) } } impl fmt::Display for Script { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name()) } } impl FromStr for Script { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().trim() { "latin" => Ok(Script::Latin), "cyrillic" => Ok(Script::Cyrillic), "arabic" => Ok(Script::Arabic), "devanagari" => Ok(Script::Devanagari), "hiragana" => Ok(Script::Hiragana), "katakana" => Ok(Script::Katakana), "ethiopic" => Ok(Script::Ethiopic), "hebrew" => Ok(Script::Hebrew), "bengali" => Ok(Script::Bengali), "georgian" => Ok(Script::Georgian), "mandarin" => Ok(Script::Mandarin), "hangul" => Ok(Script::Hangul), "greek" => Ok(Script::Greek), "kannada" => Ok(Script::Kannada), "tamil" => Ok(Script::Tamil), "thai" => Ok(Script::Thai), "gujarati" => Ok(Script::Gujarati), "gurmukhi" => Ok(Script::Gurmukhi), "telugu" => Ok(Script::Telugu), "malayalam" => Ok(Script::Malayalam), "oriya" => Ok(Script::Oriya), "myanmar" => Ok(Script::Myanmar), "sinhala" => Ok(Script::Sinhala), "khmer" => Ok(Script::Khmer), _ => Err(Error::ParseScript(s.to_string())), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_all() { assert_eq!(Script::all().len(), 24); let all = Script::all(); assert!(all.contains(&Script::Cyrillic)); assert!(all.contains(&Script::Arabic)); assert!(all.contains(&Script::Latin)); } #[test] fn test_from_str() { for &script in Script::all() { let s = script.name(); assert_eq!(s.parse::<Script>().unwrap(), script); assert_eq!(s.to_lowercase().parse::<Script>().unwrap(), script); assert_eq!(s.to_uppercase().parse::<Script>().unwrap(), script); } let result = "foobar".parse::<Script>(); assert!(matches!(result, Err(Error::ParseScript(_)))); } #[test] fn test_langs()
}
{ // Vec of all langs obtained with script.langs() let script_langs: Vec<Lang> = Script::all() .iter() .map(|script| script.langs()) .flatten() .copied() .collect(); // Ensure all langs belong at least to one script for lang in Lang::all() { assert!(script_langs.contains(&lang)); } }
identifier_body