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
lib.rs
pub mod car; use car::car_factory::CarFactory; use car::car_type::{Body, Colour}; use car::Car; pub struct
{ cars: Vec<Car>, car_factory: CarFactory, } impl Parking { pub fn new() -> Parking { Parking { cars: Vec::new(), car_factory: CarFactory::new(), } } pub fn add_car( &mut self, license_plate: &str, parking_place_number: u8, body: Body, colour: Colour, ) { self.cars.push(Car::new( license_plate.to_string(), parking_place_number, self.car_factory.get_car_type_id(body, colour), )); } pub fn print(&mut self) { for car in &self.cars { car.print(self.car_factory.get_car_type(car.car_type_id).unwrap()); } println!("\nNumber of cars: {}", self.cars.len()); self.car_factory.print(); } }
Parking
identifier_name
lib.rs
pub mod car; use car::car_factory::CarFactory; use car::car_type::{Body, Colour}; use car::Car; pub struct Parking { cars: Vec<Car>, car_factory: CarFactory, } impl Parking { pub fn new() -> Parking { Parking { cars: Vec::new(), car_factory: CarFactory::new(), } } pub fn add_car( &mut self,
) { self.cars.push(Car::new( license_plate.to_string(), parking_place_number, self.car_factory.get_car_type_id(body, colour), )); } pub fn print(&mut self) { for car in &self.cars { car.print(self.car_factory.get_car_type(car.car_type_id).unwrap()); } println!("\nNumber of cars: {}", self.cars.len()); self.car_factory.print(); } }
license_plate: &str, parking_place_number: u8, body: Body, colour: Colour,
random_line_split
lib.rs
pub mod car; use car::car_factory::CarFactory; use car::car_type::{Body, Colour}; use car::Car; pub struct Parking { cars: Vec<Car>, car_factory: CarFactory, } impl Parking { pub fn new() -> Parking { Parking { cars: Vec::new(), car_factory: CarFactory::new(), } } pub fn add_car( &mut self, license_plate: &str, parking_place_number: u8, body: Body, colour: Colour, ) { self.cars.push(Car::new( license_plate.to_string(), parking_place_number, self.car_factory.get_car_type_id(body, colour), )); } pub fn print(&mut self)
}
{ for car in &self.cars { car.print(self.car_factory.get_car_type(car.car_type_id).unwrap()); } println!("\nNumber of cars: {}", self.cars.len()); self.car_factory.print(); }
identifier_body
glcommon.rs
use core::prelude::*; use opengles::gl2; use opengles::gl2::{GLuint, GLint}; use core::borrow::{Cow, IntoCow}; use collections::string::String; pub type GLResult<T> = Result<T, MString>; pub type MString = Cow<'static, String, str>; fn get_gl_error_name(error: u32) -> &'static str { match error { gl2::NO_ERROR => "GL_NO_ERROR", gl2::INVALID_ENUM => "GL_INVALID_ENUM", gl2::INVALID_VALUE => "GL_INVALID_VALUE", gl2::INVALID_OPERATION => "GL_INVALID_OPERATION", gl2::INVALID_FRAMEBUFFER_OPERATION => "GL_INVALID_FRAMEBUFFER_OPERATION", gl2::OUT_OF_MEMORY => "GL_OUT_OF_MEMORY", _ => "unknown error!", } } pub fn check_gl_error(name: &str) { loop { match gl2::get_error() { 0 => break, error => logi!("after {} glError (0x{}): {}\n", name, error, get_gl_error_name(error)), } } } #[allow(dead_code)] pub fn check_framebuffer_complete() -> bool { let (err, result) = match gl2::check_framebuffer_status(gl2::FRAMEBUFFER) { gl2::FRAMEBUFFER_COMPLETE => ("FRAMEBUFFER_COMPLETE", true), gl2::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_ATTACHMENT", false), gl2::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", false), gl2::FRAMEBUFFER_INCOMPLETE_DIMENSIONS => ("FRAMEBUFFER_INCOMPLETE_DIMENSIONS", false), gl2::FRAMEBUFFER_UNSUPPORTED => ("FRAMEBUFFER_UNSUPPORTED", false), _ => ("unknown error!", false) }; debug_logi!("framebuffer status: {}", err); result } pub fn load_shader(shader_type: gl2::GLenum, source: &str) -> GLResult<GLuint> { let shader = gl2::create_shader(shader_type); if shader!= 0 { gl2::shader_source(shader, [source.as_bytes()].as_slice()); gl2::compile_shader(shader); let compiled = gl2::get_shader_iv(shader, gl2::COMPILE_STATUS); if compiled!= 0 { Ok(shader) } else { let log = gl2::get_shader_info_log(shader).into_cow(); loge!("Could not compile shader {}:\n{}\n", shader_type, log); gl2::delete_shader(shader); Err(log) } } else { Err(format!("Unknown error initializing shader type {}", shader_type).into_cow()) } } pub fn create_program(vertex_source: &str, fragment_source: &str) -> GLResult<GLuint> { let vert_shader = try!(load_shader(gl2::VERTEX_SHADER, vertex_source)); let pixel_shader = try!(load_shader(gl2::FRAGMENT_SHADER, fragment_source)); let program = gl2::create_program(); if program == 0 { return Err("Unknown error creating shader program".into_cow()); } gl2::attach_shader(program, vert_shader); check_gl_error("glAttachShader"); gl2::attach_shader(program, pixel_shader); check_gl_error("glAttachShader"); gl2::link_program(program); if gl2::get_program_iv(program, gl2::LINK_STATUS) as u8 == gl2::TRUE { Ok(program) } else { let log = gl2::get_program_info_log(program).into_cow(); loge!("Could not link program: \n{}\n", log); gl2::delete_program(program); Err(log) } } pub fn get_shader_handle(program: GLuint, name: &str) -> Option<GLuint> { let handle = gl2::get_attrib_location(program, name); check_gl_error(format!("get_shader_handle({})", name).as_slice()); if handle == -1 { None } else { Some(handle as GLuint) } } /// gl silently ignores writes to uniform -1, so this is not strictly necessary pub fn get_uniform_handle_option(program: GLuint, name: &str) -> Option<GLint> { let handle = gl2::get_uniform_location(program, name); check_gl_error(format!("get_uniform_handle({})", name).as_slice()); if handle == -1 { None } else { Some(handle) } } pub trait Shader { fn new(vertopt: MString, fragopt: MString) -> GLResult<Self>; } pub struct Defaults<Init> { pub val: Init } pub trait FillDefaults<Init> { type Unfilled; fn fill_defaults(unfilled: <Self as FillDefaults<Init>>::Unfilled) -> Defaults<Init>; } pub trait UsingDefaults<Init> { type Defaults; //fn fill_defaults(Init) -> <Self as UsingDefaults<Init>>::Defaults; fn maybe_init(Init) -> GLResult<Self>; fn get_source(&self) -> &<Self as UsingDefaults<Init>>::Defaults; } pub trait UsingDefaultsSafe { } macro_rules! glattrib_f32 ( // struct elements ($handle:expr, $count:expr, $item:ident, $elem:ident) => ({ unsafe { // XXX probably also unsafe let firstref = $item.get_unchecked(0);
gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean, mem::size_of_val(firstref) as i32, // XXX this actually derefences firstref and is completely unsafe // is there better way to do offsetof in rust? there ought to be mem::transmute(&firstref.$elem)); } check_gl_error(stringify!(vertex_attrib_pointer($elem))); gl2::enable_vertex_attrib_array($handle); check_gl_error("enable_vertex_array"); }); // densely-packed array ($handle:expr, $count:expr, $item:ident) => ({ unsafe { let firstref = $item.get_unchecked(0) ; gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean, 0, mem::transmute(firstref)); } check_gl_error(stringify!(vertex_attrib_pointer($handle))); gl2::enable_vertex_attrib_array($handle); check_gl_error("enable_vertex_array"); }); ); macro_rules! gl_bindtexture ( ($texunit:expr, $kind:expr, $texture:expr, $handle:expr) => ({ gl2::active_texture(gl2::TEXTURE0 + $texunit); check_gl_error(stringify!(active_texture($texture))); gl2::bind_texture($kind, $texture); check_gl_error(stringify!(bind_texture($texture))); gl2::uniform_1i($handle, $texunit); check_gl_error(stringify!(uniform1i($texture))); }); );
random_line_split
glcommon.rs
use core::prelude::*; use opengles::gl2; use opengles::gl2::{GLuint, GLint}; use core::borrow::{Cow, IntoCow}; use collections::string::String; pub type GLResult<T> = Result<T, MString>; pub type MString = Cow<'static, String, str>; fn get_gl_error_name(error: u32) -> &'static str { match error { gl2::NO_ERROR => "GL_NO_ERROR", gl2::INVALID_ENUM => "GL_INVALID_ENUM", gl2::INVALID_VALUE => "GL_INVALID_VALUE", gl2::INVALID_OPERATION => "GL_INVALID_OPERATION", gl2::INVALID_FRAMEBUFFER_OPERATION => "GL_INVALID_FRAMEBUFFER_OPERATION", gl2::OUT_OF_MEMORY => "GL_OUT_OF_MEMORY", _ => "unknown error!", } } pub fn check_gl_error(name: &str) { loop { match gl2::get_error() { 0 => break, error => logi!("after {} glError (0x{}): {}\n", name, error, get_gl_error_name(error)), } } } #[allow(dead_code)] pub fn check_framebuffer_complete() -> bool { let (err, result) = match gl2::check_framebuffer_status(gl2::FRAMEBUFFER) { gl2::FRAMEBUFFER_COMPLETE => ("FRAMEBUFFER_COMPLETE", true), gl2::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_ATTACHMENT", false), gl2::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", false), gl2::FRAMEBUFFER_INCOMPLETE_DIMENSIONS => ("FRAMEBUFFER_INCOMPLETE_DIMENSIONS", false), gl2::FRAMEBUFFER_UNSUPPORTED => ("FRAMEBUFFER_UNSUPPORTED", false), _ => ("unknown error!", false) }; debug_logi!("framebuffer status: {}", err); result } pub fn load_shader(shader_type: gl2::GLenum, source: &str) -> GLResult<GLuint> { let shader = gl2::create_shader(shader_type); if shader!= 0 { gl2::shader_source(shader, [source.as_bytes()].as_slice()); gl2::compile_shader(shader); let compiled = gl2::get_shader_iv(shader, gl2::COMPILE_STATUS); if compiled!= 0 { Ok(shader) } else { let log = gl2::get_shader_info_log(shader).into_cow(); loge!("Could not compile shader {}:\n{}\n", shader_type, log); gl2::delete_shader(shader); Err(log) } } else { Err(format!("Unknown error initializing shader type {}", shader_type).into_cow()) } } pub fn create_program(vertex_source: &str, fragment_source: &str) -> GLResult<GLuint> { let vert_shader = try!(load_shader(gl2::VERTEX_SHADER, vertex_source)); let pixel_shader = try!(load_shader(gl2::FRAGMENT_SHADER, fragment_source)); let program = gl2::create_program(); if program == 0 { return Err("Unknown error creating shader program".into_cow()); } gl2::attach_shader(program, vert_shader); check_gl_error("glAttachShader"); gl2::attach_shader(program, pixel_shader); check_gl_error("glAttachShader"); gl2::link_program(program); if gl2::get_program_iv(program, gl2::LINK_STATUS) as u8 == gl2::TRUE { Ok(program) } else { let log = gl2::get_program_info_log(program).into_cow(); loge!("Could not link program: \n{}\n", log); gl2::delete_program(program); Err(log) } } pub fn get_shader_handle(program: GLuint, name: &str) -> Option<GLuint> { let handle = gl2::get_attrib_location(program, name); check_gl_error(format!("get_shader_handle({})", name).as_slice()); if handle == -1 { None } else { Some(handle as GLuint) } } /// gl silently ignores writes to uniform -1, so this is not strictly necessary pub fn get_uniform_handle_option(program: GLuint, name: &str) -> Option<GLint> { let handle = gl2::get_uniform_location(program, name); check_gl_error(format!("get_uniform_handle({})", name).as_slice()); if handle == -1 { None } else { Some(handle) } } pub trait Shader { fn new(vertopt: MString, fragopt: MString) -> GLResult<Self>; } pub struct
<Init> { pub val: Init } pub trait FillDefaults<Init> { type Unfilled; fn fill_defaults(unfilled: <Self as FillDefaults<Init>>::Unfilled) -> Defaults<Init>; } pub trait UsingDefaults<Init> { type Defaults; //fn fill_defaults(Init) -> <Self as UsingDefaults<Init>>::Defaults; fn maybe_init(Init) -> GLResult<Self>; fn get_source(&self) -> &<Self as UsingDefaults<Init>>::Defaults; } pub trait UsingDefaultsSafe { } macro_rules! glattrib_f32 ( // struct elements ($handle:expr, $count:expr, $item:ident, $elem:ident) => ({ unsafe { // XXX probably also unsafe let firstref = $item.get_unchecked(0); gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean, mem::size_of_val(firstref) as i32, // XXX this actually derefences firstref and is completely unsafe // is there better way to do offsetof in rust? there ought to be mem::transmute(&firstref.$elem)); } check_gl_error(stringify!(vertex_attrib_pointer($elem))); gl2::enable_vertex_attrib_array($handle); check_gl_error("enable_vertex_array"); }); // densely-packed array ($handle:expr, $count:expr, $item:ident) => ({ unsafe { let firstref = $item.get_unchecked(0) ; gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean, 0, mem::transmute(firstref)); } check_gl_error(stringify!(vertex_attrib_pointer($handle))); gl2::enable_vertex_attrib_array($handle); check_gl_error("enable_vertex_array"); }); ); macro_rules! gl_bindtexture ( ($texunit:expr, $kind:expr, $texture:expr, $handle:expr) => ({ gl2::active_texture(gl2::TEXTURE0 + $texunit); check_gl_error(stringify!(active_texture($texture))); gl2::bind_texture($kind, $texture); check_gl_error(stringify!(bind_texture($texture))); gl2::uniform_1i($handle, $texunit); check_gl_error(stringify!(uniform1i($texture))); }); );
Defaults
identifier_name
glcommon.rs
use core::prelude::*; use opengles::gl2; use opengles::gl2::{GLuint, GLint}; use core::borrow::{Cow, IntoCow}; use collections::string::String; pub type GLResult<T> = Result<T, MString>; pub type MString = Cow<'static, String, str>; fn get_gl_error_name(error: u32) -> &'static str { match error { gl2::NO_ERROR => "GL_NO_ERROR", gl2::INVALID_ENUM => "GL_INVALID_ENUM", gl2::INVALID_VALUE => "GL_INVALID_VALUE", gl2::INVALID_OPERATION => "GL_INVALID_OPERATION", gl2::INVALID_FRAMEBUFFER_OPERATION => "GL_INVALID_FRAMEBUFFER_OPERATION", gl2::OUT_OF_MEMORY => "GL_OUT_OF_MEMORY", _ => "unknown error!", } } pub fn check_gl_error(name: &str) { loop { match gl2::get_error() { 0 => break, error => logi!("after {} glError (0x{}): {}\n", name, error, get_gl_error_name(error)), } } } #[allow(dead_code)] pub fn check_framebuffer_complete() -> bool
pub fn load_shader(shader_type: gl2::GLenum, source: &str) -> GLResult<GLuint> { let shader = gl2::create_shader(shader_type); if shader!= 0 { gl2::shader_source(shader, [source.as_bytes()].as_slice()); gl2::compile_shader(shader); let compiled = gl2::get_shader_iv(shader, gl2::COMPILE_STATUS); if compiled!= 0 { Ok(shader) } else { let log = gl2::get_shader_info_log(shader).into_cow(); loge!("Could not compile shader {}:\n{}\n", shader_type, log); gl2::delete_shader(shader); Err(log) } } else { Err(format!("Unknown error initializing shader type {}", shader_type).into_cow()) } } pub fn create_program(vertex_source: &str, fragment_source: &str) -> GLResult<GLuint> { let vert_shader = try!(load_shader(gl2::VERTEX_SHADER, vertex_source)); let pixel_shader = try!(load_shader(gl2::FRAGMENT_SHADER, fragment_source)); let program = gl2::create_program(); if program == 0 { return Err("Unknown error creating shader program".into_cow()); } gl2::attach_shader(program, vert_shader); check_gl_error("glAttachShader"); gl2::attach_shader(program, pixel_shader); check_gl_error("glAttachShader"); gl2::link_program(program); if gl2::get_program_iv(program, gl2::LINK_STATUS) as u8 == gl2::TRUE { Ok(program) } else { let log = gl2::get_program_info_log(program).into_cow(); loge!("Could not link program: \n{}\n", log); gl2::delete_program(program); Err(log) } } pub fn get_shader_handle(program: GLuint, name: &str) -> Option<GLuint> { let handle = gl2::get_attrib_location(program, name); check_gl_error(format!("get_shader_handle({})", name).as_slice()); if handle == -1 { None } else { Some(handle as GLuint) } } /// gl silently ignores writes to uniform -1, so this is not strictly necessary pub fn get_uniform_handle_option(program: GLuint, name: &str) -> Option<GLint> { let handle = gl2::get_uniform_location(program, name); check_gl_error(format!("get_uniform_handle({})", name).as_slice()); if handle == -1 { None } else { Some(handle) } } pub trait Shader { fn new(vertopt: MString, fragopt: MString) -> GLResult<Self>; } pub struct Defaults<Init> { pub val: Init } pub trait FillDefaults<Init> { type Unfilled; fn fill_defaults(unfilled: <Self as FillDefaults<Init>>::Unfilled) -> Defaults<Init>; } pub trait UsingDefaults<Init> { type Defaults; //fn fill_defaults(Init) -> <Self as UsingDefaults<Init>>::Defaults; fn maybe_init(Init) -> GLResult<Self>; fn get_source(&self) -> &<Self as UsingDefaults<Init>>::Defaults; } pub trait UsingDefaultsSafe { } macro_rules! glattrib_f32 ( // struct elements ($handle:expr, $count:expr, $item:ident, $elem:ident) => ({ unsafe { // XXX probably also unsafe let firstref = $item.get_unchecked(0); gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean, mem::size_of_val(firstref) as i32, // XXX this actually derefences firstref and is completely unsafe // is there better way to do offsetof in rust? there ought to be mem::transmute(&firstref.$elem)); } check_gl_error(stringify!(vertex_attrib_pointer($elem))); gl2::enable_vertex_attrib_array($handle); check_gl_error("enable_vertex_array"); }); // densely-packed array ($handle:expr, $count:expr, $item:ident) => ({ unsafe { let firstref = $item.get_unchecked(0) ; gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean, 0, mem::transmute(firstref)); } check_gl_error(stringify!(vertex_attrib_pointer($handle))); gl2::enable_vertex_attrib_array($handle); check_gl_error("enable_vertex_array"); }); ); macro_rules! gl_bindtexture ( ($texunit:expr, $kind:expr, $texture:expr, $handle:expr) => ({ gl2::active_texture(gl2::TEXTURE0 + $texunit); check_gl_error(stringify!(active_texture($texture))); gl2::bind_texture($kind, $texture); check_gl_error(stringify!(bind_texture($texture))); gl2::uniform_1i($handle, $texunit); check_gl_error(stringify!(uniform1i($texture))); }); );
{ let (err, result) = match gl2::check_framebuffer_status(gl2::FRAMEBUFFER) { gl2::FRAMEBUFFER_COMPLETE => ("FRAMEBUFFER_COMPLETE", true), gl2::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_ATTACHMENT", false), gl2::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", false), gl2::FRAMEBUFFER_INCOMPLETE_DIMENSIONS => ("FRAMEBUFFER_INCOMPLETE_DIMENSIONS", false), gl2::FRAMEBUFFER_UNSUPPORTED => ("FRAMEBUFFER_UNSUPPORTED", false), _ => ("unknown error!", false) }; debug_logi!("framebuffer status: {}", err); result }
identifier_body
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session pub fn new() -> Box<Self> { box Session { items: Vec::new(), } } pub unsafe fn
(&mut self, irq: u8) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_irq(irq); } scheduler::end_no_ints(reenable); } pub unsafe fn on_poll(&mut self) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_poll(); } scheduler::end_no_ints(reenable); } /// Open a new resource pub fn open(&mut self, url: &Url, flags: usize) -> Option<Box<Resource>> { if url.scheme().len() == 0 { let mut list = String::new(); for item in self.items.iter() { let scheme = item.scheme(); if!scheme.is_empty() { if!list.is_empty() { list = list + "\n" + scheme; } else { list = scheme.to_string(); } } } Some(box VecResource::new(Url::new(), list.into_bytes())) } else { for mut item in self.items.iter_mut() { if item.scheme() == url.scheme() { return item.open(url, flags); } } None } } }
on_irq
identifier_name
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session
pub fn new() -> Box<Self> { box Session { items: Vec::new(), } } pub unsafe fn on_irq(&mut self, irq: u8) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_irq(irq); } scheduler::end_no_ints(reenable); } pub unsafe fn on_poll(&mut self) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_poll(); } scheduler::end_no_ints(reenable); } /// Open a new resource pub fn open(&mut self, url: &Url, flags: usize) -> Option<Box<Resource>> { if url.scheme().len() == 0 { let mut list = String::new(); for item in self.items.iter() { let scheme = item.scheme(); if!scheme.is_empty() { if!list.is_empty() { list = list + "\n" + scheme; } else { list = scheme.to_string(); } } } Some(box VecResource::new(Url::new(), list.into_bytes())) } else { for mut item in self.items.iter_mut() { if item.scheme() == url.scheme() { return item.open(url, flags); } } None } } }
random_line_split
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session pub fn new() -> Box<Self> { box Session { items: Vec::new(), } } pub unsafe fn on_irq(&mut self, irq: u8) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_irq(irq); } scheduler::end_no_ints(reenable); } pub unsafe fn on_poll(&mut self) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_poll(); } scheduler::end_no_ints(reenable); } /// Open a new resource pub fn open(&mut self, url: &Url, flags: usize) -> Option<Box<Resource>>
} } None } } }
{ if url.scheme().len() == 0 { let mut list = String::new(); for item in self.items.iter() { let scheme = item.scheme(); if !scheme.is_empty() { if !list.is_empty() { list = list + "\n" + scheme; } else { list = scheme.to_string(); } } } Some(box VecResource::new(Url::new(), list.into_bytes())) } else { for mut item in self.items.iter_mut() { if item.scheme() == url.scheme() { return item.open(url, flags);
identifier_body
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session pub fn new() -> Box<Self> { box Session { items: Vec::new(), } } pub unsafe fn on_irq(&mut self, irq: u8) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_irq(irq); } scheduler::end_no_ints(reenable); } pub unsafe fn on_poll(&mut self) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_poll(); } scheduler::end_no_ints(reenable); } /// Open a new resource pub fn open(&mut self, url: &Url, flags: usize) -> Option<Box<Resource>> { if url.scheme().len() == 0
else { for mut item in self.items.iter_mut() { if item.scheme() == url.scheme() { return item.open(url, flags); } } None } } }
{ let mut list = String::new(); for item in self.items.iter() { let scheme = item.scheme(); if !scheme.is_empty() { if !list.is_empty() { list = list + "\n" + scheme; } else { list = scheme.to_string(); } } } Some(box VecResource::new(Url::new(), list.into_bytes())) }
conditional_block
issue-9446.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. // run-pass struct
(String); impl Wrapper { pub fn new(wrapped: String) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_string()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-box ty Wrapper::new("Bob".to_string()).say_hi(); } }
Wrapper
identifier_name
issue-9446.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. // run-pass struct Wrapper(String); impl Wrapper { pub fn new(wrapped: String) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) {
impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_string()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-box ty Wrapper::new("Bob".to_string()).say_hi(); } }
let Wrapper(ref s) = *self; println!("hello {}", *s); } }
random_line_split
issue-9446.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. // run-pass struct Wrapper(String); impl Wrapper { pub fn new(wrapped: String) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self)
} pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_string()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-box ty Wrapper::new("Bob".to_string()).say_hi(); } }
{}
identifier_body
htmlhrelement.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 crate::dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, LayoutDom}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{Element, RawLayoutElementHelpers}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use crate::dom::virtualmethods::VirtualMethods; use cssparser::RGBA; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; #[dom_struct]
} impl HTMLHRElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLHRElement { HTMLHRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLHRElement> { Node::reflect_node( Box::new(HTMLHRElement::new_inherited(local_name, prefix, document)), document, HTMLHRElementBinding::Wrap, ) } } impl HTMLHRElementMethods for HTMLHRElement { // https://html.spec.whatwg.org/multipage/#dom-hr-align make_getter!(Align, "align"); // https://html.spec.whatwg.org/multipage/#dom-hr-align make_atomic_setter!(SetAlign, "align"); // https://html.spec.whatwg.org/multipage/#dom-hr-color make_getter!(Color, "color"); // https://html.spec.whatwg.org/multipage/#dom-hr-color make_legacy_color_setter!(SetColor, "color"); // https://html.spec.whatwg.org/multipage/#dom-hr-width make_getter!(Width, "width"); // https://html.spec.whatwg.org/multipage/#dom-hr-width make_dimension_setter!(SetWidth, "width"); } pub trait HTMLHRLayoutHelpers { fn get_color(&self) -> Option<RGBA>; fn get_width(&self) -> LengthOrPercentageOrAuto; } impl HTMLHRLayoutHelpers for LayoutDom<HTMLHRElement> { #[allow(unsafe_code)] fn get_color(&self) -> Option<RGBA> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("color")) .and_then(AttrValue::as_color) .cloned() } } #[allow(unsafe_code)] fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_dimension) .cloned() .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl VirtualMethods for HTMLHRElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("align") => AttrValue::from_dimension(value.into()), &local_name!("color") => AttrValue::from_legacy_color(value.into()), &local_name!("width") => AttrValue::from_dimension(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(name, value), } } }
pub struct HTMLHRElement { htmlelement: HTMLElement,
random_line_split
htmlhrelement.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 crate::dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, LayoutDom}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{Element, RawLayoutElementHelpers}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use crate::dom::virtualmethods::VirtualMethods; use cssparser::RGBA; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; #[dom_struct] pub struct HTMLHRElement { htmlelement: HTMLElement, } impl HTMLHRElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLHRElement { HTMLHRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLHRElement> { Node::reflect_node( Box::new(HTMLHRElement::new_inherited(local_name, prefix, document)), document, HTMLHRElementBinding::Wrap, ) } } impl HTMLHRElementMethods for HTMLHRElement { // https://html.spec.whatwg.org/multipage/#dom-hr-align make_getter!(Align, "align"); // https://html.spec.whatwg.org/multipage/#dom-hr-align make_atomic_setter!(SetAlign, "align"); // https://html.spec.whatwg.org/multipage/#dom-hr-color make_getter!(Color, "color"); // https://html.spec.whatwg.org/multipage/#dom-hr-color make_legacy_color_setter!(SetColor, "color"); // https://html.spec.whatwg.org/multipage/#dom-hr-width make_getter!(Width, "width"); // https://html.spec.whatwg.org/multipage/#dom-hr-width make_dimension_setter!(SetWidth, "width"); } pub trait HTMLHRLayoutHelpers { fn get_color(&self) -> Option<RGBA>; fn get_width(&self) -> LengthOrPercentageOrAuto; } impl HTMLHRLayoutHelpers for LayoutDom<HTMLHRElement> { #[allow(unsafe_code)] fn get_color(&self) -> Option<RGBA> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("color")) .and_then(AttrValue::as_color) .cloned() } } #[allow(unsafe_code)] fn
(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_dimension) .cloned() .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl VirtualMethods for HTMLHRElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("align") => AttrValue::from_dimension(value.into()), &local_name!("color") => AttrValue::from_legacy_color(value.into()), &local_name!("width") => AttrValue::from_dimension(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(name, value), } } }
get_width
identifier_name
extern-call-scrub.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. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions extern crate libc; use std::thread::Thread; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1 { data } else { count(data - 1) + count(data - 1) } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) let _t = Thread::spawn(move|| { let result = count(12); println!("result = {}", result); assert_eq!(result, 2048);
}
});
random_line_split
extern-call-scrub.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. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions extern crate libc; use std::thread::Thread; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1
else { count(data - 1) + count(data - 1) } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) let _t = Thread::spawn(move|| { let result = count(12); println!("result = {}", result); assert_eq!(result, 2048); }); }
{ data }
conditional_block
extern-call-scrub.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. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions extern crate libc; use std::thread::Thread; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1 { data } else { count(data - 1) + count(data - 1) } } fn
(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) let _t = Thread::spawn(move|| { let result = count(12); println!("result = {}", result); assert_eq!(result, 2048); }); }
count
identifier_name
extern-call-scrub.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. // This time we're testing repeatedly going up and down both stacks to // make sure the stack pointers are maintained properly in both // directions extern crate libc; use std::thread::Thread; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t
fn count(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) let _t = Thread::spawn(move|| { let result = count(12); println!("result = {}", result); assert_eq!(result, 2048); }); }
{ if data == 1 { data } else { count(data - 1) + count(data - 1) } }
identifier_body
background.rs
use super::SkewTContext; use crate::{ app::config::{self}, coords::TPCoords, gui::DrawingArgs, }; use metfor::{Celsius, CelsiusDiff, HectoPascal, Quantity}; impl SkewTContext { pub fn draw_clear_background(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.background_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); const MINT: Celsius = Celsius(-160.0); const MAXT: Celsius = Celsius(100.0); self.draw_temperature_band(MINT, MAXT, args); } pub fn draw_temperature_banding(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.background_band_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); let mut start_line = -160i32; while start_line < 100 { let t1 = Celsius(f64::from(start_line)); let t2 = t1 + CelsiusDiff(10.0); self.draw_temperature_band(t1, t2, args); start_line += 20; } } pub fn draw_hail_growth_zone(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.hail_zone_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); self.draw_temperature_band(Celsius(-30.0), Celsius(-10.0), args); } pub fn draw_dendtritic_growth_zone(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.dendritic_zone_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); self.draw_temperature_band(Celsius(-18.0), Celsius(-12.0), args); } fn draw_temperature_band(&self, cold_t: Celsius, warm_t: Celsius, args: DrawingArgs<'_, '_>) { let cr = args.cr; // Assume color has already been set up for us. const MAXP: HectoPascal = config::MAXP; const MINP: HectoPascal = config::MINP; let mut coords = [ (warm_t.unpack(), MAXP.unpack()), (warm_t.unpack(), MINP.unpack()), (cold_t.unpack(), MINP.unpack()), (cold_t.unpack(), MAXP.unpack()), ]; // Convert points to screen coords for coord in &mut coords { let screen_coords = self.convert_tp_to_screen(TPCoords { temperature: Celsius(coord.0), pressure: HectoPascal(coord.1), }); coord.0 = screen_coords.x; coord.1 = screen_coords.y; } let mut coord_iter = coords.iter(); for coord in coord_iter.by_ref().take(1) { cr.move_to(coord.0, coord.1); } for coord in coord_iter { cr.line_to(coord.0, coord.1);
} }
} cr.close_path(); cr.fill().unwrap();
random_line_split
background.rs
use super::SkewTContext; use crate::{ app::config::{self}, coords::TPCoords, gui::DrawingArgs, }; use metfor::{Celsius, CelsiusDiff, HectoPascal, Quantity}; impl SkewTContext { pub fn draw_clear_background(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.background_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); const MINT: Celsius = Celsius(-160.0); const MAXT: Celsius = Celsius(100.0); self.draw_temperature_band(MINT, MAXT, args); } pub fn draw_temperature_banding(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.background_band_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); let mut start_line = -160i32; while start_line < 100 { let t1 = Celsius(f64::from(start_line)); let t2 = t1 + CelsiusDiff(10.0); self.draw_temperature_band(t1, t2, args); start_line += 20; } } pub fn draw_hail_growth_zone(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.hail_zone_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); self.draw_temperature_band(Celsius(-30.0), Celsius(-10.0), args); } pub fn draw_dendtritic_growth_zone(&self, args: DrawingArgs<'_, '_>)
fn draw_temperature_band(&self, cold_t: Celsius, warm_t: Celsius, args: DrawingArgs<'_, '_>) { let cr = args.cr; // Assume color has already been set up for us. const MAXP: HectoPascal = config::MAXP; const MINP: HectoPascal = config::MINP; let mut coords = [ (warm_t.unpack(), MAXP.unpack()), (warm_t.unpack(), MINP.unpack()), (cold_t.unpack(), MINP.unpack()), (cold_t.unpack(), MAXP.unpack()), ]; // Convert points to screen coords for coord in &mut coords { let screen_coords = self.convert_tp_to_screen(TPCoords { temperature: Celsius(coord.0), pressure: HectoPascal(coord.1), }); coord.0 = screen_coords.x; coord.1 = screen_coords.y; } let mut coord_iter = coords.iter(); for coord in coord_iter.by_ref().take(1) { cr.move_to(coord.0, coord.1); } for coord in coord_iter { cr.line_to(coord.0, coord.1); } cr.close_path(); cr.fill().unwrap(); } }
{ let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.dendritic_zone_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); self.draw_temperature_band(Celsius(-18.0), Celsius(-12.0), args); }
identifier_body
background.rs
use super::SkewTContext; use crate::{ app::config::{self}, coords::TPCoords, gui::DrawingArgs, }; use metfor::{Celsius, CelsiusDiff, HectoPascal, Quantity}; impl SkewTContext { pub fn draw_clear_background(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.background_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); const MINT: Celsius = Celsius(-160.0); const MAXT: Celsius = Celsius(100.0); self.draw_temperature_band(MINT, MAXT, args); } pub fn draw_temperature_banding(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.background_band_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); let mut start_line = -160i32; while start_line < 100 { let t1 = Celsius(f64::from(start_line)); let t2 = t1 + CelsiusDiff(10.0); self.draw_temperature_band(t1, t2, args); start_line += 20; } } pub fn draw_hail_growth_zone(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.hail_zone_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); self.draw_temperature_band(Celsius(-30.0), Celsius(-10.0), args); } pub fn draw_dendtritic_growth_zone(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.dendritic_zone_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); self.draw_temperature_band(Celsius(-18.0), Celsius(-12.0), args); } fn
(&self, cold_t: Celsius, warm_t: Celsius, args: DrawingArgs<'_, '_>) { let cr = args.cr; // Assume color has already been set up for us. const MAXP: HectoPascal = config::MAXP; const MINP: HectoPascal = config::MINP; let mut coords = [ (warm_t.unpack(), MAXP.unpack()), (warm_t.unpack(), MINP.unpack()), (cold_t.unpack(), MINP.unpack()), (cold_t.unpack(), MAXP.unpack()), ]; // Convert points to screen coords for coord in &mut coords { let screen_coords = self.convert_tp_to_screen(TPCoords { temperature: Celsius(coord.0), pressure: HectoPascal(coord.1), }); coord.0 = screen_coords.x; coord.1 = screen_coords.y; } let mut coord_iter = coords.iter(); for coord in coord_iter.by_ref().take(1) { cr.move_to(coord.0, coord.1); } for coord in coord_iter { cr.line_to(coord.0, coord.1); } cr.close_path(); cr.fill().unwrap(); } }
draw_temperature_band
identifier_name
asm.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. /* * Inline assembly support. */ use self::State::*; use ast; use codemap; use codemap::Span; use ext::base; use ext::base::*; use parse::token::InternedString; use parse::token; use ptr::P; enum State { Asm, Outputs, Inputs, Clobbers, Options, StateNone } impl State { fn
(&self) -> State { match *self { Asm => Outputs, Outputs => Inputs, Inputs => Clobbers, Clobbers => Options, Options => StateNone, StateNone => StateNone } } } static OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"]; pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let mut p = cx.new_parser_from_tts(tts); let mut asm = InternedString::new(""); let mut asm_str_style = None; let mut outputs = Vec::new(); let mut inputs = Vec::new(); let mut clobs = Vec::new(); let mut volatile = false; let mut alignstack = false; let mut dialect = ast::AsmAtt; let mut state = Asm; 'statement: loop { match state { Asm => { let (s, style) = match expr_to_string(cx, p.parse_expr(), "inline assembly must be a string literal") { Some((s, st)) => (s, st), // let compilation continue None => return DummyResult::expr(sp), }; asm = s; asm_str_style = Some(style); } Outputs => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if outputs.len()!= 0 { p.eat(&token::Comma); } let (constraint, _str_style) = p.parse_str(); let span = p.last_span; p.expect(&token::OpenDelim(token::Paren)); let out = p.parse_expr(); p.expect(&token::CloseDelim(token::Paren)); // Expands a read+write operand into two operands. // // Use '+' modifier when you want the same expression // to be both an input and an output at the same time. // It's the opposite of '=&' which means that the memory // cannot be shared with any other operand (usually when // a register is clobbered early.) let output = match constraint.get().slice_shift_char() { Some(('=', _)) => None, Some(('+', operand)) => { Some(token::intern_and_get_ident(format!( "={}", operand).as_slice())) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); None } }; let is_rw = output.is_some(); outputs.push((output.unwrap_or(constraint), out, is_rw)); } } Inputs => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if inputs.len()!= 0 { p.eat(&token::Comma); } let (constraint, _str_style) = p.parse_str(); if constraint.get().starts_with("=") { cx.span_err(p.last_span, "input operand constraint contains '='"); } else if constraint.get().starts_with("+") { cx.span_err(p.last_span, "input operand constraint contains '+'"); } p.expect(&token::OpenDelim(token::Paren)); let input = p.parse_expr(); p.expect(&token::CloseDelim(token::Paren)); inputs.push((constraint, input)); } } Clobbers => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if clobs.len()!= 0 { p.eat(&token::Comma); } let (s, _str_style) = p.parse_str(); if OPTIONS.iter().any(|opt| s.equiv(opt)) { cx.span_warn(p.last_span, "expected a clobber, found an option"); } clobs.push(s); } } Options => { let (option, _str_style) = p.parse_str(); if option.equiv(&("volatile")) { // Indicates that the inline assembly has side effects // and must not be optimized out along with its outputs. volatile = true; } else if option.equiv(&("alignstack")) { alignstack = true; } else if option.equiv(&("intel")) { dialect = ast::AsmIntel; } else { cx.span_warn(p.last_span, "unrecognized option"); } if p.token == token::Comma { p.eat(&token::Comma); } } StateNone => () } loop { // MOD_SEP is a double colon '::' without space in between. // When encountered, the state must be advanced twice. match (&p.token, state.next(), state.next().next()) { (&token::Colon, StateNone, _) | (&token::ModSep, _, StateNone) => { p.bump(); break'statement; } (&token::Colon, st, _) | (&token::ModSep, _, st) => { p.bump(); state = st; } (&token::Eof, _, _) => break'statement, _ => break } } } let expn_id = cx.codemap().record_expansion(codemap::ExpnInfo { call_site: sp, callee: codemap::NameAndSpan { name: "asm".to_string(), format: codemap::MacroBang, span: None, }, }); MacExpr::new(P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprInlineAsm(ast::InlineAsm { asm: token::intern_and_get_ident(asm.get()), asm_str_style: asm_str_style.unwrap(), outputs: outputs, inputs: inputs, clobbers: clobs, volatile: volatile, alignstack: alignstack, dialect: dialect, expn_id: expn_id, }), span: sp })) }
next
identifier_name
asm.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. /* * Inline assembly support. */ use self::State::*; use ast; use codemap; use codemap::Span; use ext::base; use ext::base::*; use parse::token::InternedString; use parse::token; use ptr::P; enum State { Asm, Outputs, Inputs, Clobbers, Options, StateNone } impl State { fn next(&self) -> State { match *self { Asm => Outputs, Outputs => Inputs, Inputs => Clobbers, Clobbers => Options, Options => StateNone, StateNone => StateNone } } } static OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"]; pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let mut p = cx.new_parser_from_tts(tts); let mut asm = InternedString::new(""); let mut asm_str_style = None; let mut outputs = Vec::new(); let mut inputs = Vec::new(); let mut clobs = Vec::new(); let mut volatile = false; let mut alignstack = false; let mut dialect = ast::AsmAtt; let mut state = Asm; 'statement: loop { match state { Asm => { let (s, style) = match expr_to_string(cx, p.parse_expr(), "inline assembly must be a string literal") { Some((s, st)) => (s, st), // let compilation continue None => return DummyResult::expr(sp), }; asm = s; asm_str_style = Some(style); } Outputs => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if outputs.len()!= 0 { p.eat(&token::Comma); }
let span = p.last_span; p.expect(&token::OpenDelim(token::Paren)); let out = p.parse_expr(); p.expect(&token::CloseDelim(token::Paren)); // Expands a read+write operand into two operands. // // Use '+' modifier when you want the same expression // to be both an input and an output at the same time. // It's the opposite of '=&' which means that the memory // cannot be shared with any other operand (usually when // a register is clobbered early.) let output = match constraint.get().slice_shift_char() { Some(('=', _)) => None, Some(('+', operand)) => { Some(token::intern_and_get_ident(format!( "={}", operand).as_slice())) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); None } }; let is_rw = output.is_some(); outputs.push((output.unwrap_or(constraint), out, is_rw)); } } Inputs => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if inputs.len()!= 0 { p.eat(&token::Comma); } let (constraint, _str_style) = p.parse_str(); if constraint.get().starts_with("=") { cx.span_err(p.last_span, "input operand constraint contains '='"); } else if constraint.get().starts_with("+") { cx.span_err(p.last_span, "input operand constraint contains '+'"); } p.expect(&token::OpenDelim(token::Paren)); let input = p.parse_expr(); p.expect(&token::CloseDelim(token::Paren)); inputs.push((constraint, input)); } } Clobbers => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if clobs.len()!= 0 { p.eat(&token::Comma); } let (s, _str_style) = p.parse_str(); if OPTIONS.iter().any(|opt| s.equiv(opt)) { cx.span_warn(p.last_span, "expected a clobber, found an option"); } clobs.push(s); } } Options => { let (option, _str_style) = p.parse_str(); if option.equiv(&("volatile")) { // Indicates that the inline assembly has side effects // and must not be optimized out along with its outputs. volatile = true; } else if option.equiv(&("alignstack")) { alignstack = true; } else if option.equiv(&("intel")) { dialect = ast::AsmIntel; } else { cx.span_warn(p.last_span, "unrecognized option"); } if p.token == token::Comma { p.eat(&token::Comma); } } StateNone => () } loop { // MOD_SEP is a double colon '::' without space in between. // When encountered, the state must be advanced twice. match (&p.token, state.next(), state.next().next()) { (&token::Colon, StateNone, _) | (&token::ModSep, _, StateNone) => { p.bump(); break'statement; } (&token::Colon, st, _) | (&token::ModSep, _, st) => { p.bump(); state = st; } (&token::Eof, _, _) => break'statement, _ => break } } } let expn_id = cx.codemap().record_expansion(codemap::ExpnInfo { call_site: sp, callee: codemap::NameAndSpan { name: "asm".to_string(), format: codemap::MacroBang, span: None, }, }); MacExpr::new(P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprInlineAsm(ast::InlineAsm { asm: token::intern_and_get_ident(asm.get()), asm_str_style: asm_str_style.unwrap(), outputs: outputs, inputs: inputs, clobbers: clobs, volatile: volatile, alignstack: alignstack, dialect: dialect, expn_id: expn_id, }), span: sp })) }
let (constraint, _str_style) = p.parse_str();
random_line_split
asm.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. /* * Inline assembly support. */ use self::State::*; use ast; use codemap; use codemap::Span; use ext::base; use ext::base::*; use parse::token::InternedString; use parse::token; use ptr::P; enum State { Asm, Outputs, Inputs, Clobbers, Options, StateNone } impl State { fn next(&self) -> State
} static OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"]; pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let mut p = cx.new_parser_from_tts(tts); let mut asm = InternedString::new(""); let mut asm_str_style = None; let mut outputs = Vec::new(); let mut inputs = Vec::new(); let mut clobs = Vec::new(); let mut volatile = false; let mut alignstack = false; let mut dialect = ast::AsmAtt; let mut state = Asm; 'statement: loop { match state { Asm => { let (s, style) = match expr_to_string(cx, p.parse_expr(), "inline assembly must be a string literal") { Some((s, st)) => (s, st), // let compilation continue None => return DummyResult::expr(sp), }; asm = s; asm_str_style = Some(style); } Outputs => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if outputs.len()!= 0 { p.eat(&token::Comma); } let (constraint, _str_style) = p.parse_str(); let span = p.last_span; p.expect(&token::OpenDelim(token::Paren)); let out = p.parse_expr(); p.expect(&token::CloseDelim(token::Paren)); // Expands a read+write operand into two operands. // // Use '+' modifier when you want the same expression // to be both an input and an output at the same time. // It's the opposite of '=&' which means that the memory // cannot be shared with any other operand (usually when // a register is clobbered early.) let output = match constraint.get().slice_shift_char() { Some(('=', _)) => None, Some(('+', operand)) => { Some(token::intern_and_get_ident(format!( "={}", operand).as_slice())) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); None } }; let is_rw = output.is_some(); outputs.push((output.unwrap_or(constraint), out, is_rw)); } } Inputs => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if inputs.len()!= 0 { p.eat(&token::Comma); } let (constraint, _str_style) = p.parse_str(); if constraint.get().starts_with("=") { cx.span_err(p.last_span, "input operand constraint contains '='"); } else if constraint.get().starts_with("+") { cx.span_err(p.last_span, "input operand constraint contains '+'"); } p.expect(&token::OpenDelim(token::Paren)); let input = p.parse_expr(); p.expect(&token::CloseDelim(token::Paren)); inputs.push((constraint, input)); } } Clobbers => { while p.token!= token::Eof && p.token!= token::Colon && p.token!= token::ModSep { if clobs.len()!= 0 { p.eat(&token::Comma); } let (s, _str_style) = p.parse_str(); if OPTIONS.iter().any(|opt| s.equiv(opt)) { cx.span_warn(p.last_span, "expected a clobber, found an option"); } clobs.push(s); } } Options => { let (option, _str_style) = p.parse_str(); if option.equiv(&("volatile")) { // Indicates that the inline assembly has side effects // and must not be optimized out along with its outputs. volatile = true; } else if option.equiv(&("alignstack")) { alignstack = true; } else if option.equiv(&("intel")) { dialect = ast::AsmIntel; } else { cx.span_warn(p.last_span, "unrecognized option"); } if p.token == token::Comma { p.eat(&token::Comma); } } StateNone => () } loop { // MOD_SEP is a double colon '::' without space in between. // When encountered, the state must be advanced twice. match (&p.token, state.next(), state.next().next()) { (&token::Colon, StateNone, _) | (&token::ModSep, _, StateNone) => { p.bump(); break'statement; } (&token::Colon, st, _) | (&token::ModSep, _, st) => { p.bump(); state = st; } (&token::Eof, _, _) => break'statement, _ => break } } } let expn_id = cx.codemap().record_expansion(codemap::ExpnInfo { call_site: sp, callee: codemap::NameAndSpan { name: "asm".to_string(), format: codemap::MacroBang, span: None, }, }); MacExpr::new(P(ast::Expr { id: ast::DUMMY_NODE_ID, node: ast::ExprInlineAsm(ast::InlineAsm { asm: token::intern_and_get_ident(asm.get()), asm_str_style: asm_str_style.unwrap(), outputs: outputs, inputs: inputs, clobbers: clobs, volatile: volatile, alignstack: alignstack, dialect: dialect, expn_id: expn_id, }), span: sp })) }
{ match *self { Asm => Outputs, Outputs => Inputs, Inputs => Clobbers, Clobbers => Options, Options => StateNone, StateNone => StateNone } }
identifier_body
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub enum Error { APIClient(api_client::Error), ArtifactIdentMismatch((String, String, String)), /// Occurs when there is no valid toml of json in the environment variable BadEnvConfig(String), BadGlyphStyle(String), CantUploadGossipToml, ChannelNotFound, CryptoKeyError(String), DownloadFailed(String), EditorEnv(env::VarError), EditStatus, FileNameError, /// Occurs when a file that should exist does not or could not be read. FileNotFound(String), GossipFileRelativePath(String), HabitatCore(hcore::Error), InstallHookFailed(PackageIdent), InterpreterNotFound(PackageIdent, Box<Self>), InvalidEventStreamToken(String), InvalidInstallHookMode(String), /// Occurs when making lower level IO calls. IO(io::Error), /// Errors when joining paths :) JoinPathsError(env::JoinPathsError), MissingCLIInputError(String), NamedPipeTimeoutOnStart(String, String, io::Error), NativeTls(native_tls::Error), NetParseError(net::AddrParseError), OfflineArtifactNotFound(PackageIdent), OfflineOriginKeyNotFound(String), OfflinePackageNotFound(PackageIdent), PackageNotFound(String), /// Occurs upon errors related to file or directory permissions. PermissionFailed(String), /// When an error occurs serializing rendering context RenderContextSerialization(serde_json::Error), RootRequired, StatusFileCorrupt(PathBuf), StrFromUtf8Error(str::Utf8Error), StringFromUtf8Error(string::FromUtf8Error), /// When an error occurs registering template file // Boxed due to clippy::large_enum_variant TemplateFileError(Box<handlebars::TemplateFileError>), /// When an error occurs rendering template /// The error is constructed with a handlebars::RenderError's format string instead /// of the handlebars::RenderError itself because the cause field of the /// handlebars::RenderError in the handlebars crate version we use implements send /// and not sync which can lead to upstream compile errors when dealing with the /// failure crate. We should change this to a RenderError after we update the /// handlebars crate. See https://github.com/sunng87/handlebars-rust/issues/194 TemplateRenderError(String), /// When an error occurs merging toml TomlMergeError(String), /// When an error occurs parsing toml TomlParser(toml::de::Error), TomlSerializeError(toml::ser::Error), WireDecode(String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match *self { Error::APIClient(ref err) => format!("{}", err), Error::ArtifactIdentMismatch((ref a, ref ai, ref i)) => { format!("Artifact ident {} for `{}' does not match expected ident {}", ai, a, i) } Error::BadEnvConfig(ref varname) => { format!("Unable to find valid TOML or JSON in {} ENVVAR", varname) } Error::BadGlyphStyle(ref style) => format!("Unknown symbol style '{}'", style), Error::CantUploadGossipToml => { "Can't upload gossip.toml, it's a reserved file name".to_string() } Error::ChannelNotFound => "Channel not found".to_string(), Error::CryptoKeyError(ref s) => format!("Missing or invalid key: {}", s), Error::DownloadFailed(ref msg) => msg.to_string(), Error::EditorEnv(ref e) => format!("Missing EDITOR environment variable: {}", e), Error::EditStatus => "Failed edit text command".to_string(), Error::FileNameError => "Failed to extract a filename".to_string(), Error::FileNotFound(ref e) => format!("File not found at: {}", e), Error::GossipFileRelativePath(ref s) => { format!("Path for gossip file cannot have relative components (eg:..): {}", s) } Error::HabitatCore(ref e) => format!("{}", e), Error::MissingCLIInputError(ref arg) => { format!("Missing required CLI argument!: {}", arg) } Error::InstallHookFailed(ref ident) => { format!("Install hook exited unsuccessfully: {}", ident) } Error::InterpreterNotFound(ref ident, ref e) => { format!("Unable to install interpreter ident: {} - {}", ident, e) } Error::InvalidEventStreamToken(ref s) => { format!("Invalid event stream token provided: '{}'", s) } Error::InvalidInstallHookMode(ref e) => { format!("Invalid InstallHookMode conversion from {}", e) } Error::IO(ref err) => format!("{}", err), Error::JoinPathsError(ref err) => format!("{}", err), Error::NamedPipeTimeoutOnStart(ref group, ref hook, ref err) => { format!("Unable to start powershell named pipe for {} hook of {}: {}", hook, group, err) } Error::NativeTls(ref err) => format!("TLS error '{}'", err), Error::NetParseError(ref err) => format!("{}", err), Error::OfflineArtifactNotFound(ref ident) => { format!("Cached artifact not found in offline mode: {}", ident) } Error::OfflineOriginKeyNotFound(ref name_with_rev) => { format!("Cached origin key not found in offline mode: {}", name_with_rev) } Error::OfflinePackageNotFound(ref ident) => { format!("No installed package or cached artifact could be found locally in \ offline mode: {}", ident) } Error::PackageNotFound(ref e) => format!("Package not found. {}", e), Error::PermissionFailed(ref e) => e.to_string(), Error::RenderContextSerialization(ref e) => { format!("Unable to serialize rendering context, {}", e) } Error::RootRequired => { "Root or administrator permissions required to complete operation".to_string() } Error::StatusFileCorrupt(ref path) => { format!("Unable to decode contents of INSTALL_STATUS file, {}", path.display()) } Error::StrFromUtf8Error(ref e) => format!("{}", e), Error::StringFromUtf8Error(ref e) => format!("{}", e), Error::TemplateFileError(ref err) => format!("{:?}", err), Error::TemplateRenderError(ref err) => err.to_string(), Error::TomlMergeError(ref e) => format!("Failed to merge TOML: {}", e), Error::TomlParser(ref err) => format!("Failed to parse TOML: {}", err), Error::TomlSerializeError(ref e) => format!("Can't serialize TOML: {}", e), Error::WireDecode(ref m) => format!("Failed to decode wire message: {}", m), }; write!(f, "{}", msg) } } impl error::Error for Error {} impl From<api_client::Error> for Error { fn from(err: api_client::Error) -> Self { Error::APIClient(err) } } impl From<handlebars::TemplateFileError> for Error { fn from(err: handlebars::TemplateFileError) -> Self { Error::TemplateFileError(Box::new(err)) } } impl From<hcore::Error> for Error { fn from(err: hcore::Error) -> Self { Error::HabitatCore(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::IO(err) } } impl From<env::JoinPathsError> for Error { fn from(err: env::JoinPathsError) -> Self { Error::JoinPathsError(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self { Error::StrFromUtf8Error(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::StringFromUtf8Error(err) } } impl From<toml::ser::Error> for Error { fn from(err: toml::ser::Error) -> Self { Error::TomlSerializeError(err) } } impl From<net::AddrParseError> for Error { fn
(err: net::AddrParseError) -> Self { Error::NetParseError(err) } } impl From<native_tls::Error> for Error { fn from(error: native_tls::Error) -> Self { Error::NativeTls(error) } }
from
identifier_name
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub enum Error { APIClient(api_client::Error), ArtifactIdentMismatch((String, String, String)), /// Occurs when there is no valid toml of json in the environment variable BadEnvConfig(String), BadGlyphStyle(String), CantUploadGossipToml, ChannelNotFound, CryptoKeyError(String), DownloadFailed(String), EditorEnv(env::VarError), EditStatus, FileNameError, /// Occurs when a file that should exist does not or could not be read. FileNotFound(String), GossipFileRelativePath(String), HabitatCore(hcore::Error), InstallHookFailed(PackageIdent), InterpreterNotFound(PackageIdent, Box<Self>), InvalidEventStreamToken(String), InvalidInstallHookMode(String), /// Occurs when making lower level IO calls. IO(io::Error), /// Errors when joining paths :) JoinPathsError(env::JoinPathsError), MissingCLIInputError(String), NamedPipeTimeoutOnStart(String, String, io::Error), NativeTls(native_tls::Error), NetParseError(net::AddrParseError), OfflineArtifactNotFound(PackageIdent), OfflineOriginKeyNotFound(String), OfflinePackageNotFound(PackageIdent), PackageNotFound(String), /// Occurs upon errors related to file or directory permissions. PermissionFailed(String), /// When an error occurs serializing rendering context RenderContextSerialization(serde_json::Error), RootRequired, StatusFileCorrupt(PathBuf), StrFromUtf8Error(str::Utf8Error), StringFromUtf8Error(string::FromUtf8Error), /// When an error occurs registering template file // Boxed due to clippy::large_enum_variant TemplateFileError(Box<handlebars::TemplateFileError>), /// When an error occurs rendering template /// The error is constructed with a handlebars::RenderError's format string instead /// of the handlebars::RenderError itself because the cause field of the /// handlebars::RenderError in the handlebars crate version we use implements send /// and not sync which can lead to upstream compile errors when dealing with the /// failure crate. We should change this to a RenderError after we update the /// handlebars crate. See https://github.com/sunng87/handlebars-rust/issues/194 TemplateRenderError(String), /// When an error occurs merging toml TomlMergeError(String), /// When an error occurs parsing toml TomlParser(toml::de::Error), TomlSerializeError(toml::ser::Error), WireDecode(String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match *self { Error::APIClient(ref err) => format!("{}", err), Error::ArtifactIdentMismatch((ref a, ref ai, ref i)) => { format!("Artifact ident {} for `{}' does not match expected ident {}", ai, a, i) } Error::BadEnvConfig(ref varname) => { format!("Unable to find valid TOML or JSON in {} ENVVAR", varname) } Error::BadGlyphStyle(ref style) => format!("Unknown symbol style '{}'", style), Error::CantUploadGossipToml => { "Can't upload gossip.toml, it's a reserved file name".to_string() } Error::ChannelNotFound => "Channel not found".to_string(), Error::CryptoKeyError(ref s) => format!("Missing or invalid key: {}", s), Error::DownloadFailed(ref msg) => msg.to_string(), Error::EditorEnv(ref e) => format!("Missing EDITOR environment variable: {}", e), Error::EditStatus => "Failed edit text command".to_string(), Error::FileNameError => "Failed to extract a filename".to_string(), Error::FileNotFound(ref e) => format!("File not found at: {}", e), Error::GossipFileRelativePath(ref s) => { format!("Path for gossip file cannot have relative components (eg:..): {}", s) } Error::HabitatCore(ref e) => format!("{}", e), Error::MissingCLIInputError(ref arg) => { format!("Missing required CLI argument!: {}", arg) } Error::InstallHookFailed(ref ident) => { format!("Install hook exited unsuccessfully: {}", ident) } Error::InterpreterNotFound(ref ident, ref e) => { format!("Unable to install interpreter ident: {} - {}", ident, e) } Error::InvalidEventStreamToken(ref s) => { format!("Invalid event stream token provided: '{}'", s) } Error::InvalidInstallHookMode(ref e) => { format!("Invalid InstallHookMode conversion from {}", e) } Error::IO(ref err) => format!("{}", err), Error::JoinPathsError(ref err) => format!("{}", err), Error::NamedPipeTimeoutOnStart(ref group, ref hook, ref err) => { format!("Unable to start powershell named pipe for {} hook of {}: {}", hook, group, err) } Error::NativeTls(ref err) => format!("TLS error '{}'", err), Error::NetParseError(ref err) => format!("{}", err), Error::OfflineArtifactNotFound(ref ident) => { format!("Cached artifact not found in offline mode: {}", ident) } Error::OfflineOriginKeyNotFound(ref name_with_rev) => { format!("Cached origin key not found in offline mode: {}", name_with_rev) } Error::OfflinePackageNotFound(ref ident) => { format!("No installed package or cached artifact could be found locally in \ offline mode: {}", ident) } Error::PackageNotFound(ref e) => format!("Package not found. {}", e), Error::PermissionFailed(ref e) => e.to_string(), Error::RenderContextSerialization(ref e) => { format!("Unable to serialize rendering context, {}", e) } Error::RootRequired => { "Root or administrator permissions required to complete operation".to_string() } Error::StatusFileCorrupt(ref path) => { format!("Unable to decode contents of INSTALL_STATUS file, {}", path.display()) } Error::StrFromUtf8Error(ref e) => format!("{}", e), Error::StringFromUtf8Error(ref e) => format!("{}", e), Error::TemplateFileError(ref err) => format!("{:?}", err), Error::TemplateRenderError(ref err) => err.to_string(), Error::TomlMergeError(ref e) => format!("Failed to merge TOML: {}", e), Error::TomlParser(ref err) => format!("Failed to parse TOML: {}", err), Error::TomlSerializeError(ref e) => format!("Can't serialize TOML: {}", e), Error::WireDecode(ref m) => format!("Failed to decode wire message: {}", m), }; write!(f, "{}", msg) } } impl error::Error for Error {} impl From<api_client::Error> for Error { fn from(err: api_client::Error) -> Self { Error::APIClient(err) } } impl From<handlebars::TemplateFileError> for Error { fn from(err: handlebars::TemplateFileError) -> Self { Error::TemplateFileError(Box::new(err)) } } impl From<hcore::Error> for Error { fn from(err: hcore::Error) -> Self { Error::HabitatCore(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::IO(err) } } impl From<env::JoinPathsError> for Error { fn from(err: env::JoinPathsError) -> Self { Error::JoinPathsError(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self { Error::StrFromUtf8Error(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::StringFromUtf8Error(err) } } impl From<toml::ser::Error> for Error {
} impl From<net::AddrParseError> for Error { fn from(err: net::AddrParseError) -> Self { Error::NetParseError(err) } } impl From<native_tls::Error> for Error { fn from(error: native_tls::Error) -> Self { Error::NativeTls(error) } }
fn from(err: toml::ser::Error) -> Self { Error::TomlSerializeError(err) }
random_line_split
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub enum Error { APIClient(api_client::Error), ArtifactIdentMismatch((String, String, String)), /// Occurs when there is no valid toml of json in the environment variable BadEnvConfig(String), BadGlyphStyle(String), CantUploadGossipToml, ChannelNotFound, CryptoKeyError(String), DownloadFailed(String), EditorEnv(env::VarError), EditStatus, FileNameError, /// Occurs when a file that should exist does not or could not be read. FileNotFound(String), GossipFileRelativePath(String), HabitatCore(hcore::Error), InstallHookFailed(PackageIdent), InterpreterNotFound(PackageIdent, Box<Self>), InvalidEventStreamToken(String), InvalidInstallHookMode(String), /// Occurs when making lower level IO calls. IO(io::Error), /// Errors when joining paths :) JoinPathsError(env::JoinPathsError), MissingCLIInputError(String), NamedPipeTimeoutOnStart(String, String, io::Error), NativeTls(native_tls::Error), NetParseError(net::AddrParseError), OfflineArtifactNotFound(PackageIdent), OfflineOriginKeyNotFound(String), OfflinePackageNotFound(PackageIdent), PackageNotFound(String), /// Occurs upon errors related to file or directory permissions. PermissionFailed(String), /// When an error occurs serializing rendering context RenderContextSerialization(serde_json::Error), RootRequired, StatusFileCorrupt(PathBuf), StrFromUtf8Error(str::Utf8Error), StringFromUtf8Error(string::FromUtf8Error), /// When an error occurs registering template file // Boxed due to clippy::large_enum_variant TemplateFileError(Box<handlebars::TemplateFileError>), /// When an error occurs rendering template /// The error is constructed with a handlebars::RenderError's format string instead /// of the handlebars::RenderError itself because the cause field of the /// handlebars::RenderError in the handlebars crate version we use implements send /// and not sync which can lead to upstream compile errors when dealing with the /// failure crate. We should change this to a RenderError after we update the /// handlebars crate. See https://github.com/sunng87/handlebars-rust/issues/194 TemplateRenderError(String), /// When an error occurs merging toml TomlMergeError(String), /// When an error occurs parsing toml TomlParser(toml::de::Error), TomlSerializeError(toml::ser::Error), WireDecode(String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match *self { Error::APIClient(ref err) => format!("{}", err), Error::ArtifactIdentMismatch((ref a, ref ai, ref i)) => { format!("Artifact ident {} for `{}' does not match expected ident {}", ai, a, i) } Error::BadEnvConfig(ref varname) => { format!("Unable to find valid TOML or JSON in {} ENVVAR", varname) } Error::BadGlyphStyle(ref style) => format!("Unknown symbol style '{}'", style), Error::CantUploadGossipToml => { "Can't upload gossip.toml, it's a reserved file name".to_string() } Error::ChannelNotFound => "Channel not found".to_string(), Error::CryptoKeyError(ref s) => format!("Missing or invalid key: {}", s), Error::DownloadFailed(ref msg) => msg.to_string(), Error::EditorEnv(ref e) => format!("Missing EDITOR environment variable: {}", e), Error::EditStatus => "Failed edit text command".to_string(), Error::FileNameError => "Failed to extract a filename".to_string(), Error::FileNotFound(ref e) => format!("File not found at: {}", e), Error::GossipFileRelativePath(ref s) => { format!("Path for gossip file cannot have relative components (eg:..): {}", s) } Error::HabitatCore(ref e) => format!("{}", e), Error::MissingCLIInputError(ref arg) => { format!("Missing required CLI argument!: {}", arg) } Error::InstallHookFailed(ref ident) => { format!("Install hook exited unsuccessfully: {}", ident) } Error::InterpreterNotFound(ref ident, ref e) => { format!("Unable to install interpreter ident: {} - {}", ident, e) } Error::InvalidEventStreamToken(ref s) => { format!("Invalid event stream token provided: '{}'", s) } Error::InvalidInstallHookMode(ref e) => { format!("Invalid InstallHookMode conversion from {}", e) } Error::IO(ref err) => format!("{}", err), Error::JoinPathsError(ref err) => format!("{}", err), Error::NamedPipeTimeoutOnStart(ref group, ref hook, ref err) => { format!("Unable to start powershell named pipe for {} hook of {}: {}", hook, group, err) } Error::NativeTls(ref err) => format!("TLS error '{}'", err), Error::NetParseError(ref err) => format!("{}", err), Error::OfflineArtifactNotFound(ref ident) => { format!("Cached artifact not found in offline mode: {}", ident) } Error::OfflineOriginKeyNotFound(ref name_with_rev) =>
Error::OfflinePackageNotFound(ref ident) => { format!("No installed package or cached artifact could be found locally in \ offline mode: {}", ident) } Error::PackageNotFound(ref e) => format!("Package not found. {}", e), Error::PermissionFailed(ref e) => e.to_string(), Error::RenderContextSerialization(ref e) => { format!("Unable to serialize rendering context, {}", e) } Error::RootRequired => { "Root or administrator permissions required to complete operation".to_string() } Error::StatusFileCorrupt(ref path) => { format!("Unable to decode contents of INSTALL_STATUS file, {}", path.display()) } Error::StrFromUtf8Error(ref e) => format!("{}", e), Error::StringFromUtf8Error(ref e) => format!("{}", e), Error::TemplateFileError(ref err) => format!("{:?}", err), Error::TemplateRenderError(ref err) => err.to_string(), Error::TomlMergeError(ref e) => format!("Failed to merge TOML: {}", e), Error::TomlParser(ref err) => format!("Failed to parse TOML: {}", err), Error::TomlSerializeError(ref e) => format!("Can't serialize TOML: {}", e), Error::WireDecode(ref m) => format!("Failed to decode wire message: {}", m), }; write!(f, "{}", msg) } } impl error::Error for Error {} impl From<api_client::Error> for Error { fn from(err: api_client::Error) -> Self { Error::APIClient(err) } } impl From<handlebars::TemplateFileError> for Error { fn from(err: handlebars::TemplateFileError) -> Self { Error::TemplateFileError(Box::new(err)) } } impl From<hcore::Error> for Error { fn from(err: hcore::Error) -> Self { Error::HabitatCore(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::IO(err) } } impl From<env::JoinPathsError> for Error { fn from(err: env::JoinPathsError) -> Self { Error::JoinPathsError(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self { Error::StrFromUtf8Error(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::StringFromUtf8Error(err) } } impl From<toml::ser::Error> for Error { fn from(err: toml::ser::Error) -> Self { Error::TomlSerializeError(err) } } impl From<net::AddrParseError> for Error { fn from(err: net::AddrParseError) -> Self { Error::NetParseError(err) } } impl From<native_tls::Error> for Error { fn from(error: native_tls::Error) -> Self { Error::NativeTls(error) } }
{ format!("Cached origin key not found in offline mode: {}", name_with_rev) }
conditional_block
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub enum Error { APIClient(api_client::Error), ArtifactIdentMismatch((String, String, String)), /// Occurs when there is no valid toml of json in the environment variable BadEnvConfig(String), BadGlyphStyle(String), CantUploadGossipToml, ChannelNotFound, CryptoKeyError(String), DownloadFailed(String), EditorEnv(env::VarError), EditStatus, FileNameError, /// Occurs when a file that should exist does not or could not be read. FileNotFound(String), GossipFileRelativePath(String), HabitatCore(hcore::Error), InstallHookFailed(PackageIdent), InterpreterNotFound(PackageIdent, Box<Self>), InvalidEventStreamToken(String), InvalidInstallHookMode(String), /// Occurs when making lower level IO calls. IO(io::Error), /// Errors when joining paths :) JoinPathsError(env::JoinPathsError), MissingCLIInputError(String), NamedPipeTimeoutOnStart(String, String, io::Error), NativeTls(native_tls::Error), NetParseError(net::AddrParseError), OfflineArtifactNotFound(PackageIdent), OfflineOriginKeyNotFound(String), OfflinePackageNotFound(PackageIdent), PackageNotFound(String), /// Occurs upon errors related to file or directory permissions. PermissionFailed(String), /// When an error occurs serializing rendering context RenderContextSerialization(serde_json::Error), RootRequired, StatusFileCorrupt(PathBuf), StrFromUtf8Error(str::Utf8Error), StringFromUtf8Error(string::FromUtf8Error), /// When an error occurs registering template file // Boxed due to clippy::large_enum_variant TemplateFileError(Box<handlebars::TemplateFileError>), /// When an error occurs rendering template /// The error is constructed with a handlebars::RenderError's format string instead /// of the handlebars::RenderError itself because the cause field of the /// handlebars::RenderError in the handlebars crate version we use implements send /// and not sync which can lead to upstream compile errors when dealing with the /// failure crate. We should change this to a RenderError after we update the /// handlebars crate. See https://github.com/sunng87/handlebars-rust/issues/194 TemplateRenderError(String), /// When an error occurs merging toml TomlMergeError(String), /// When an error occurs parsing toml TomlParser(toml::de::Error), TomlSerializeError(toml::ser::Error), WireDecode(String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match *self { Error::APIClient(ref err) => format!("{}", err), Error::ArtifactIdentMismatch((ref a, ref ai, ref i)) => { format!("Artifact ident {} for `{}' does not match expected ident {}", ai, a, i) } Error::BadEnvConfig(ref varname) => { format!("Unable to find valid TOML or JSON in {} ENVVAR", varname) } Error::BadGlyphStyle(ref style) => format!("Unknown symbol style '{}'", style), Error::CantUploadGossipToml => { "Can't upload gossip.toml, it's a reserved file name".to_string() } Error::ChannelNotFound => "Channel not found".to_string(), Error::CryptoKeyError(ref s) => format!("Missing or invalid key: {}", s), Error::DownloadFailed(ref msg) => msg.to_string(), Error::EditorEnv(ref e) => format!("Missing EDITOR environment variable: {}", e), Error::EditStatus => "Failed edit text command".to_string(), Error::FileNameError => "Failed to extract a filename".to_string(), Error::FileNotFound(ref e) => format!("File not found at: {}", e), Error::GossipFileRelativePath(ref s) => { format!("Path for gossip file cannot have relative components (eg:..): {}", s) } Error::HabitatCore(ref e) => format!("{}", e), Error::MissingCLIInputError(ref arg) => { format!("Missing required CLI argument!: {}", arg) } Error::InstallHookFailed(ref ident) => { format!("Install hook exited unsuccessfully: {}", ident) } Error::InterpreterNotFound(ref ident, ref e) => { format!("Unable to install interpreter ident: {} - {}", ident, e) } Error::InvalidEventStreamToken(ref s) => { format!("Invalid event stream token provided: '{}'", s) } Error::InvalidInstallHookMode(ref e) => { format!("Invalid InstallHookMode conversion from {}", e) } Error::IO(ref err) => format!("{}", err), Error::JoinPathsError(ref err) => format!("{}", err), Error::NamedPipeTimeoutOnStart(ref group, ref hook, ref err) => { format!("Unable to start powershell named pipe for {} hook of {}: {}", hook, group, err) } Error::NativeTls(ref err) => format!("TLS error '{}'", err), Error::NetParseError(ref err) => format!("{}", err), Error::OfflineArtifactNotFound(ref ident) => { format!("Cached artifact not found in offline mode: {}", ident) } Error::OfflineOriginKeyNotFound(ref name_with_rev) => { format!("Cached origin key not found in offline mode: {}", name_with_rev) } Error::OfflinePackageNotFound(ref ident) => { format!("No installed package or cached artifact could be found locally in \ offline mode: {}", ident) } Error::PackageNotFound(ref e) => format!("Package not found. {}", e), Error::PermissionFailed(ref e) => e.to_string(), Error::RenderContextSerialization(ref e) => { format!("Unable to serialize rendering context, {}", e) } Error::RootRequired => { "Root or administrator permissions required to complete operation".to_string() } Error::StatusFileCorrupt(ref path) => { format!("Unable to decode contents of INSTALL_STATUS file, {}", path.display()) } Error::StrFromUtf8Error(ref e) => format!("{}", e), Error::StringFromUtf8Error(ref e) => format!("{}", e), Error::TemplateFileError(ref err) => format!("{:?}", err), Error::TemplateRenderError(ref err) => err.to_string(), Error::TomlMergeError(ref e) => format!("Failed to merge TOML: {}", e), Error::TomlParser(ref err) => format!("Failed to parse TOML: {}", err), Error::TomlSerializeError(ref e) => format!("Can't serialize TOML: {}", e), Error::WireDecode(ref m) => format!("Failed to decode wire message: {}", m), }; write!(f, "{}", msg) } } impl error::Error for Error {} impl From<api_client::Error> for Error { fn from(err: api_client::Error) -> Self { Error::APIClient(err) } } impl From<handlebars::TemplateFileError> for Error { fn from(err: handlebars::TemplateFileError) -> Self { Error::TemplateFileError(Box::new(err)) } } impl From<hcore::Error> for Error { fn from(err: hcore::Error) -> Self { Error::HabitatCore(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self
} impl From<env::JoinPathsError> for Error { fn from(err: env::JoinPathsError) -> Self { Error::JoinPathsError(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self { Error::StrFromUtf8Error(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::StringFromUtf8Error(err) } } impl From<toml::ser::Error> for Error { fn from(err: toml::ser::Error) -> Self { Error::TomlSerializeError(err) } } impl From<net::AddrParseError> for Error { fn from(err: net::AddrParseError) -> Self { Error::NetParseError(err) } } impl From<native_tls::Error> for Error { fn from(error: native_tls::Error) -> Self { Error::NativeTls(error) } }
{ Error::IO(err) }
identifier_body
read_spec.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 lig::read::{read, read_attribute, read_entity, read_value}; use lig::*; use ligature::{Attribute, Entity, Statement, Value}; #[test] fn read_entities() { let e = "<test>"; assert_eq!( read_entity(e), Entity::new("test").map_err(|_| LigError("Could not create entity.".into()))
fn read_attributes() -> Result<(), LigError> { let a = "@<test>"; assert_eq!(read_attribute(a)?, Attribute::new("test")?); Ok(()) } #[test] fn read_string_literals() -> Result<(), LigError> { let s = "\"test\""; assert_eq!(read_value(s)?, Value::StringLiteral("test".to_string())); Ok(()) } #[test] fn read_integer_literals() -> Result<(), LigError> { let i = "243"; assert_eq!(read_value(i)?, Value::IntegerLiteral(243)); Ok(()) } #[test] fn read_float_literals() -> Result<(), LigError> { let f = "1.2"; assert_eq!(read_value(f)?, Value::FloatLiteral(1.2)); Ok(()) } #[test] fn read_byte_arrays_literals() -> Result<(), LigError> { let b = "0x00ff"; assert_eq!(read_value(b)?, Value::BytesLiteral(vec![0, 255])); Ok(()) } #[test] fn read_entity_as_value() -> Result<(), LigError> { let e = "<test>"; assert_eq!(read_value(e)?, Value::Entity(Entity::new("test")?)); Ok(()) } #[test] fn read_empty_set_of_statements() -> Result<(), LigError> { let s = ""; let expected: Vec<Statement> = vec![]; assert_eq!(read(s)?, expected); Ok(()) } #[test] fn read_set_of_statements() -> Result<(), LigError> { let s = "<e> @<a> 123 <c>\n<e2> @<a> <e> <c2>\n"; let expected = vec![ Statement { entity: Entity::new("e")?, attribute: Attribute::new("a")?, value: Value::IntegerLiteral(123), context: Entity::new("c")?, }, Statement { entity: Entity::new("e2")?, attribute: Attribute::new("a")?, value: Value::Entity(Entity::new("e")?), context: Entity::new("c2")?, }, ]; assert_eq!(read(s)?, expected); Ok(()) }
); } #[test]
random_line_split
read_spec.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 lig::read::{read, read_attribute, read_entity, read_value}; use lig::*; use ligature::{Attribute, Entity, Statement, Value}; #[test] fn read_entities()
#[test] fn read_attributes() -> Result<(), LigError> { let a = "@<test>"; assert_eq!(read_attribute(a)?, Attribute::new("test")?); Ok(()) } #[test] fn read_string_literals() -> Result<(), LigError> { let s = "\"test\""; assert_eq!(read_value(s)?, Value::StringLiteral("test".to_string())); Ok(()) } #[test] fn read_integer_literals() -> Result<(), LigError> { let i = "243"; assert_eq!(read_value(i)?, Value::IntegerLiteral(243)); Ok(()) } #[test] fn read_float_literals() -> Result<(), LigError> { let f = "1.2"; assert_eq!(read_value(f)?, Value::FloatLiteral(1.2)); Ok(()) } #[test] fn read_byte_arrays_literals() -> Result<(), LigError> { let b = "0x00ff"; assert_eq!(read_value(b)?, Value::BytesLiteral(vec![0, 255])); Ok(()) } #[test] fn read_entity_as_value() -> Result<(), LigError> { let e = "<test>"; assert_eq!(read_value(e)?, Value::Entity(Entity::new("test")?)); Ok(()) } #[test] fn read_empty_set_of_statements() -> Result<(), LigError> { let s = ""; let expected: Vec<Statement> = vec![]; assert_eq!(read(s)?, expected); Ok(()) } #[test] fn read_set_of_statements() -> Result<(), LigError> { let s = "<e> @<a> 123 <c>\n<e2> @<a> <e> <c2>\n"; let expected = vec![ Statement { entity: Entity::new("e")?, attribute: Attribute::new("a")?, value: Value::IntegerLiteral(123), context: Entity::new("c")?, }, Statement { entity: Entity::new("e2")?, attribute: Attribute::new("a")?, value: Value::Entity(Entity::new("e")?), context: Entity::new("c2")?, }, ]; assert_eq!(read(s)?, expected); Ok(()) }
{ let e = "<test>"; assert_eq!( read_entity(e), Entity::new("test").map_err(|_| LigError("Could not create entity.".into())) ); }
identifier_body
read_spec.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 lig::read::{read, read_attribute, read_entity, read_value}; use lig::*; use ligature::{Attribute, Entity, Statement, Value}; #[test] fn read_entities() { let e = "<test>"; assert_eq!( read_entity(e), Entity::new("test").map_err(|_| LigError("Could not create entity.".into())) ); } #[test] fn read_attributes() -> Result<(), LigError> { let a = "@<test>"; assert_eq!(read_attribute(a)?, Attribute::new("test")?); Ok(()) } #[test] fn read_string_literals() -> Result<(), LigError> { let s = "\"test\""; assert_eq!(read_value(s)?, Value::StringLiteral("test".to_string())); Ok(()) } #[test] fn read_integer_literals() -> Result<(), LigError> { let i = "243"; assert_eq!(read_value(i)?, Value::IntegerLiteral(243)); Ok(()) } #[test] fn
() -> Result<(), LigError> { let f = "1.2"; assert_eq!(read_value(f)?, Value::FloatLiteral(1.2)); Ok(()) } #[test] fn read_byte_arrays_literals() -> Result<(), LigError> { let b = "0x00ff"; assert_eq!(read_value(b)?, Value::BytesLiteral(vec![0, 255])); Ok(()) } #[test] fn read_entity_as_value() -> Result<(), LigError> { let e = "<test>"; assert_eq!(read_value(e)?, Value::Entity(Entity::new("test")?)); Ok(()) } #[test] fn read_empty_set_of_statements() -> Result<(), LigError> { let s = ""; let expected: Vec<Statement> = vec![]; assert_eq!(read(s)?, expected); Ok(()) } #[test] fn read_set_of_statements() -> Result<(), LigError> { let s = "<e> @<a> 123 <c>\n<e2> @<a> <e> <c2>\n"; let expected = vec![ Statement { entity: Entity::new("e")?, attribute: Attribute::new("a")?, value: Value::IntegerLiteral(123), context: Entity::new("c")?, }, Statement { entity: Entity::new("e2")?, attribute: Attribute::new("a")?, value: Value::Entity(Entity::new("e")?), context: Entity::new("c2")?, }, ]; assert_eq!(read(s)?, expected); Ok(()) }
read_float_literals
identifier_name
input.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 script_traits::MouseButton; use std::path::Path; use std::mem::size_of; use std::mem::transmute; use std::mem::zeroed; use std::os::errno; use std::os::unix::AsRawFd; use std::num::Float; use std::fs::File; use std::thread; use std::sync::mpsc::Sender; use std::io::Read; use geom::point::TypedPoint2D; use libc::c_int; use libc::c_long; use libc::time_t; use compositing::windowing::WindowEvent; use compositing::windowing::MouseWindowEvent; extern { // XXX: no variadic form in std libs? fn ioctl(fd: c_int, req: c_int,...) -> c_int; } #[repr(C)] struct linux_input_event { sec: time_t, msec: c_long, evt_type: u16, code: u16, value: i32, } #[repr(C)] struct linux_input_absinfo { value: i32, minimum: i32, maximum: i32, fuzz: i32, flat: i32, resolution: i32, } const IOC_NONE: c_int = 0; const IOC_WRITE: c_int = 1; const IOC_READ: c_int = 2; fn ioc(dir: c_int, ioctype: c_int, nr: c_int, size: c_int) -> c_int { dir << 30 | size << 16 | ioctype << 8 | nr } fn ev_ioc_g_abs(abs: u16) -> c_int { ioc(IOC_READ, 'E' as c_int, (0x40 + abs) as i32, size_of::<linux_input_absinfo>() as i32) } const EV_SYN: u16 = 0; const EV_ABS: u16 = 3; const EV_REPORT: u16 = 0; const ABS_MT_SLOT: u16 = 0x2F; const ABS_MT_TOUCH_MAJOR: u16 = 0x30; const ABS_MT_TOUCH_MINOR: u16 = 0x31; const ABS_MT_WIDTH_MAJOR: u16 = 0x32; const ABS_MT_WIDTH_MINOR: u16 = 0x33; const ABS_MT_ORIENTATION: u16 = 0x34; const ABS_MT_POSITION_X: u16 = 0x35; const ABS_MT_POSITION_Y: u16 = 0x36; const ABS_MT_TRACKING_ID: u16 = 0x39; struct InputSlot { tracking_id: i32, x: i32, y: i32, } fn dist(x1: i32, x2: i32, y1: i32, y2: i32) -> f32 { let deltaX = (x2 - x1) as f32; let deltaY = (y2 - y1) as f32; (deltaX * deltaX + deltaY * deltaY).sqrt() } fn read_input_device(device_path: &Path, sender: &Sender<WindowEvent>) { let mut device = match File::open(device_path) { Ok(dev) => dev, Err(e) => { println!("Couldn't open device! {}", e); return; }, }; let fd = device.as_raw_fd(); let mut x_info: linux_input_absinfo = unsafe { zeroed() }; let mut y_info: linux_input_absinfo = unsafe { zeroed() }; unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info); if ret < 0 { println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno()); } } unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info); if ret < 0 { println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno()); } } let touchWidth = x_info.maximum - x_info.minimum; let touchHeight = y_info.maximum - y_info.minimum; println!("xMin: {}, yMin: {}, touchWidth: {}, touchHeight: {}", x_info.minimum, y_info.minimum, touchWidth, touchHeight); // XXX: Why isn't size_of treated as constant? // let buf: [u8; (16 * size_of::<linux_input_event>())]; let mut buf: [u8; (16 * 16)] = unsafe { zeroed() }; let mut slots: [InputSlot; 10] = unsafe { zeroed() }; for slot in slots.iter_mut() { slot.tracking_id = -1; } let mut last_x = 0; let mut last_y = 0; let mut first_x = 0; let mut first_y = 0; let mut last_dist: f32 = 0f32; let mut touch_count: i32 = 0; let mut current_slot: uint = 0; // XXX: Need to use the real dimensions of the screen let screen_dist = dist(0, 480, 854, 0); loop { let read = match device.read(buf.as_mut_slice()) { Ok(count) => { assert!(count % size_of::<linux_input_event>() == 0, "Unexpected input device read length!"); count }, Err(e) => { println!("Couldn't read device! {}", e); return; } }; let count = read / size_of::<linux_input_event>(); let events: *mut linux_input_event = unsafe { transmute(buf.as_mut_ptr()) }; let mut tracking_updated = false; for idx in range(0, count as int) { let event: &linux_input_event = unsafe { transmute(events.offset(idx)) }; match (event.evt_type, event.code) { (EV_SYN, EV_REPORT) => { let slotA = &slots[0]; if tracking_updated { tracking_updated = false; if slotA.tracking_id == -1 { println!("Touch up"); let delta_x = slotA.x - first_x; let delta_y = slotA.y - first_y; let dist = delta_x * delta_x + delta_y * delta_y; if dist < 16 { let click_pt = TypedPoint2D(slotA.x as f32, slotA.y as f32); println!("Dispatching click!"); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseDown(MouseButton::Left, click_pt))) .ok().unwrap(); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp(MouseButton::Left, click_pt))) .ok().unwrap(); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::Click(MouseButton::Left, click_pt))) .ok().unwrap(); } } else { println!("Touch down"); last_x = slotA.x; last_y = slotA.y; first_x = slotA.x; first_y = slotA.y; if touch_count >= 2 { let slotB = &slots[1]; last_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y); } } } else { println!("Touch move x: {}, y: {}", slotA.x, slotA.y); sender.send(WindowEvent::Scroll(TypedPoint2D((slotA.x - last_x) as f32, (slotA.y - last_y) as f32), TypedPoint2D(slotA.x, slotA.y))).ok().unwrap(); last_x = slotA.x; last_y = slotA.y; if touch_count >= 2 { let slotB = &slots[1]; let cur_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y); println!("Zooming {} {} {} {}", cur_dist, last_dist, screen_dist, ((screen_dist + (cur_dist - last_dist))/screen_dist)); sender.send(WindowEvent::Zoom((screen_dist + (cur_dist - last_dist))/screen_dist)).ok().unwrap(); last_dist = cur_dist; } } }, (EV_SYN, _) => println!("Unknown SYN code {}", event.code), (EV_ABS, ABS_MT_SLOT) => { if (event.value as uint) < slots.len() { current_slot = event.value as uint; } else { println!("Invalid slot! {}", event.value); } }, (EV_ABS, ABS_MT_TOUCH_MAJOR) => (), (EV_ABS, ABS_MT_TOUCH_MINOR) => (), (EV_ABS, ABS_MT_WIDTH_MAJOR) => (), (EV_ABS, ABS_MT_WIDTH_MINOR) => (), (EV_ABS, ABS_MT_ORIENTATION) => (), (EV_ABS, ABS_MT_POSITION_X) => { slots[current_slot].x = event.value - x_info.minimum; }, (EV_ABS, ABS_MT_POSITION_Y) => { slots[current_slot].y = event.value - y_info.minimum; }, (EV_ABS, ABS_MT_TRACKING_ID) => { let current_id = slots[current_slot].tracking_id; if current_id!= event.value && (current_id == -1 || event.value == -1) { tracking_updated = true; if event.value == -1
else { touch_count += 1; } } slots[current_slot].tracking_id = event.value; }, (EV_ABS, _) => println!("Unknown ABS code {}", event.code), (_, _) => println!("Unknown event type {}", event.evt_type), } } } } pub fn run_input_loop(event_sender: &Sender<WindowEvent>) { let sender = event_sender.clone(); thread::spawn(move || { // XXX need to scan all devices and read every one. let touchinputdev = Path::new("/dev/input/event0"); read_input_device(&touchinputdev, &sender); }); }
{ touch_count -= 1; }
conditional_block
input.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 script_traits::MouseButton; use std::path::Path; use std::mem::size_of; use std::mem::transmute; use std::mem::zeroed; use std::os::errno; use std::os::unix::AsRawFd; use std::num::Float; use std::fs::File; use std::thread; use std::sync::mpsc::Sender; use std::io::Read; use geom::point::TypedPoint2D; use libc::c_int; use libc::c_long; use libc::time_t; use compositing::windowing::WindowEvent; use compositing::windowing::MouseWindowEvent; extern { // XXX: no variadic form in std libs? fn ioctl(fd: c_int, req: c_int,...) -> c_int; } #[repr(C)] struct linux_input_event { sec: time_t, msec: c_long, evt_type: u16, code: u16, value: i32, } #[repr(C)] struct linux_input_absinfo { value: i32, minimum: i32, maximum: i32, fuzz: i32, flat: i32, resolution: i32, } const IOC_NONE: c_int = 0; const IOC_WRITE: c_int = 1; const IOC_READ: c_int = 2; fn ioc(dir: c_int, ioctype: c_int, nr: c_int, size: c_int) -> c_int { dir << 30 | size << 16 | ioctype << 8 | nr } fn ev_ioc_g_abs(abs: u16) -> c_int { ioc(IOC_READ, 'E' as c_int, (0x40 + abs) as i32, size_of::<linux_input_absinfo>() as i32) } const EV_SYN: u16 = 0; const EV_ABS: u16 = 3; const EV_REPORT: u16 = 0; const ABS_MT_SLOT: u16 = 0x2F; const ABS_MT_TOUCH_MAJOR: u16 = 0x30; const ABS_MT_TOUCH_MINOR: u16 = 0x31; const ABS_MT_WIDTH_MAJOR: u16 = 0x32; const ABS_MT_WIDTH_MINOR: u16 = 0x33; const ABS_MT_ORIENTATION: u16 = 0x34; const ABS_MT_POSITION_X: u16 = 0x35; const ABS_MT_POSITION_Y: u16 = 0x36; const ABS_MT_TRACKING_ID: u16 = 0x39; struct InputSlot { tracking_id: i32, x: i32, y: i32, } fn dist(x1: i32, x2: i32, y1: i32, y2: i32) -> f32 { let deltaX = (x2 - x1) as f32; let deltaY = (y2 - y1) as f32; (deltaX * deltaX + deltaY * deltaY).sqrt() } fn
(device_path: &Path, sender: &Sender<WindowEvent>) { let mut device = match File::open(device_path) { Ok(dev) => dev, Err(e) => { println!("Couldn't open device! {}", e); return; }, }; let fd = device.as_raw_fd(); let mut x_info: linux_input_absinfo = unsafe { zeroed() }; let mut y_info: linux_input_absinfo = unsafe { zeroed() }; unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info); if ret < 0 { println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno()); } } unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info); if ret < 0 { println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno()); } } let touchWidth = x_info.maximum - x_info.minimum; let touchHeight = y_info.maximum - y_info.minimum; println!("xMin: {}, yMin: {}, touchWidth: {}, touchHeight: {}", x_info.minimum, y_info.minimum, touchWidth, touchHeight); // XXX: Why isn't size_of treated as constant? // let buf: [u8; (16 * size_of::<linux_input_event>())]; let mut buf: [u8; (16 * 16)] = unsafe { zeroed() }; let mut slots: [InputSlot; 10] = unsafe { zeroed() }; for slot in slots.iter_mut() { slot.tracking_id = -1; } let mut last_x = 0; let mut last_y = 0; let mut first_x = 0; let mut first_y = 0; let mut last_dist: f32 = 0f32; let mut touch_count: i32 = 0; let mut current_slot: uint = 0; // XXX: Need to use the real dimensions of the screen let screen_dist = dist(0, 480, 854, 0); loop { let read = match device.read(buf.as_mut_slice()) { Ok(count) => { assert!(count % size_of::<linux_input_event>() == 0, "Unexpected input device read length!"); count }, Err(e) => { println!("Couldn't read device! {}", e); return; } }; let count = read / size_of::<linux_input_event>(); let events: *mut linux_input_event = unsafe { transmute(buf.as_mut_ptr()) }; let mut tracking_updated = false; for idx in range(0, count as int) { let event: &linux_input_event = unsafe { transmute(events.offset(idx)) }; match (event.evt_type, event.code) { (EV_SYN, EV_REPORT) => { let slotA = &slots[0]; if tracking_updated { tracking_updated = false; if slotA.tracking_id == -1 { println!("Touch up"); let delta_x = slotA.x - first_x; let delta_y = slotA.y - first_y; let dist = delta_x * delta_x + delta_y * delta_y; if dist < 16 { let click_pt = TypedPoint2D(slotA.x as f32, slotA.y as f32); println!("Dispatching click!"); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseDown(MouseButton::Left, click_pt))) .ok().unwrap(); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp(MouseButton::Left, click_pt))) .ok().unwrap(); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::Click(MouseButton::Left, click_pt))) .ok().unwrap(); } } else { println!("Touch down"); last_x = slotA.x; last_y = slotA.y; first_x = slotA.x; first_y = slotA.y; if touch_count >= 2 { let slotB = &slots[1]; last_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y); } } } else { println!("Touch move x: {}, y: {}", slotA.x, slotA.y); sender.send(WindowEvent::Scroll(TypedPoint2D((slotA.x - last_x) as f32, (slotA.y - last_y) as f32), TypedPoint2D(slotA.x, slotA.y))).ok().unwrap(); last_x = slotA.x; last_y = slotA.y; if touch_count >= 2 { let slotB = &slots[1]; let cur_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y); println!("Zooming {} {} {} {}", cur_dist, last_dist, screen_dist, ((screen_dist + (cur_dist - last_dist))/screen_dist)); sender.send(WindowEvent::Zoom((screen_dist + (cur_dist - last_dist))/screen_dist)).ok().unwrap(); last_dist = cur_dist; } } }, (EV_SYN, _) => println!("Unknown SYN code {}", event.code), (EV_ABS, ABS_MT_SLOT) => { if (event.value as uint) < slots.len() { current_slot = event.value as uint; } else { println!("Invalid slot! {}", event.value); } }, (EV_ABS, ABS_MT_TOUCH_MAJOR) => (), (EV_ABS, ABS_MT_TOUCH_MINOR) => (), (EV_ABS, ABS_MT_WIDTH_MAJOR) => (), (EV_ABS, ABS_MT_WIDTH_MINOR) => (), (EV_ABS, ABS_MT_ORIENTATION) => (), (EV_ABS, ABS_MT_POSITION_X) => { slots[current_slot].x = event.value - x_info.minimum; }, (EV_ABS, ABS_MT_POSITION_Y) => { slots[current_slot].y = event.value - y_info.minimum; }, (EV_ABS, ABS_MT_TRACKING_ID) => { let current_id = slots[current_slot].tracking_id; if current_id!= event.value && (current_id == -1 || event.value == -1) { tracking_updated = true; if event.value == -1 { touch_count -= 1; } else { touch_count += 1; } } slots[current_slot].tracking_id = event.value; }, (EV_ABS, _) => println!("Unknown ABS code {}", event.code), (_, _) => println!("Unknown event type {}", event.evt_type), } } } } pub fn run_input_loop(event_sender: &Sender<WindowEvent>) { let sender = event_sender.clone(); thread::spawn(move || { // XXX need to scan all devices and read every one. let touchinputdev = Path::new("/dev/input/event0"); read_input_device(&touchinputdev, &sender); }); }
read_input_device
identifier_name
input.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 script_traits::MouseButton; use std::path::Path; use std::mem::size_of; use std::mem::transmute; use std::mem::zeroed; use std::os::errno; use std::os::unix::AsRawFd; use std::num::Float; use std::fs::File; use std::thread; use std::sync::mpsc::Sender; use std::io::Read; use geom::point::TypedPoint2D; use libc::c_int; use libc::c_long; use libc::time_t; use compositing::windowing::WindowEvent; use compositing::windowing::MouseWindowEvent; extern { // XXX: no variadic form in std libs? fn ioctl(fd: c_int, req: c_int,...) -> c_int; } #[repr(C)] struct linux_input_event { sec: time_t, msec: c_long, evt_type: u16, code: u16, value: i32, } #[repr(C)] struct linux_input_absinfo { value: i32, minimum: i32, maximum: i32, fuzz: i32, flat: i32, resolution: i32, } const IOC_NONE: c_int = 0; const IOC_WRITE: c_int = 1; const IOC_READ: c_int = 2; fn ioc(dir: c_int, ioctype: c_int, nr: c_int, size: c_int) -> c_int { dir << 30 | size << 16 | ioctype << 8 | nr } fn ev_ioc_g_abs(abs: u16) -> c_int { ioc(IOC_READ, 'E' as c_int, (0x40 + abs) as i32, size_of::<linux_input_absinfo>() as i32) } const EV_SYN: u16 = 0; const EV_ABS: u16 = 3; const EV_REPORT: u16 = 0; const ABS_MT_SLOT: u16 = 0x2F; const ABS_MT_TOUCH_MAJOR: u16 = 0x30; const ABS_MT_TOUCH_MINOR: u16 = 0x31; const ABS_MT_WIDTH_MAJOR: u16 = 0x32; const ABS_MT_WIDTH_MINOR: u16 = 0x33; const ABS_MT_ORIENTATION: u16 = 0x34; const ABS_MT_POSITION_X: u16 = 0x35; const ABS_MT_POSITION_Y: u16 = 0x36; const ABS_MT_TRACKING_ID: u16 = 0x39; struct InputSlot { tracking_id: i32, x: i32, y: i32, } fn dist(x1: i32, x2: i32, y1: i32, y2: i32) -> f32 { let deltaX = (x2 - x1) as f32; let deltaY = (y2 - y1) as f32; (deltaX * deltaX + deltaY * deltaY).sqrt() } fn read_input_device(device_path: &Path, sender: &Sender<WindowEvent>) { let mut device = match File::open(device_path) { Ok(dev) => dev, Err(e) => { println!("Couldn't open device! {}", e); return; }, }; let fd = device.as_raw_fd(); let mut x_info: linux_input_absinfo = unsafe { zeroed() }; let mut y_info: linux_input_absinfo = unsafe { zeroed() };
println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno()); } } unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info); if ret < 0 { println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno()); } } let touchWidth = x_info.maximum - x_info.minimum; let touchHeight = y_info.maximum - y_info.minimum; println!("xMin: {}, yMin: {}, touchWidth: {}, touchHeight: {}", x_info.minimum, y_info.minimum, touchWidth, touchHeight); // XXX: Why isn't size_of treated as constant? // let buf: [u8; (16 * size_of::<linux_input_event>())]; let mut buf: [u8; (16 * 16)] = unsafe { zeroed() }; let mut slots: [InputSlot; 10] = unsafe { zeroed() }; for slot in slots.iter_mut() { slot.tracking_id = -1; } let mut last_x = 0; let mut last_y = 0; let mut first_x = 0; let mut first_y = 0; let mut last_dist: f32 = 0f32; let mut touch_count: i32 = 0; let mut current_slot: uint = 0; // XXX: Need to use the real dimensions of the screen let screen_dist = dist(0, 480, 854, 0); loop { let read = match device.read(buf.as_mut_slice()) { Ok(count) => { assert!(count % size_of::<linux_input_event>() == 0, "Unexpected input device read length!"); count }, Err(e) => { println!("Couldn't read device! {}", e); return; } }; let count = read / size_of::<linux_input_event>(); let events: *mut linux_input_event = unsafe { transmute(buf.as_mut_ptr()) }; let mut tracking_updated = false; for idx in range(0, count as int) { let event: &linux_input_event = unsafe { transmute(events.offset(idx)) }; match (event.evt_type, event.code) { (EV_SYN, EV_REPORT) => { let slotA = &slots[0]; if tracking_updated { tracking_updated = false; if slotA.tracking_id == -1 { println!("Touch up"); let delta_x = slotA.x - first_x; let delta_y = slotA.y - first_y; let dist = delta_x * delta_x + delta_y * delta_y; if dist < 16 { let click_pt = TypedPoint2D(slotA.x as f32, slotA.y as f32); println!("Dispatching click!"); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseDown(MouseButton::Left, click_pt))) .ok().unwrap(); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp(MouseButton::Left, click_pt))) .ok().unwrap(); sender.send(WindowEvent::MouseWindowEventClass(MouseWindowEvent::Click(MouseButton::Left, click_pt))) .ok().unwrap(); } } else { println!("Touch down"); last_x = slotA.x; last_y = slotA.y; first_x = slotA.x; first_y = slotA.y; if touch_count >= 2 { let slotB = &slots[1]; last_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y); } } } else { println!("Touch move x: {}, y: {}", slotA.x, slotA.y); sender.send(WindowEvent::Scroll(TypedPoint2D((slotA.x - last_x) as f32, (slotA.y - last_y) as f32), TypedPoint2D(slotA.x, slotA.y))).ok().unwrap(); last_x = slotA.x; last_y = slotA.y; if touch_count >= 2 { let slotB = &slots[1]; let cur_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y); println!("Zooming {} {} {} {}", cur_dist, last_dist, screen_dist, ((screen_dist + (cur_dist - last_dist))/screen_dist)); sender.send(WindowEvent::Zoom((screen_dist + (cur_dist - last_dist))/screen_dist)).ok().unwrap(); last_dist = cur_dist; } } }, (EV_SYN, _) => println!("Unknown SYN code {}", event.code), (EV_ABS, ABS_MT_SLOT) => { if (event.value as uint) < slots.len() { current_slot = event.value as uint; } else { println!("Invalid slot! {}", event.value); } }, (EV_ABS, ABS_MT_TOUCH_MAJOR) => (), (EV_ABS, ABS_MT_TOUCH_MINOR) => (), (EV_ABS, ABS_MT_WIDTH_MAJOR) => (), (EV_ABS, ABS_MT_WIDTH_MINOR) => (), (EV_ABS, ABS_MT_ORIENTATION) => (), (EV_ABS, ABS_MT_POSITION_X) => { slots[current_slot].x = event.value - x_info.minimum; }, (EV_ABS, ABS_MT_POSITION_Y) => { slots[current_slot].y = event.value - y_info.minimum; }, (EV_ABS, ABS_MT_TRACKING_ID) => { let current_id = slots[current_slot].tracking_id; if current_id!= event.value && (current_id == -1 || event.value == -1) { tracking_updated = true; if event.value == -1 { touch_count -= 1; } else { touch_count += 1; } } slots[current_slot].tracking_id = event.value; }, (EV_ABS, _) => println!("Unknown ABS code {}", event.code), (_, _) => println!("Unknown event type {}", event.evt_type), } } } } pub fn run_input_loop(event_sender: &Sender<WindowEvent>) { let sender = event_sender.clone(); thread::spawn(move || { // XXX need to scan all devices and read every one. let touchinputdev = Path::new("/dev/input/event0"); read_input_device(&touchinputdev, &sender); }); }
unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info); if ret < 0 {
random_line_split
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrameElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector};
use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct HTMLFrameElement { pub htmlelement: HTMLElement } impl HTMLFrameElementDerived for EventTarget { fn is_htmlframeelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId)) } } impl HTMLFrameElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFrameElement { HTMLFrameElement { htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFrameElement> { let element = HTMLFrameElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap) } } impl Reflectable for HTMLFrameElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
use dom::document::Document; use dom::element::HTMLFrameElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId};
random_line_split
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrameElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLFrameElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct HTMLFrameElement { pub htmlelement: HTMLElement } impl HTMLFrameElementDerived for EventTarget { fn is_htmlframeelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId)) } } impl HTMLFrameElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFrameElement { HTMLFrameElement { htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFrameElement> { let element = HTMLFrameElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap) } } impl Reflectable for HTMLFrameElement { fn reflector<'a>(&'a self) -> &'a Reflector
}
{ self.htmlelement.reflector() }
identifier_body
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrameElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLFrameElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct HTMLFrameElement { pub htmlelement: HTMLElement } impl HTMLFrameElementDerived for EventTarget { fn is_htmlframeelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId)) } } impl HTMLFrameElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFrameElement { HTMLFrameElement { htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn
(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFrameElement> { let element = HTMLFrameElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap) } } impl Reflectable for HTMLFrameElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
new
identifier_name
mod.rs
// Copyright 2013-2014 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. //! Native thread-blocking I/O implementation //! //! This module contains the implementation of native thread-blocking //! implementations of I/O on all platforms. This module is not intended to be //! used directly, but rather the rust runtime will fall back to using it if //! necessary. //! //! Rust code normally runs inside of green tasks with a local scheduler using //! asynchronous I/O to cooperate among tasks. This model is not always //! available, however, and that's where these native implementations come into //! play. The only dependencies of these modules are the normal system libraries //! that you would find on the respective platform. #![allow(non_snake_case_functions)] use libc::c_int; use libc; use std::c_str::CString; use std::os; use std::rt::rtio; use std::rt::rtio::{IoResult, IoError}; // Local re-exports pub use self::file::FileDesc; pub use self::process::Process; mod helper_thread; // Native I/O implementations pub mod addrinfo; pub mod net; pub mod process; mod util; #[cfg(unix)] #[path = "file_unix.rs"] pub mod file; #[cfg(windows)] #[path = "file_windows.rs"] pub mod file; #[cfg(target_os = "macos")] #[cfg(target_os = "ios")] #[cfg(target_os = "freebsd")] #[cfg(target_os = "dragonfly")] #[cfg(target_os = "android")] #[cfg(target_os = "linux")] #[path = "timer_unix.rs"] pub mod timer; #[cfg(target_os = "windows")] #[path = "timer_windows.rs"] pub mod timer; #[cfg(unix)] #[path = "pipe_unix.rs"] pub mod pipe; #[cfg(windows)] #[path = "pipe_windows.rs"] pub mod pipe; #[cfg(windows)] #[path = "tty_windows.rs"] mod tty; #[cfg(unix)] #[path = "c_unix.rs"] mod c; #[cfg(windows)] #[path = "c_windows.rs"] mod c; fn unimpl() -> IoError { #[cfg(unix)] use libc::ENOSYS as ERROR; #[cfg(windows)] use libc::ERROR_CALL_NOT_IMPLEMENTED as ERROR; IoError { code: ERROR as uint, extra: 0, detail: Some("not yet supported by the `native` runtime, maybe try `green`.".to_string()), } } fn last_error() -> IoError { let errno = os::errno() as uint; IoError { code: os::errno() as uint, extra: 0, detail: Some(os::error_string(errno)), } } // unix has nonzero values as errors fn mkerr_libc(ret: libc::c_int) -> IoResult<()> { if ret!= 0 { Err(last_error()) } else { Ok(()) } } // windows has zero values as errors #[cfg(windows)] fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> { if ret == 0 { Err(last_error()) } else { Ok(()) } } #[cfg(windows)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::errno() as int == libc::WSAEINTR as int => {} n => return n, } } } #[cfg(unix)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::errno() as int == libc::EINTR as int => {} n => return n, } } } fn keep_going(data: &[u8], f: |*const u8, uint| -> i64) -> i64 { let origamt = data.len(); let mut data = data.as_ptr(); let mut amt = origamt; while amt > 0 { let ret = retry(|| f(data, amt) as libc::c_int); if ret == 0 { break } else if ret!= -1 { amt -= ret as uint; data = unsafe { data.offset(ret as int) }; } else { return ret as i64; } } return (origamt - amt) as i64; } /// Implementation of rt::rtio's IoFactory trait to generate handles to the /// native I/O functionality. pub struct IoFactory { _cannot_construct_outside_of_this_module: () } impl IoFactory { pub fn new() -> IoFactory { net::init(); IoFactory { _cannot_construct_outside_of_this_module: () } } } impl rtio::IoFactory for IoFactory { // networking fn tcp_connect(&mut self, addr: rtio::SocketAddr, timeout: Option<u64>) -> IoResult<Box<rtio::RtioTcpStream + Send>> { net::TcpStream::connect(addr, timeout).map(|s| { box s as Box<rtio::RtioTcpStream + Send> }) } fn tcp_bind(&mut self, addr: rtio::SocketAddr) -> IoResult<Box<rtio::RtioTcpListener + Send>> { net::TcpListener::bind(addr).map(|s| { box s as Box<rtio::RtioTcpListener + Send> }) } fn
(&mut self, addr: rtio::SocketAddr) -> IoResult<Box<rtio::RtioUdpSocket + Send>> { net::UdpSocket::bind(addr).map(|u| { box u as Box<rtio::RtioUdpSocket + Send> }) } fn unix_bind(&mut self, path: &CString) -> IoResult<Box<rtio::RtioUnixListener + Send>> { pipe::UnixListener::bind(path).map(|s| { box s as Box<rtio::RtioUnixListener + Send> }) } fn unix_connect(&mut self, path: &CString, timeout: Option<u64>) -> IoResult<Box<rtio::RtioPipe + Send>> { pipe::UnixStream::connect(path, timeout).map(|s| { box s as Box<rtio::RtioPipe + Send> }) } fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>, hint: Option<rtio::AddrinfoHint>) -> IoResult<Vec<rtio::AddrinfoInfo>> { addrinfo::GetAddrInfoRequest::run(host, servname, hint) } // filesystem operations fn fs_from_raw_fd(&mut self, fd: c_int, close: rtio::CloseBehavior) -> Box<rtio::RtioFileStream + Send> { let close = match close { rtio::CloseSynchronously | rtio::CloseAsynchronously => true, rtio::DontClose => false }; box file::FileDesc::new(fd, close) as Box<rtio::RtioFileStream + Send> } fn fs_open(&mut self, path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess) -> IoResult<Box<rtio::RtioFileStream + Send>> { file::open(path, fm, fa).map(|fd| box fd as Box<rtio::RtioFileStream + Send>) } fn fs_unlink(&mut self, path: &CString) -> IoResult<()> { file::unlink(path) } fn fs_stat(&mut self, path: &CString) -> IoResult<rtio::FileStat> { file::stat(path) } fn fs_mkdir(&mut self, path: &CString, mode: uint) -> IoResult<()> { file::mkdir(path, mode) } fn fs_chmod(&mut self, path: &CString, mode: uint) -> IoResult<()> { file::chmod(path, mode) } fn fs_rmdir(&mut self, path: &CString) -> IoResult<()> { file::rmdir(path) } fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> { file::rename(path, to) } fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<Vec<CString>> { file::readdir(path) } fn fs_lstat(&mut self, path: &CString) -> IoResult<rtio::FileStat> { file::lstat(path) } fn fs_chown(&mut self, path: &CString, uid: int, gid: int) -> IoResult<()> { file::chown(path, uid, gid) } fn fs_readlink(&mut self, path: &CString) -> IoResult<CString> { file::readlink(path) } fn fs_symlink(&mut self, src: &CString, dst: &CString) -> IoResult<()> { file::symlink(src, dst) } fn fs_link(&mut self, src: &CString, dst: &CString) -> IoResult<()> { file::link(src, dst) } fn fs_utime(&mut self, src: &CString, atime: u64, mtime: u64) -> IoResult<()> { file::utime(src, atime, mtime) } // misc fn timer_init(&mut self) -> IoResult<Box<rtio::RtioTimer + Send>> { timer::Timer::new().map(|t| box t as Box<rtio::RtioTimer + Send>) } fn spawn(&mut self, cfg: rtio::ProcessConfig) -> IoResult<(Box<rtio::RtioProcess + Send>, Vec<Option<Box<rtio::RtioPipe + Send>>>)> { process::Process::spawn(cfg).map(|(p, io)| { (box p as Box<rtio::RtioProcess + Send>, io.move_iter().map(|p| p.map(|p| { box p as Box<rtio::RtioPipe + Send> })).collect()) }) } fn kill(&mut self, pid: libc::pid_t, signum: int) -> IoResult<()> { process::Process::kill(pid, signum) } fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<rtio::RtioPipe + Send>> { Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioPipe + Send>) } #[cfg(unix)] fn tty_open(&mut self, fd: c_int, _readable: bool) -> IoResult<Box<rtio::RtioTTY + Send>> { if unsafe { libc::isatty(fd) }!= 0 { Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioTTY + Send>) } else { Err(IoError { code: libc::ENOTTY as uint, extra: 0, detail: None, }) } } #[cfg(windows)] fn tty_open(&mut self, fd: c_int, _readable: bool) -> IoResult<Box<rtio::RtioTTY + Send>> { if tty::is_tty(fd) { Ok(box tty::WindowsTTY::new(fd) as Box<rtio::RtioTTY + Send>) } else { Err(IoError { code: libc::ERROR_INVALID_HANDLE as uint, extra: 0, detail: None, }) } } fn signal(&mut self, _signal: int, _cb: Box<rtio::Callback>) -> IoResult<Box<rtio::RtioSignal + Send>> { Err(unimpl()) } }
udp_bind
identifier_name
mod.rs
// Copyright 2013-2014 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. //! Native thread-blocking I/O implementation //! //! This module contains the implementation of native thread-blocking //! implementations of I/O on all platforms. This module is not intended to be //! used directly, but rather the rust runtime will fall back to using it if //! necessary. //! //! Rust code normally runs inside of green tasks with a local scheduler using //! asynchronous I/O to cooperate among tasks. This model is not always //! available, however, and that's where these native implementations come into //! play. The only dependencies of these modules are the normal system libraries //! that you would find on the respective platform. #![allow(non_snake_case_functions)] use libc::c_int; use libc; use std::c_str::CString; use std::os; use std::rt::rtio; use std::rt::rtio::{IoResult, IoError}; // Local re-exports pub use self::file::FileDesc; pub use self::process::Process; mod helper_thread; // Native I/O implementations pub mod addrinfo; pub mod net; pub mod process; mod util; #[cfg(unix)] #[path = "file_unix.rs"] pub mod file; #[cfg(windows)] #[path = "file_windows.rs"] pub mod file; #[cfg(target_os = "macos")] #[cfg(target_os = "ios")] #[cfg(target_os = "freebsd")] #[cfg(target_os = "dragonfly")] #[cfg(target_os = "android")] #[cfg(target_os = "linux")] #[path = "timer_unix.rs"] pub mod timer; #[cfg(target_os = "windows")] #[path = "timer_windows.rs"] pub mod timer; #[cfg(unix)] #[path = "pipe_unix.rs"] pub mod pipe; #[cfg(windows)] #[path = "pipe_windows.rs"] pub mod pipe; #[cfg(windows)] #[path = "tty_windows.rs"] mod tty; #[cfg(unix)] #[path = "c_unix.rs"] mod c; #[cfg(windows)] #[path = "c_windows.rs"] mod c; fn unimpl() -> IoError { #[cfg(unix)] use libc::ENOSYS as ERROR; #[cfg(windows)] use libc::ERROR_CALL_NOT_IMPLEMENTED as ERROR; IoError { code: ERROR as uint, extra: 0, detail: Some("not yet supported by the `native` runtime, maybe try `green`.".to_string()), } } fn last_error() -> IoError { let errno = os::errno() as uint; IoError { code: os::errno() as uint, extra: 0, detail: Some(os::error_string(errno)), } } // unix has nonzero values as errors fn mkerr_libc(ret: libc::c_int) -> IoResult<()> { if ret!= 0 { Err(last_error()) } else { Ok(()) } } // windows has zero values as errors #[cfg(windows)] fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> { if ret == 0 { Err(last_error()) } else { Ok(()) } } #[cfg(windows)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::errno() as int == libc::WSAEINTR as int => {} n => return n, } } } #[cfg(unix)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::errno() as int == libc::EINTR as int =>
n => return n, } } } fn keep_going(data: &[u8], f: |*const u8, uint| -> i64) -> i64 { let origamt = data.len(); let mut data = data.as_ptr(); let mut amt = origamt; while amt > 0 { let ret = retry(|| f(data, amt) as libc::c_int); if ret == 0 { break } else if ret!= -1 { amt -= ret as uint; data = unsafe { data.offset(ret as int) }; } else { return ret as i64; } } return (origamt - amt) as i64; } /// Implementation of rt::rtio's IoFactory trait to generate handles to the /// native I/O functionality. pub struct IoFactory { _cannot_construct_outside_of_this_module: () } impl IoFactory { pub fn new() -> IoFactory { net::init(); IoFactory { _cannot_construct_outside_of_this_module: () } } } impl rtio::IoFactory for IoFactory { // networking fn tcp_connect(&mut self, addr: rtio::SocketAddr, timeout: Option<u64>) -> IoResult<Box<rtio::RtioTcpStream + Send>> { net::TcpStream::connect(addr, timeout).map(|s| { box s as Box<rtio::RtioTcpStream + Send> }) } fn tcp_bind(&mut self, addr: rtio::SocketAddr) -> IoResult<Box<rtio::RtioTcpListener + Send>> { net::TcpListener::bind(addr).map(|s| { box s as Box<rtio::RtioTcpListener + Send> }) } fn udp_bind(&mut self, addr: rtio::SocketAddr) -> IoResult<Box<rtio::RtioUdpSocket + Send>> { net::UdpSocket::bind(addr).map(|u| { box u as Box<rtio::RtioUdpSocket + Send> }) } fn unix_bind(&mut self, path: &CString) -> IoResult<Box<rtio::RtioUnixListener + Send>> { pipe::UnixListener::bind(path).map(|s| { box s as Box<rtio::RtioUnixListener + Send> }) } fn unix_connect(&mut self, path: &CString, timeout: Option<u64>) -> IoResult<Box<rtio::RtioPipe + Send>> { pipe::UnixStream::connect(path, timeout).map(|s| { box s as Box<rtio::RtioPipe + Send> }) } fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>, hint: Option<rtio::AddrinfoHint>) -> IoResult<Vec<rtio::AddrinfoInfo>> { addrinfo::GetAddrInfoRequest::run(host, servname, hint) } // filesystem operations fn fs_from_raw_fd(&mut self, fd: c_int, close: rtio::CloseBehavior) -> Box<rtio::RtioFileStream + Send> { let close = match close { rtio::CloseSynchronously | rtio::CloseAsynchronously => true, rtio::DontClose => false }; box file::FileDesc::new(fd, close) as Box<rtio::RtioFileStream + Send> } fn fs_open(&mut self, path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess) -> IoResult<Box<rtio::RtioFileStream + Send>> { file::open(path, fm, fa).map(|fd| box fd as Box<rtio::RtioFileStream + Send>) } fn fs_unlink(&mut self, path: &CString) -> IoResult<()> { file::unlink(path) } fn fs_stat(&mut self, path: &CString) -> IoResult<rtio::FileStat> { file::stat(path) } fn fs_mkdir(&mut self, path: &CString, mode: uint) -> IoResult<()> { file::mkdir(path, mode) } fn fs_chmod(&mut self, path: &CString, mode: uint) -> IoResult<()> { file::chmod(path, mode) } fn fs_rmdir(&mut self, path: &CString) -> IoResult<()> { file::rmdir(path) } fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> { file::rename(path, to) } fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<Vec<CString>> { file::readdir(path) } fn fs_lstat(&mut self, path: &CString) -> IoResult<rtio::FileStat> { file::lstat(path) } fn fs_chown(&mut self, path: &CString, uid: int, gid: int) -> IoResult<()> { file::chown(path, uid, gid) } fn fs_readlink(&mut self, path: &CString) -> IoResult<CString> { file::readlink(path) } fn fs_symlink(&mut self, src: &CString, dst: &CString) -> IoResult<()> { file::symlink(src, dst) } fn fs_link(&mut self, src: &CString, dst: &CString) -> IoResult<()> { file::link(src, dst) } fn fs_utime(&mut self, src: &CString, atime: u64, mtime: u64) -> IoResult<()> { file::utime(src, atime, mtime) } // misc fn timer_init(&mut self) -> IoResult<Box<rtio::RtioTimer + Send>> { timer::Timer::new().map(|t| box t as Box<rtio::RtioTimer + Send>) } fn spawn(&mut self, cfg: rtio::ProcessConfig) -> IoResult<(Box<rtio::RtioProcess + Send>, Vec<Option<Box<rtio::RtioPipe + Send>>>)> { process::Process::spawn(cfg).map(|(p, io)| { (box p as Box<rtio::RtioProcess + Send>, io.move_iter().map(|p| p.map(|p| { box p as Box<rtio::RtioPipe + Send> })).collect()) }) } fn kill(&mut self, pid: libc::pid_t, signum: int) -> IoResult<()> { process::Process::kill(pid, signum) } fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<rtio::RtioPipe + Send>> { Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioPipe + Send>) } #[cfg(unix)] fn tty_open(&mut self, fd: c_int, _readable: bool) -> IoResult<Box<rtio::RtioTTY + Send>> { if unsafe { libc::isatty(fd) }!= 0 { Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioTTY + Send>) } else { Err(IoError { code: libc::ENOTTY as uint, extra: 0, detail: None, }) } } #[cfg(windows)] fn tty_open(&mut self, fd: c_int, _readable: bool) -> IoResult<Box<rtio::RtioTTY + Send>> { if tty::is_tty(fd) { Ok(box tty::WindowsTTY::new(fd) as Box<rtio::RtioTTY + Send>) } else { Err(IoError { code: libc::ERROR_INVALID_HANDLE as uint, extra: 0, detail: None, }) } } fn signal(&mut self, _signal: int, _cb: Box<rtio::Callback>) -> IoResult<Box<rtio::RtioSignal + Send>> { Err(unimpl()) } }
{}
conditional_block
mod.rs
// Copyright 2013-2014 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. //! Native thread-blocking I/O implementation //! //! This module contains the implementation of native thread-blocking //! implementations of I/O on all platforms. This module is not intended to be //! used directly, but rather the rust runtime will fall back to using it if //! necessary. //! //! Rust code normally runs inside of green tasks with a local scheduler using //! asynchronous I/O to cooperate among tasks. This model is not always //! available, however, and that's where these native implementations come into //! play. The only dependencies of these modules are the normal system libraries //! that you would find on the respective platform. #![allow(non_snake_case_functions)] use libc::c_int; use libc; use std::c_str::CString; use std::os; use std::rt::rtio; use std::rt::rtio::{IoResult, IoError}; // Local re-exports pub use self::file::FileDesc; pub use self::process::Process; mod helper_thread; // Native I/O implementations pub mod addrinfo; pub mod net;
#[cfg(unix)] #[path = "file_unix.rs"] pub mod file; #[cfg(windows)] #[path = "file_windows.rs"] pub mod file; #[cfg(target_os = "macos")] #[cfg(target_os = "ios")] #[cfg(target_os = "freebsd")] #[cfg(target_os = "dragonfly")] #[cfg(target_os = "android")] #[cfg(target_os = "linux")] #[path = "timer_unix.rs"] pub mod timer; #[cfg(target_os = "windows")] #[path = "timer_windows.rs"] pub mod timer; #[cfg(unix)] #[path = "pipe_unix.rs"] pub mod pipe; #[cfg(windows)] #[path = "pipe_windows.rs"] pub mod pipe; #[cfg(windows)] #[path = "tty_windows.rs"] mod tty; #[cfg(unix)] #[path = "c_unix.rs"] mod c; #[cfg(windows)] #[path = "c_windows.rs"] mod c; fn unimpl() -> IoError { #[cfg(unix)] use libc::ENOSYS as ERROR; #[cfg(windows)] use libc::ERROR_CALL_NOT_IMPLEMENTED as ERROR; IoError { code: ERROR as uint, extra: 0, detail: Some("not yet supported by the `native` runtime, maybe try `green`.".to_string()), } } fn last_error() -> IoError { let errno = os::errno() as uint; IoError { code: os::errno() as uint, extra: 0, detail: Some(os::error_string(errno)), } } // unix has nonzero values as errors fn mkerr_libc(ret: libc::c_int) -> IoResult<()> { if ret!= 0 { Err(last_error()) } else { Ok(()) } } // windows has zero values as errors #[cfg(windows)] fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> { if ret == 0 { Err(last_error()) } else { Ok(()) } } #[cfg(windows)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::errno() as int == libc::WSAEINTR as int => {} n => return n, } } } #[cfg(unix)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::errno() as int == libc::EINTR as int => {} n => return n, } } } fn keep_going(data: &[u8], f: |*const u8, uint| -> i64) -> i64 { let origamt = data.len(); let mut data = data.as_ptr(); let mut amt = origamt; while amt > 0 { let ret = retry(|| f(data, amt) as libc::c_int); if ret == 0 { break } else if ret!= -1 { amt -= ret as uint; data = unsafe { data.offset(ret as int) }; } else { return ret as i64; } } return (origamt - amt) as i64; } /// Implementation of rt::rtio's IoFactory trait to generate handles to the /// native I/O functionality. pub struct IoFactory { _cannot_construct_outside_of_this_module: () } impl IoFactory { pub fn new() -> IoFactory { net::init(); IoFactory { _cannot_construct_outside_of_this_module: () } } } impl rtio::IoFactory for IoFactory { // networking fn tcp_connect(&mut self, addr: rtio::SocketAddr, timeout: Option<u64>) -> IoResult<Box<rtio::RtioTcpStream + Send>> { net::TcpStream::connect(addr, timeout).map(|s| { box s as Box<rtio::RtioTcpStream + Send> }) } fn tcp_bind(&mut self, addr: rtio::SocketAddr) -> IoResult<Box<rtio::RtioTcpListener + Send>> { net::TcpListener::bind(addr).map(|s| { box s as Box<rtio::RtioTcpListener + Send> }) } fn udp_bind(&mut self, addr: rtio::SocketAddr) -> IoResult<Box<rtio::RtioUdpSocket + Send>> { net::UdpSocket::bind(addr).map(|u| { box u as Box<rtio::RtioUdpSocket + Send> }) } fn unix_bind(&mut self, path: &CString) -> IoResult<Box<rtio::RtioUnixListener + Send>> { pipe::UnixListener::bind(path).map(|s| { box s as Box<rtio::RtioUnixListener + Send> }) } fn unix_connect(&mut self, path: &CString, timeout: Option<u64>) -> IoResult<Box<rtio::RtioPipe + Send>> { pipe::UnixStream::connect(path, timeout).map(|s| { box s as Box<rtio::RtioPipe + Send> }) } fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>, hint: Option<rtio::AddrinfoHint>) -> IoResult<Vec<rtio::AddrinfoInfo>> { addrinfo::GetAddrInfoRequest::run(host, servname, hint) } // filesystem operations fn fs_from_raw_fd(&mut self, fd: c_int, close: rtio::CloseBehavior) -> Box<rtio::RtioFileStream + Send> { let close = match close { rtio::CloseSynchronously | rtio::CloseAsynchronously => true, rtio::DontClose => false }; box file::FileDesc::new(fd, close) as Box<rtio::RtioFileStream + Send> } fn fs_open(&mut self, path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess) -> IoResult<Box<rtio::RtioFileStream + Send>> { file::open(path, fm, fa).map(|fd| box fd as Box<rtio::RtioFileStream + Send>) } fn fs_unlink(&mut self, path: &CString) -> IoResult<()> { file::unlink(path) } fn fs_stat(&mut self, path: &CString) -> IoResult<rtio::FileStat> { file::stat(path) } fn fs_mkdir(&mut self, path: &CString, mode: uint) -> IoResult<()> { file::mkdir(path, mode) } fn fs_chmod(&mut self, path: &CString, mode: uint) -> IoResult<()> { file::chmod(path, mode) } fn fs_rmdir(&mut self, path: &CString) -> IoResult<()> { file::rmdir(path) } fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> { file::rename(path, to) } fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<Vec<CString>> { file::readdir(path) } fn fs_lstat(&mut self, path: &CString) -> IoResult<rtio::FileStat> { file::lstat(path) } fn fs_chown(&mut self, path: &CString, uid: int, gid: int) -> IoResult<()> { file::chown(path, uid, gid) } fn fs_readlink(&mut self, path: &CString) -> IoResult<CString> { file::readlink(path) } fn fs_symlink(&mut self, src: &CString, dst: &CString) -> IoResult<()> { file::symlink(src, dst) } fn fs_link(&mut self, src: &CString, dst: &CString) -> IoResult<()> { file::link(src, dst) } fn fs_utime(&mut self, src: &CString, atime: u64, mtime: u64) -> IoResult<()> { file::utime(src, atime, mtime) } // misc fn timer_init(&mut self) -> IoResult<Box<rtio::RtioTimer + Send>> { timer::Timer::new().map(|t| box t as Box<rtio::RtioTimer + Send>) } fn spawn(&mut self, cfg: rtio::ProcessConfig) -> IoResult<(Box<rtio::RtioProcess + Send>, Vec<Option<Box<rtio::RtioPipe + Send>>>)> { process::Process::spawn(cfg).map(|(p, io)| { (box p as Box<rtio::RtioProcess + Send>, io.move_iter().map(|p| p.map(|p| { box p as Box<rtio::RtioPipe + Send> })).collect()) }) } fn kill(&mut self, pid: libc::pid_t, signum: int) -> IoResult<()> { process::Process::kill(pid, signum) } fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<rtio::RtioPipe + Send>> { Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioPipe + Send>) } #[cfg(unix)] fn tty_open(&mut self, fd: c_int, _readable: bool) -> IoResult<Box<rtio::RtioTTY + Send>> { if unsafe { libc::isatty(fd) }!= 0 { Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioTTY + Send>) } else { Err(IoError { code: libc::ENOTTY as uint, extra: 0, detail: None, }) } } #[cfg(windows)] fn tty_open(&mut self, fd: c_int, _readable: bool) -> IoResult<Box<rtio::RtioTTY + Send>> { if tty::is_tty(fd) { Ok(box tty::WindowsTTY::new(fd) as Box<rtio::RtioTTY + Send>) } else { Err(IoError { code: libc::ERROR_INVALID_HANDLE as uint, extra: 0, detail: None, }) } } fn signal(&mut self, _signal: int, _cb: Box<rtio::Callback>) -> IoResult<Box<rtio::RtioSignal + Send>> { Err(unimpl()) } }
pub mod process; mod util;
random_line_split
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = options.spec.get_packages(ws)?; let mut targets: Vec<_> = packages .into_iter() .flat_map(|pkg| { pkg.manifest() .targets() .iter() .filter(|target| filter_fn(target)) }) .map(Target::name) .collect(); targets.sort(); Ok(targets) } fn print_available_targets( filter_fn: fn(&Target) -> bool, ws: &Workspace<'_>, options: &CompileOptions, option_name: &str, plural_name: &str, ) -> CargoResult<()> { let targets = get_available_targets(filter_fn, ws, options)?; let mut output = String::new(); writeln!(output, "\"{}\" takes one argument.", option_name)?; if targets.is_empty() { writeln!(output, "No {} available.", plural_name)?; } else { writeln!(output, "Available {}:", plural_name)?; for target in targets { writeln!(output, " {}", target)?; } } bail!("{}", output) } pub fn print_available_packages(ws: &Workspace<'_>) -> CargoResult<()> { let packages = ws .members() .map(|pkg| pkg.name().as_str()) .collect::<Vec<_>>(); let mut output = "\"--package <SPEC>\" requires a SPEC format value, \ which can be any package ID specifier in the dependency graph.\n\ Run `cargo help pkgid` for more information about SPEC format.\n\n" .to_string(); if packages.is_empty() { // This would never happen. // Just in case something regresses we covers it here. writeln!(output, "No packages available.")?; } else { writeln!(output, "Possible packages/workspace members:")?; for package in packages { writeln!(output, " {}", package)?; } } bail!("{}", output) } pub fn print_available_examples(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()>
pub fn print_available_binaries(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bin, ws, options, "--bin", "binaries") } pub fn print_available_benches(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bench, ws, options, "--bench", "benches") } pub fn print_available_tests(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_test, ws, options, "--test", "tests") }
{ print_available_targets(Target::is_example, ws, options, "--example", "examples") }
identifier_body
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = options.spec.get_packages(ws)?; let mut targets: Vec<_> = packages .into_iter() .flat_map(|pkg| { pkg.manifest() .targets() .iter() .filter(|target| filter_fn(target)) }) .map(Target::name) .collect(); targets.sort(); Ok(targets) } fn
( filter_fn: fn(&Target) -> bool, ws: &Workspace<'_>, options: &CompileOptions, option_name: &str, plural_name: &str, ) -> CargoResult<()> { let targets = get_available_targets(filter_fn, ws, options)?; let mut output = String::new(); writeln!(output, "\"{}\" takes one argument.", option_name)?; if targets.is_empty() { writeln!(output, "No {} available.", plural_name)?; } else { writeln!(output, "Available {}:", plural_name)?; for target in targets { writeln!(output, " {}", target)?; } } bail!("{}", output) } pub fn print_available_packages(ws: &Workspace<'_>) -> CargoResult<()> { let packages = ws .members() .map(|pkg| pkg.name().as_str()) .collect::<Vec<_>>(); let mut output = "\"--package <SPEC>\" requires a SPEC format value, \ which can be any package ID specifier in the dependency graph.\n\ Run `cargo help pkgid` for more information about SPEC format.\n\n" .to_string(); if packages.is_empty() { // This would never happen. // Just in case something regresses we covers it here. writeln!(output, "No packages available.")?; } else { writeln!(output, "Possible packages/workspace members:")?; for package in packages { writeln!(output, " {}", package)?; } } bail!("{}", output) } pub fn print_available_examples(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_example, ws, options, "--example", "examples") } pub fn print_available_binaries(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bin, ws, options, "--bin", "binaries") } pub fn print_available_benches(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bench, ws, options, "--bench", "benches") } pub fn print_available_tests(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_test, ws, options, "--test", "tests") }
print_available_targets
identifier_name
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = options.spec.get_packages(ws)?; let mut targets: Vec<_> = packages .into_iter() .flat_map(|pkg| { pkg.manifest() .targets() .iter() .filter(|target| filter_fn(target)) }) .map(Target::name) .collect(); targets.sort(); Ok(targets) } fn print_available_targets( filter_fn: fn(&Target) -> bool, ws: &Workspace<'_>, options: &CompileOptions, option_name: &str, plural_name: &str, ) -> CargoResult<()> { let targets = get_available_targets(filter_fn, ws, options)?; let mut output = String::new(); writeln!(output, "\"{}\" takes one argument.", option_name)?; if targets.is_empty() { writeln!(output, "No {} available.", plural_name)?; } else { writeln!(output, "Available {}:", plural_name)?; for target in targets { writeln!(output, " {}", target)?; } } bail!("{}", output) } pub fn print_available_packages(ws: &Workspace<'_>) -> CargoResult<()> { let packages = ws .members() .map(|pkg| pkg.name().as_str()) .collect::<Vec<_>>(); let mut output = "\"--package <SPEC>\" requires a SPEC format value, \ which can be any package ID specifier in the dependency graph.\n\ Run `cargo help pkgid` for more information about SPEC format.\n\n" .to_string(); if packages.is_empty() { // This would never happen. // Just in case something regresses we covers it here. writeln!(output, "No packages available.")?; } else
bail!("{}", output) } pub fn print_available_examples(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_example, ws, options, "--example", "examples") } pub fn print_available_binaries(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bin, ws, options, "--bin", "binaries") } pub fn print_available_benches(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bench, ws, options, "--bench", "benches") } pub fn print_available_tests(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_test, ws, options, "--test", "tests") }
{ writeln!(output, "Possible packages/workspace members:")?; for package in packages { writeln!(output, " {}", package)?; } }
conditional_block
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = options.spec.get_packages(ws)?; let mut targets: Vec<_> = packages .into_iter() .flat_map(|pkg| { pkg.manifest() .targets() .iter() .filter(|target| filter_fn(target)) }) .map(Target::name) .collect(); targets.sort(); Ok(targets) } fn print_available_targets( filter_fn: fn(&Target) -> bool, ws: &Workspace<'_>, options: &CompileOptions, option_name: &str, plural_name: &str, ) -> CargoResult<()> { let targets = get_available_targets(filter_fn, ws, options)?; let mut output = String::new(); writeln!(output, "\"{}\" takes one argument.", option_name)?; if targets.is_empty() { writeln!(output, "No {} available.", plural_name)?; } else { writeln!(output, "Available {}:", plural_name)?; for target in targets { writeln!(output, " {}", target)?; } } bail!("{}", output) } pub fn print_available_packages(ws: &Workspace<'_>) -> CargoResult<()> { let packages = ws
which can be any package ID specifier in the dependency graph.\n\ Run `cargo help pkgid` for more information about SPEC format.\n\n" .to_string(); if packages.is_empty() { // This would never happen. // Just in case something regresses we covers it here. writeln!(output, "No packages available.")?; } else { writeln!(output, "Possible packages/workspace members:")?; for package in packages { writeln!(output, " {}", package)?; } } bail!("{}", output) } pub fn print_available_examples(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_example, ws, options, "--example", "examples") } pub fn print_available_binaries(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bin, ws, options, "--bin", "binaries") } pub fn print_available_benches(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bench, ws, options, "--bench", "benches") } pub fn print_available_tests(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_test, ws, options, "--test", "tests") }
.members() .map(|pkg| pkg.name().as_str()) .collect::<Vec<_>>(); let mut output = "\"--package <SPEC>\" requires a SPEC format value, \
random_line_split
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn
(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAINT_SPEC>) -> Self { R(reader) } } #[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"] pub struct INEPINT_R(crate::FieldReader<u16, u16>); impl INEPINT_R { pub(crate) fn new(bits: u16) -> Self { INEPINT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for INEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `OutEPInt` reader - OUT Endpoint Interrupt Bits"] pub struct OUTEPINT_R(crate::FieldReader<u16, u16>); impl OUTEPINT_R { pub(crate) fn new(bits: u16) -> Self { OUTEPINT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for OUTEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"] #[inline(always)] pub fn in_ep_int(&self) -> INEPINT_R { INEPINT_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - OUT Endpoint Interrupt Bits"] #[inline(always)] pub fn out_epint(&self) -> OUTEPINT_R { OUTEPINT_R::new(((self.bits >> 16) & 0xffff) as u16) } } #[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"] pub struct DAINT_SPEC; impl crate::RegisterSpec for DAINT_SPEC { type Ux = u32; } #[doc = "`read()` method returns [daint::R](R) reader structure"] impl crate::Readable for DAINT_SPEC { type Reader = R; } #[doc = "`reset()` method sets DAINT to value 0"] impl crate::Resettable for DAINT_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
deref
identifier_name
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAINT_SPEC>) -> Self { R(reader) } } #[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"] pub struct INEPINT_R(crate::FieldReader<u16, u16>); impl INEPINT_R { pub(crate) fn new(bits: u16) -> Self { INEPINT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for INEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `OutEPInt` reader - OUT Endpoint Interrupt Bits"] pub struct OUTEPINT_R(crate::FieldReader<u16, u16>); impl OUTEPINT_R { pub(crate) fn new(bits: u16) -> Self
} impl core::ops::Deref for OUTEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"] #[inline(always)] pub fn in_ep_int(&self) -> INEPINT_R { INEPINT_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - OUT Endpoint Interrupt Bits"] #[inline(always)] pub fn out_epint(&self) -> OUTEPINT_R { OUTEPINT_R::new(((self.bits >> 16) & 0xffff) as u16) } } #[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"] pub struct DAINT_SPEC; impl crate::RegisterSpec for DAINT_SPEC { type Ux = u32; } #[doc = "`read()` method returns [daint::R](R) reader structure"] impl crate::Readable for DAINT_SPEC { type Reader = R; } #[doc = "`reset()` method sets DAINT to value 0"] impl crate::Resettable for DAINT_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
{ OUTEPINT_R(crate::FieldReader::new(bits)) }
identifier_body
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAINT_SPEC>) -> Self { R(reader) } } #[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"] pub struct INEPINT_R(crate::FieldReader<u16, u16>); impl INEPINT_R { pub(crate) fn new(bits: u16) -> Self { INEPINT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for INEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `OutEPInt` reader - OUT Endpoint Interrupt Bits"] pub struct OUTEPINT_R(crate::FieldReader<u16, u16>); impl OUTEPINT_R { pub(crate) fn new(bits: u16) -> Self { OUTEPINT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for OUTEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"] #[inline(always)] pub fn in_ep_int(&self) -> INEPINT_R { INEPINT_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - OUT Endpoint Interrupt Bits"] #[inline(always)] pub fn out_epint(&self) -> OUTEPINT_R { OUTEPINT_R::new(((self.bits >> 16) & 0xffff) as u16) }
pub struct DAINT_SPEC; impl crate::RegisterSpec for DAINT_SPEC { type Ux = u32; } #[doc = "`read()` method returns [daint::R](R) reader structure"] impl crate::Readable for DAINT_SPEC { type Reader = R; } #[doc = "`reset()` method sets DAINT to value 0"] impl crate::Resettable for DAINT_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
} #[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"]
random_line_split
htmlhrelement.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::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use util::str::DOMString; #[dom_struct] pub struct HTMLHRElement { htmlelement: HTMLElement, } impl HTMLHRElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement { HTMLHRElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHRElement>
}
{ let element = HTMLHRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap) }
identifier_body
htmlhrelement.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::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use util::str::DOMString; #[dom_struct] pub struct HTMLHRElement { htmlelement: HTMLElement, } impl HTMLHRElement { fn
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement { HTMLHRElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHRElement> { let element = HTMLHRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap) } }
new_inherited
identifier_name
htmlhrelement.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::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use util::str::DOMString; #[dom_struct] pub struct HTMLHRElement { htmlelement: HTMLElement, } impl HTMLHRElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement { HTMLHRElement {
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHRElement> { let element = HTMLHRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap) } }
htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo_element_definition.mako.rs`. If you touch that file, you probably //! need to update the checked-in files for Servo. use cssparser::{ToCss, serialize_identifier}; use gecko_bindings::structs::{self, CSSPseudoElementType}; use properties::{ComputedValues, PropertyFlags}; use properties::longhands::display::computed_value as display; use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl}; use std::fmt; use string_cache::Atom; include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs")); impl ::selectors::parser::PseudoElement for PseudoElement { type Impl = SelectorImpl; fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool { if!self.supports_user_action_state() { return false; } return pseudo_class.is_safe_user_action_state(); } } impl PseudoElement { /// Returns the kind of cascade type that a given pseudo is going to use. /// /// In Gecko we only compute ::before and ::after eagerly. We save the rules /// for anonymous boxes separately, so we resolve them as precomputed /// pseudos. /// /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`. pub fn cascade_type(&self) -> PseudoElementCascadeType { if self.is_eager() { debug_assert!(!self.is_anon_box()); return PseudoElementCascadeType::Eager } if self.is_anon_box() { return PseudoElementCascadeType::Precomputed } PseudoElementCascadeType::Lazy } /// Whether the pseudo-element should inherit from the default computed /// values instead of from the parent element. /// /// This is not the common thing, but there are some pseudos (namely: /// ::backdrop), that shouldn't inherit from the parent element. pub fn inherits_from_default_values(&self) -> bool { matches!(*self, PseudoElement::Backdrop) } /// Gets the canonical index of this eagerly-cascaded pseudo-element. #[inline] pub fn eager_index(&self) -> usize { EAGER_PSEUDOS.iter().position(|p| p == self) .expect("Not an eager pseudo") } /// Creates a pseudo-element from an eager index. #[inline] pub fn from_eager_index(i: usize) -> Self { EAGER_PSEUDOS[i].clone() } /// Whether the current pseudo element is ::before or ::after. #[inline] pub fn is_before_or_after(&self) -> bool { self.is_before() || self.is_after() } /// Whether this pseudo-element is the ::before pseudo. #[inline] pub fn is_before(&self) -> bool { *self == PseudoElement::Before } /// Whether this pseudo-element is the ::after pseudo. #[inline] pub fn is_after(&self) -> bool { *self == PseudoElement::After } /// Whether this pseudo-element is ::first-letter. #[inline] pub fn is_first_letter(&self) -> bool { *self == PseudoElement::FirstLetter } /// Whether this pseudo-element is ::first-line. #[inline] pub fn is_first_line(&self) -> bool { *self == PseudoElement::FirstLine } /// Whether this pseudo-element is ::-moz-fieldset-content. #[inline] pub fn is_fieldset_content(&self) -> bool { *self == PseudoElement::FieldsetContent } /// Whether this pseudo-element is lazily-cascaded. #[inline] pub fn is_lazy(&self) -> bool { !self.is_eager() &&!self.is_precomputed() } /// Whether this pseudo-element is web-exposed. pub fn exposed_in_non_ua_sheets(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0 } /// Whether this pseudo-element supports user action selectors. pub fn supports_user_action_state(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE)!= 0 } /// Whether this pseudo-element skips flex/grid container display-based /// fixup. #[inline] pub fn skip_item_based_display_fixup(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0 } /// Whether this pseudo-element is precomputed. #[inline] pub fn is_precomputed(&self) -> bool
/// Covert non-canonical pseudo-element to canonical one, and keep a /// canonical one as it is. pub fn canonical(&self) -> PseudoElement { match *self { PseudoElement::MozPlaceholder => PseudoElement::Placeholder, _ => self.clone(), } } /// Property flag that properties must have to apply to this pseudo-element. #[inline] pub fn property_restriction(&self) -> Option<PropertyFlags> { match *self { PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER), PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE), PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER), _ => None, } } /// Whether this pseudo-element should actually exist if it has /// the given styles. pub fn should_exist(&self, style: &ComputedValues) -> bool { let display = style.get_box().clone_display(); if display == display::T::none { return false; } if self.is_before_or_after() && style.ineffective_content_property() { return false; } true } }
{ self.is_anon_box() }
identifier_body
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo_element_definition.mako.rs`. If you touch that file, you probably //! need to update the checked-in files for Servo. use cssparser::{ToCss, serialize_identifier}; use gecko_bindings::structs::{self, CSSPseudoElementType}; use properties::{ComputedValues, PropertyFlags}; use properties::longhands::display::computed_value as display; use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl}; use std::fmt; use string_cache::Atom; include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs")); impl ::selectors::parser::PseudoElement for PseudoElement { type Impl = SelectorImpl; fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool { if!self.supports_user_action_state() { return false; } return pseudo_class.is_safe_user_action_state(); } } impl PseudoElement { /// Returns the kind of cascade type that a given pseudo is going to use. /// /// In Gecko we only compute ::before and ::after eagerly. We save the rules /// for anonymous boxes separately, so we resolve them as precomputed /// pseudos. /// /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`. pub fn cascade_type(&self) -> PseudoElementCascadeType { if self.is_eager() { debug_assert!(!self.is_anon_box()); return PseudoElementCascadeType::Eager } if self.is_anon_box() { return PseudoElementCascadeType::Precomputed } PseudoElementCascadeType::Lazy } /// Whether the pseudo-element should inherit from the default computed /// values instead of from the parent element. /// /// This is not the common thing, but there are some pseudos (namely: /// ::backdrop), that shouldn't inherit from the parent element. pub fn inherits_from_default_values(&self) -> bool { matches!(*self, PseudoElement::Backdrop) } /// Gets the canonical index of this eagerly-cascaded pseudo-element. #[inline] pub fn eager_index(&self) -> usize { EAGER_PSEUDOS.iter().position(|p| p == self) .expect("Not an eager pseudo") } /// Creates a pseudo-element from an eager index. #[inline] pub fn from_eager_index(i: usize) -> Self { EAGER_PSEUDOS[i].clone() } /// Whether the current pseudo element is ::before or ::after. #[inline] pub fn is_before_or_after(&self) -> bool { self.is_before() || self.is_after() } /// Whether this pseudo-element is the ::before pseudo. #[inline] pub fn is_before(&self) -> bool { *self == PseudoElement::Before } /// Whether this pseudo-element is the ::after pseudo. #[inline] pub fn is_after(&self) -> bool { *self == PseudoElement::After } /// Whether this pseudo-element is ::first-letter. #[inline] pub fn is_first_letter(&self) -> bool { *self == PseudoElement::FirstLetter } /// Whether this pseudo-element is ::first-line. #[inline] pub fn is_first_line(&self) -> bool { *self == PseudoElement::FirstLine } /// Whether this pseudo-element is ::-moz-fieldset-content. #[inline] pub fn is_fieldset_content(&self) -> bool { *self == PseudoElement::FieldsetContent } /// Whether this pseudo-element is lazily-cascaded. #[inline] pub fn is_lazy(&self) -> bool { !self.is_eager() &&!self.is_precomputed() } /// Whether this pseudo-element is web-exposed. pub fn exposed_in_non_ua_sheets(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0 } /// Whether this pseudo-element supports user action selectors. pub fn supports_user_action_state(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE)!= 0 } /// Whether this pseudo-element skips flex/grid container display-based /// fixup. #[inline] pub fn skip_item_based_display_fixup(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0 } /// Whether this pseudo-element is precomputed. #[inline] pub fn is_precomputed(&self) -> bool { self.is_anon_box() } /// Covert non-canonical pseudo-element to canonical one, and keep a /// canonical one as it is. pub fn canonical(&self) -> PseudoElement { match *self { PseudoElement::MozPlaceholder => PseudoElement::Placeholder, _ => self.clone(), } } /// Property flag that properties must have to apply to this pseudo-element. #[inline] pub fn property_restriction(&self) -> Option<PropertyFlags> { match *self { PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER), PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE), PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER), _ => None, } } /// Whether this pseudo-element should actually exist if it has /// the given styles. pub fn should_exist(&self, style: &ComputedValues) -> bool { let display = style.get_box().clone_display(); if display == display::T::none { return false; } if self.is_before_or_after() && style.ineffective_content_property() { return false; } true }
}
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo_element_definition.mako.rs`. If you touch that file, you probably //! need to update the checked-in files for Servo. use cssparser::{ToCss, serialize_identifier}; use gecko_bindings::structs::{self, CSSPseudoElementType}; use properties::{ComputedValues, PropertyFlags}; use properties::longhands::display::computed_value as display; use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl}; use std::fmt; use string_cache::Atom; include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs")); impl ::selectors::parser::PseudoElement for PseudoElement { type Impl = SelectorImpl; fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool { if!self.supports_user_action_state() { return false; } return pseudo_class.is_safe_user_action_state(); } } impl PseudoElement { /// Returns the kind of cascade type that a given pseudo is going to use. /// /// In Gecko we only compute ::before and ::after eagerly. We save the rules /// for anonymous boxes separately, so we resolve them as precomputed /// pseudos. /// /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`. pub fn cascade_type(&self) -> PseudoElementCascadeType { if self.is_eager() { debug_assert!(!self.is_anon_box()); return PseudoElementCascadeType::Eager } if self.is_anon_box() { return PseudoElementCascadeType::Precomputed } PseudoElementCascadeType::Lazy } /// Whether the pseudo-element should inherit from the default computed /// values instead of from the parent element. /// /// This is not the common thing, but there are some pseudos (namely: /// ::backdrop), that shouldn't inherit from the parent element. pub fn inherits_from_default_values(&self) -> bool { matches!(*self, PseudoElement::Backdrop) } /// Gets the canonical index of this eagerly-cascaded pseudo-element. #[inline] pub fn eager_index(&self) -> usize { EAGER_PSEUDOS.iter().position(|p| p == self) .expect("Not an eager pseudo") } /// Creates a pseudo-element from an eager index. #[inline] pub fn from_eager_index(i: usize) -> Self { EAGER_PSEUDOS[i].clone() } /// Whether the current pseudo element is ::before or ::after. #[inline] pub fn is_before_or_after(&self) -> bool { self.is_before() || self.is_after() } /// Whether this pseudo-element is the ::before pseudo. #[inline] pub fn is_before(&self) -> bool { *self == PseudoElement::Before } /// Whether this pseudo-element is the ::after pseudo. #[inline] pub fn is_after(&self) -> bool { *self == PseudoElement::After } /// Whether this pseudo-element is ::first-letter. #[inline] pub fn is_first_letter(&self) -> bool { *self == PseudoElement::FirstLetter } /// Whether this pseudo-element is ::first-line. #[inline] pub fn is_first_line(&self) -> bool { *self == PseudoElement::FirstLine } /// Whether this pseudo-element is ::-moz-fieldset-content. #[inline] pub fn is_fieldset_content(&self) -> bool { *self == PseudoElement::FieldsetContent } /// Whether this pseudo-element is lazily-cascaded. #[inline] pub fn is_lazy(&self) -> bool { !self.is_eager() &&!self.is_precomputed() } /// Whether this pseudo-element is web-exposed. pub fn exposed_in_non_ua_sheets(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0 } /// Whether this pseudo-element supports user action selectors. pub fn supports_user_action_state(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE)!= 0 } /// Whether this pseudo-element skips flex/grid container display-based /// fixup. #[inline] pub fn skip_item_based_display_fixup(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0 } /// Whether this pseudo-element is precomputed. #[inline] pub fn is_precomputed(&self) -> bool { self.is_anon_box() } /// Covert non-canonical pseudo-element to canonical one, and keep a /// canonical one as it is. pub fn canonical(&self) -> PseudoElement { match *self { PseudoElement::MozPlaceholder => PseudoElement::Placeholder, _ => self.clone(), } } /// Property flag that properties must have to apply to this pseudo-element. #[inline] pub fn
(&self) -> Option<PropertyFlags> { match *self { PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER), PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE), PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER), _ => None, } } /// Whether this pseudo-element should actually exist if it has /// the given styles. pub fn should_exist(&self, style: &ComputedValues) -> bool { let display = style.get_box().clone_display(); if display == display::T::none { return false; } if self.is_before_or_after() && style.ineffective_content_property() { return false; } true } }
property_restriction
identifier_name
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each record is separated by a special '#' character (on a line by itself), which can be changed with the --separator flag. There is also a condensed view (-c or --condense) that will shorten the contents of each field to provide a summary view. Usage: xsv flatten [options] [<input>] flatten options: -c, --condense <arg> Limits the length of each field to the value specified. If the field is UTF-8 encoded, then <arg> refers to the number of code points. Otherwise, it refers to the number of bytes. -s, --separator <arg> A string of characters to write after each record. When non-empty, a new line is automatically appended to the separator. [default: #] Common options: -h, --help Display this message -n, --no-headers When set, the first row will not be interpreted as headers. When set, the name of each field will be its index. -d, --delimiter <arg> The field delimiter for reading CSV data. Must be a single character. (default:,) "; #[derive(RustcDecodable)] struct Args { arg_input: Option<String>, flag_condense: Option<usize>, flag_separator: String, flag_no_headers: bool, flag_delimiter: Option<Delimiter>, } pub fn run(argv: &[&str]) -> CliResult<()>
wtr.write_all(&header)?; } wtr.write_all(b"\t")?; wtr.write_all(&*util::condense( Cow::Borrowed(&*field), args.flag_condense))?; wtr.write_all(b"\n")?; } } wtr.flush()?; Ok(()) }
{ let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = TabWriter::new(io::stdout()); let mut first = true; for r in rdr.byte_records() { if !first && !args.flag_separator.is_empty() { writeln!(&mut wtr, "{}", args.flag_separator)?; } first = false; let r = r?; for (i, (header, field)) in headers.iter().zip(&r).enumerate() { if rconfig.no_headers { write!(&mut wtr, "{}", i)?; } else {
identifier_body
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each record is separated by a special '#' character (on a line by itself), which can be changed with the --separator flag. There is also a condensed view (-c or --condense) that will shorten the contents of each field to provide a summary view. Usage: xsv flatten [options] [<input>] flatten options: -c, --condense <arg> Limits the length of each field to the value specified. If the field is UTF-8 encoded, then <arg> refers to the number of code points. Otherwise, it refers to the number of bytes. -s, --separator <arg> A string of characters to write after each record. When non-empty, a new line is automatically appended to the separator. [default: #]
-d, --delimiter <arg> The field delimiter for reading CSV data. Must be a single character. (default:,) "; #[derive(RustcDecodable)] struct Args { arg_input: Option<String>, flag_condense: Option<usize>, flag_separator: String, flag_no_headers: bool, flag_delimiter: Option<Delimiter>, } pub fn run(argv: &[&str]) -> CliResult<()> { let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = TabWriter::new(io::stdout()); let mut first = true; for r in rdr.byte_records() { if!first &&!args.flag_separator.is_empty() { writeln!(&mut wtr, "{}", args.flag_separator)?; } first = false; let r = r?; for (i, (header, field)) in headers.iter().zip(&r).enumerate() { if rconfig.no_headers { write!(&mut wtr, "{}", i)?; } else { wtr.write_all(&header)?; } wtr.write_all(b"\t")?; wtr.write_all(&*util::condense( Cow::Borrowed(&*field), args.flag_condense))?; wtr.write_all(b"\n")?; } } wtr.flush()?; Ok(()) }
Common options: -h, --help Display this message -n, --no-headers When set, the first row will not be interpreted as headers. When set, the name of each field will be its index.
random_line_split
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each record is separated by a special '#' character (on a line by itself), which can be changed with the --separator flag. There is also a condensed view (-c or --condense) that will shorten the contents of each field to provide a summary view. Usage: xsv flatten [options] [<input>] flatten options: -c, --condense <arg> Limits the length of each field to the value specified. If the field is UTF-8 encoded, then <arg> refers to the number of code points. Otherwise, it refers to the number of bytes. -s, --separator <arg> A string of characters to write after each record. When non-empty, a new line is automatically appended to the separator. [default: #] Common options: -h, --help Display this message -n, --no-headers When set, the first row will not be interpreted as headers. When set, the name of each field will be its index. -d, --delimiter <arg> The field delimiter for reading CSV data. Must be a single character. (default:,) "; #[derive(RustcDecodable)] struct Args { arg_input: Option<String>, flag_condense: Option<usize>, flag_separator: String, flag_no_headers: bool, flag_delimiter: Option<Delimiter>, } pub fn run(argv: &[&str]) -> CliResult<()> { let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = TabWriter::new(io::stdout()); let mut first = true; for r in rdr.byte_records() { if!first &&!args.flag_separator.is_empty() { writeln!(&mut wtr, "{}", args.flag_separator)?; } first = false; let r = r?; for (i, (header, field)) in headers.iter().zip(&r).enumerate() { if rconfig.no_headers { write!(&mut wtr, "{}", i)?; } else
wtr.write_all(b"\t")?; wtr.write_all(&*util::condense( Cow::Borrowed(&*field), args.flag_condense))?; wtr.write_all(b"\n")?; } } wtr.flush()?; Ok(()) }
{ wtr.write_all(&header)?; }
conditional_block
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each record is separated by a special '#' character (on a line by itself), which can be changed with the --separator flag. There is also a condensed view (-c or --condense) that will shorten the contents of each field to provide a summary view. Usage: xsv flatten [options] [<input>] flatten options: -c, --condense <arg> Limits the length of each field to the value specified. If the field is UTF-8 encoded, then <arg> refers to the number of code points. Otherwise, it refers to the number of bytes. -s, --separator <arg> A string of characters to write after each record. When non-empty, a new line is automatically appended to the separator. [default: #] Common options: -h, --help Display this message -n, --no-headers When set, the first row will not be interpreted as headers. When set, the name of each field will be its index. -d, --delimiter <arg> The field delimiter for reading CSV data. Must be a single character. (default:,) "; #[derive(RustcDecodable)] struct Args { arg_input: Option<String>, flag_condense: Option<usize>, flag_separator: String, flag_no_headers: bool, flag_delimiter: Option<Delimiter>, } pub fn
(argv: &[&str]) -> CliResult<()> { let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = TabWriter::new(io::stdout()); let mut first = true; for r in rdr.byte_records() { if!first &&!args.flag_separator.is_empty() { writeln!(&mut wtr, "{}", args.flag_separator)?; } first = false; let r = r?; for (i, (header, field)) in headers.iter().zip(&r).enumerate() { if rconfig.no_headers { write!(&mut wtr, "{}", i)?; } else { wtr.write_all(&header)?; } wtr.write_all(b"\t")?; wtr.write_all(&*util::condense( Cow::Borrowed(&*field), args.flag_condense))?; wtr.write_all(b"\n")?; } } wtr.flush()?; Ok(()) }
run
identifier_name
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if a slice is sorted properly. pub fn check_sorted<E>(candidate: &[E]) where E: Ord + Clone + Debug { let sorted = { let mut copy = candidate.iter().cloned().collect::<Vec<_>>(); copy.sort(); copy }; assert_eq!(sorted.as_slice(), candidate); } #[test] fn test_check_sorted() { let sorted = vec![1, 2, 3, 4, 5]; check_sorted(&sorted); } #[test] #[should_panic] fn test_check_unsorted() { let unsorted = vec![1, 3, 2]; check_sorted(&unsorted); } #[cfg(test)] mod tests { use regex::Regex; use std::collections::HashSet; use std::io::{BufReader, BufRead}; use std::fs::{self, File}; use std::path::Path; /// A test to check if all source files are covered by `Cargo.toml` #[test] fn check_sources_covered() { let sources = get_source_files(); let bins = get_toml_paths(); let not_covered = get_not_covered(&sources, &bins); if!not_covered.is_empty() { println!("Error, the following source files are not covered by Cargo.toml:"); for source in &not_covered { println!("{}", source); } panic!("Please add the previous source files to Cargo.toml"); } } /// Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::read_dir("./src").unwrap(); paths.map(|p| { p.unwrap() .path() .file_name() .unwrap() .to_os_string() .into_string() .unwrap() }) .filter(|s| s[..].ends_with(".rs")) .collect() } /// Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open("./Cargo.toml").unwrap(); let reader = BufReader::new(c_toml); let regex = Regex::new("path = \"(.*)\"").unwrap(); reader.lines() .filter_map(|l| { let l = l.unwrap(); regex.captures(&l).map(|c| { c.at(1) .map(|s| Path::new(s)) .unwrap() .file_name() .unwrap() .to_string_lossy() .into_owned() }) }) .collect() } /// Returns the filenames of the source files which are not covered by Cargo.toml fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String>
}
{ sources.difference(paths).collect() }
identifier_body
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if a slice is sorted properly. pub fn check_sorted<E>(candidate: &[E]) where E: Ord + Clone + Debug { let sorted = { let mut copy = candidate.iter().cloned().collect::<Vec<_>>(); copy.sort(); copy }; assert_eq!(sorted.as_slice(), candidate); } #[test] fn test_check_sorted() { let sorted = vec![1, 2, 3, 4, 5]; check_sorted(&sorted); } #[test] #[should_panic] fn
() { let unsorted = vec![1, 3, 2]; check_sorted(&unsorted); } #[cfg(test)] mod tests { use regex::Regex; use std::collections::HashSet; use std::io::{BufReader, BufRead}; use std::fs::{self, File}; use std::path::Path; /// A test to check if all source files are covered by `Cargo.toml` #[test] fn check_sources_covered() { let sources = get_source_files(); let bins = get_toml_paths(); let not_covered = get_not_covered(&sources, &bins); if!not_covered.is_empty() { println!("Error, the following source files are not covered by Cargo.toml:"); for source in &not_covered { println!("{}", source); } panic!("Please add the previous source files to Cargo.toml"); } } /// Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::read_dir("./src").unwrap(); paths.map(|p| { p.unwrap() .path() .file_name() .unwrap() .to_os_string() .into_string() .unwrap() }) .filter(|s| s[..].ends_with(".rs")) .collect() } /// Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open("./Cargo.toml").unwrap(); let reader = BufReader::new(c_toml); let regex = Regex::new("path = \"(.*)\"").unwrap(); reader.lines() .filter_map(|l| { let l = l.unwrap(); regex.captures(&l).map(|c| { c.at(1) .map(|s| Path::new(s)) .unwrap() .file_name() .unwrap() .to_string_lossy() .into_owned() }) }) .collect() } /// Returns the filenames of the source files which are not covered by Cargo.toml fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { sources.difference(paths).collect() } }
test_check_unsorted
identifier_name
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if a slice is sorted properly. pub fn check_sorted<E>(candidate: &[E]) where E: Ord + Clone + Debug { let sorted = { let mut copy = candidate.iter().cloned().collect::<Vec<_>>(); copy.sort(); copy }; assert_eq!(sorted.as_slice(), candidate); } #[test] fn test_check_sorted() { let sorted = vec![1, 2, 3, 4, 5]; check_sorted(&sorted); } #[test] #[should_panic] fn test_check_unsorted() { let unsorted = vec![1, 3, 2]; check_sorted(&unsorted); } #[cfg(test)] mod tests { use regex::Regex; use std::collections::HashSet; use std::io::{BufReader, BufRead}; use std::fs::{self, File}; use std::path::Path; /// A test to check if all source files are covered by `Cargo.toml` #[test] fn check_sources_covered() { let sources = get_source_files(); let bins = get_toml_paths(); let not_covered = get_not_covered(&sources, &bins); if!not_covered.is_empty()
} /// Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::read_dir("./src").unwrap(); paths.map(|p| { p.unwrap() .path() .file_name() .unwrap() .to_os_string() .into_string() .unwrap() }) .filter(|s| s[..].ends_with(".rs")) .collect() } /// Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open("./Cargo.toml").unwrap(); let reader = BufReader::new(c_toml); let regex = Regex::new("path = \"(.*)\"").unwrap(); reader.lines() .filter_map(|l| { let l = l.unwrap(); regex.captures(&l).map(|c| { c.at(1) .map(|s| Path::new(s)) .unwrap() .file_name() .unwrap() .to_string_lossy() .into_owned() }) }) .collect() } /// Returns the filenames of the source files which are not covered by Cargo.toml fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { sources.difference(paths).collect() } }
{ println!("Error, the following source files are not covered by Cargo.toml:"); for source in &not_covered { println!("{}", source); } panic!("Please add the previous source files to Cargo.toml"); }
conditional_block
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if a slice is sorted properly. pub fn check_sorted<E>(candidate: &[E]) where E: Ord + Clone + Debug { let sorted = { let mut copy = candidate.iter().cloned().collect::<Vec<_>>(); copy.sort(); copy }; assert_eq!(sorted.as_slice(), candidate); } #[test] fn test_check_sorted() { let sorted = vec![1, 2, 3, 4, 5]; check_sorted(&sorted); } #[test] #[should_panic] fn test_check_unsorted() { let unsorted = vec![1, 3, 2]; check_sorted(&unsorted); } #[cfg(test)] mod tests { use regex::Regex; use std::collections::HashSet; use std::io::{BufReader, BufRead}; use std::fs::{self, File}; use std::path::Path; /// A test to check if all source files are covered by `Cargo.toml` #[test] fn check_sources_covered() { let sources = get_source_files(); let bins = get_toml_paths(); let not_covered = get_not_covered(&sources, &bins); if!not_covered.is_empty() { println!("Error, the following source files are not covered by Cargo.toml:"); for source in &not_covered { println!("{}", source); } panic!("Please add the previous source files to Cargo.toml"); } } /// Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::read_dir("./src").unwrap(); paths.map(|p| { p.unwrap() .path() .file_name() .unwrap() .to_os_string() .into_string() .unwrap() }) .filter(|s| s[..].ends_with(".rs")) .collect()
/// Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open("./Cargo.toml").unwrap(); let reader = BufReader::new(c_toml); let regex = Regex::new("path = \"(.*)\"").unwrap(); reader.lines() .filter_map(|l| { let l = l.unwrap(); regex.captures(&l).map(|c| { c.at(1) .map(|s| Path::new(s)) .unwrap() .file_name() .unwrap() .to_string_lossy() .into_owned() }) }) .collect() } /// Returns the filenames of the source files which are not covered by Cargo.toml fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { sources.difference(paths).collect() } }
}
random_line_split
expr-match-generic-unique1.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. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] fn
<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = match true { true => { expected.clone() }, _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); } pub fn main() { test_box(); }
test_generic
identifier_name
expr-match-generic-unique1.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. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] fn test_generic<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = match true { true =>
, _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); } pub fn main() { test_box(); }
{ expected.clone() }
conditional_block
expr-match-generic-unique1.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. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] fn test_generic<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = match true { true => { expected.clone() }, _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_box()
pub fn main() { test_box(); }
{ fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); }
identifier_body
expr-match-generic-unique1.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. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] fn test_generic<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = match true { true => { expected.clone() },
assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); } pub fn main() { test_box(); }
_ => panic!("wat") };
random_line_split
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::time::Duration; use sdl2_image::{INIT_PNG, INIT_JPG}; const MS_PER_UPDATE: i64 = 15; fn
() { // start sdl2 with everything let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut lag = 0; let mut last_tick: DateTime<UTC> = UTC::now(); let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap(); // Create a window let window = match video_ctx.window("Mageon", common::DEF_WINDOW_WIDTH, common::DEF_WINDOW_HEIGHT).position_centered().opengl().build() { Ok(window) => window, Err(err) => panic!("failed to create window: {:?}", err) }; // Create a rendering context let renderer = match window.renderer().build() { Ok(renderer) => renderer, Err(err) => panic!("failed to create renderer: {:?}", err) }; let mut events = ctx.event_pump().unwrap(); let mut game = Game::new(); let mut visualizer = Visualizer::new(renderer); // loop until we receive a QuitEvent 'event : loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, _ => game.proc_event(event), } } let ms = (UTC::now() - last_tick).num_milliseconds(); last_tick = UTC::now(); lag = lag + ms; while lag > MS_PER_UPDATE { game.update(); lag = lag - MS_PER_UPDATE; } // println!("{}", 1000.0/(ms as f64)); visualizer.draw(&game, (lag as f64)/(MS_PER_UPDATE as f64)); std::thread::sleep(Duration::from_millis(1)); } }
main
identifier_name
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::time::Duration; use sdl2_image::{INIT_PNG, INIT_JPG}; const MS_PER_UPDATE: i64 = 15; fn main()
let mut events = ctx.event_pump().unwrap(); let mut game = Game::new(); let mut visualizer = Visualizer::new(renderer); // loop until we receive a QuitEvent 'event : loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, _ => game.proc_event(event), } } let ms = (UTC::now() - last_tick).num_milliseconds(); last_tick = UTC::now(); lag = lag + ms; while lag > MS_PER_UPDATE { game.update(); lag = lag - MS_PER_UPDATE; } // println!("{}", 1000.0/(ms as f64)); visualizer.draw(&game, (lag as f64)/(MS_PER_UPDATE as f64)); std::thread::sleep(Duration::from_millis(1)); } }
{ // start sdl2 with everything let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut lag = 0; let mut last_tick: DateTime<UTC> = UTC::now(); let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap(); // Create a window let window = match video_ctx.window("Mageon", common::DEF_WINDOW_WIDTH, common::DEF_WINDOW_HEIGHT).position_centered().opengl().build() { Ok(window) => window, Err(err) => panic!("failed to create window: {:?}", err) }; // Create a rendering context let renderer = match window.renderer().build() { Ok(renderer) => renderer, Err(err) => panic!("failed to create renderer: {:?}", err) };
identifier_body
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::time::Duration; use sdl2_image::{INIT_PNG, INIT_JPG}; const MS_PER_UPDATE: i64 = 15; fn main() { // start sdl2 with everything let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut lag = 0; let mut last_tick: DateTime<UTC> = UTC::now(); let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap(); // Create a window let window = match video_ctx.window("Mageon", common::DEF_WINDOW_WIDTH, common::DEF_WINDOW_HEIGHT).position_centered().opengl().build() { Ok(window) => window, Err(err) => panic!("failed to create window: {:?}", err) }; // Create a rendering context let renderer = match window.renderer().build() { Ok(renderer) => renderer, Err(err) => panic!("failed to create renderer: {:?}", err) }; let mut events = ctx.event_pump().unwrap(); let mut game = Game::new();
let mut visualizer = Visualizer::new(renderer); // loop until we receive a QuitEvent 'event : loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, _ => game.proc_event(event), } } let ms = (UTC::now() - last_tick).num_milliseconds(); last_tick = UTC::now(); lag = lag + ms; while lag > MS_PER_UPDATE { game.update(); lag = lag - MS_PER_UPDATE; } // println!("{}", 1000.0/(ms as f64)); visualizer.draw(&game, (lag as f64)/(MS_PER_UPDATE as f64)); std::thread::sleep(Duration::from_millis(1)); } }
random_line_split
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) } pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)]; let null = cx.null(); f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx) } pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let zero = cx.number(0.0); let o = f.construct(&mut cx, vec![zero])?; let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?; let args: Vec<Handle<JsValue>> = vec![]; get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx) } trait CheckArgument<'a> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>; } impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> { self.argument::<V>(i) } } pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.check_argument::<JsString>(0)?; cx.check_argument::<JsNumber>(1)?; Ok(cx.undefined()) } pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> { panic!("zomg") } pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err(); panic!("this should override the RangeError") } pub fn
(mut cx: FunctionContext) -> JsResult<JsNumber> { let n = cx.len(); Ok(cx.number(n)) } pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.this().upcast()) } pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> { let this = cx.this(); let this = this.downcast::<JsObject>().or_throw(&mut cx)?; let t = cx.boolean(true); this.set(&mut cx, "modified", t)?; Ok(cx.undefined()) } pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> { let b = cx.argument_opt(0).is_some(); Ok(cx.boolean(b)) } pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.argument(0)?; Ok(s) } pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = 0; for _ in 1..100 { cx.execute_scoped(|mut cx| { let n = cx.number(1); i += n.value() as i32; }); } Ok(cx.number(i)) } pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = cx.number(0); for _ in 1..100 { i = cx.compute_scoped(|mut cx| { let n = cx.number(1); Ok(cx.number((i.value() as i32) + (n.value() as i32))) })?; } Ok(i) } pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast()); Ok(cx.try_catch(|cx| { let _ = cx.throw(v)?; Ok(cx.string("unreachable").upcast()) }).unwrap_or_else(|err| err)) } pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let f: Handle<JsFunction> = cx.argument(0)?; Ok(cx.try_catch(|cx| { let global = cx.global(); let args: Vec<Handle<JsValue>> = vec![]; f.call(cx, global, args) }).unwrap_or_else(|err| err)) } pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { panic!("oh no") }) .unwrap_or_else(|err| err)) } pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { Err(Throw) }) .unwrap_or_else(|err| err)) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber>() { Ok(cx.string(format!("{}", e))) } else { panic!() } }
num_arguments
identifier_name
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) } pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)]; let null = cx.null(); f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx) } pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let zero = cx.number(0.0); let o = f.construct(&mut cx, vec![zero])?; let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?; let args: Vec<Handle<JsValue>> = vec![]; get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx) } trait CheckArgument<'a> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>; } impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> { self.argument::<V>(i) } } pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.check_argument::<JsString>(0)?; cx.check_argument::<JsNumber>(1)?; Ok(cx.undefined()) } pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> { panic!("zomg") } pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err(); panic!("this should override the RangeError") } pub fn num_arguments(mut cx: FunctionContext) -> JsResult<JsNumber> { let n = cx.len(); Ok(cx.number(n)) } pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.this().upcast()) } pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> { let this = cx.this(); let this = this.downcast::<JsObject>().or_throw(&mut cx)?; let t = cx.boolean(true); this.set(&mut cx, "modified", t)?; Ok(cx.undefined()) } pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> { let b = cx.argument_opt(0).is_some(); Ok(cx.boolean(b)) } pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.argument(0)?; Ok(s) } pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = 0; for _ in 1..100 { cx.execute_scoped(|mut cx| { let n = cx.number(1); i += n.value() as i32; }); } Ok(cx.number(i)) } pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = cx.number(0); for _ in 1..100 { i = cx.compute_scoped(|mut cx| { let n = cx.number(1); Ok(cx.number((i.value() as i32) + (n.value() as i32))) })?; } Ok(i) } pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast()); Ok(cx.try_catch(|cx| { let _ = cx.throw(v)?; Ok(cx.string("unreachable").upcast()) }).unwrap_or_else(|err| err)) } pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let f: Handle<JsFunction> = cx.argument(0)?; Ok(cx.try_catch(|cx| { let global = cx.global(); let args: Vec<Handle<JsValue>> = vec![]; f.call(cx, global, args) }).unwrap_or_else(|err| err)) } pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { panic!("oh no") }) .unwrap_or_else(|err| err)) } pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { Err(Throw) }) .unwrap_or_else(|err| err)) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString>
{ let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber>() { Ok(cx.string(format!("{}", e))) } else { panic!() } }
identifier_body
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) } pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)]; let null = cx.null(); f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx) } pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let zero = cx.number(0.0); let o = f.construct(&mut cx, vec![zero])?; let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?; let args: Vec<Handle<JsValue>> = vec![]; get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx) } trait CheckArgument<'a> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>; } impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> { self.argument::<V>(i) } } pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.check_argument::<JsString>(0)?; cx.check_argument::<JsNumber>(1)?; Ok(cx.undefined()) } pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> { panic!("zomg") } pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err(); panic!("this should override the RangeError") } pub fn num_arguments(mut cx: FunctionContext) -> JsResult<JsNumber> { let n = cx.len(); Ok(cx.number(n)) } pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.this().upcast()) } pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> { let this = cx.this(); let this = this.downcast::<JsObject>().or_throw(&mut cx)?; let t = cx.boolean(true); this.set(&mut cx, "modified", t)?; Ok(cx.undefined()) } pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> { let b = cx.argument_opt(0).is_some(); Ok(cx.boolean(b)) } pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.argument(0)?; Ok(s) } pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = 0; for _ in 1..100 { cx.execute_scoped(|mut cx| { let n = cx.number(1); i += n.value() as i32; }); }
pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = cx.number(0); for _ in 1..100 { i = cx.compute_scoped(|mut cx| { let n = cx.number(1); Ok(cx.number((i.value() as i32) + (n.value() as i32))) })?; } Ok(i) } pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast()); Ok(cx.try_catch(|cx| { let _ = cx.throw(v)?; Ok(cx.string("unreachable").upcast()) }).unwrap_or_else(|err| err)) } pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let f: Handle<JsFunction> = cx.argument(0)?; Ok(cx.try_catch(|cx| { let global = cx.global(); let args: Vec<Handle<JsValue>> = vec![]; f.call(cx, global, args) }).unwrap_or_else(|err| err)) } pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { panic!("oh no") }) .unwrap_or_else(|err| err)) } pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { Err(Throw) }) .unwrap_or_else(|err| err)) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber>() { Ok(cx.string(format!("{}", e))) } else { panic!() } }
Ok(cx.number(i)) }
random_line_split
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) } pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)]; let null = cx.null(); f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx) } pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> { let f = cx.argument::<JsFunction>(0)?; let zero = cx.number(0.0); let o = f.construct(&mut cx, vec![zero])?; let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?; let args: Vec<Handle<JsValue>> = vec![]; get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx) } trait CheckArgument<'a> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>; } impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> { fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> { self.argument::<V>(i) } } pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.check_argument::<JsString>(0)?; cx.check_argument::<JsNumber>(1)?; Ok(cx.undefined()) } pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> { panic!("zomg") } pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> { cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err(); panic!("this should override the RangeError") } pub fn num_arguments(mut cx: FunctionContext) -> JsResult<JsNumber> { let n = cx.len(); Ok(cx.number(n)) } pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.this().upcast()) } pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> { let this = cx.this(); let this = this.downcast::<JsObject>().or_throw(&mut cx)?; let t = cx.boolean(true); this.set(&mut cx, "modified", t)?; Ok(cx.undefined()) } pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> { let b = cx.argument_opt(0).is_some(); Ok(cx.boolean(b)) } pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.argument(0)?; Ok(s) } pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = 0; for _ in 1..100 { cx.execute_scoped(|mut cx| { let n = cx.number(1); i += n.value() as i32; }); } Ok(cx.number(i)) } pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = cx.number(0); for _ in 1..100 { i = cx.compute_scoped(|mut cx| { let n = cx.number(1); Ok(cx.number((i.value() as i32) + (n.value() as i32))) })?; } Ok(i) } pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast()); Ok(cx.try_catch(|cx| { let _ = cx.throw(v)?; Ok(cx.string("unreachable").upcast()) }).unwrap_or_else(|err| err)) } pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { let f: Handle<JsFunction> = cx.argument(0)?; Ok(cx.try_catch(|cx| { let global = cx.global(); let args: Vec<Handle<JsValue>> = vec![]; f.call(cx, global, args) }).unwrap_or_else(|err| err)) } pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { panic!("oh no") }) .unwrap_or_else(|err| err)) } pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.try_catch(|_| { Err(Throw) }) .unwrap_or_else(|err| err)) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber>()
else { panic!() } }
{ Ok(cx.string(format!("{}", e))) }
conditional_block
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { // return res.redirect("/login"); // } // let user = user.unwrap(); let year = req.param("year").and_then(|y| y.parse::<i32>().ok()); if year.is_none()
let year = year.unwrap(); let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id); let data = WorksheetModel { year: year, has_activities: activities.len() > 0, activities: activities.iter().map(|a| ActivityModel { points: a.points, description: a.description.clone() }).collect() }; res.render("templates/worksheet", &data) } #[derive(RustcEncodable)] struct WorksheetModel { year: i32, has_activities: bool, activities: Vec<ActivityModel> } #[derive(RustcEncodable)] struct ActivityModel { points: i32, description: String }
{ res.set(StatusCode::BadRequest); return res.send("Invalid year"); }
conditional_block
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { // return res.redirect("/login"); // } // let user = user.unwrap(); let year = req.param("year").and_then(|y| y.parse::<i32>().ok()); if year.is_none() { res.set(StatusCode::BadRequest); return res.send("Invalid year"); } let year = year.unwrap(); let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id); let data = WorksheetModel { year: year, has_activities: activities.len() > 0, activities: activities.iter().map(|a| ActivityModel { points: a.points, description: a.description.clone() }).collect() }; res.render("templates/worksheet", &data)
} #[derive(RustcEncodable)] struct WorksheetModel { year: i32, has_activities: bool, activities: Vec<ActivityModel> } #[derive(RustcEncodable)] struct ActivityModel { points: i32, description: String }
random_line_split
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { // return res.redirect("/login"); // } // let user = user.unwrap(); let year = req.param("year").and_then(|y| y.parse::<i32>().ok()); if year.is_none() { res.set(StatusCode::BadRequest); return res.send("Invalid year"); } let year = year.unwrap(); let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id); let data = WorksheetModel { year: year, has_activities: activities.len() > 0, activities: activities.iter().map(|a| ActivityModel { points: a.points, description: a.description.clone() }).collect() }; res.render("templates/worksheet", &data) } #[derive(RustcEncodable)] struct WorksheetModel { year: i32, has_activities: bool, activities: Vec<ActivityModel> } #[derive(RustcEncodable)] struct
{ points: i32, description: String }
ActivityModel
identifier_name
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> PrimeSeq { PrimeSeq { values: vec![], max: 2 } } } impl Seq<u64> for PrimeSeq { fn range(&self, start: usize, end: usize) -> &[u64] { return &self.values[start..end]; } fn inverse(&self, elem: &u64) -> Option<usize> { return match self.values.binary_search(elem) { Ok(index) => Some(index), Err(_) => None, } } } pub fn isqrt(number: u64) -> u64 { return (number as f64).sqrt().ceil() as u64; } pub fn factors(number: u64) -> Vec<u64> { let mut result = vec![]; let mut remain = number; let mut i = 2; while (i <= remain) { if remain % i == 0 { remain /= i; result.push(i); } else { i += 1; } } return result; } pub fn subset_products(factors: &Vec<u64>) -> Vec<u64> { let result = Vec::new(); for a in factors { } return result; } /** * a and b must be sorted arrays * returns tuple of common and non-common factors */ pub fn common_factors(a: &Vec<u64>, b: &Vec<u64>) -> (Vec<u64>, Vec<u64>) { let mut common = Vec::new(); let mut inverse = Vec::new(); let mut a_index = 0; let mut b_index = 0; let max_len = if a.len() > b.len() { a.len() } else { b.len() }; while a_index < a.len() && b_index < b.len() { let a_val = a[a_index]; let b_val = b[b_index]; if (a_val == b_val) { common.push(a_val); a_index += 1; b_index += 1; } else if (a_val < b_val) { inverse.push(a_val); a_index += 1; } else { inverse.push(b_val); b_index += 1; } } for a_remain in a_index..a.len() { inverse.push(a[a_remain]); } for b_remain in b_index..b.len() { inverse.push(b[b_remain]); } return (common, inverse); } pub fn is_prime(number: u64) -> bool { for i in 2..isqrt(number) { if number % i == 0 { return false; } } return true; } /* * maximum set */ pub fn maximum_factors(factors: &Vec<Vec<u64>>) -> Vec<u64> { let mut progress = vec![0; factors.len() as usize]; let mut common = Vec::new(); let mut complete = false; while!complete { let mut nothing_remaining = true; let mut lowest_index = 0; let mut lowest = 999999999; for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len()) { nothing_remaining = false; // check if value is lowest let val = current_set[current_progress]; if val < lowest { lowest_index = index; lowest = val; } } } for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len() && current_set[current_progress] <= lowest) { progress[index] += 1; } } complete = nothing_remaining; if!complete { common.push(lowest); } } return common; } pub fn high_freq_factors(factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> { let all_factors = maximum_factors(factors);
let mut common = Vec::new(); if (all_factors.len() == 0) { return common; } let mut first = 0; let highest = all_factors[all_factors.len() - 1]; for comp in all_factors { if comp > 255 { return common; } let mut lowest_index = 0; let mut lowest = highest; let mut freq = 0; let mut have_remaining = false; //println!("{:?} :: {:?} :: {:?}", first, progress, lowest); for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len()) { have_remaining = true; let val = current_set[current_progress]; if val <= lowest { lowest_index = index; lowest = val; } if val == comp { freq += 1; } } } if!have_remaining || common.len() > limit as usize { return common; } if freq > min_freq { first += 1; for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len() && current_set[current_progress] <= comp) { progress[index] += 1; } } common.push(comp); } else { progress[lowest_index] += 1; } } return common; } pub fn find_primes(ps: &mut PrimeSeq, max: u64) { let mut number = ps.max; while number < max { let mut isprime = true; for i in 2..isqrt(number) { if number % i == 0 { isprime = false; } } if isprime { ps.values.push(number); } number += 1; } ps.max = max; } pub fn fib(n: u64) -> (u64, u64, u64) { let mut count = 1; let mut fb1 = 1; let mut fb2 = 2; while fb2 <= n { count += 1; fb2 = fb1 + fb2; fb1 = fb2 - fb1; } return (count, n - fb1, fb2 - n); } pub fn sum(numbers: Vec<u64>) -> u64 { let mut total = 0; for i in numbers { total += i; } return total; } pub fn product(numbers: &Vec<u64>) -> u64 { let mut p = 1; for i in numbers { p *= i; } return p; } pub fn sequence(seq: &Seq<u64>, start: u32, size: usize) { let mut grid = vec![0; size * size]; let start: usize = start as usize; for i in 0..size*size { let number = start + i; grid[i] = number; } for i in 0..size { for j in 0..size { print!("{}, ", grid[i * size + j]) } println!(""); } } pub fn fill_sine(data: &mut [i16]) { for t in 0..data.len() { let fq = (t as f32) * 0.03; let x = fq.sin() * 2500.0; data[t] = x as i16; } } pub fn fill_bits(data: &mut [i16]) { for t in 0..data.len() { let ts = ((t as f32) * 0.1) as i16; let val = (ts | (ts >> 11 | ts >> 7)).wrapping_mul(ts & (ts >> 13 | ts >> 11)); data[t] = val as i16; } } pub fn fill_wave(start: usize, end: usize, max: usize, data: &mut [f64]) { let mul = (f64::consts::PI * 2.0) / (data.len() as f64); let vol = (data.len() as f64) * 0.05; for t in 0..data.len() { let fq = (t as f64) * mul * 1000.0; let x = fq.sin() * vol; data[t] += x as f64; } } pub fn fill_test(start: usize, end: usize, max: usize, data: &mut [f64]) { let smodulo = (max % start) as f64; let sdivide = (max / start) as f64; let emodulo = (max % end) as f64; let edivide = (max / end) as f64; let mul = (f64::consts::PI * 2.0) / (data.len() as f64); let vol = (((emodulo / edivide) * (smodulo / sdivide)).log(2.0) - 20.0) * 40.0; println!("vol {}", vol); for t in 0..data.len() { let fq = (t as f64) * mul * 200.0; let x = fq.sin() * vol; data[t] += x as f64; } } pub fn fill_with(filler: fn(usize, usize, usize, data: &mut [f64]), data: &mut [f64], samples: usize) { let sample_min = 30000; let sample_max = 1000000; let mut rng = rand::thread_rng(); for s in 0..samples { println!("filling {}/{}", s, samples); let start = rng.gen_range(0, data.len()); let end = rng.gen_range(start, data.len()); let length = end - start; if sample_min < length && length < sample_max { filler(start, end, data.len(), &mut data[start..end]); } } } pub fn data_to_i16(out_data: &mut [i16], in_data: &[f64]) { for t in 0..in_data.len() { out_data[t] = in_data[t] as i16; } } pub fn data_to_f32(out_data: &mut [f32], in_data: &[f64]) { for t in 0..in_data.len() { out_data[t] = in_data[t] as f32; } }
let mut progress = vec![0; factors.len() as usize];
random_line_split
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> PrimeSeq { PrimeSeq { values: vec![], max: 2 } } } impl Seq<u64> for PrimeSeq { fn range(&self, start: usize, end: usize) -> &[u64] { return &self.values[start..end]; } fn inverse(&self, elem: &u64) -> Option<usize> { return match self.values.binary_search(elem) { Ok(index) => Some(index), Err(_) => None, } } } pub fn isqrt(number: u64) -> u64 { return (number as f64).sqrt().ceil() as u64; } pub fn factors(number: u64) -> Vec<u64> { let mut result = vec![]; let mut remain = number; let mut i = 2; while (i <= remain) { if remain % i == 0 { remain /= i; result.push(i); } else { i += 1; } } return result; } pub fn subset_products(factors: &Vec<u64>) -> Vec<u64> { let result = Vec::new(); for a in factors { } return result; } /** * a and b must be sorted arrays * returns tuple of common and non-common factors */ pub fn common_factors(a: &Vec<u64>, b: &Vec<u64>) -> (Vec<u64>, Vec<u64>) { let mut common = Vec::new(); let mut inverse = Vec::new(); let mut a_index = 0; let mut b_index = 0; let max_len = if a.len() > b.len() { a.len() } else { b.len() }; while a_index < a.len() && b_index < b.len() { let a_val = a[a_index]; let b_val = b[b_index]; if (a_val == b_val) { common.push(a_val); a_index += 1; b_index += 1; } else if (a_val < b_val) { inverse.push(a_val); a_index += 1; } else { inverse.push(b_val); b_index += 1; } } for a_remain in a_index..a.len() { inverse.push(a[a_remain]); } for b_remain in b_index..b.len() { inverse.push(b[b_remain]); } return (common, inverse); } pub fn is_prime(number: u64) -> bool { for i in 2..isqrt(number) { if number % i == 0 { return false; } } return true; } /* * maximum set */ pub fn maximum_factors(factors: &Vec<Vec<u64>>) -> Vec<u64> { let mut progress = vec![0; factors.len() as usize]; let mut common = Vec::new(); let mut complete = false; while!complete { let mut nothing_remaining = true; let mut lowest_index = 0; let mut lowest = 999999999; for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len()) { nothing_remaining = false; // check if value is lowest let val = current_set[current_progress]; if val < lowest { lowest_index = index; lowest = val; } } } for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len() && current_set[current_progress] <= lowest) { progress[index] += 1; } } complete = nothing_remaining; if!complete { common.push(lowest); } } return common; } pub fn
(factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> { let all_factors = maximum_factors(factors); let mut progress = vec![0; factors.len() as usize]; let mut common = Vec::new(); if (all_factors.len() == 0) { return common; } let mut first = 0; let highest = all_factors[all_factors.len() - 1]; for comp in all_factors { if comp > 255 { return common; } let mut lowest_index = 0; let mut lowest = highest; let mut freq = 0; let mut have_remaining = false; //println!("{:?} :: {:?} :: {:?}", first, progress, lowest); for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len()) { have_remaining = true; let val = current_set[current_progress]; if val <= lowest { lowest_index = index; lowest = val; } if val == comp { freq += 1; } } } if!have_remaining || common.len() > limit as usize { return common; } if freq > min_freq { first += 1; for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len() && current_set[current_progress] <= comp) { progress[index] += 1; } } common.push(comp); } else { progress[lowest_index] += 1; } } return common; } pub fn find_primes(ps: &mut PrimeSeq, max: u64) { let mut number = ps.max; while number < max { let mut isprime = true; for i in 2..isqrt(number) { if number % i == 0 { isprime = false; } } if isprime { ps.values.push(number); } number += 1; } ps.max = max; } pub fn fib(n: u64) -> (u64, u64, u64) { let mut count = 1; let mut fb1 = 1; let mut fb2 = 2; while fb2 <= n { count += 1; fb2 = fb1 + fb2; fb1 = fb2 - fb1; } return (count, n - fb1, fb2 - n); } pub fn sum(numbers: Vec<u64>) -> u64 { let mut total = 0; for i in numbers { total += i; } return total; } pub fn product(numbers: &Vec<u64>) -> u64 { let mut p = 1; for i in numbers { p *= i; } return p; } pub fn sequence(seq: &Seq<u64>, start: u32, size: usize) { let mut grid = vec![0; size * size]; let start: usize = start as usize; for i in 0..size*size { let number = start + i; grid[i] = number; } for i in 0..size { for j in 0..size { print!("{}, ", grid[i * size + j]) } println!(""); } } pub fn fill_sine(data: &mut [i16]) { for t in 0..data.len() { let fq = (t as f32) * 0.03; let x = fq.sin() * 2500.0; data[t] = x as i16; } } pub fn fill_bits(data: &mut [i16]) { for t in 0..data.len() { let ts = ((t as f32) * 0.1) as i16; let val = (ts | (ts >> 11 | ts >> 7)).wrapping_mul(ts & (ts >> 13 | ts >> 11)); data[t] = val as i16; } } pub fn fill_wave(start: usize, end: usize, max: usize, data: &mut [f64]) { let mul = (f64::consts::PI * 2.0) / (data.len() as f64); let vol = (data.len() as f64) * 0.05; for t in 0..data.len() { let fq = (t as f64) * mul * 1000.0; let x = fq.sin() * vol; data[t] += x as f64; } } pub fn fill_test(start: usize, end: usize, max: usize, data: &mut [f64]) { let smodulo = (max % start) as f64; let sdivide = (max / start) as f64; let emodulo = (max % end) as f64; let edivide = (max / end) as f64; let mul = (f64::consts::PI * 2.0) / (data.len() as f64); let vol = (((emodulo / edivide) * (smodulo / sdivide)).log(2.0) - 20.0) * 40.0; println!("vol {}", vol); for t in 0..data.len() { let fq = (t as f64) * mul * 200.0; let x = fq.sin() * vol; data[t] += x as f64; } } pub fn fill_with(filler: fn(usize, usize, usize, data: &mut [f64]), data: &mut [f64], samples: usize) { let sample_min = 30000; let sample_max = 1000000; let mut rng = rand::thread_rng(); for s in 0..samples { println!("filling {}/{}", s, samples); let start = rng.gen_range(0, data.len()); let end = rng.gen_range(start, data.len()); let length = end - start; if sample_min < length && length < sample_max { filler(start, end, data.len(), &mut data[start..end]); } } } pub fn data_to_i16(out_data: &mut [i16], in_data: &[f64]) { for t in 0..in_data.len() { out_data[t] = in_data[t] as i16; } } pub fn data_to_f32(out_data: &mut [f32], in_data: &[f64]) { for t in 0..in_data.len() { out_data[t] = in_data[t] as f32; } }
high_freq_factors
identifier_name
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> PrimeSeq { PrimeSeq { values: vec![], max: 2 } } } impl Seq<u64> for PrimeSeq { fn range(&self, start: usize, end: usize) -> &[u64] { return &self.values[start..end]; } fn inverse(&self, elem: &u64) -> Option<usize>
} pub fn isqrt(number: u64) -> u64 { return (number as f64).sqrt().ceil() as u64; } pub fn factors(number: u64) -> Vec<u64> { let mut result = vec![]; let mut remain = number; let mut i = 2; while (i <= remain) { if remain % i == 0 { remain /= i; result.push(i); } else { i += 1; } } return result; } pub fn subset_products(factors: &Vec<u64>) -> Vec<u64> { let result = Vec::new(); for a in factors { } return result; } /** * a and b must be sorted arrays * returns tuple of common and non-common factors */ pub fn common_factors(a: &Vec<u64>, b: &Vec<u64>) -> (Vec<u64>, Vec<u64>) { let mut common = Vec::new(); let mut inverse = Vec::new(); let mut a_index = 0; let mut b_index = 0; let max_len = if a.len() > b.len() { a.len() } else { b.len() }; while a_index < a.len() && b_index < b.len() { let a_val = a[a_index]; let b_val = b[b_index]; if (a_val == b_val) { common.push(a_val); a_index += 1; b_index += 1; } else if (a_val < b_val) { inverse.push(a_val); a_index += 1; } else { inverse.push(b_val); b_index += 1; } } for a_remain in a_index..a.len() { inverse.push(a[a_remain]); } for b_remain in b_index..b.len() { inverse.push(b[b_remain]); } return (common, inverse); } pub fn is_prime(number: u64) -> bool { for i in 2..isqrt(number) { if number % i == 0 { return false; } } return true; } /* * maximum set */ pub fn maximum_factors(factors: &Vec<Vec<u64>>) -> Vec<u64> { let mut progress = vec![0; factors.len() as usize]; let mut common = Vec::new(); let mut complete = false; while!complete { let mut nothing_remaining = true; let mut lowest_index = 0; let mut lowest = 999999999; for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len()) { nothing_remaining = false; // check if value is lowest let val = current_set[current_progress]; if val < lowest { lowest_index = index; lowest = val; } } } for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len() && current_set[current_progress] <= lowest) { progress[index] += 1; } } complete = nothing_remaining; if!complete { common.push(lowest); } } return common; } pub fn high_freq_factors(factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> { let all_factors = maximum_factors(factors); let mut progress = vec![0; factors.len() as usize]; let mut common = Vec::new(); if (all_factors.len() == 0) { return common; } let mut first = 0; let highest = all_factors[all_factors.len() - 1]; for comp in all_factors { if comp > 255 { return common; } let mut lowest_index = 0; let mut lowest = highest; let mut freq = 0; let mut have_remaining = false; //println!("{:?} :: {:?} :: {:?}", first, progress, lowest); for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len()) { have_remaining = true; let val = current_set[current_progress]; if val <= lowest { lowest_index = index; lowest = val; } if val == comp { freq += 1; } } } if!have_remaining || common.len() > limit as usize { return common; } if freq > min_freq { first += 1; for index in 0..factors.len() { let current_set = &factors[index]; let current_progress = progress[index]; if (current_progress < current_set.len() && current_set[current_progress] <= comp) { progress[index] += 1; } } common.push(comp); } else { progress[lowest_index] += 1; } } return common; } pub fn find_primes(ps: &mut PrimeSeq, max: u64) { let mut number = ps.max; while number < max { let mut isprime = true; for i in 2..isqrt(number) { if number % i == 0 { isprime = false; } } if isprime { ps.values.push(number); } number += 1; } ps.max = max; } pub fn fib(n: u64) -> (u64, u64, u64) { let mut count = 1; let mut fb1 = 1; let mut fb2 = 2; while fb2 <= n { count += 1; fb2 = fb1 + fb2; fb1 = fb2 - fb1; } return (count, n - fb1, fb2 - n); } pub fn sum(numbers: Vec<u64>) -> u64 { let mut total = 0; for i in numbers { total += i; } return total; } pub fn product(numbers: &Vec<u64>) -> u64 { let mut p = 1; for i in numbers { p *= i; } return p; } pub fn sequence(seq: &Seq<u64>, start: u32, size: usize) { let mut grid = vec![0; size * size]; let start: usize = start as usize; for i in 0..size*size { let number = start + i; grid[i] = number; } for i in 0..size { for j in 0..size { print!("{}, ", grid[i * size + j]) } println!(""); } } pub fn fill_sine(data: &mut [i16]) { for t in 0..data.len() { let fq = (t as f32) * 0.03; let x = fq.sin() * 2500.0; data[t] = x as i16; } } pub fn fill_bits(data: &mut [i16]) { for t in 0..data.len() { let ts = ((t as f32) * 0.1) as i16; let val = (ts | (ts >> 11 | ts >> 7)).wrapping_mul(ts & (ts >> 13 | ts >> 11)); data[t] = val as i16; } } pub fn fill_wave(start: usize, end: usize, max: usize, data: &mut [f64]) { let mul = (f64::consts::PI * 2.0) / (data.len() as f64); let vol = (data.len() as f64) * 0.05; for t in 0..data.len() { let fq = (t as f64) * mul * 1000.0; let x = fq.sin() * vol; data[t] += x as f64; } } pub fn fill_test(start: usize, end: usize, max: usize, data: &mut [f64]) { let smodulo = (max % start) as f64; let sdivide = (max / start) as f64; let emodulo = (max % end) as f64; let edivide = (max / end) as f64; let mul = (f64::consts::PI * 2.0) / (data.len() as f64); let vol = (((emodulo / edivide) * (smodulo / sdivide)).log(2.0) - 20.0) * 40.0; println!("vol {}", vol); for t in 0..data.len() { let fq = (t as f64) * mul * 200.0; let x = fq.sin() * vol; data[t] += x as f64; } } pub fn fill_with(filler: fn(usize, usize, usize, data: &mut [f64]), data: &mut [f64], samples: usize) { let sample_min = 30000; let sample_max = 1000000; let mut rng = rand::thread_rng(); for s in 0..samples { println!("filling {}/{}", s, samples); let start = rng.gen_range(0, data.len()); let end = rng.gen_range(start, data.len()); let length = end - start; if sample_min < length && length < sample_max { filler(start, end, data.len(), &mut data[start..end]); } } } pub fn data_to_i16(out_data: &mut [i16], in_data: &[f64]) { for t in 0..in_data.len() { out_data[t] = in_data[t] as i16; } } pub fn data_to_f32(out_data: &mut [f32], in_data: &[f64]) { for t in 0..in_data.len() { out_data[t] = in_data[t] as f32; } }
{ return match self.values.binary_search(elem) { Ok(index) => Some(index), Err(_) => None, } }
identifier_body
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt}; /// Errors that occur during serialization. #[derive(Debug)] pub enum V2DeflateSerializeError { /// The underlying serialization failed InternalSerializationError(V2SerializeError), /// An i/o operation failed. IoError(io::Error), } impl std::convert::From<std::io::Error> for V2DeflateSerializeError { fn from(e: std::io::Error) -> Self { V2DeflateSerializeError::IoError(e) } } impl fmt::Display for V2DeflateSerializeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { V2DeflateSerializeError::InternalSerializationError(e) => { write!(f, "The underlying serialization failed: {}", e) } V2DeflateSerializeError::IoError(e) => { write!(f, "The underlying serialization failed: {}", e) } } } } impl error::Error for V2DeflateSerializeError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { V2DeflateSerializeError::InternalSerializationError(e) => Some(e), V2DeflateSerializeError::IoError(e) => Some(e), } } } /// Serializer for the V2 + DEFLATE binary format. /// /// It's called "deflate" to stay consistent with the naming used in the Java implementation, but /// it actually uses zlib's wrapper format around plain DEFLATE. pub struct V2DeflateSerializer { uncompressed_buf: Vec<u8>, compressed_buf: Vec<u8>, v2_serializer: V2Serializer, } impl Default for V2DeflateSerializer { fn default() -> Self { Self::new() } } impl V2DeflateSerializer { /// Create a new serializer. pub fn
() -> V2DeflateSerializer { V2DeflateSerializer { uncompressed_buf: Vec::new(), compressed_buf: Vec::new(), v2_serializer: V2Serializer::new(), } } } impl Serializer for V2DeflateSerializer { type SerializeError = V2DeflateSerializeError; fn serialize<T: Counter, W: Write>( &mut self, h: &Histogram<T>, writer: &mut W, ) -> Result<usize, V2DeflateSerializeError> { // TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk // could be compressed and written to the compressed buf, possibly using an approach like // that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055. // This would reduce the overall buffer size needed for plain v2 serialization, and be // more cache friendly. self.uncompressed_buf.clear(); self.compressed_buf.clear(); // TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer let uncompressed_len = self .v2_serializer .serialize(h, &mut self.uncompressed_buf) .map_err(V2DeflateSerializeError::InternalSerializationError)?; debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len); // On randomized test histograms we get about 10% compression, but of course random data // doesn't compress well. Real-world data may compress better, so let's assume a more // optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's // still only one more allocation the first time it's needed. self.compressed_buf.reserve(self.uncompressed_buf.len() / 2); self.compressed_buf .write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?; // placeholder for length self.compressed_buf.write_u32::<BigEndian>(0)?; // TODO pluggable compressors? configurable compression levels? // TODO benchmark https://github.com/sile/libflate // TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the // data instead of shrinking it (which we cannot really predict), writing to compressed_buf // could panic as Vec overflows its internal `usize`. { // TODO reuse deflate buf, or switch to lower-level flate2::Compress let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default()); compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?; let _ = compressor.finish()?; } // fill in length placeholder. Won't underflow since length is always at least 8, and won't // overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if // counter is u64). let total_compressed_len = self.compressed_buf.len(); (&mut self.compressed_buf[4..8]) .write_u32::<BigEndian>((total_compressed_len as u32) - 8)?; writer.write_all(&self.compressed_buf)?; Ok(total_compressed_len) } }
new
identifier_name
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt}; /// Errors that occur during serialization. #[derive(Debug)] pub enum V2DeflateSerializeError { /// The underlying serialization failed InternalSerializationError(V2SerializeError), /// An i/o operation failed. IoError(io::Error), } impl std::convert::From<std::io::Error> for V2DeflateSerializeError { fn from(e: std::io::Error) -> Self
} impl fmt::Display for V2DeflateSerializeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { V2DeflateSerializeError::InternalSerializationError(e) => { write!(f, "The underlying serialization failed: {}", e) } V2DeflateSerializeError::IoError(e) => { write!(f, "The underlying serialization failed: {}", e) } } } } impl error::Error for V2DeflateSerializeError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { V2DeflateSerializeError::InternalSerializationError(e) => Some(e), V2DeflateSerializeError::IoError(e) => Some(e), } } } /// Serializer for the V2 + DEFLATE binary format. /// /// It's called "deflate" to stay consistent with the naming used in the Java implementation, but /// it actually uses zlib's wrapper format around plain DEFLATE. pub struct V2DeflateSerializer { uncompressed_buf: Vec<u8>, compressed_buf: Vec<u8>, v2_serializer: V2Serializer, } impl Default for V2DeflateSerializer { fn default() -> Self { Self::new() } } impl V2DeflateSerializer { /// Create a new serializer. pub fn new() -> V2DeflateSerializer { V2DeflateSerializer { uncompressed_buf: Vec::new(), compressed_buf: Vec::new(), v2_serializer: V2Serializer::new(), } } } impl Serializer for V2DeflateSerializer { type SerializeError = V2DeflateSerializeError; fn serialize<T: Counter, W: Write>( &mut self, h: &Histogram<T>, writer: &mut W, ) -> Result<usize, V2DeflateSerializeError> { // TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk // could be compressed and written to the compressed buf, possibly using an approach like // that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055. // This would reduce the overall buffer size needed for plain v2 serialization, and be // more cache friendly. self.uncompressed_buf.clear(); self.compressed_buf.clear(); // TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer let uncompressed_len = self .v2_serializer .serialize(h, &mut self.uncompressed_buf) .map_err(V2DeflateSerializeError::InternalSerializationError)?; debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len); // On randomized test histograms we get about 10% compression, but of course random data // doesn't compress well. Real-world data may compress better, so let's assume a more // optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's // still only one more allocation the first time it's needed. self.compressed_buf.reserve(self.uncompressed_buf.len() / 2); self.compressed_buf .write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?; // placeholder for length self.compressed_buf.write_u32::<BigEndian>(0)?; // TODO pluggable compressors? configurable compression levels? // TODO benchmark https://github.com/sile/libflate // TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the // data instead of shrinking it (which we cannot really predict), writing to compressed_buf // could panic as Vec overflows its internal `usize`. { // TODO reuse deflate buf, or switch to lower-level flate2::Compress let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default()); compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?; let _ = compressor.finish()?; } // fill in length placeholder. Won't underflow since length is always at least 8, and won't // overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if // counter is u64). let total_compressed_len = self.compressed_buf.len(); (&mut self.compressed_buf[4..8]) .write_u32::<BigEndian>((total_compressed_len as u32) - 8)?; writer.write_all(&self.compressed_buf)?; Ok(total_compressed_len) } }
{ V2DeflateSerializeError::IoError(e) }
identifier_body
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt}; /// Errors that occur during serialization. #[derive(Debug)] pub enum V2DeflateSerializeError { /// The underlying serialization failed InternalSerializationError(V2SerializeError), /// An i/o operation failed. IoError(io::Error), } impl std::convert::From<std::io::Error> for V2DeflateSerializeError { fn from(e: std::io::Error) -> Self { V2DeflateSerializeError::IoError(e) } } impl fmt::Display for V2DeflateSerializeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { V2DeflateSerializeError::InternalSerializationError(e) => { write!(f, "The underlying serialization failed: {}", e) } V2DeflateSerializeError::IoError(e) => { write!(f, "The underlying serialization failed: {}", e) } } } } impl error::Error for V2DeflateSerializeError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { V2DeflateSerializeError::InternalSerializationError(e) => Some(e), V2DeflateSerializeError::IoError(e) => Some(e), } } } /// Serializer for the V2 + DEFLATE binary format. /// /// It's called "deflate" to stay consistent with the naming used in the Java implementation, but /// it actually uses zlib's wrapper format around plain DEFLATE. pub struct V2DeflateSerializer { uncompressed_buf: Vec<u8>, compressed_buf: Vec<u8>, v2_serializer: V2Serializer, } impl Default for V2DeflateSerializer { fn default() -> Self { Self::new() } } impl V2DeflateSerializer { /// Create a new serializer. pub fn new() -> V2DeflateSerializer { V2DeflateSerializer { uncompressed_buf: Vec::new(), compressed_buf: Vec::new(), v2_serializer: V2Serializer::new(), } } } impl Serializer for V2DeflateSerializer { type SerializeError = V2DeflateSerializeError; fn serialize<T: Counter, W: Write>( &mut self, h: &Histogram<T>, writer: &mut W, ) -> Result<usize, V2DeflateSerializeError> { // TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk // could be compressed and written to the compressed buf, possibly using an approach like // that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055. // This would reduce the overall buffer size needed for plain v2 serialization, and be // more cache friendly. self.uncompressed_buf.clear(); self.compressed_buf.clear(); // TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer let uncompressed_len = self .v2_serializer .serialize(h, &mut self.uncompressed_buf) .map_err(V2DeflateSerializeError::InternalSerializationError)?; debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len); // On randomized test histograms we get about 10% compression, but of course random data // doesn't compress well. Real-world data may compress better, so let's assume a more // optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's // still only one more allocation the first time it's needed. self.compressed_buf.reserve(self.uncompressed_buf.len() / 2); self.compressed_buf
// TODO pluggable compressors? configurable compression levels? // TODO benchmark https://github.com/sile/libflate // TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the // data instead of shrinking it (which we cannot really predict), writing to compressed_buf // could panic as Vec overflows its internal `usize`. { // TODO reuse deflate buf, or switch to lower-level flate2::Compress let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default()); compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?; let _ = compressor.finish()?; } // fill in length placeholder. Won't underflow since length is always at least 8, and won't // overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if // counter is u64). let total_compressed_len = self.compressed_buf.len(); (&mut self.compressed_buf[4..8]) .write_u32::<BigEndian>((total_compressed_len as u32) - 8)?; writer.write_all(&self.compressed_buf)?; Ok(total_compressed_len) } }
.write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?; // placeholder for length self.compressed_buf.write_u32::<BigEndian>(0)?;
random_line_split
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt}; /// Errors that occur during serialization. #[derive(Debug)] pub enum V2DeflateSerializeError { /// The underlying serialization failed InternalSerializationError(V2SerializeError), /// An i/o operation failed. IoError(io::Error), } impl std::convert::From<std::io::Error> for V2DeflateSerializeError { fn from(e: std::io::Error) -> Self { V2DeflateSerializeError::IoError(e) } } impl fmt::Display for V2DeflateSerializeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { V2DeflateSerializeError::InternalSerializationError(e) => { write!(f, "The underlying serialization failed: {}", e) } V2DeflateSerializeError::IoError(e) =>
} } } impl error::Error for V2DeflateSerializeError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { V2DeflateSerializeError::InternalSerializationError(e) => Some(e), V2DeflateSerializeError::IoError(e) => Some(e), } } } /// Serializer for the V2 + DEFLATE binary format. /// /// It's called "deflate" to stay consistent with the naming used in the Java implementation, but /// it actually uses zlib's wrapper format around plain DEFLATE. pub struct V2DeflateSerializer { uncompressed_buf: Vec<u8>, compressed_buf: Vec<u8>, v2_serializer: V2Serializer, } impl Default for V2DeflateSerializer { fn default() -> Self { Self::new() } } impl V2DeflateSerializer { /// Create a new serializer. pub fn new() -> V2DeflateSerializer { V2DeflateSerializer { uncompressed_buf: Vec::new(), compressed_buf: Vec::new(), v2_serializer: V2Serializer::new(), } } } impl Serializer for V2DeflateSerializer { type SerializeError = V2DeflateSerializeError; fn serialize<T: Counter, W: Write>( &mut self, h: &Histogram<T>, writer: &mut W, ) -> Result<usize, V2DeflateSerializeError> { // TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk // could be compressed and written to the compressed buf, possibly using an approach like // that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055. // This would reduce the overall buffer size needed for plain v2 serialization, and be // more cache friendly. self.uncompressed_buf.clear(); self.compressed_buf.clear(); // TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer let uncompressed_len = self .v2_serializer .serialize(h, &mut self.uncompressed_buf) .map_err(V2DeflateSerializeError::InternalSerializationError)?; debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len); // On randomized test histograms we get about 10% compression, but of course random data // doesn't compress well. Real-world data may compress better, so let's assume a more // optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's // still only one more allocation the first time it's needed. self.compressed_buf.reserve(self.uncompressed_buf.len() / 2); self.compressed_buf .write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?; // placeholder for length self.compressed_buf.write_u32::<BigEndian>(0)?; // TODO pluggable compressors? configurable compression levels? // TODO benchmark https://github.com/sile/libflate // TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the // data instead of shrinking it (which we cannot really predict), writing to compressed_buf // could panic as Vec overflows its internal `usize`. { // TODO reuse deflate buf, or switch to lower-level flate2::Compress let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default()); compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?; let _ = compressor.finish()?; } // fill in length placeholder. Won't underflow since length is always at least 8, and won't // overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if // counter is u64). let total_compressed_len = self.compressed_buf.len(); (&mut self.compressed_buf[4..8]) .write_u32::<BigEndian>((total_compressed_len as u32) - 8)?; writer.write_all(&self.compressed_buf)?; Ok(total_compressed_len) } }
{ write!(f, "The underlying serialization failed: {}", e) }
conditional_block
linear-for-loop.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. extern crate debug; pub fn
() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } if i == 3 { assert!((c == 'l' as u8)); } if i == 4 { assert!((c == 'o' as u8)); } //... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
main
identifier_name
linear-for-loop.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. extern crate debug;
pub fn main() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } if i == 3 { assert!((c == 'l' as u8)); } if i == 4 { assert!((c == 'o' as u8)); } //... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
random_line_split
linear-for-loop.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. extern crate debug; pub fn main()
assert_eq!(i, 11); }
{ let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } if i == 3 { assert!((c == 'l' as u8)); } if i == 4 { assert!((c == 'o' as u8)); } // ... i += 1; println!("{:?}", i); println!("{:?}", c); }
identifier_body
linear-for-loop.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. extern crate debug; pub fn main() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } if i == 3
if i == 4 { assert!((c == 'o' as u8)); } //... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
{ assert!((c == 'l' as u8)); }
conditional_block
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test() { let mutex = RMutex::new(0i32); { let mut outer_lock = mutex.lock(); { let mut inner_lock = mutex.lock(); *inner_lock = 1; } *outer_lock = 2; } assert_eq!(*mutex.lock(), 2); } #[test] fn
() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guards = Vec::new(); for _ in (0..count) { let mutex = mutex.clone(); guards.push(Thread::scoped(move || { let mut value_ref = mutex.lock(); let value = *value_ref; sleep(Duration::milliseconds(1)); *value_ref = value + 1; })); } drop(guards); assert_eq!(*mutex.lock(), count); }
test_guarding
identifier_name
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test() { let mutex = RMutex::new(0i32);
let mut outer_lock = mutex.lock(); { let mut inner_lock = mutex.lock(); *inner_lock = 1; } *outer_lock = 2; } assert_eq!(*mutex.lock(), 2); } #[test] fn test_guarding() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guards = Vec::new(); for _ in (0..count) { let mutex = mutex.clone(); guards.push(Thread::scoped(move || { let mut value_ref = mutex.lock(); let value = *value_ref; sleep(Duration::milliseconds(1)); *value_ref = value + 1; })); } drop(guards); assert_eq!(*mutex.lock(), count); }
{
random_line_split
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test()
#[test] fn test_guarding() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guards = Vec::new(); for _ in (0..count) { let mutex = mutex.clone(); guards.push(Thread::scoped(move || { let mut value_ref = mutex.lock(); let value = *value_ref; sleep(Duration::milliseconds(1)); *value_ref = value + 1; })); } drop(guards); assert_eq!(*mutex.lock(), count); }
{ let mutex = RMutex::new(0i32); { let mut outer_lock = mutex.lock(); { let mut inner_lock = mutex.lock(); *inner_lock = 1; } *outer_lock = 2; } assert_eq!(*mutex.lock(), 2); }
identifier_body
no_0215_kth_largest_element_in_an_array.rs
struct Solution; use std::cmp::Ordering; impl Solution { // by zhangyuchen. pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { Self::find(&mut nums, k as usize) } fn find(nums: &mut [i32], k: usize) -> i32 { let mut pos = 1; // 第一个大于等于哨兵的位置 let sentinel = nums[0]; // 哨兵 for i in 1..nums.len() { if nums[i] < sentinel { // 小于哨兵的放到哨兵左侧 let temp = nums[pos]; nums[pos] = nums[i]; nums[i] = temp; pos += 1; } } // 把哨兵放到它应该在的位置, pos-1 是最靠右的小于哨兵的位置 let temp = nums[pos - 1]; nums[pos - 1] = sentinel; nums[0] = temp; let right_len = nums.len() - pos + 1; // 右边的大小,包含哨兵(即哨兵是第几大) println!( "nums = {:?}, k = {}, pos = {}, right_len={}", nums, k, pos, right_len ); match right_len.cmp(&k) { // 正好等于 k,说明哨兵就是第 k 大的数。 Ordering::Equal => sentinel, // [哨兵, len()] 长度大于 k,说明第 k 大的数在右边 Ordering::Greater => { let (_, right) = nums.split_at_mut(pos); Self::find(right, k) } // 说明右边的数都是比较大的,但第 k 大的数在左边呢。 Ordering::Less => { // left 不包含哨兵了 let (left, _) = nums.split_at_mut(pos - 1); Self::find(left, k - right_len) } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_find_kth_largest_example1() { assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5); } #[test] fn test_find_kth_largest_example2() { assert_eq!( Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), 4 ); } #[test] fn test_find_kth_largest_example3() { assert_eq!(Solution::find_kth_largest(vec![5, 2, 4, 1, 3, 6, 0], 4), 3); } }
identifier_name
no_0215_kth_largest_element_in_an_array.rs
struct Solution; use std::cmp::Ordering; impl Solution { // by zhangyuchen. pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { Self::find(&mut nums, k as usize) } fn find(nums: &mut [i32], k: usize) -> i32 {
// 小于哨兵的放到哨兵左侧 let temp = nums[pos]; nums[pos] = nums[i]; nums[i] = temp; pos += 1; } } // 把哨兵放到它应该在的位置, pos-1 是最靠右的小于哨兵的位置 let temp = nums[pos - 1]; nums[pos - 1] = sentinel; nums[0] = temp; let right_len = nums.len() - pos + 1; // 右边的大小,包含哨兵(即哨兵是第几大) println!( "nums = {:?}, k = {}, pos = {}, right_len={}", nums, k, pos, right_len ); match right_len.cmp(&k) { // 正好等于 k,说明哨兵就是第 k 大的数。 Ordering::Equal => sentinel, // [哨兵, len()] 长度大于 k,说明第 k 大的数在右边 Ordering::Greater => { let (_, right) = nums.split_at_mut(pos); Self::find(right, k) } // 说明右边的数都是比较大的,但第 k 大的数在左边呢。 Ordering::Less => { // left 不包含哨兵了 let (left, _) = nums.split_at_mut(pos - 1); Self::find(left, k - right_len) } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_find_kth_largest_example1() { assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5); } #[test] fn test_find_kth_largest_example2() { assert_eq!( Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), 4 ); } #[test] fn test_find_kth_largest_example3() { assert_eq!(Solution::find_kth_largest(vec![5, 2, 4, 1, 3, 6, 0], 4), 3); } }
let mut pos = 1; // 第一个大于等于哨兵的位置 let sentinel = nums[0]; // 哨兵 for i in 1..nums.len() { if nums[i] < sentinel {
random_line_split
text_view.rs
use std::ops::Deref; use std::sync::Arc; use std::sync::{Mutex, MutexGuard}; use owning_ref::{ArcRef, OwningHandle}; use unicode_width::UnicodeWidthStr; use crate::align::*; use crate::theme::Effect; use crate::utils::lines::spans::{LinesIterator, Row}; use crate::utils::markup::StyledString; use crate::view::{SizeCache, View}; use crate::{Printer, Vec2, With, XY}; // Content type used internally for caching and storage type InnerContentType = Arc<StyledString>; /// Provides access to the content of a [`TextView`]. /// /// [`TextView`]: struct.TextView.html /// /// Cloning this object will still point to the same content. /// /// # Examples /// /// ```rust /// # use cursive_core::views::{TextView, TextContent}; /// let mut content = TextContent::new("content"); /// let view = TextView::new_with_content(content.clone()); /// /// // Later, possibly in a different thread /// content.set_content("new content"); /// assert!(view.get_content().source().contains("new")); /// ``` #[derive(Clone)] pub struct TextContent { content: Arc<Mutex<TextContentInner>>, } impl TextContent { /// Creates a new text content around the given value. /// /// Parses the given value. pub fn new<S>(content: S) -> Self where S: Into<StyledString>, { let content = Arc::new(content.into()); TextContent { content: Arc::new(Mutex::new(TextContentInner { content_value: content, content_cache: Arc::new(StyledString::default()), size_cache: None, })), } } } /// A reference to the text content. /// /// This can be deref'ed into a [`StyledString`]. /// /// [`StyledString`]:../utils/markup/type.StyledString.html /// /// This keeps the content locked. Do not store this! pub struct TextContentRef { _handle: OwningHandle< ArcRef<Mutex<TextContentInner>>, MutexGuard<'static, TextContentInner>, >, // We also need to keep a copy of Arc so `deref` can return // a reference to the `StyledString` data: Arc<StyledString>, } impl Deref for TextContentRef { type Target = StyledString; fn deref(&self) -> &StyledString { self.data.as_ref() } } impl TextContent { /// Replaces the content with the given value. pub fn set_content<S>(&self, content: S) where S: Into<StyledString>, { self.with_content(|c| { *Arc::make_mut(&mut c.content_value) = content.into(); }); } /// Append `content` to the end of a `TextView`. pub fn append<S>(&self, content: S) where S: Into<StyledString>, { self.with_content(|c| { // This will only clone content if content_cached and content_value // are sharing the same underlying Rc. Arc::make_mut(&mut c.content_value).append(content); }) } /// Returns a reference to the content. /// /// This locks the data while the returned value is alive, /// so don't keep it too long. pub fn get_content(&self) -> TextContentRef { TextContentInner::get_content(&self.content) } /// Apply the given closure to the inner content, and bust the cache afterward. fn with_content<F, O>(&self, f: F) -> O where F: FnOnce(&mut TextContentInner) -> O, { let mut content = self.content.lock().unwrap(); let out = f(&mut content); content.size_cache = None; out } } /// Internel representation of the content for a `TextView`. /// /// This is mostly just a `StyledString`. /// /// Can be shared (through a `Arc<Mutex>`). struct TextContentInner { // content: String, content_value: InnerContentType, content_cache: InnerContentType, // We keep the cache here so it can be busted when we change the content. size_cache: Option<XY<SizeCache>>, } impl TextContentInner { /// From a shareable content (Arc + Mutex), return a fn get_content(content: &Arc<Mutex<TextContentInner>>) -> TextContentRef { let arc_ref: ArcRef<Mutex<TextContentInner>> = ArcRef::new(Arc::clone(content)); let _handle = OwningHandle::new_with_fn(arc_ref, |mutex| unsafe { (*mutex).lock().unwrap() }); let data = Arc::clone(&_handle.content_value); TextContentRef { _handle, data } } fn is_cache_valid(&self, size: Vec2) -> bool { match self.size_cache { None => false, Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y), } } fn get_cache(&self) -> &InnerContentType { &self.content_cache } } /// A simple view showing a fixed text. /// /// # Examples /// /// ```rust /// # use cursive_core::Cursive; /// # use cursive_core::views::TextView; /// let mut siv = Cursive::dummy(); /// /// siv.add_layer(TextView::new("Hello world!")); /// ``` pub struct TextView { // content: String, content: TextContent, rows: Vec<Row>, align: Align, // TODO: remove now that we have styled text? effect: Effect, // True if we can wrap long lines. wrap: bool, // ScrollBase make many scrolling-related things easier last_size: Vec2, width: Option<usize>, } impl TextView { /// Creates a new TextView with the given content. pub fn new<S>(content: S) -> Self where S: Into<StyledString>, { Self::new_with_content(TextContent::new(content)) } /// Creates a new TextView using the given `TextContent`. /// /// If you kept a clone of the given content, you'll be able to update it /// remotely. /// /// # Examples /// /// ```rust /// # use cursive_core::views::{TextView, TextContent}; /// let mut content = TextContent::new("content"); /// let view = TextView::new_with_content(content.clone()); /// /// // Later, possibly in a different thread /// content.set_content("new content"); /// assert!(view.get_content().source().contains("new")); /// ``` pub fn new_with_content(content: TextContent) -> Self { TextView { content, effect: Effect::Simple, rows: Vec::new(), wrap: true, align: Align::top_left(), last_size: Vec2::zero(), width: None, } } /// Creates a new empty `TextView`. pub fn empty() -> Self { TextView::new("") } /// Sets the effect for the entire content. pub fn set_effect(&mut self, effect: Effect) { self.effect = effect; } /// Sets the effect for the entire content. /// /// Chainable variant. pub fn effect(self, effect: Effect) -> Self { self.with(|s| s.set_effect(effect)) } /// Disables content wrap for this view. /// /// This may be useful if you want horizontal scrolling. pub fn no_wrap(self) -> Self { self.with(|s| s.set_content_wrap(false)) } /// Controls content wrap for this view. /// /// If `true` (the default), text will wrap long lines when needed. pub fn set_content_wrap(&mut self, wrap: bool) { self.wrap = wrap; } /// Sets the horizontal alignment for this view. pub fn h_align(mut self, h: HAlign) -> Self { self.align.h = h; self } /// Sets the vertical alignment for this view. pub fn v_align(mut self, v: VAlign) -> Self
/// Sets the alignment for this view. pub fn align(mut self, a: Align) -> Self { self.align = a; self } /// Center the text horizontally and vertically inside the view. pub fn center(mut self) -> Self { self.align = Align::center(); self } /// Replace the text in this view. /// /// Chainable variant. pub fn content<S>(self, content: S) -> Self where S: Into<StyledString>, { self.with(|s| s.set_content(content)) } /// Replace the text in this view. pub fn set_content<S>(&mut self, content: S) where S: Into<StyledString>, { self.content.set_content(content); } /// Append `content` to the end of a `TextView`. pub fn append<S>(&mut self, content: S) where S: Into<StyledString>, { self.content.append(content); } /// Returns the current text in this view. pub fn get_content(&self) -> TextContentRef { TextContentInner::get_content(&self.content.content) } /// Returns a shared reference to the content, allowing content mutation. pub fn get_shared_content(&mut self) -> TextContent { // We take &mut here without really needing it, // because it sort of "makes sense". TextContent { content: Arc::clone(&self.content.content), } } // This must be non-destructive, as it may be called // multiple times during layout. fn compute_rows(&mut self, size: Vec2) { let size = if self.wrap { size } else { Vec2::max_value() }; let mut content = self.content.content.lock().unwrap(); if content.is_cache_valid(size) { return; } // Completely bust the cache // Just in case we fail, we don't want to leave a bad cache. content.size_cache = None; content.content_cache = Arc::clone(&content.content_value); if size.x == 0 { // Nothing we can do at this point. return; } self.rows = LinesIterator::new(content.get_cache().as_ref(), size.x).collect(); // Desired width self.width = self.rows.iter().map(|row| row.width).max(); } } impl View for TextView { fn draw(&self, printer: &Printer) { let h = self.rows.len(); // If the content is smaller than the view, align it somewhere. let offset = self.align.v.get_offset(h, printer.size.y); let printer = &printer.offset((0, offset)); let content = self.content.content.lock().unwrap(); printer.with_effect(self.effect, |printer| { for (y, row) in self.rows.iter().enumerate() { let l = row.width; let mut x = self.align.h.get_offset(l, printer.size.x); for span in row.resolve(content.get_cache().as_ref()) { printer.with_style(*span.attr, |printer| { printer.print((x, y), span.content); x += span.content.width(); }); } } }); } fn needs_relayout(&self) -> bool { let content = self.content.content.lock().unwrap(); content.size_cache.is_none() } fn required_size(&mut self, size: Vec2) -> Vec2 { self.compute_rows(size); Vec2::new(self.width.unwrap_or(0), self.rows.len()) } fn layout(&mut self, size: Vec2) { // Compute the text rows. self.last_size = size; self.compute_rows(size); // The entire "virtual" size (includes all rows) let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len()); // Build a fresh cache. let mut content = self.content.content.lock().unwrap(); content.size_cache = Some(SizeCache::build(my_size, size)); } }
{ self.align.v = v; self }
identifier_body
text_view.rs
use std::ops::Deref; use std::sync::Arc; use std::sync::{Mutex, MutexGuard}; use owning_ref::{ArcRef, OwningHandle}; use unicode_width::UnicodeWidthStr; use crate::align::*; use crate::theme::Effect; use crate::utils::lines::spans::{LinesIterator, Row}; use crate::utils::markup::StyledString; use crate::view::{SizeCache, View}; use crate::{Printer, Vec2, With, XY}; // Content type used internally for caching and storage type InnerContentType = Arc<StyledString>; /// Provides access to the content of a [`TextView`]. /// /// [`TextView`]: struct.TextView.html /// /// Cloning this object will still point to the same content. /// /// # Examples /// /// ```rust /// # use cursive_core::views::{TextView, TextContent}; /// let mut content = TextContent::new("content"); /// let view = TextView::new_with_content(content.clone()); /// /// // Later, possibly in a different thread /// content.set_content("new content"); /// assert!(view.get_content().source().contains("new")); /// ``` #[derive(Clone)] pub struct TextContent { content: Arc<Mutex<TextContentInner>>, } impl TextContent { /// Creates a new text content around the given value. /// /// Parses the given value. pub fn new<S>(content: S) -> Self where S: Into<StyledString>, { let content = Arc::new(content.into()); TextContent { content: Arc::new(Mutex::new(TextContentInner { content_value: content, content_cache: Arc::new(StyledString::default()), size_cache: None, })), } } } /// A reference to the text content. /// /// This can be deref'ed into a [`StyledString`]. /// /// [`StyledString`]:../utils/markup/type.StyledString.html /// /// This keeps the content locked. Do not store this! pub struct TextContentRef { _handle: OwningHandle< ArcRef<Mutex<TextContentInner>>, MutexGuard<'static, TextContentInner>, >, // We also need to keep a copy of Arc so `deref` can return // a reference to the `StyledString` data: Arc<StyledString>, } impl Deref for TextContentRef { type Target = StyledString; fn deref(&self) -> &StyledString { self.data.as_ref() } } impl TextContent { /// Replaces the content with the given value. pub fn set_content<S>(&self, content: S) where S: Into<StyledString>, { self.with_content(|c| { *Arc::make_mut(&mut c.content_value) = content.into(); }); } /// Append `content` to the end of a `TextView`. pub fn append<S>(&self, content: S) where S: Into<StyledString>, { self.with_content(|c| { // This will only clone content if content_cached and content_value // are sharing the same underlying Rc. Arc::make_mut(&mut c.content_value).append(content); }) } /// Returns a reference to the content. /// /// This locks the data while the returned value is alive, /// so don't keep it too long. pub fn get_content(&self) -> TextContentRef { TextContentInner::get_content(&self.content) } /// Apply the given closure to the inner content, and bust the cache afterward. fn with_content<F, O>(&self, f: F) -> O where F: FnOnce(&mut TextContentInner) -> O, { let mut content = self.content.lock().unwrap(); let out = f(&mut content); content.size_cache = None; out } } /// Internel representation of the content for a `TextView`. /// /// This is mostly just a `StyledString`. /// /// Can be shared (through a `Arc<Mutex>`). struct TextContentInner { // content: String, content_value: InnerContentType, content_cache: InnerContentType, // We keep the cache here so it can be busted when we change the content. size_cache: Option<XY<SizeCache>>, } impl TextContentInner { /// From a shareable content (Arc + Mutex), return a fn get_content(content: &Arc<Mutex<TextContentInner>>) -> TextContentRef { let arc_ref: ArcRef<Mutex<TextContentInner>> = ArcRef::new(Arc::clone(content)); let _handle = OwningHandle::new_with_fn(arc_ref, |mutex| unsafe { (*mutex).lock().unwrap() }); let data = Arc::clone(&_handle.content_value); TextContentRef { _handle, data } } fn is_cache_valid(&self, size: Vec2) -> bool { match self.size_cache { None => false, Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y), } } fn get_cache(&self) -> &InnerContentType { &self.content_cache } } /// A simple view showing a fixed text. /// /// # Examples /// /// ```rust /// # use cursive_core::Cursive; /// # use cursive_core::views::TextView; /// let mut siv = Cursive::dummy(); /// /// siv.add_layer(TextView::new("Hello world!")); /// ``` pub struct TextView { // content: String, content: TextContent, rows: Vec<Row>, align: Align, // TODO: remove now that we have styled text? effect: Effect, // True if we can wrap long lines. wrap: bool, // ScrollBase make many scrolling-related things easier last_size: Vec2, width: Option<usize>, } impl TextView { /// Creates a new TextView with the given content. pub fn new<S>(content: S) -> Self where S: Into<StyledString>, { Self::new_with_content(TextContent::new(content)) } /// Creates a new TextView using the given `TextContent`. /// /// If you kept a clone of the given content, you'll be able to update it /// remotely. /// /// # Examples /// /// ```rust /// # use cursive_core::views::{TextView, TextContent}; /// let mut content = TextContent::new("content"); /// let view = TextView::new_with_content(content.clone()); /// /// // Later, possibly in a different thread /// content.set_content("new content"); /// assert!(view.get_content().source().contains("new")); /// ``` pub fn new_with_content(content: TextContent) -> Self { TextView { content, effect: Effect::Simple, rows: Vec::new(), wrap: true, align: Align::top_left(), last_size: Vec2::zero(), width: None, } } /// Creates a new empty `TextView`. pub fn empty() -> Self { TextView::new("") } /// Sets the effect for the entire content. pub fn set_effect(&mut self, effect: Effect) { self.effect = effect; } /// Sets the effect for the entire content. /// /// Chainable variant. pub fn effect(self, effect: Effect) -> Self { self.with(|s| s.set_effect(effect)) } /// Disables content wrap for this view. /// /// This may be useful if you want horizontal scrolling. pub fn
(self) -> Self { self.with(|s| s.set_content_wrap(false)) } /// Controls content wrap for this view. /// /// If `true` (the default), text will wrap long lines when needed. pub fn set_content_wrap(&mut self, wrap: bool) { self.wrap = wrap; } /// Sets the horizontal alignment for this view. pub fn h_align(mut self, h: HAlign) -> Self { self.align.h = h; self } /// Sets the vertical alignment for this view. pub fn v_align(mut self, v: VAlign) -> Self { self.align.v = v; self } /// Sets the alignment for this view. pub fn align(mut self, a: Align) -> Self { self.align = a; self } /// Center the text horizontally and vertically inside the view. pub fn center(mut self) -> Self { self.align = Align::center(); self } /// Replace the text in this view. /// /// Chainable variant. pub fn content<S>(self, content: S) -> Self where S: Into<StyledString>, { self.with(|s| s.set_content(content)) } /// Replace the text in this view. pub fn set_content<S>(&mut self, content: S) where S: Into<StyledString>, { self.content.set_content(content); } /// Append `content` to the end of a `TextView`. pub fn append<S>(&mut self, content: S) where S: Into<StyledString>, { self.content.append(content); } /// Returns the current text in this view. pub fn get_content(&self) -> TextContentRef { TextContentInner::get_content(&self.content.content) } /// Returns a shared reference to the content, allowing content mutation. pub fn get_shared_content(&mut self) -> TextContent { // We take &mut here without really needing it, // because it sort of "makes sense". TextContent { content: Arc::clone(&self.content.content), } } // This must be non-destructive, as it may be called // multiple times during layout. fn compute_rows(&mut self, size: Vec2) { let size = if self.wrap { size } else { Vec2::max_value() }; let mut content = self.content.content.lock().unwrap(); if content.is_cache_valid(size) { return; } // Completely bust the cache // Just in case we fail, we don't want to leave a bad cache. content.size_cache = None; content.content_cache = Arc::clone(&content.content_value); if size.x == 0 { // Nothing we can do at this point. return; } self.rows = LinesIterator::new(content.get_cache().as_ref(), size.x).collect(); // Desired width self.width = self.rows.iter().map(|row| row.width).max(); } } impl View for TextView { fn draw(&self, printer: &Printer) { let h = self.rows.len(); // If the content is smaller than the view, align it somewhere. let offset = self.align.v.get_offset(h, printer.size.y); let printer = &printer.offset((0, offset)); let content = self.content.content.lock().unwrap(); printer.with_effect(self.effect, |printer| { for (y, row) in self.rows.iter().enumerate() { let l = row.width; let mut x = self.align.h.get_offset(l, printer.size.x); for span in row.resolve(content.get_cache().as_ref()) { printer.with_style(*span.attr, |printer| { printer.print((x, y), span.content); x += span.content.width(); }); } } }); } fn needs_relayout(&self) -> bool { let content = self.content.content.lock().unwrap(); content.size_cache.is_none() } fn required_size(&mut self, size: Vec2) -> Vec2 { self.compute_rows(size); Vec2::new(self.width.unwrap_or(0), self.rows.len()) } fn layout(&mut self, size: Vec2) { // Compute the text rows. self.last_size = size; self.compute_rows(size); // The entire "virtual" size (includes all rows) let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len()); // Build a fresh cache. let mut content = self.content.content.lock().unwrap(); content.size_cache = Some(SizeCache::build(my_size, size)); } }
no_wrap
identifier_name
text_view.rs
use std::ops::Deref; use std::sync::Arc; use std::sync::{Mutex, MutexGuard}; use owning_ref::{ArcRef, OwningHandle}; use unicode_width::UnicodeWidthStr; use crate::align::*; use crate::theme::Effect; use crate::utils::lines::spans::{LinesIterator, Row}; use crate::utils::markup::StyledString; use crate::view::{SizeCache, View}; use crate::{Printer, Vec2, With, XY}; // Content type used internally for caching and storage type InnerContentType = Arc<StyledString>; /// Provides access to the content of a [`TextView`]. /// /// [`TextView`]: struct.TextView.html /// /// Cloning this object will still point to the same content. /// /// # Examples /// /// ```rust /// # use cursive_core::views::{TextView, TextContent}; /// let mut content = TextContent::new("content"); /// let view = TextView::new_with_content(content.clone()); /// /// // Later, possibly in a different thread /// content.set_content("new content"); /// assert!(view.get_content().source().contains("new")); /// ``` #[derive(Clone)] pub struct TextContent { content: Arc<Mutex<TextContentInner>>, } impl TextContent { /// Creates a new text content around the given value. /// /// Parses the given value. pub fn new<S>(content: S) -> Self where S: Into<StyledString>, { let content = Arc::new(content.into()); TextContent { content: Arc::new(Mutex::new(TextContentInner { content_value: content, content_cache: Arc::new(StyledString::default()), size_cache: None, })), } } } /// A reference to the text content. /// /// This can be deref'ed into a [`StyledString`]. /// /// [`StyledString`]:../utils/markup/type.StyledString.html /// /// This keeps the content locked. Do not store this! pub struct TextContentRef { _handle: OwningHandle<
>, // We also need to keep a copy of Arc so `deref` can return // a reference to the `StyledString` data: Arc<StyledString>, } impl Deref for TextContentRef { type Target = StyledString; fn deref(&self) -> &StyledString { self.data.as_ref() } } impl TextContent { /// Replaces the content with the given value. pub fn set_content<S>(&self, content: S) where S: Into<StyledString>, { self.with_content(|c| { *Arc::make_mut(&mut c.content_value) = content.into(); }); } /// Append `content` to the end of a `TextView`. pub fn append<S>(&self, content: S) where S: Into<StyledString>, { self.with_content(|c| { // This will only clone content if content_cached and content_value // are sharing the same underlying Rc. Arc::make_mut(&mut c.content_value).append(content); }) } /// Returns a reference to the content. /// /// This locks the data while the returned value is alive, /// so don't keep it too long. pub fn get_content(&self) -> TextContentRef { TextContentInner::get_content(&self.content) } /// Apply the given closure to the inner content, and bust the cache afterward. fn with_content<F, O>(&self, f: F) -> O where F: FnOnce(&mut TextContentInner) -> O, { let mut content = self.content.lock().unwrap(); let out = f(&mut content); content.size_cache = None; out } } /// Internel representation of the content for a `TextView`. /// /// This is mostly just a `StyledString`. /// /// Can be shared (through a `Arc<Mutex>`). struct TextContentInner { // content: String, content_value: InnerContentType, content_cache: InnerContentType, // We keep the cache here so it can be busted when we change the content. size_cache: Option<XY<SizeCache>>, } impl TextContentInner { /// From a shareable content (Arc + Mutex), return a fn get_content(content: &Arc<Mutex<TextContentInner>>) -> TextContentRef { let arc_ref: ArcRef<Mutex<TextContentInner>> = ArcRef::new(Arc::clone(content)); let _handle = OwningHandle::new_with_fn(arc_ref, |mutex| unsafe { (*mutex).lock().unwrap() }); let data = Arc::clone(&_handle.content_value); TextContentRef { _handle, data } } fn is_cache_valid(&self, size: Vec2) -> bool { match self.size_cache { None => false, Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y), } } fn get_cache(&self) -> &InnerContentType { &self.content_cache } } /// A simple view showing a fixed text. /// /// # Examples /// /// ```rust /// # use cursive_core::Cursive; /// # use cursive_core::views::TextView; /// let mut siv = Cursive::dummy(); /// /// siv.add_layer(TextView::new("Hello world!")); /// ``` pub struct TextView { // content: String, content: TextContent, rows: Vec<Row>, align: Align, // TODO: remove now that we have styled text? effect: Effect, // True if we can wrap long lines. wrap: bool, // ScrollBase make many scrolling-related things easier last_size: Vec2, width: Option<usize>, } impl TextView { /// Creates a new TextView with the given content. pub fn new<S>(content: S) -> Self where S: Into<StyledString>, { Self::new_with_content(TextContent::new(content)) } /// Creates a new TextView using the given `TextContent`. /// /// If you kept a clone of the given content, you'll be able to update it /// remotely. /// /// # Examples /// /// ```rust /// # use cursive_core::views::{TextView, TextContent}; /// let mut content = TextContent::new("content"); /// let view = TextView::new_with_content(content.clone()); /// /// // Later, possibly in a different thread /// content.set_content("new content"); /// assert!(view.get_content().source().contains("new")); /// ``` pub fn new_with_content(content: TextContent) -> Self { TextView { content, effect: Effect::Simple, rows: Vec::new(), wrap: true, align: Align::top_left(), last_size: Vec2::zero(), width: None, } } /// Creates a new empty `TextView`. pub fn empty() -> Self { TextView::new("") } /// Sets the effect for the entire content. pub fn set_effect(&mut self, effect: Effect) { self.effect = effect; } /// Sets the effect for the entire content. /// /// Chainable variant. pub fn effect(self, effect: Effect) -> Self { self.with(|s| s.set_effect(effect)) } /// Disables content wrap for this view. /// /// This may be useful if you want horizontal scrolling. pub fn no_wrap(self) -> Self { self.with(|s| s.set_content_wrap(false)) } /// Controls content wrap for this view. /// /// If `true` (the default), text will wrap long lines when needed. pub fn set_content_wrap(&mut self, wrap: bool) { self.wrap = wrap; } /// Sets the horizontal alignment for this view. pub fn h_align(mut self, h: HAlign) -> Self { self.align.h = h; self } /// Sets the vertical alignment for this view. pub fn v_align(mut self, v: VAlign) -> Self { self.align.v = v; self } /// Sets the alignment for this view. pub fn align(mut self, a: Align) -> Self { self.align = a; self } /// Center the text horizontally and vertically inside the view. pub fn center(mut self) -> Self { self.align = Align::center(); self } /// Replace the text in this view. /// /// Chainable variant. pub fn content<S>(self, content: S) -> Self where S: Into<StyledString>, { self.with(|s| s.set_content(content)) } /// Replace the text in this view. pub fn set_content<S>(&mut self, content: S) where S: Into<StyledString>, { self.content.set_content(content); } /// Append `content` to the end of a `TextView`. pub fn append<S>(&mut self, content: S) where S: Into<StyledString>, { self.content.append(content); } /// Returns the current text in this view. pub fn get_content(&self) -> TextContentRef { TextContentInner::get_content(&self.content.content) } /// Returns a shared reference to the content, allowing content mutation. pub fn get_shared_content(&mut self) -> TextContent { // We take &mut here without really needing it, // because it sort of "makes sense". TextContent { content: Arc::clone(&self.content.content), } } // This must be non-destructive, as it may be called // multiple times during layout. fn compute_rows(&mut self, size: Vec2) { let size = if self.wrap { size } else { Vec2::max_value() }; let mut content = self.content.content.lock().unwrap(); if content.is_cache_valid(size) { return; } // Completely bust the cache // Just in case we fail, we don't want to leave a bad cache. content.size_cache = None; content.content_cache = Arc::clone(&content.content_value); if size.x == 0 { // Nothing we can do at this point. return; } self.rows = LinesIterator::new(content.get_cache().as_ref(), size.x).collect(); // Desired width self.width = self.rows.iter().map(|row| row.width).max(); } } impl View for TextView { fn draw(&self, printer: &Printer) { let h = self.rows.len(); // If the content is smaller than the view, align it somewhere. let offset = self.align.v.get_offset(h, printer.size.y); let printer = &printer.offset((0, offset)); let content = self.content.content.lock().unwrap(); printer.with_effect(self.effect, |printer| { for (y, row) in self.rows.iter().enumerate() { let l = row.width; let mut x = self.align.h.get_offset(l, printer.size.x); for span in row.resolve(content.get_cache().as_ref()) { printer.with_style(*span.attr, |printer| { printer.print((x, y), span.content); x += span.content.width(); }); } } }); } fn needs_relayout(&self) -> bool { let content = self.content.content.lock().unwrap(); content.size_cache.is_none() } fn required_size(&mut self, size: Vec2) -> Vec2 { self.compute_rows(size); Vec2::new(self.width.unwrap_or(0), self.rows.len()) } fn layout(&mut self, size: Vec2) { // Compute the text rows. self.last_size = size; self.compute_rows(size); // The entire "virtual" size (includes all rows) let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len()); // Build a fresh cache. let mut content = self.content.content.lock().unwrap(); content.size_cache = Some(SizeCache::build(my_size, size)); } }
ArcRef<Mutex<TextContentInner>>, MutexGuard<'static, TextContentInner>,
random_line_split
regions-fn-subtyping-2.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. // Issue #2263. // Here, `f` is a function that takes a pointer `x` and a function // `g`, where `g` requires its argument `y` to be in the same region // that `x` is in.
fn has_same_region(f: &fn<'a>(x: &'a int, g: &fn(y: &'a int))) { // `f` should be the type that `wants_same_region` wants, but // right now the compiler complains that it isn't. wants_same_region(f); } fn wants_same_region(_f: &fn<'b>(x: &'b int, g: &fn(y: &'b int))) { } pub fn main() { }
random_line_split
regions-fn-subtyping-2.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. // Issue #2263. // Here, `f` is a function that takes a pointer `x` and a function // `g`, where `g` requires its argument `y` to be in the same region // that `x` is in. fn has_same_region(f: &fn<'a>(x: &'a int, g: &fn(y: &'a int))) { // `f` should be the type that `wants_same_region` wants, but // right now the compiler complains that it isn't. wants_same_region(f); } fn wants_same_region(_f: &fn<'b>(x: &'b int, g: &fn(y: &'b int))) { } pub fn
() { }
main
identifier_name
regions-fn-subtyping-2.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. // Issue #2263. // Here, `f` is a function that takes a pointer `x` and a function // `g`, where `g` requires its argument `y` to be in the same region // that `x` is in. fn has_same_region(f: &fn<'a>(x: &'a int, g: &fn(y: &'a int))) { // `f` should be the type that `wants_same_region` wants, but // right now the compiler complains that it isn't. wants_same_region(f); } fn wants_same_region(_f: &fn<'b>(x: &'b int, g: &fn(y: &'b int)))
pub fn main() { }
{ }
identifier_body
types.rs
use game::{Position, Move, Score, NumPlies, NumMoves}; #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)] pub struct NumNodes(pub u64); #[derive(Clone, Debug)] pub struct State { pub pos: Position, pub prev_pos: Option<Position>, pub prev_move: Option<Move>, pub param: Param, } #[derive(Clone, Debug)] pub struct Param { pub ponder: bool, pub search_moves: Option<Vec<Move>>, pub depth: Option<NumPlies>, pub nodes: Option<NumNodes>, pub mate: Option<NumMoves>, pub hash_size: usize, } impl Param { pub fn new(hash_size: usize) -> Self { Param { ponder: false, search_moves: None, depth: None, nodes: None, mate: None, hash_size: hash_size, } } } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Cmd { SetDebug(bool), PonderHit, Stop, } #[derive(PartialEq, Eq, Clone, Debug)] pub struct BestMove(pub Move, pub Option<Move>); #[derive(Clone, Debug)] pub struct Report { pub data: Data, pub score: Score, pub pv: Vec<Move>, } #[derive(Clone, Debug)] pub struct Data { pub nodes: NumNodes, pub depth: NumPlies, } // TODO put actual data here #[derive(Clone, Debug)] pub struct InnerData { pub nodes: NumNodes, } impl InnerData { pub fn one_node() -> InnerData { InnerData { nodes: NumNodes(1) } } pub fn combine(self, other: InnerData) -> InnerData { InnerData { nodes: NumNodes(self.nodes.0 + other.nodes.0) } } pub fn increment(self) -> InnerData
}
{ InnerData { nodes: NumNodes(self.nodes.0 + 1) } }
identifier_body
types.rs
use game::{Position, Move, Score, NumPlies, NumMoves}; #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)] pub struct NumNodes(pub u64); #[derive(Clone, Debug)] pub struct State { pub pos: Position, pub prev_pos: Option<Position>, pub prev_move: Option<Move>, pub param: Param, } #[derive(Clone, Debug)] pub struct Param { pub ponder: bool, pub search_moves: Option<Vec<Move>>, pub depth: Option<NumPlies>, pub nodes: Option<NumNodes>, pub mate: Option<NumMoves>, pub hash_size: usize, } impl Param { pub fn new(hash_size: usize) -> Self { Param { ponder: false, search_moves: None, depth: None, nodes: None, mate: None, hash_size: hash_size, } } } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Cmd { SetDebug(bool), PonderHit, Stop, } #[derive(PartialEq, Eq, Clone, Debug)] pub struct
(pub Move, pub Option<Move>); #[derive(Clone, Debug)] pub struct Report { pub data: Data, pub score: Score, pub pv: Vec<Move>, } #[derive(Clone, Debug)] pub struct Data { pub nodes: NumNodes, pub depth: NumPlies, } // TODO put actual data here #[derive(Clone, Debug)] pub struct InnerData { pub nodes: NumNodes, } impl InnerData { pub fn one_node() -> InnerData { InnerData { nodes: NumNodes(1) } } pub fn combine(self, other: InnerData) -> InnerData { InnerData { nodes: NumNodes(self.nodes.0 + other.nodes.0) } } pub fn increment(self) -> InnerData { InnerData { nodes: NumNodes(self.nodes.0 + 1) } } }
BestMove
identifier_name