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
triangle.rs
extern mod gl; extern mod glfw; extern mod sgl; use sgl::buffer::*; use sgl::vertex_array::*; use sgl::shader::*; use sgl::shader_program::*; fn draw_array(vao: &VertexArray,first: gl::types::GLint,size: gl::types::GLsizei) { vao.bind(); gl::DrawArrays(gl::TRIANGLES, first,size); } fn draw_element_array(vao: &VertexArray,ibo: &IndexBuffer)
#[start] fn start(argc: int, argv: **u8, crate_map: *u8) -> int { // Run GLFW on the main thread std::rt::start_on_main_thread(argc, argv, crate_map, main) } fn main() { static vertices: [gl::types::GLfloat,..6] = [ -0.5, -0.5, 0.5, -0.5, -0.5, 0.5 ]; static color: [gl::types::GLfloat,..9] = [ 1.0, 0.0,0.0, 0.0, 1.0,0.0, 0.0, 0.0,1.0 ]; static indecies: [gl::types::GLuint,..6] = [ 0,1,2,3,4,5 ]; do glfw::set_error_callback |_, description| { printfln!("GLFW Error: %s", description); } do glfw::start { // Choose a GL profile that is compatible with OS X 10.7+ glfw::window_hint::context_version(4, 3); glfw::window_hint::opengl_profile(glfw::OPENGL_CORE_PROFILE); glfw::window_hint::opengl_forward_compat(true); let window = glfw::Window::create(800, 600, "OpenGL", glfw::Windowed).unwrap(); window.make_context_current(); // Load the OpenGL function pointers gl::load_with(glfw::get_proc_address); // Create Vertex Array Object // Create a Vertex Buffer Object and copy the vertex data to it let vbo = VertexBuffer::new(vertices, gl::STATIC_DRAW); let color_vbo = VertexBuffer::new(color, gl::STATIC_DRAW); let vertex_source = std::io::read_whole_file_str(&std::path::Path("triangle.vs")).unwrap(); let fragment_source = std::io::read_whole_file_str(&std::path::Path("triangle.fs")).unwrap(); // Create and compile the vertex shader let vertex_shader = Shader::new_vs(~"triangle.vs",vertex_source).unwrap(); // Create and compile the fragment shader let fragment_shader = Shader::new_fs(~"triangle.fs",fragment_source).unwrap(); // Link the vertex and fragment shader into a shader program let shader_program = ShaderProgram::new([&vertex_shader, &fragment_shader]).unwrap(); shader_program.use_program(); shader_program.set_uniform1f(~"value",1.0f32); //shader_program.bind_frag_location(1,~"123123outColor"); let ibo = IndexBuffer::new(indecies, gl::STATIC_DRAW); let vao = VertexArray::new(); vao.bind_attrib(shader_program.get_attrib_location("position"), 2, &vbo); vao.bind_attrib(shader_program.get_attrib_location("color"), 3, &color_vbo); while!window.should_close() { // Poll events glfw::poll_events(); // Clear the screen to black gl::ClearColor(0.0, 0.0, 0.0, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); //vao.bind(); draw_array(&vao,0,3); // Swap buffers window.swap_buffers(); } } }
{ vao.bind(); ibo.bind(); unsafe { gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, std::ptr::null()); } }
identifier_body
triangle.rs
extern mod gl; extern mod glfw; extern mod sgl; use sgl::buffer::*; use sgl::vertex_array::*; use sgl::shader::*; use sgl::shader_program::*; fn draw_array(vao: &VertexArray,first: gl::types::GLint,size: gl::types::GLsizei) { vao.bind(); gl::DrawArrays(gl::TRIANGLES, first,size); } fn draw_element_array(vao: &VertexArray,ibo: &IndexBuffer) { vao.bind(); ibo.bind(); unsafe { gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, std::ptr::null()); } } #[start] fn
(argc: int, argv: **u8, crate_map: *u8) -> int { // Run GLFW on the main thread std::rt::start_on_main_thread(argc, argv, crate_map, main) } fn main() { static vertices: [gl::types::GLfloat,..6] = [ -0.5, -0.5, 0.5, -0.5, -0.5, 0.5 ]; static color: [gl::types::GLfloat,..9] = [ 1.0, 0.0,0.0, 0.0, 1.0,0.0, 0.0, 0.0,1.0 ]; static indecies: [gl::types::GLuint,..6] = [ 0,1,2,3,4,5 ]; do glfw::set_error_callback |_, description| { printfln!("GLFW Error: %s", description); } do glfw::start { // Choose a GL profile that is compatible with OS X 10.7+ glfw::window_hint::context_version(4, 3); glfw::window_hint::opengl_profile(glfw::OPENGL_CORE_PROFILE); glfw::window_hint::opengl_forward_compat(true); let window = glfw::Window::create(800, 600, "OpenGL", glfw::Windowed).unwrap(); window.make_context_current(); // Load the OpenGL function pointers gl::load_with(glfw::get_proc_address); // Create Vertex Array Object // Create a Vertex Buffer Object and copy the vertex data to it let vbo = VertexBuffer::new(vertices, gl::STATIC_DRAW); let color_vbo = VertexBuffer::new(color, gl::STATIC_DRAW); let vertex_source = std::io::read_whole_file_str(&std::path::Path("triangle.vs")).unwrap(); let fragment_source = std::io::read_whole_file_str(&std::path::Path("triangle.fs")).unwrap(); // Create and compile the vertex shader let vertex_shader = Shader::new_vs(~"triangle.vs",vertex_source).unwrap(); // Create and compile the fragment shader let fragment_shader = Shader::new_fs(~"triangle.fs",fragment_source).unwrap(); // Link the vertex and fragment shader into a shader program let shader_program = ShaderProgram::new([&vertex_shader, &fragment_shader]).unwrap(); shader_program.use_program(); shader_program.set_uniform1f(~"value",1.0f32); //shader_program.bind_frag_location(1,~"123123outColor"); let ibo = IndexBuffer::new(indecies, gl::STATIC_DRAW); let vao = VertexArray::new(); vao.bind_attrib(shader_program.get_attrib_location("position"), 2, &vbo); vao.bind_attrib(shader_program.get_attrib_location("color"), 3, &color_vbo); while!window.should_close() { // Poll events glfw::poll_events(); // Clear the screen to black gl::ClearColor(0.0, 0.0, 0.0, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); //vao.bind(); draw_array(&vao,0,3); // Swap buffers window.swap_buffers(); } } }
start
identifier_name
triangle.rs
extern mod gl; extern mod glfw; extern mod sgl; use sgl::buffer::*; use sgl::vertex_array::*; use sgl::shader::*; use sgl::shader_program::*; fn draw_array(vao: &VertexArray,first: gl::types::GLint,size: gl::types::GLsizei) { vao.bind(); gl::DrawArrays(gl::TRIANGLES, first,size); } fn draw_element_array(vao: &VertexArray,ibo: &IndexBuffer) { vao.bind(); ibo.bind(); unsafe { gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, std::ptr::null()); } } #[start] fn start(argc: int, argv: **u8, crate_map: *u8) -> int { // Run GLFW on the main thread std::rt::start_on_main_thread(argc, argv, crate_map, main) } fn main() { static vertices: [gl::types::GLfloat,..6] = [ -0.5, -0.5, 0.5, -0.5, -0.5, 0.5 ]; static color: [gl::types::GLfloat,..9] = [ 1.0, 0.0,0.0, 0.0, 1.0,0.0, 0.0, 0.0,1.0 ]; static indecies: [gl::types::GLuint,..6] = [
printfln!("GLFW Error: %s", description); } do glfw::start { // Choose a GL profile that is compatible with OS X 10.7+ glfw::window_hint::context_version(4, 3); glfw::window_hint::opengl_profile(glfw::OPENGL_CORE_PROFILE); glfw::window_hint::opengl_forward_compat(true); let window = glfw::Window::create(800, 600, "OpenGL", glfw::Windowed).unwrap(); window.make_context_current(); // Load the OpenGL function pointers gl::load_with(glfw::get_proc_address); // Create Vertex Array Object // Create a Vertex Buffer Object and copy the vertex data to it let vbo = VertexBuffer::new(vertices, gl::STATIC_DRAW); let color_vbo = VertexBuffer::new(color, gl::STATIC_DRAW); let vertex_source = std::io::read_whole_file_str(&std::path::Path("triangle.vs")).unwrap(); let fragment_source = std::io::read_whole_file_str(&std::path::Path("triangle.fs")).unwrap(); // Create and compile the vertex shader let vertex_shader = Shader::new_vs(~"triangle.vs",vertex_source).unwrap(); // Create and compile the fragment shader let fragment_shader = Shader::new_fs(~"triangle.fs",fragment_source).unwrap(); // Link the vertex and fragment shader into a shader program let shader_program = ShaderProgram::new([&vertex_shader, &fragment_shader]).unwrap(); shader_program.use_program(); shader_program.set_uniform1f(~"value",1.0f32); //shader_program.bind_frag_location(1,~"123123outColor"); let ibo = IndexBuffer::new(indecies, gl::STATIC_DRAW); let vao = VertexArray::new(); vao.bind_attrib(shader_program.get_attrib_location("position"), 2, &vbo); vao.bind_attrib(shader_program.get_attrib_location("color"), 3, &color_vbo); while!window.should_close() { // Poll events glfw::poll_events(); // Clear the screen to black gl::ClearColor(0.0, 0.0, 0.0, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); //vao.bind(); draw_array(&vao,0,3); // Swap buffers window.swap_buffers(); } } }
0,1,2,3,4,5 ]; do glfw::set_error_callback |_, description| {
random_line_split
parser.rs
use std::collections::HashSet; use std::ffi::OsStr; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; use anyhow::Context; use protobuf::descriptor::FileDescriptorSet; use crate::protoc; use crate::pure; use crate::which_parser::WhichParser; use crate::ParsedAndTypechecked; /// Configure and invoke `.proto` parser. #[derive(Default, Debug)] pub struct Parser { which_parser: WhichParser, pub(crate) includes: Vec<PathBuf>, pub(crate) inputs: Vec<PathBuf>, pub(crate) protoc: Option<PathBuf>, pub(crate) protoc_extra_args: Vec<OsString>, } impl Parser { /// Create new default configured parser. pub fn new() -> Parser
/// Use pure rust parser. pub fn pure(&mut self) -> &mut Self { self.which_parser = WhichParser::Pure; self } /// Use `protoc` for parsing. pub fn protoc(&mut self) -> &mut Self { self.which_parser = WhichParser::Protoc; self } /// Add an include directory. pub fn include(&mut self, include: impl AsRef<Path>) -> &mut Self { self.includes.push(include.as_ref().to_owned()); self } /// Add include directories. pub fn includes(&mut self, includes: impl IntoIterator<Item = impl AsRef<Path>>) -> &mut Self { for include in includes { self.include(include); } self } /// Append a `.proto` file path to compile pub fn input(&mut self, input: impl AsRef<Path>) -> &mut Self { self.inputs.push(input.as_ref().to_owned()); self } /// Append multiple `.proto` file paths to compile pub fn inputs(&mut self, inputs: impl IntoIterator<Item = impl AsRef<Path>>) -> &mut Self { for input in inputs { self.input(input); } self } /// Specify `protoc` path used for parsing. /// /// This is ignored if pure rust parser is used. pub fn protoc_path(&mut self, protoc: &Path) -> &mut Self { self.protoc = Some(protoc.to_owned()); self } /// Extra arguments to pass to `protoc` command (like experimental options). /// /// This is ignored if pure rust parser is used. pub fn protoc_extra_args( &mut self, args: impl IntoIterator<Item = impl AsRef<OsStr>>, ) -> &mut Self { self.protoc_extra_args = args.into_iter().map(|s| s.as_ref().to_owned()).collect(); self } /// Parse `.proto` files and typecheck them using pure Rust parser of `protoc` command. pub fn parse_and_typecheck(&self) -> anyhow::Result<ParsedAndTypechecked> { match &self.which_parser { WhichParser::Pure => { pure::parse_and_typecheck::parse_and_typecheck(&self).context("using pure parser") } WhichParser::Protoc => protoc::parse_and_typecheck::parse_and_typecheck(&self) .context("using protoc parser"), } } /// Parse and convert result to `FileDescriptorSet`. pub fn file_descriptor_set(&self) -> anyhow::Result<FileDescriptorSet> { let mut generated = self.parse_and_typecheck()?; let relative_paths: HashSet<_> = generated .relative_paths .iter() .map(|path| path.to_string()) .collect(); generated .file_descriptors .retain(|fd| relative_paths.contains(fd.name())); let mut fds = FileDescriptorSet::new(); fds.file = generated.file_descriptors; Ok(fds) } }
{ Parser::default() }
identifier_body
parser.rs
use std::collections::HashSet; use std::ffi::OsStr; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; use anyhow::Context; use protobuf::descriptor::FileDescriptorSet; use crate::protoc; use crate::pure; use crate::which_parser::WhichParser; use crate::ParsedAndTypechecked; /// Configure and invoke `.proto` parser. #[derive(Default, Debug)] pub struct Parser { which_parser: WhichParser, pub(crate) includes: Vec<PathBuf>, pub(crate) inputs: Vec<PathBuf>, pub(crate) protoc: Option<PathBuf>, pub(crate) protoc_extra_args: Vec<OsString>, } impl Parser { /// Create new default configured parser. pub fn new() -> Parser { Parser::default() } /// Use pure rust parser. pub fn pure(&mut self) -> &mut Self { self.which_parser = WhichParser::Pure; self } /// Use `protoc` for parsing. pub fn protoc(&mut self) -> &mut Self { self.which_parser = WhichParser::Protoc; self } /// Add an include directory. pub fn include(&mut self, include: impl AsRef<Path>) -> &mut Self { self.includes.push(include.as_ref().to_owned()); self } /// Add include directories. pub fn
(&mut self, includes: impl IntoIterator<Item = impl AsRef<Path>>) -> &mut Self { for include in includes { self.include(include); } self } /// Append a `.proto` file path to compile pub fn input(&mut self, input: impl AsRef<Path>) -> &mut Self { self.inputs.push(input.as_ref().to_owned()); self } /// Append multiple `.proto` file paths to compile pub fn inputs(&mut self, inputs: impl IntoIterator<Item = impl AsRef<Path>>) -> &mut Self { for input in inputs { self.input(input); } self } /// Specify `protoc` path used for parsing. /// /// This is ignored if pure rust parser is used. pub fn protoc_path(&mut self, protoc: &Path) -> &mut Self { self.protoc = Some(protoc.to_owned()); self } /// Extra arguments to pass to `protoc` command (like experimental options). /// /// This is ignored if pure rust parser is used. pub fn protoc_extra_args( &mut self, args: impl IntoIterator<Item = impl AsRef<OsStr>>, ) -> &mut Self { self.protoc_extra_args = args.into_iter().map(|s| s.as_ref().to_owned()).collect(); self } /// Parse `.proto` files and typecheck them using pure Rust parser of `protoc` command. pub fn parse_and_typecheck(&self) -> anyhow::Result<ParsedAndTypechecked> { match &self.which_parser { WhichParser::Pure => { pure::parse_and_typecheck::parse_and_typecheck(&self).context("using pure parser") } WhichParser::Protoc => protoc::parse_and_typecheck::parse_and_typecheck(&self) .context("using protoc parser"), } } /// Parse and convert result to `FileDescriptorSet`. pub fn file_descriptor_set(&self) -> anyhow::Result<FileDescriptorSet> { let mut generated = self.parse_and_typecheck()?; let relative_paths: HashSet<_> = generated .relative_paths .iter() .map(|path| path.to_string()) .collect(); generated .file_descriptors .retain(|fd| relative_paths.contains(fd.name())); let mut fds = FileDescriptorSet::new(); fds.file = generated.file_descriptors; Ok(fds) } }
includes
identifier_name
parser.rs
use std::collections::HashSet; use std::ffi::OsStr; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; use anyhow::Context; use protobuf::descriptor::FileDescriptorSet; use crate::protoc; use crate::pure; use crate::which_parser::WhichParser; use crate::ParsedAndTypechecked; /// Configure and invoke `.proto` parser. #[derive(Default, Debug)] pub struct Parser { which_parser: WhichParser, pub(crate) includes: Vec<PathBuf>, pub(crate) inputs: Vec<PathBuf>,
pub(crate) protoc_extra_args: Vec<OsString>, } impl Parser { /// Create new default configured parser. pub fn new() -> Parser { Parser::default() } /// Use pure rust parser. pub fn pure(&mut self) -> &mut Self { self.which_parser = WhichParser::Pure; self } /// Use `protoc` for parsing. pub fn protoc(&mut self) -> &mut Self { self.which_parser = WhichParser::Protoc; self } /// Add an include directory. pub fn include(&mut self, include: impl AsRef<Path>) -> &mut Self { self.includes.push(include.as_ref().to_owned()); self } /// Add include directories. pub fn includes(&mut self, includes: impl IntoIterator<Item = impl AsRef<Path>>) -> &mut Self { for include in includes { self.include(include); } self } /// Append a `.proto` file path to compile pub fn input(&mut self, input: impl AsRef<Path>) -> &mut Self { self.inputs.push(input.as_ref().to_owned()); self } /// Append multiple `.proto` file paths to compile pub fn inputs(&mut self, inputs: impl IntoIterator<Item = impl AsRef<Path>>) -> &mut Self { for input in inputs { self.input(input); } self } /// Specify `protoc` path used for parsing. /// /// This is ignored if pure rust parser is used. pub fn protoc_path(&mut self, protoc: &Path) -> &mut Self { self.protoc = Some(protoc.to_owned()); self } /// Extra arguments to pass to `protoc` command (like experimental options). /// /// This is ignored if pure rust parser is used. pub fn protoc_extra_args( &mut self, args: impl IntoIterator<Item = impl AsRef<OsStr>>, ) -> &mut Self { self.protoc_extra_args = args.into_iter().map(|s| s.as_ref().to_owned()).collect(); self } /// Parse `.proto` files and typecheck them using pure Rust parser of `protoc` command. pub fn parse_and_typecheck(&self) -> anyhow::Result<ParsedAndTypechecked> { match &self.which_parser { WhichParser::Pure => { pure::parse_and_typecheck::parse_and_typecheck(&self).context("using pure parser") } WhichParser::Protoc => protoc::parse_and_typecheck::parse_and_typecheck(&self) .context("using protoc parser"), } } /// Parse and convert result to `FileDescriptorSet`. pub fn file_descriptor_set(&self) -> anyhow::Result<FileDescriptorSet> { let mut generated = self.parse_and_typecheck()?; let relative_paths: HashSet<_> = generated .relative_paths .iter() .map(|path| path.to_string()) .collect(); generated .file_descriptors .retain(|fd| relative_paths.contains(fd.name())); let mut fds = FileDescriptorSet::new(); fds.file = generated.file_descriptors; Ok(fds) } }
pub(crate) protoc: Option<PathBuf>,
random_line_split
blob_url_store.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::filemanager_thread::FileOrigin; use servo_url::ServoUrl; use std::str::FromStr; use url::Url; use uuid::Uuid; /// Errors returned to Blob URL Store request #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum BlobURLStoreError { /// Invalid File UUID InvalidFileID, /// Invalid URL origin InvalidOrigin, /// Invalid entry content InvalidEntry, /// Invalid range InvalidRange, /// External error, from like file system, I/O etc. External(String), } /// Standalone blob buffer object #[derive(Clone, Debug, Deserialize, Serialize)] pub struct
{ pub filename: Option<String>, /// MIME type string pub type_string: String, /// Size of content in bytes pub size: u64, /// Content of blob pub bytes: Vec<u8>, } /// Parse URL as Blob URL scheme's definition /// /// <https://w3c.github.io/FileAPI/#DefinitionOfScheme> pub fn parse_blob_url(url: &ServoUrl) -> Result<(Uuid, FileOrigin), ()> { let url_inner = Url::parse(url.path()).map_err(|_| ())?; let segs = url_inner .path_segments() .map(|c| c.collect::<Vec<_>>()) .ok_or(())?; if url.query().is_some() || segs.len() > 1 { return Err(()); } let id = { let id = segs.first().ok_or(())?; Uuid::from_str(id).map_err(|_| ())? }; Ok((id, get_blob_origin(&ServoUrl::from_url(url_inner)))) } /// Given an URL, returning the Origin that a Blob created under this /// URL should have. /// /// HACK(izgzhen): Not well-specified on spec, and it is a bit a hack /// both due to ambiguity of spec and that we have to serialization the /// Origin here. pub fn get_blob_origin(url: &ServoUrl) -> FileOrigin { if url.scheme() == "file" { // NOTE: by default this is "null" (Opaque), which is not ideal "file://".to_string() } else { url.origin().ascii_serialization() } }
BlobBuf
identifier_name
blob_url_store.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::filemanager_thread::FileOrigin; use servo_url::ServoUrl; use std::str::FromStr; use url::Url; use uuid::Uuid; /// Errors returned to Blob URL Store request #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum BlobURLStoreError { /// Invalid File UUID InvalidFileID, /// Invalid URL origin InvalidOrigin, /// Invalid entry content InvalidEntry, /// Invalid range InvalidRange, /// External error, from like file system, I/O etc. External(String), } /// Standalone blob buffer object #[derive(Clone, Debug, Deserialize, Serialize)] pub struct BlobBuf { pub filename: Option<String>, /// MIME type string pub type_string: String, /// Size of content in bytes pub size: u64, /// Content of blob pub bytes: Vec<u8>, } /// Parse URL as Blob URL scheme's definition /// /// <https://w3c.github.io/FileAPI/#DefinitionOfScheme> pub fn parse_blob_url(url: &ServoUrl) -> Result<(Uuid, FileOrigin), ()> { let url_inner = Url::parse(url.path()).map_err(|_| ())?; let segs = url_inner .path_segments() .map(|c| c.collect::<Vec<_>>()) .ok_or(())?; if url.query().is_some() || segs.len() > 1 { return Err(()); } let id = {
let id = segs.first().ok_or(())?; Uuid::from_str(id).map_err(|_| ())? }; Ok((id, get_blob_origin(&ServoUrl::from_url(url_inner)))) } /// Given an URL, returning the Origin that a Blob created under this /// URL should have. /// /// HACK(izgzhen): Not well-specified on spec, and it is a bit a hack /// both due to ambiguity of spec and that we have to serialization the /// Origin here. pub fn get_blob_origin(url: &ServoUrl) -> FileOrigin { if url.scheme() == "file" { // NOTE: by default this is "null" (Opaque), which is not ideal "file://".to_string() } else { url.origin().ascii_serialization() } }
random_line_split
blob_url_store.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::filemanager_thread::FileOrigin; use servo_url::ServoUrl; use std::str::FromStr; use url::Url; use uuid::Uuid; /// Errors returned to Blob URL Store request #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum BlobURLStoreError { /// Invalid File UUID InvalidFileID, /// Invalid URL origin InvalidOrigin, /// Invalid entry content InvalidEntry, /// Invalid range InvalidRange, /// External error, from like file system, I/O etc. External(String), } /// Standalone blob buffer object #[derive(Clone, Debug, Deserialize, Serialize)] pub struct BlobBuf { pub filename: Option<String>, /// MIME type string pub type_string: String, /// Size of content in bytes pub size: u64, /// Content of blob pub bytes: Vec<u8>, } /// Parse URL as Blob URL scheme's definition /// /// <https://w3c.github.io/FileAPI/#DefinitionOfScheme> pub fn parse_blob_url(url: &ServoUrl) -> Result<(Uuid, FileOrigin), ()> { let url_inner = Url::parse(url.path()).map_err(|_| ())?; let segs = url_inner .path_segments() .map(|c| c.collect::<Vec<_>>()) .ok_or(())?; if url.query().is_some() || segs.len() > 1 { return Err(()); } let id = { let id = segs.first().ok_or(())?; Uuid::from_str(id).map_err(|_| ())? }; Ok((id, get_blob_origin(&ServoUrl::from_url(url_inner)))) } /// Given an URL, returning the Origin that a Blob created under this /// URL should have. /// /// HACK(izgzhen): Not well-specified on spec, and it is a bit a hack /// both due to ambiguity of spec and that we have to serialization the /// Origin here. pub fn get_blob_origin(url: &ServoUrl) -> FileOrigin { if url.scheme() == "file"
else { url.origin().ascii_serialization() } }
{ // NOTE: by default this is "null" (Opaque), which is not ideal "file://".to_string() }
conditional_block
multiple_return_terminators.rs
//! This pass removes jumps to basic blocks containing only a return, and replaces them with a //! return instead. use crate::{simplify, MirPass}; use rustc_index::bit_set::BitSet; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; pub struct MultipleReturnTerminators; impl<'tcx> MirPass<'tcx> for MultipleReturnTerminators { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>)
} if let TerminatorKind::Goto { target } = bb.terminator().kind { if bbs_simple_returns.contains(target) { bb.terminator_mut().kind = TerminatorKind::Return; } } } simplify::remove_dead_blocks(tcx, body) } }
{ if tcx.sess.mir_opt_level() < 4 { return; } // find basic blocks with no statement and a return terminator let mut bbs_simple_returns = BitSet::new_empty(body.basic_blocks().len()); let def_id = body.source.def_id(); let bbs = body.basic_blocks_mut(); for idx in bbs.indices() { if bbs[idx].statements.is_empty() && bbs[idx].terminator().kind == TerminatorKind::Return { bbs_simple_returns.insert(idx); } } for bb in bbs { if !tcx.consider_optimizing(|| format!("MultipleReturnTerminators {:?} ", def_id)) { break;
identifier_body
multiple_return_terminators.rs
//! This pass removes jumps to basic blocks containing only a return, and replaces them with a //! return instead. use crate::{simplify, MirPass}; use rustc_index::bit_set::BitSet; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; pub struct MultipleReturnTerminators; impl<'tcx> MirPass<'tcx> for MultipleReturnTerminators { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if tcx.sess.mir_opt_level() < 4 { return; } // find basic blocks with no statement and a return terminator let mut bbs_simple_returns = BitSet::new_empty(body.basic_blocks().len()); let def_id = body.source.def_id(); let bbs = body.basic_blocks_mut(); for idx in bbs.indices() { if bbs[idx].statements.is_empty() && bbs[idx].terminator().kind == TerminatorKind::Return
} for bb in bbs { if!tcx.consider_optimizing(|| format!("MultipleReturnTerminators {:?} ", def_id)) { break; } if let TerminatorKind::Goto { target } = bb.terminator().kind { if bbs_simple_returns.contains(target) { bb.terminator_mut().kind = TerminatorKind::Return; } } } simplify::remove_dead_blocks(tcx, body) } }
{ bbs_simple_returns.insert(idx); }
conditional_block
multiple_return_terminators.rs
//! This pass removes jumps to basic blocks containing only a return, and replaces them with a //! return instead. use crate::{simplify, MirPass}; use rustc_index::bit_set::BitSet; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; pub struct MultipleReturnTerminators; impl<'tcx> MirPass<'tcx> for MultipleReturnTerminators { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if tcx.sess.mir_opt_level() < 4 { return; } // find basic blocks with no statement and a return terminator let mut bbs_simple_returns = BitSet::new_empty(body.basic_blocks().len()); let def_id = body.source.def_id(); let bbs = body.basic_blocks_mut(); for idx in bbs.indices() { if bbs[idx].statements.is_empty() && bbs[idx].terminator().kind == TerminatorKind::Return { bbs_simple_returns.insert(idx); } } for bb in bbs { if!tcx.consider_optimizing(|| format!("MultipleReturnTerminators {:?} ", def_id)) { break; } if let TerminatorKind::Goto { target } = bb.terminator().kind { if bbs_simple_returns.contains(target) { bb.terminator_mut().kind = TerminatorKind::Return;
simplify::remove_dead_blocks(tcx, body) } }
} } }
random_line_split
multiple_return_terminators.rs
//! This pass removes jumps to basic blocks containing only a return, and replaces them with a //! return instead. use crate::{simplify, MirPass}; use rustc_index::bit_set::BitSet; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; pub struct MultipleReturnTerminators; impl<'tcx> MirPass<'tcx> for MultipleReturnTerminators { fn
(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if tcx.sess.mir_opt_level() < 4 { return; } // find basic blocks with no statement and a return terminator let mut bbs_simple_returns = BitSet::new_empty(body.basic_blocks().len()); let def_id = body.source.def_id(); let bbs = body.basic_blocks_mut(); for idx in bbs.indices() { if bbs[idx].statements.is_empty() && bbs[idx].terminator().kind == TerminatorKind::Return { bbs_simple_returns.insert(idx); } } for bb in bbs { if!tcx.consider_optimizing(|| format!("MultipleReturnTerminators {:?} ", def_id)) { break; } if let TerminatorKind::Goto { target } = bb.terminator().kind { if bbs_simple_returns.contains(target) { bb.terminator_mut().kind = TerminatorKind::Return; } } } simplify::remove_dead_blocks(tcx, body) } }
run_pass
identifier_name
solver.rs
b| b).count() } let (choices, cell) = grid.cells() // We swap order so min sorts correctly .map(|(cell_id, values)| (count_true(values), cell_id)) .filter(|&(choices, _)| choices!= 1) .min() .unwrap_or((1, CellId(0))); (cell, choices) } // Pops a (Grid, [Box<Strategy>]) pair off the top of the stack, // and pushes `n` duplicates of it back onto the stack. fn duplicate_last_grid_n_times(&mut self, n: usize) { let grid = self.grids.pop().expect("SolutionsIter bug: duplicate_last_n_grids called on empty iter"); let split_index = self.strategies.len() - self.strategies_per_grid; let strategies = self.strategies.split_off(split_index); for _ in 1..n { self.grids.push(grid.clone()); self.strategies.extend(strategies.iter().map(|s| s.boxed_clone())); } self.grids.push(grid); self.strategies.extend(strategies.into_iter()); } // Returns `n` pairs of (Grid, [Box<Strategy>]) from the top of the stack. fn last_n_grids(&mut self, n: usize) -> Take<Rev<Zip<IterMut<Grid>, ChunksMut<Box<Strategy>>>>> { self.grids.iter_mut() .zip(self.strategies.chunks_mut(self.strategies_per_grid)) .rev() .take(n) } } impl Iterator for SolutionsIter { type Item = Grid; fn next(&mut self) -> Option<Self::Item> { while let Some(grid) = self.grids.pop() { let (cell, number_of_choices) = SolutionsIter::find_least_underconstrained_cell(&grid); let new_strategies_len = self.strategies.len() - self.strategies_per_grid; if number_of_choices == 0 { self.strategies.truncate(new_strategies_len); continue; } if number_of_choices == 1 { self.strategies.truncate(new_strategies_len); return Some(grid); } // Hookay, looks like we'll have to guess. :( // Start by prepping grids and strategies... wish I could figure out how to do this with one fewer allocations. self.grids.push(grid); self.duplicate_last_grid_n_times(number_of_choices); for (n, (mut grid, mut strategies)) in self.last_n_grids(number_of_choices).enumerate() { let mut vetoes: Vec<CaseId> = grid.cell(cell) .filter(|&(_, &possible)| possible) .map(|(case_id, _)| case_id) .collect(); vetoes.swap_remove(n); SolutionsIter::deduce(&mut grid, &mut strategies, vetoes); } } None } } /// Common interface for sudoku strategies /// /// A `Strategy` is something that can narrow down the possible solutions of a puzzle, but which /// may not be able to solve a puzzle by itself. The idea is that a solver could combine multiple /// strategies to minimize the need for guessing. /// /// Note that a `Strategy` is NOT required to incorporate its own inferences, so for best results /// a `Strategy`'s own inferences should be fed back into it. pub trait Strategy { /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Strategy` of cell/value combinations that are known /// to be impossible. The `Strategy` must ignore any vetoes it's already aware of. fn veto(&mut self, vetoes: &[CaseId]); /// Returns a mutable reference to a Vec of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto the `Vec` returned by /// `inferences()`. It's fine to mess with the `Vec` however you want, such as clearing /// it after reading it. /// /// Note that `inferences()` is allowed to return `CaseId`s that have already been marked /// as impossible. fn inferences(&mut self) -> &mut Vec<CaseId>; /// Returns a boxed clone of the `Strategy`. /// /// This allows the `Strategy` to be copied without knowledge of its type. fn boxed_clone(&self) -> Box<Strategy>; } /// Infers solution constraints by partitioning possibilities /// /// Given the constraints of a sudoku puzzle, a `Partitioner` can infer additional constraints, /// whittling down the possibities, potentially even solving a puzzle by itself. It figures out /// constraints by detecting when possible values/positions can be split into disjoint partitions. /// For example, if two cells in the same clique are both limited to having the values 5 or 8, /// then no other cells in the clique can be 5 or 8. Similarly, if the values 3 and 4 can only be /// in two possible cells, then those cells cannot be anything other than a 3 or 4. The /// partitioner applies that idea with partitions of any size, not just two values/cells. In /// particular, handling partitions of size 1 is equivalent to simple sudoku strategies like /// eliminating values already used by cells in the same clique. A major limitation of /// `Partitioner` is that it can only detect explicit partitions, not implicit ones: Although /// it can detect a partition where three cells are each restricted to the values 4, 5 and 6, it /// can't detect a partition where a cell is 4 or 5, another is 5 or 6 and a final cell is 4 or 6. /// /// Once a `Partitioner` is constructed, `veto()` is used to inform it of any `CaseId`s that /// cannot be true. As cases are vetoed, the `Partitioner` accumulates `inferences`. Note that /// currently `Partitioner` doesn't automatically use the inferences it generates. This has the /// advantage that calls to `veto()` should complete in time proportional to the number of /// `CaseId`s vetoed, but has the disadvantage that you must feed the `Partitioner`'s `inferences` /// back into itself to get the most `inferences` out of it. /// /// # Examples /// /// ```rust /// use std::fmt::Write; /// use std::mem; /// /// use rusudoku::grid::Grid; /// use rusudoku::rules::Rules; /// use rusudoku::solver::Partitioner; /// /// let puzzle = "1 _ _ _\n\ /// _ 2 _ _\n\ /// 3 _ _ _\n\ /// _ _ 4 _\n"; /// let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); /// let mut grid = Grid::read(&mut lines).unwrap(); /// let rules = Rules::new_standard(grid.size()).unwrap(); /// let mut partitioner = Partitioner::new(&rules); /// let mut vetoes: Vec<_> = grid.vetoes().collect(); /// while vetoes.len() > 0 { /// partitioner.veto(vetoes.iter().cloned()); /// grid.veto(vetoes.iter().cloned()); /// vetoes = mem::replace(&mut partitioner.inferences, vec![]); /// } /// let mut output = String::new(); /// write!(&mut output, "{}", grid); /// assert_eq!(output, "1 3 2 4\n\ /// 4 2 3 1\n\ /// 3 4 1 2\n\ /// 2 1 4 3\n"); /// ``` #[derive(Clone)] pub struct Partitioner<R> { rules: R, grid: Grid, lookups: LookupPair, /// The list of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto this `Vec`. It's fine /// to mess with `inferences` however you want, such as clearing it after reading it. pub inferences: Vec<CaseId>, } // Pair of mappings from possibilities to referrers (see below) #[derive(Clone)] struct LookupPair { valueset_cells: Lookup<ValueId, CellId>, cellset_values: Lookup<CellId, ValueId>, } type Lookup<K, V> = collections::HashMap<(CliqueId, Vec<K>), Vec<V>>; impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<ValueId, CellId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.valueset_cells } } impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<CellId, ValueId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.cellset_values } } // The way this works is: It thinks of each clique as having a binary relation between // values and the clique's cells. It knows it has found a partition when N cells all have // the same N values. When that happens it knows all other cells cannot have those N values. // Symmetrically, when N values all have the same N cells, then other values cannot have // those N cells. // // In order to efficiently detect this, each clique uses a pair of mappings. To detect // when N cells have the same N values, it has a mapping from "possibilities" (sets of // values) to the list of "referrers" (cells that have those possibilities). When updating // these bookkeeping structures, it checks if number possibilities is the same as the number // of referrers; if so it subtracts the possibilities from non-referrers. // // Likewise, it has symmetric data structures for finding when N values have the same N // cells. In this case, the "possibilities" are a set of cells, and the "referrers" are // sets of values. // // In order to avoid having nested mappings (and the associated extra allocations), all // cliques share a pair of mappings (self.lookups) from possibilities to referrers. Each // clique's possibilities are kept separate from one another by including the clique's id // in the mapping's key. // // Additionally, in order to aid with comparison (and finding elements) without requiring // too many allocations, possibilities and referrers are stored as sorted Vecs. // // One final note about terminology used by this code... An "axis" is the set of all // elements that could potentially be in a set of "possibilities", and a "cross-axis" // is the set of all elements that could potentially be in a set of "referrers". // The terms "axis" and "cross-axis" come from thinking of a clique's relation between // cells and values as 2D grid. In generic type parameters, the axis's type is A and // the cross-axis's type is C. impl<'a, R> Partitioner<R> where R: Deref<Target=Rules> + Clone + 'a { /// Creates a new `Partitioner` /// /// This requires a reference to a set of `Rules` so the `Partitioner` knows what cells /// must be different from eachother. pub fn new(rules: R) -> Partitioner<R> { let grid = Grid::new(rules.size()); let mut valueset_cells = collections::HashMap::new(); let mut cellset_values = collections::HashMap::new(); let values: Vec<_> = grid.range_iter::<ValueId>().collect(); for clique_id in rules.clique_ids() { let cells = &rules[clique_id]; valueset_cells.insert((clique_id, values.clone()), cells.to_vec()); cellset_values.insert((clique_id, cells.to_vec()), values.clone()); } Partitioner { grid: grid, rules: rules, lookups: LookupPair { valueset_cells: valueset_cells, cellset_values: cellset_values, }, inferences: vec![], } } /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Partitioner` of cell/value combinations that are known /// to be impossible. pub fn veto<I>(&mut self, vetoes: I) where I: Iterator<Item=CaseId> { let rules = &mut self.rules.clone(); for veto in vetoes { if!self.grid[veto] { continue; } let (veto_cell, veto_value): (CellId, ValueId) = self.grid.convert(veto); let all_values: Vec<_> = self.grid.range_iter::<ValueId>().collect(); for &clique_id in rules.cliques(veto_cell) { let cells = &rules[clique_id]; self.remove_possibility(clique_id, (&all_values[..], cells), (veto_value, veto_cell)); self.remove_possibility(clique_id, (cells, &all_values[..]), (veto_cell, veto_value)); } self.grid[veto] = false; } } // The core idea of what this does, is it marks `cross_axis_item` as // no longer referring to a set of possibilities that includes `axis_item`, // updating the bookkeeping as appropriate fn remove_possibility<A, C>(&'a mut self, clique_id: CliqueId, (axis, cross_axis): (&[A], &[C]), (axis_item, cross_axis_item): (A, C)) where A: Copy + Eq + Hash + Ord + 'a, C: Copy + Ord + 'a, CaseId: FromIndex<(A,C)>, &'a mut Lookup<A, C>: From<&'a mut LookupPair> { let grid = &self.grid; let referrers_lookup: &mut Lookup<A, C> = (&mut self.lookups).into(); let possibilities: Vec<_> = axis.iter() .cloned() .filter(|&axis_id| { let case_id: CaseId = grid.convert((axis_id, cross_axis_item)); grid[case_id] }).collect(); let mut key = (clique_id, possibilities); // Here we remove `cross_axis_item` from the list of `referrers` of `possibilities`, // and check if we've found a partition. let referrers_len = { let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for possibilities"); Self::remove(referrers, &cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); referrers.len() }; if referrers_len == 0 { referrers_lookup.remove(&key); } // `cross_axis_item`s new `possibilties` are (possibilities - axis_item) // It's easiest/fastest to just tweak `possibilities` to remove the `axis_item`. Self::remove(&mut key.1, &axis_item); // Here we add `cross_axis_item` to the list of `referrers` of the the new // `possibilities` and check if we've found a partition. if!referrers_lookup.contains_key(&key) { // avoiding entry() because it'd consume key referrers_lookup.insert(key.clone(), vec![]); }
Self::insert(referrers, cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); } fn check_for_partition<A, C>(possibilities: &Vec<A>, referrers: &[C], cross_axis: &[C], grid: &Grid, inferences: &mut Vec<CaseId>) where A: Copy, C: Copy + Ord, CaseId: FromIndex<(A,C)> { if possibilities.len() == referrers.len() { // This is really saying "veto the cartesian product of non-referrers and // possibilities". for &cross_element in cross_axis { if referrers.binary_search(&cross_element).is_err() { for &element in possibilities { let case_id: CaseId = grid.convert((element, cross_element)); inferences.push(case_id); } } } } } // Removes element `e` from an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn remove<T: Ord>(v: &mut Vec<T>, e: &T) { let i = v.binary_search(e) .expect("Partitioner bug: Bookkeeping missing expected element"); v.remove(i); } // Inserts element `e` into an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn insert<T: Ord>(v: &mut Vec<T>, e: T) { let i = v.binary_search(&e) .err().expect("Partitioner bug: Bookkeeping already had element."); v.insert(i, e); } } impl<R> Strategy for Partitioner<R> where R: Deref<Target=Rules> + Clone +'static { fn veto(&mut self, vetoes: &[CaseId]) { self.veto(vetoes.iter().cloned()); } fn inferences(&mut self) -> &mut Vec<CaseId> { &mut self.inferences } fn boxed_clone(&self) -> Box<Strategy> { Box::new(self.clone()) } } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; use std::mem; use std::rc::Rc; use super::super::grid::{CaseId, Grid}; use super::super::rules::Rules; #[test] fn test_value_exclusion() { // Restrict upper-left cell to be a 1. let vetoes = [1, 2, 3]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1, 4, 8, 12, // as is the rest of the zone, 16, 20, // and the rest of the column. 32, 48, ]); } #[test] fn test_cell_exclusion() { // Veto the right 3 cells of the top row from being 1. let vetoes = [4, 8, 12]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The top left cell is required to be 1. 1, 2, 3, ]); } #[test] fn test_multicell_partitioning() { // Restrict the left 2 cells of the top row to be a 1 or 2. let vetoes = [2, 3, 6, 7]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1 or 2, 8, 9, 12, 13, // as is the rest of the zone. 16, 17, 20, 21, ]); } fn infer_from_vetoes(size: usize, vetoes: &[usize]) -> Vec<usize> { let rules = Rules::new_standard(size).unwrap(); let mut partitioner = Partitioner::new(&rules); partitioner.veto(vetoes.iter().cloned().map(CaseId)); partitioner.inferences.sort(); partitioner.inferences.dedup(); partitioner.inferences.into_iter() .map(|CaseId(case_id)| case_id) .collect() } #[test] fn test_solve_basic4() { let solution = fully_partition("1 _ _ _\n\ _ 2 _ _\n\ 3 _ _ _\n\
let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for new possibilities.");
random_line_split
solver.rs
| b).count() } let (choices, cell) = grid.cells() // We swap order so min sorts correctly .map(|(cell_id, values)| (count_true(values), cell_id)) .filter(|&(choices, _)| choices!= 1) .min() .unwrap_or((1, CellId(0))); (cell, choices) } // Pops a (Grid, [Box<Strategy>]) pair off the top of the stack, // and pushes `n` duplicates of it back onto the stack. fn duplicate_last_grid_n_times(&mut self, n: usize) { let grid = self.grids.pop().expect("SolutionsIter bug: duplicate_last_n_grids called on empty iter"); let split_index = self.strategies.len() - self.strategies_per_grid; let strategies = self.strategies.split_off(split_index); for _ in 1..n { self.grids.push(grid.clone()); self.strategies.extend(strategies.iter().map(|s| s.boxed_clone())); } self.grids.push(grid); self.strategies.extend(strategies.into_iter()); } // Returns `n` pairs of (Grid, [Box<Strategy>]) from the top of the stack. fn last_n_grids(&mut self, n: usize) -> Take<Rev<Zip<IterMut<Grid>, ChunksMut<Box<Strategy>>>>> { self.grids.iter_mut() .zip(self.strategies.chunks_mut(self.strategies_per_grid)) .rev() .take(n) } } impl Iterator for SolutionsIter { type Item = Grid; fn next(&mut self) -> Option<Self::Item> { while let Some(grid) = self.grids.pop() { let (cell, number_of_choices) = SolutionsIter::find_least_underconstrained_cell(&grid); let new_strategies_len = self.strategies.len() - self.strategies_per_grid; if number_of_choices == 0 { self.strategies.truncate(new_strategies_len); continue; } if number_of_choices == 1 { self.strategies.truncate(new_strategies_len); return Some(grid); } // Hookay, looks like we'll have to guess. :( // Start by prepping grids and strategies... wish I could figure out how to do this with one fewer allocations. self.grids.push(grid); self.duplicate_last_grid_n_times(number_of_choices); for (n, (mut grid, mut strategies)) in self.last_n_grids(number_of_choices).enumerate() { let mut vetoes: Vec<CaseId> = grid.cell(cell) .filter(|&(_, &possible)| possible) .map(|(case_id, _)| case_id) .collect(); vetoes.swap_remove(n); SolutionsIter::deduce(&mut grid, &mut strategies, vetoes); } } None } } /// Common interface for sudoku strategies /// /// A `Strategy` is something that can narrow down the possible solutions of a puzzle, but which /// may not be able to solve a puzzle by itself. The idea is that a solver could combine multiple /// strategies to minimize the need for guessing. /// /// Note that a `Strategy` is NOT required to incorporate its own inferences, so for best results /// a `Strategy`'s own inferences should be fed back into it. pub trait Strategy { /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Strategy` of cell/value combinations that are known /// to be impossible. The `Strategy` must ignore any vetoes it's already aware of. fn veto(&mut self, vetoes: &[CaseId]); /// Returns a mutable reference to a Vec of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto the `Vec` returned by /// `inferences()`. It's fine to mess with the `Vec` however you want, such as clearing /// it after reading it. /// /// Note that `inferences()` is allowed to return `CaseId`s that have already been marked /// as impossible. fn inferences(&mut self) -> &mut Vec<CaseId>; /// Returns a boxed clone of the `Strategy`. /// /// This allows the `Strategy` to be copied without knowledge of its type. fn boxed_clone(&self) -> Box<Strategy>; } /// Infers solution constraints by partitioning possibilities /// /// Given the constraints of a sudoku puzzle, a `Partitioner` can infer additional constraints, /// whittling down the possibities, potentially even solving a puzzle by itself. It figures out /// constraints by detecting when possible values/positions can be split into disjoint partitions. /// For example, if two cells in the same clique are both limited to having the values 5 or 8, /// then no other cells in the clique can be 5 or 8. Similarly, if the values 3 and 4 can only be /// in two possible cells, then those cells cannot be anything other than a 3 or 4. The /// partitioner applies that idea with partitions of any size, not just two values/cells. In /// particular, handling partitions of size 1 is equivalent to simple sudoku strategies like /// eliminating values already used by cells in the same clique. A major limitation of /// `Partitioner` is that it can only detect explicit partitions, not implicit ones: Although /// it can detect a partition where three cells are each restricted to the values 4, 5 and 6, it /// can't detect a partition where a cell is 4 or 5, another is 5 or 6 and a final cell is 4 or 6. /// /// Once a `Partitioner` is constructed, `veto()` is used to inform it of any `CaseId`s that /// cannot be true. As cases are vetoed, the `Partitioner` accumulates `inferences`. Note that /// currently `Partitioner` doesn't automatically use the inferences it generates. This has the /// advantage that calls to `veto()` should complete in time proportional to the number of /// `CaseId`s vetoed, but has the disadvantage that you must feed the `Partitioner`'s `inferences` /// back into itself to get the most `inferences` out of it. /// /// # Examples /// /// ```rust /// use std::fmt::Write; /// use std::mem; /// /// use rusudoku::grid::Grid; /// use rusudoku::rules::Rules; /// use rusudoku::solver::Partitioner; /// /// let puzzle = "1 _ _ _\n\ /// _ 2 _ _\n\ /// 3 _ _ _\n\ /// _ _ 4 _\n"; /// let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); /// let mut grid = Grid::read(&mut lines).unwrap(); /// let rules = Rules::new_standard(grid.size()).unwrap(); /// let mut partitioner = Partitioner::new(&rules); /// let mut vetoes: Vec<_> = grid.vetoes().collect(); /// while vetoes.len() > 0 { /// partitioner.veto(vetoes.iter().cloned()); /// grid.veto(vetoes.iter().cloned()); /// vetoes = mem::replace(&mut partitioner.inferences, vec![]); /// } /// let mut output = String::new(); /// write!(&mut output, "{}", grid); /// assert_eq!(output, "1 3 2 4\n\ /// 4 2 3 1\n\ /// 3 4 1 2\n\ /// 2 1 4 3\n"); /// ``` #[derive(Clone)] pub struct Partitioner<R> { rules: R, grid: Grid, lookups: LookupPair, /// The list of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto this `Vec`. It's fine /// to mess with `inferences` however you want, such as clearing it after reading it. pub inferences: Vec<CaseId>, } // Pair of mappings from possibilities to referrers (see below) #[derive(Clone)] struct LookupPair { valueset_cells: Lookup<ValueId, CellId>, cellset_values: Lookup<CellId, ValueId>, } type Lookup<K, V> = collections::HashMap<(CliqueId, Vec<K>), Vec<V>>; impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<ValueId, CellId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.valueset_cells } } impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<CellId, ValueId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.cellset_values } } // The way this works is: It thinks of each clique as having a binary relation between // values and the clique's cells. It knows it has found a partition when N cells all have // the same N values. When that happens it knows all other cells cannot have those N values. // Symmetrically, when N values all have the same N cells, then other values cannot have // those N cells. // // In order to efficiently detect this, each clique uses a pair of mappings. To detect // when N cells have the same N values, it has a mapping from "possibilities" (sets of // values) to the list of "referrers" (cells that have those possibilities). When updating // these bookkeeping structures, it checks if number possibilities is the same as the number // of referrers; if so it subtracts the possibilities from non-referrers. // // Likewise, it has symmetric data structures for finding when N values have the same N // cells. In this case, the "possibilities" are a set of cells, and the "referrers" are // sets of values. // // In order to avoid having nested mappings (and the associated extra allocations), all // cliques share a pair of mappings (self.lookups) from possibilities to referrers. Each // clique's possibilities are kept separate from one another by including the clique's id // in the mapping's key. // // Additionally, in order to aid with comparison (and finding elements) without requiring // too many allocations, possibilities and referrers are stored as sorted Vecs. // // One final note about terminology used by this code... An "axis" is the set of all // elements that could potentially be in a set of "possibilities", and a "cross-axis" // is the set of all elements that could potentially be in a set of "referrers". // The terms "axis" and "cross-axis" come from thinking of a clique's relation between // cells and values as 2D grid. In generic type parameters, the axis's type is A and // the cross-axis's type is C. impl<'a, R> Partitioner<R> where R: Deref<Target=Rules> + Clone + 'a { /// Creates a new `Partitioner` /// /// This requires a reference to a set of `Rules` so the `Partitioner` knows what cells /// must be different from eachother. pub fn
(rules: R) -> Partitioner<R> { let grid = Grid::new(rules.size()); let mut valueset_cells = collections::HashMap::new(); let mut cellset_values = collections::HashMap::new(); let values: Vec<_> = grid.range_iter::<ValueId>().collect(); for clique_id in rules.clique_ids() { let cells = &rules[clique_id]; valueset_cells.insert((clique_id, values.clone()), cells.to_vec()); cellset_values.insert((clique_id, cells.to_vec()), values.clone()); } Partitioner { grid: grid, rules: rules, lookups: LookupPair { valueset_cells: valueset_cells, cellset_values: cellset_values, }, inferences: vec![], } } /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Partitioner` of cell/value combinations that are known /// to be impossible. pub fn veto<I>(&mut self, vetoes: I) where I: Iterator<Item=CaseId> { let rules = &mut self.rules.clone(); for veto in vetoes { if!self.grid[veto] { continue; } let (veto_cell, veto_value): (CellId, ValueId) = self.grid.convert(veto); let all_values: Vec<_> = self.grid.range_iter::<ValueId>().collect(); for &clique_id in rules.cliques(veto_cell) { let cells = &rules[clique_id]; self.remove_possibility(clique_id, (&all_values[..], cells), (veto_value, veto_cell)); self.remove_possibility(clique_id, (cells, &all_values[..]), (veto_cell, veto_value)); } self.grid[veto] = false; } } // The core idea of what this does, is it marks `cross_axis_item` as // no longer referring to a set of possibilities that includes `axis_item`, // updating the bookkeeping as appropriate fn remove_possibility<A, C>(&'a mut self, clique_id: CliqueId, (axis, cross_axis): (&[A], &[C]), (axis_item, cross_axis_item): (A, C)) where A: Copy + Eq + Hash + Ord + 'a, C: Copy + Ord + 'a, CaseId: FromIndex<(A,C)>, &'a mut Lookup<A, C>: From<&'a mut LookupPair> { let grid = &self.grid; let referrers_lookup: &mut Lookup<A, C> = (&mut self.lookups).into(); let possibilities: Vec<_> = axis.iter() .cloned() .filter(|&axis_id| { let case_id: CaseId = grid.convert((axis_id, cross_axis_item)); grid[case_id] }).collect(); let mut key = (clique_id, possibilities); // Here we remove `cross_axis_item` from the list of `referrers` of `possibilities`, // and check if we've found a partition. let referrers_len = { let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for possibilities"); Self::remove(referrers, &cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); referrers.len() }; if referrers_len == 0 { referrers_lookup.remove(&key); } // `cross_axis_item`s new `possibilties` are (possibilities - axis_item) // It's easiest/fastest to just tweak `possibilities` to remove the `axis_item`. Self::remove(&mut key.1, &axis_item); // Here we add `cross_axis_item` to the list of `referrers` of the the new // `possibilities` and check if we've found a partition. if!referrers_lookup.contains_key(&key) { // avoiding entry() because it'd consume key referrers_lookup.insert(key.clone(), vec![]); } let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for new possibilities."); Self::insert(referrers, cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); } fn check_for_partition<A, C>(possibilities: &Vec<A>, referrers: &[C], cross_axis: &[C], grid: &Grid, inferences: &mut Vec<CaseId>) where A: Copy, C: Copy + Ord, CaseId: FromIndex<(A,C)> { if possibilities.len() == referrers.len() { // This is really saying "veto the cartesian product of non-referrers and // possibilities". for &cross_element in cross_axis { if referrers.binary_search(&cross_element).is_err() { for &element in possibilities { let case_id: CaseId = grid.convert((element, cross_element)); inferences.push(case_id); } } } } } // Removes element `e` from an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn remove<T: Ord>(v: &mut Vec<T>, e: &T) { let i = v.binary_search(e) .expect("Partitioner bug: Bookkeeping missing expected element"); v.remove(i); } // Inserts element `e` into an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn insert<T: Ord>(v: &mut Vec<T>, e: T) { let i = v.binary_search(&e) .err().expect("Partitioner bug: Bookkeeping already had element."); v.insert(i, e); } } impl<R> Strategy for Partitioner<R> where R: Deref<Target=Rules> + Clone +'static { fn veto(&mut self, vetoes: &[CaseId]) { self.veto(vetoes.iter().cloned()); } fn inferences(&mut self) -> &mut Vec<CaseId> { &mut self.inferences } fn boxed_clone(&self) -> Box<Strategy> { Box::new(self.clone()) } } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; use std::mem; use std::rc::Rc; use super::super::grid::{CaseId, Grid}; use super::super::rules::Rules; #[test] fn test_value_exclusion() { // Restrict upper-left cell to be a 1. let vetoes = [1, 2, 3]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1, 4, 8, 12, // as is the rest of the zone, 16, 20, // and the rest of the column. 32, 48, ]); } #[test] fn test_cell_exclusion() { // Veto the right 3 cells of the top row from being 1. let vetoes = [4, 8, 12]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The top left cell is required to be 1. 1, 2, 3, ]); } #[test] fn test_multicell_partitioning() { // Restrict the left 2 cells of the top row to be a 1 or 2. let vetoes = [2, 3, 6, 7]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1 or 2, 8, 9, 12, 13, // as is the rest of the zone. 16, 17, 20, 21, ]); } fn infer_from_vetoes(size: usize, vetoes: &[usize]) -> Vec<usize> { let rules = Rules::new_standard(size).unwrap(); let mut partitioner = Partitioner::new(&rules); partitioner.veto(vetoes.iter().cloned().map(CaseId)); partitioner.inferences.sort(); partitioner.inferences.dedup(); partitioner.inferences.into_iter() .map(|CaseId(case_id)| case_id) .collect() } #[test] fn test_solve_basic4() { let solution = fully_partition("1 _ _ _\n\ _ 2 _ _\n\ 3 _ _ _\n\
new
identifier_name
solver.rs
| b).count() } let (choices, cell) = grid.cells() // We swap order so min sorts correctly .map(|(cell_id, values)| (count_true(values), cell_id)) .filter(|&(choices, _)| choices!= 1) .min() .unwrap_or((1, CellId(0))); (cell, choices) } // Pops a (Grid, [Box<Strategy>]) pair off the top of the stack, // and pushes `n` duplicates of it back onto the stack. fn duplicate_last_grid_n_times(&mut self, n: usize) { let grid = self.grids.pop().expect("SolutionsIter bug: duplicate_last_n_grids called on empty iter"); let split_index = self.strategies.len() - self.strategies_per_grid; let strategies = self.strategies.split_off(split_index); for _ in 1..n { self.grids.push(grid.clone()); self.strategies.extend(strategies.iter().map(|s| s.boxed_clone())); } self.grids.push(grid); self.strategies.extend(strategies.into_iter()); } // Returns `n` pairs of (Grid, [Box<Strategy>]) from the top of the stack. fn last_n_grids(&mut self, n: usize) -> Take<Rev<Zip<IterMut<Grid>, ChunksMut<Box<Strategy>>>>> { self.grids.iter_mut() .zip(self.strategies.chunks_mut(self.strategies_per_grid)) .rev() .take(n) } } impl Iterator for SolutionsIter { type Item = Grid; fn next(&mut self) -> Option<Self::Item> { while let Some(grid) = self.grids.pop() { let (cell, number_of_choices) = SolutionsIter::find_least_underconstrained_cell(&grid); let new_strategies_len = self.strategies.len() - self.strategies_per_grid; if number_of_choices == 0 { self.strategies.truncate(new_strategies_len); continue; } if number_of_choices == 1 { self.strategies.truncate(new_strategies_len); return Some(grid); } // Hookay, looks like we'll have to guess. :( // Start by prepping grids and strategies... wish I could figure out how to do this with one fewer allocations. self.grids.push(grid); self.duplicate_last_grid_n_times(number_of_choices); for (n, (mut grid, mut strategies)) in self.last_n_grids(number_of_choices).enumerate() { let mut vetoes: Vec<CaseId> = grid.cell(cell) .filter(|&(_, &possible)| possible) .map(|(case_id, _)| case_id) .collect(); vetoes.swap_remove(n); SolutionsIter::deduce(&mut grid, &mut strategies, vetoes); } } None } } /// Common interface for sudoku strategies /// /// A `Strategy` is something that can narrow down the possible solutions of a puzzle, but which /// may not be able to solve a puzzle by itself. The idea is that a solver could combine multiple /// strategies to minimize the need for guessing. /// /// Note that a `Strategy` is NOT required to incorporate its own inferences, so for best results /// a `Strategy`'s own inferences should be fed back into it. pub trait Strategy { /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Strategy` of cell/value combinations that are known /// to be impossible. The `Strategy` must ignore any vetoes it's already aware of. fn veto(&mut self, vetoes: &[CaseId]); /// Returns a mutable reference to a Vec of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto the `Vec` returned by /// `inferences()`. It's fine to mess with the `Vec` however you want, such as clearing /// it after reading it. /// /// Note that `inferences()` is allowed to return `CaseId`s that have already been marked /// as impossible. fn inferences(&mut self) -> &mut Vec<CaseId>; /// Returns a boxed clone of the `Strategy`. /// /// This allows the `Strategy` to be copied without knowledge of its type. fn boxed_clone(&self) -> Box<Strategy>; } /// Infers solution constraints by partitioning possibilities /// /// Given the constraints of a sudoku puzzle, a `Partitioner` can infer additional constraints, /// whittling down the possibities, potentially even solving a puzzle by itself. It figures out /// constraints by detecting when possible values/positions can be split into disjoint partitions. /// For example, if two cells in the same clique are both limited to having the values 5 or 8, /// then no other cells in the clique can be 5 or 8. Similarly, if the values 3 and 4 can only be /// in two possible cells, then those cells cannot be anything other than a 3 or 4. The /// partitioner applies that idea with partitions of any size, not just two values/cells. In /// particular, handling partitions of size 1 is equivalent to simple sudoku strategies like /// eliminating values already used by cells in the same clique. A major limitation of /// `Partitioner` is that it can only detect explicit partitions, not implicit ones: Although /// it can detect a partition where three cells are each restricted to the values 4, 5 and 6, it /// can't detect a partition where a cell is 4 or 5, another is 5 or 6 and a final cell is 4 or 6. /// /// Once a `Partitioner` is constructed, `veto()` is used to inform it of any `CaseId`s that /// cannot be true. As cases are vetoed, the `Partitioner` accumulates `inferences`. Note that /// currently `Partitioner` doesn't automatically use the inferences it generates. This has the /// advantage that calls to `veto()` should complete in time proportional to the number of /// `CaseId`s vetoed, but has the disadvantage that you must feed the `Partitioner`'s `inferences` /// back into itself to get the most `inferences` out of it. /// /// # Examples /// /// ```rust /// use std::fmt::Write; /// use std::mem; /// /// use rusudoku::grid::Grid; /// use rusudoku::rules::Rules; /// use rusudoku::solver::Partitioner; /// /// let puzzle = "1 _ _ _\n\ /// _ 2 _ _\n\ /// 3 _ _ _\n\ /// _ _ 4 _\n"; /// let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); /// let mut grid = Grid::read(&mut lines).unwrap(); /// let rules = Rules::new_standard(grid.size()).unwrap(); /// let mut partitioner = Partitioner::new(&rules); /// let mut vetoes: Vec<_> = grid.vetoes().collect(); /// while vetoes.len() > 0 { /// partitioner.veto(vetoes.iter().cloned()); /// grid.veto(vetoes.iter().cloned()); /// vetoes = mem::replace(&mut partitioner.inferences, vec![]); /// } /// let mut output = String::new(); /// write!(&mut output, "{}", grid); /// assert_eq!(output, "1 3 2 4\n\ /// 4 2 3 1\n\ /// 3 4 1 2\n\ /// 2 1 4 3\n"); /// ``` #[derive(Clone)] pub struct Partitioner<R> { rules: R, grid: Grid, lookups: LookupPair, /// The list of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto this `Vec`. It's fine /// to mess with `inferences` however you want, such as clearing it after reading it. pub inferences: Vec<CaseId>, } // Pair of mappings from possibilities to referrers (see below) #[derive(Clone)] struct LookupPair { valueset_cells: Lookup<ValueId, CellId>, cellset_values: Lookup<CellId, ValueId>, } type Lookup<K, V> = collections::HashMap<(CliqueId, Vec<K>), Vec<V>>; impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<ValueId, CellId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.valueset_cells } } impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<CellId, ValueId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.cellset_values } } // The way this works is: It thinks of each clique as having a binary relation between // values and the clique's cells. It knows it has found a partition when N cells all have // the same N values. When that happens it knows all other cells cannot have those N values. // Symmetrically, when N values all have the same N cells, then other values cannot have // those N cells. // // In order to efficiently detect this, each clique uses a pair of mappings. To detect // when N cells have the same N values, it has a mapping from "possibilities" (sets of // values) to the list of "referrers" (cells that have those possibilities). When updating // these bookkeeping structures, it checks if number possibilities is the same as the number // of referrers; if so it subtracts the possibilities from non-referrers. // // Likewise, it has symmetric data structures for finding when N values have the same N // cells. In this case, the "possibilities" are a set of cells, and the "referrers" are // sets of values. // // In order to avoid having nested mappings (and the associated extra allocations), all // cliques share a pair of mappings (self.lookups) from possibilities to referrers. Each // clique's possibilities are kept separate from one another by including the clique's id // in the mapping's key. // // Additionally, in order to aid with comparison (and finding elements) without requiring // too many allocations, possibilities and referrers are stored as sorted Vecs. // // One final note about terminology used by this code... An "axis" is the set of all // elements that could potentially be in a set of "possibilities", and a "cross-axis" // is the set of all elements that could potentially be in a set of "referrers". // The terms "axis" and "cross-axis" come from thinking of a clique's relation between // cells and values as 2D grid. In generic type parameters, the axis's type is A and // the cross-axis's type is C. impl<'a, R> Partitioner<R> where R: Deref<Target=Rules> + Clone + 'a { /// Creates a new `Partitioner` /// /// This requires a reference to a set of `Rules` so the `Partitioner` knows what cells /// must be different from eachother. pub fn new(rules: R) -> Partitioner<R> { let grid = Grid::new(rules.size()); let mut valueset_cells = collections::HashMap::new(); let mut cellset_values = collections::HashMap::new(); let values: Vec<_> = grid.range_iter::<ValueId>().collect(); for clique_id in rules.clique_ids() { let cells = &rules[clique_id]; valueset_cells.insert((clique_id, values.clone()), cells.to_vec()); cellset_values.insert((clique_id, cells.to_vec()), values.clone()); } Partitioner { grid: grid, rules: rules, lookups: LookupPair { valueset_cells: valueset_cells, cellset_values: cellset_values, }, inferences: vec![], } } /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Partitioner` of cell/value combinations that are known /// to be impossible. pub fn veto<I>(&mut self, vetoes: I) where I: Iterator<Item=CaseId> { let rules = &mut self.rules.clone(); for veto in vetoes { if!self.grid[veto] { continue; } let (veto_cell, veto_value): (CellId, ValueId) = self.grid.convert(veto); let all_values: Vec<_> = self.grid.range_iter::<ValueId>().collect(); for &clique_id in rules.cliques(veto_cell) { let cells = &rules[clique_id]; self.remove_possibility(clique_id, (&all_values[..], cells), (veto_value, veto_cell)); self.remove_possibility(clique_id, (cells, &all_values[..]), (veto_cell, veto_value)); } self.grid[veto] = false; } } // The core idea of what this does, is it marks `cross_axis_item` as // no longer referring to a set of possibilities that includes `axis_item`, // updating the bookkeeping as appropriate fn remove_possibility<A, C>(&'a mut self, clique_id: CliqueId, (axis, cross_axis): (&[A], &[C]), (axis_item, cross_axis_item): (A, C)) where A: Copy + Eq + Hash + Ord + 'a, C: Copy + Ord + 'a, CaseId: FromIndex<(A,C)>, &'a mut Lookup<A, C>: From<&'a mut LookupPair> { let grid = &self.grid; let referrers_lookup: &mut Lookup<A, C> = (&mut self.lookups).into(); let possibilities: Vec<_> = axis.iter() .cloned() .filter(|&axis_id| { let case_id: CaseId = grid.convert((axis_id, cross_axis_item)); grid[case_id] }).collect(); let mut key = (clique_id, possibilities); // Here we remove `cross_axis_item` from the list of `referrers` of `possibilities`, // and check if we've found a partition. let referrers_len = { let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for possibilities"); Self::remove(referrers, &cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); referrers.len() }; if referrers_len == 0 { referrers_lookup.remove(&key); } // `cross_axis_item`s new `possibilties` are (possibilities - axis_item) // It's easiest/fastest to just tweak `possibilities` to remove the `axis_item`. Self::remove(&mut key.1, &axis_item); // Here we add `cross_axis_item` to the list of `referrers` of the the new // `possibilities` and check if we've found a partition. if!referrers_lookup.contains_key(&key) { // avoiding entry() because it'd consume key referrers_lookup.insert(key.clone(), vec![]); } let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for new possibilities."); Self::insert(referrers, cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); } fn check_for_partition<A, C>(possibilities: &Vec<A>, referrers: &[C], cross_axis: &[C], grid: &Grid, inferences: &mut Vec<CaseId>) where A: Copy, C: Copy + Ord, CaseId: FromIndex<(A,C)> { if possibilities.len() == referrers.len()
} // Removes element `e` from an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn remove<T: Ord>(v: &mut Vec<T>, e: &T) { let i = v.binary_search(e) .expect("Partitioner bug: Bookkeeping missing expected element"); v.remove(i); } // Inserts element `e` into an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn insert<T: Ord>(v: &mut Vec<T>, e: T) { let i = v.binary_search(&e) .err().expect("Partitioner bug: Bookkeeping already had element."); v.insert(i, e); } } impl<R> Strategy for Partitioner<R> where R: Deref<Target=Rules> + Clone +'static { fn veto(&mut self, vetoes: &[CaseId]) { self.veto(vetoes.iter().cloned()); } fn inferences(&mut self) -> &mut Vec<CaseId> { &mut self.inferences } fn boxed_clone(&self) -> Box<Strategy> { Box::new(self.clone()) } } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; use std::mem; use std::rc::Rc; use super::super::grid::{CaseId, Grid}; use super::super::rules::Rules; #[test] fn test_value_exclusion() { // Restrict upper-left cell to be a 1. let vetoes = [1, 2, 3]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1, 4, 8, 12, // as is the rest of the zone, 16, 20, // and the rest of the column. 32, 48, ]); } #[test] fn test_cell_exclusion() { // Veto the right 3 cells of the top row from being 1. let vetoes = [4, 8, 12]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The top left cell is required to be 1. 1, 2, 3, ]); } #[test] fn test_multicell_partitioning() { // Restrict the left 2 cells of the top row to be a 1 or 2. let vetoes = [2, 3, 6, 7]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1 or 2, 8, 9, 12, 13, // as is the rest of the zone. 16, 17, 20, 21, ]); } fn infer_from_vetoes(size: usize, vetoes: &[usize]) -> Vec<usize> { let rules = Rules::new_standard(size).unwrap(); let mut partitioner = Partitioner::new(&rules); partitioner.veto(vetoes.iter().cloned().map(CaseId)); partitioner.inferences.sort(); partitioner.inferences.dedup(); partitioner.inferences.into_iter() .map(|CaseId(case_id)| case_id) .collect() } #[test] fn test_solve_basic4() { let solution = fully_partition("1 _ _ _\n\ _ 2 _ _\n\ 3 _ _ _\n\
{ // This is really saying "veto the cartesian product of non-referrers and // possibilities". for &cross_element in cross_axis { if referrers.binary_search(&cross_element).is_err() { for &element in possibilities { let case_id: CaseId = grid.convert((element, cross_element)); inferences.push(case_id); } } } }
conditional_block
solver.rs
| b).count() } let (choices, cell) = grid.cells() // We swap order so min sorts correctly .map(|(cell_id, values)| (count_true(values), cell_id)) .filter(|&(choices, _)| choices!= 1) .min() .unwrap_or((1, CellId(0))); (cell, choices) } // Pops a (Grid, [Box<Strategy>]) pair off the top of the stack, // and pushes `n` duplicates of it back onto the stack. fn duplicate_last_grid_n_times(&mut self, n: usize) { let grid = self.grids.pop().expect("SolutionsIter bug: duplicate_last_n_grids called on empty iter"); let split_index = self.strategies.len() - self.strategies_per_grid; let strategies = self.strategies.split_off(split_index); for _ in 1..n { self.grids.push(grid.clone()); self.strategies.extend(strategies.iter().map(|s| s.boxed_clone())); } self.grids.push(grid); self.strategies.extend(strategies.into_iter()); } // Returns `n` pairs of (Grid, [Box<Strategy>]) from the top of the stack. fn last_n_grids(&mut self, n: usize) -> Take<Rev<Zip<IterMut<Grid>, ChunksMut<Box<Strategy>>>>> { self.grids.iter_mut() .zip(self.strategies.chunks_mut(self.strategies_per_grid)) .rev() .take(n) } } impl Iterator for SolutionsIter { type Item = Grid; fn next(&mut self) -> Option<Self::Item> { while let Some(grid) = self.grids.pop() { let (cell, number_of_choices) = SolutionsIter::find_least_underconstrained_cell(&grid); let new_strategies_len = self.strategies.len() - self.strategies_per_grid; if number_of_choices == 0 { self.strategies.truncate(new_strategies_len); continue; } if number_of_choices == 1 { self.strategies.truncate(new_strategies_len); return Some(grid); } // Hookay, looks like we'll have to guess. :( // Start by prepping grids and strategies... wish I could figure out how to do this with one fewer allocations. self.grids.push(grid); self.duplicate_last_grid_n_times(number_of_choices); for (n, (mut grid, mut strategies)) in self.last_n_grids(number_of_choices).enumerate() { let mut vetoes: Vec<CaseId> = grid.cell(cell) .filter(|&(_, &possible)| possible) .map(|(case_id, _)| case_id) .collect(); vetoes.swap_remove(n); SolutionsIter::deduce(&mut grid, &mut strategies, vetoes); } } None } } /// Common interface for sudoku strategies /// /// A `Strategy` is something that can narrow down the possible solutions of a puzzle, but which /// may not be able to solve a puzzle by itself. The idea is that a solver could combine multiple /// strategies to minimize the need for guessing. /// /// Note that a `Strategy` is NOT required to incorporate its own inferences, so for best results /// a `Strategy`'s own inferences should be fed back into it. pub trait Strategy { /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Strategy` of cell/value combinations that are known /// to be impossible. The `Strategy` must ignore any vetoes it's already aware of. fn veto(&mut self, vetoes: &[CaseId]); /// Returns a mutable reference to a Vec of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto the `Vec` returned by /// `inferences()`. It's fine to mess with the `Vec` however you want, such as clearing /// it after reading it. /// /// Note that `inferences()` is allowed to return `CaseId`s that have already been marked /// as impossible. fn inferences(&mut self) -> &mut Vec<CaseId>; /// Returns a boxed clone of the `Strategy`. /// /// This allows the `Strategy` to be copied without knowledge of its type. fn boxed_clone(&self) -> Box<Strategy>; } /// Infers solution constraints by partitioning possibilities /// /// Given the constraints of a sudoku puzzle, a `Partitioner` can infer additional constraints, /// whittling down the possibities, potentially even solving a puzzle by itself. It figures out /// constraints by detecting when possible values/positions can be split into disjoint partitions. /// For example, if two cells in the same clique are both limited to having the values 5 or 8, /// then no other cells in the clique can be 5 or 8. Similarly, if the values 3 and 4 can only be /// in two possible cells, then those cells cannot be anything other than a 3 or 4. The /// partitioner applies that idea with partitions of any size, not just two values/cells. In /// particular, handling partitions of size 1 is equivalent to simple sudoku strategies like /// eliminating values already used by cells in the same clique. A major limitation of /// `Partitioner` is that it can only detect explicit partitions, not implicit ones: Although /// it can detect a partition where three cells are each restricted to the values 4, 5 and 6, it /// can't detect a partition where a cell is 4 or 5, another is 5 or 6 and a final cell is 4 or 6. /// /// Once a `Partitioner` is constructed, `veto()` is used to inform it of any `CaseId`s that /// cannot be true. As cases are vetoed, the `Partitioner` accumulates `inferences`. Note that /// currently `Partitioner` doesn't automatically use the inferences it generates. This has the /// advantage that calls to `veto()` should complete in time proportional to the number of /// `CaseId`s vetoed, but has the disadvantage that you must feed the `Partitioner`'s `inferences` /// back into itself to get the most `inferences` out of it. /// /// # Examples /// /// ```rust /// use std::fmt::Write; /// use std::mem; /// /// use rusudoku::grid::Grid; /// use rusudoku::rules::Rules; /// use rusudoku::solver::Partitioner; /// /// let puzzle = "1 _ _ _\n\ /// _ 2 _ _\n\ /// 3 _ _ _\n\ /// _ _ 4 _\n"; /// let mut lines = puzzle.lines().map(|line| Ok(line.to_string())); /// let mut grid = Grid::read(&mut lines).unwrap(); /// let rules = Rules::new_standard(grid.size()).unwrap(); /// let mut partitioner = Partitioner::new(&rules); /// let mut vetoes: Vec<_> = grid.vetoes().collect(); /// while vetoes.len() > 0 { /// partitioner.veto(vetoes.iter().cloned()); /// grid.veto(vetoes.iter().cloned()); /// vetoes = mem::replace(&mut partitioner.inferences, vec![]); /// } /// let mut output = String::new(); /// write!(&mut output, "{}", grid); /// assert_eq!(output, "1 3 2 4\n\ /// 4 2 3 1\n\ /// 3 4 1 2\n\ /// 2 1 4 3\n"); /// ``` #[derive(Clone)] pub struct Partitioner<R> { rules: R, grid: Grid, lookups: LookupPair, /// The list of `CaseId`s inferred to be impossible. /// /// As `CaseId`s are vetoed, new inferences will be pushed onto this `Vec`. It's fine /// to mess with `inferences` however you want, such as clearing it after reading it. pub inferences: Vec<CaseId>, } // Pair of mappings from possibilities to referrers (see below) #[derive(Clone)] struct LookupPair { valueset_cells: Lookup<ValueId, CellId>, cellset_values: Lookup<CellId, ValueId>, } type Lookup<K, V> = collections::HashMap<(CliqueId, Vec<K>), Vec<V>>; impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<ValueId, CellId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.valueset_cells } } impl<'a> From<&'a mut LookupPair> for &'a mut Lookup<CellId, ValueId> { fn from(other: &'a mut LookupPair) -> Self { &mut other.cellset_values } } // The way this works is: It thinks of each clique as having a binary relation between // values and the clique's cells. It knows it has found a partition when N cells all have // the same N values. When that happens it knows all other cells cannot have those N values. // Symmetrically, when N values all have the same N cells, then other values cannot have // those N cells. // // In order to efficiently detect this, each clique uses a pair of mappings. To detect // when N cells have the same N values, it has a mapping from "possibilities" (sets of // values) to the list of "referrers" (cells that have those possibilities). When updating // these bookkeeping structures, it checks if number possibilities is the same as the number // of referrers; if so it subtracts the possibilities from non-referrers. // // Likewise, it has symmetric data structures for finding when N values have the same N // cells. In this case, the "possibilities" are a set of cells, and the "referrers" are // sets of values. // // In order to avoid having nested mappings (and the associated extra allocations), all // cliques share a pair of mappings (self.lookups) from possibilities to referrers. Each // clique's possibilities are kept separate from one another by including the clique's id // in the mapping's key. // // Additionally, in order to aid with comparison (and finding elements) without requiring // too many allocations, possibilities and referrers are stored as sorted Vecs. // // One final note about terminology used by this code... An "axis" is the set of all // elements that could potentially be in a set of "possibilities", and a "cross-axis" // is the set of all elements that could potentially be in a set of "referrers". // The terms "axis" and "cross-axis" come from thinking of a clique's relation between // cells and values as 2D grid. In generic type parameters, the axis's type is A and // the cross-axis's type is C. impl<'a, R> Partitioner<R> where R: Deref<Target=Rules> + Clone + 'a { /// Creates a new `Partitioner` /// /// This requires a reference to a set of `Rules` so the `Partitioner` knows what cells /// must be different from eachother. pub fn new(rules: R) -> Partitioner<R> { let grid = Grid::new(rules.size()); let mut valueset_cells = collections::HashMap::new(); let mut cellset_values = collections::HashMap::new(); let values: Vec<_> = grid.range_iter::<ValueId>().collect(); for clique_id in rules.clique_ids() { let cells = &rules[clique_id]; valueset_cells.insert((clique_id, values.clone()), cells.to_vec()); cellset_values.insert((clique_id, cells.to_vec()), values.clone()); } Partitioner { grid: grid, rules: rules, lookups: LookupPair { valueset_cells: valueset_cells, cellset_values: cellset_values, }, inferences: vec![], } } /// Marks `CaseId`s as impossible. /// /// This is used to inform the `Partitioner` of cell/value combinations that are known /// to be impossible. pub fn veto<I>(&mut self, vetoes: I) where I: Iterator<Item=CaseId> { let rules = &mut self.rules.clone(); for veto in vetoes { if!self.grid[veto] { continue; } let (veto_cell, veto_value): (CellId, ValueId) = self.grid.convert(veto); let all_values: Vec<_> = self.grid.range_iter::<ValueId>().collect(); for &clique_id in rules.cliques(veto_cell) { let cells = &rules[clique_id]; self.remove_possibility(clique_id, (&all_values[..], cells), (veto_value, veto_cell)); self.remove_possibility(clique_id, (cells, &all_values[..]), (veto_cell, veto_value)); } self.grid[veto] = false; } } // The core idea of what this does, is it marks `cross_axis_item` as // no longer referring to a set of possibilities that includes `axis_item`, // updating the bookkeeping as appropriate fn remove_possibility<A, C>(&'a mut self, clique_id: CliqueId, (axis, cross_axis): (&[A], &[C]), (axis_item, cross_axis_item): (A, C)) where A: Copy + Eq + Hash + Ord + 'a, C: Copy + Ord + 'a, CaseId: FromIndex<(A,C)>, &'a mut Lookup<A, C>: From<&'a mut LookupPair> { let grid = &self.grid; let referrers_lookup: &mut Lookup<A, C> = (&mut self.lookups).into(); let possibilities: Vec<_> = axis.iter() .cloned() .filter(|&axis_id| { let case_id: CaseId = grid.convert((axis_id, cross_axis_item)); grid[case_id] }).collect(); let mut key = (clique_id, possibilities); // Here we remove `cross_axis_item` from the list of `referrers` of `possibilities`, // and check if we've found a partition. let referrers_len = { let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for possibilities"); Self::remove(referrers, &cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); referrers.len() }; if referrers_len == 0 { referrers_lookup.remove(&key); } // `cross_axis_item`s new `possibilties` are (possibilities - axis_item) // It's easiest/fastest to just tweak `possibilities` to remove the `axis_item`. Self::remove(&mut key.1, &axis_item); // Here we add `cross_axis_item` to the list of `referrers` of the the new // `possibilities` and check if we've found a partition. if!referrers_lookup.contains_key(&key) { // avoiding entry() because it'd consume key referrers_lookup.insert(key.clone(), vec![]); } let referrers = referrers_lookup.get_mut(&key) .expect("Partitioner bug: \ No referrers for new possibilities."); Self::insert(referrers, cross_axis_item); Self::check_for_partition(&key.1, referrers, cross_axis, grid, &mut self.inferences); } fn check_for_partition<A, C>(possibilities: &Vec<A>, referrers: &[C], cross_axis: &[C], grid: &Grid, inferences: &mut Vec<CaseId>) where A: Copy, C: Copy + Ord, CaseId: FromIndex<(A,C)> { if possibilities.len() == referrers.len() { // This is really saying "veto the cartesian product of non-referrers and // possibilities". for &cross_element in cross_axis { if referrers.binary_search(&cross_element).is_err() { for &element in possibilities { let case_id: CaseId = grid.convert((element, cross_element)); inferences.push(case_id); } } } } } // Removes element `e` from an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn remove<T: Ord>(v: &mut Vec<T>, e: &T) { let i = v.binary_search(e) .expect("Partitioner bug: Bookkeeping missing expected element"); v.remove(i); } // Inserts element `e` into an ordered Vec `v`, or else panics // This is just to simplify remove_possibility() slightly. fn insert<T: Ord>(v: &mut Vec<T>, e: T)
} impl<R> Strategy for Partitioner<R> where R: Deref<Target=Rules> + Clone +'static { fn veto(&mut self, vetoes: &[CaseId]) { self.veto(vetoes.iter().cloned()); } fn inferences(&mut self) -> &mut Vec<CaseId> { &mut self.inferences } fn boxed_clone(&self) -> Box<Strategy> { Box::new(self.clone()) } } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; use std::mem; use std::rc::Rc; use super::super::grid::{CaseId, Grid}; use super::super::rules::Rules; #[test] fn test_value_exclusion() { // Restrict upper-left cell to be a 1. let vetoes = [1, 2, 3]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1, 4, 8, 12, // as is the rest of the zone, 16, 20, // and the rest of the column. 32, 48, ]); } #[test] fn test_cell_exclusion() { // Veto the right 3 cells of the top row from being 1. let vetoes = [4, 8, 12]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The top left cell is required to be 1. 1, 2, 3, ]); } #[test] fn test_multicell_partitioning() { // Restrict the left 2 cells of the top row to be a 1 or 2. let vetoes = [2, 3, 6, 7]; assert_eq!(infer_from_vetoes(4, &vetoes), [ // The rest of the row is restricted from being 1 or 2, 8, 9, 12, 13, // as is the rest of the zone. 16, 17, 20, 21, ]); } fn infer_from_vetoes(size: usize, vetoes: &[usize]) -> Vec<usize> { let rules = Rules::new_standard(size).unwrap(); let mut partitioner = Partitioner::new(&rules); partitioner.veto(vetoes.iter().cloned().map(CaseId)); partitioner.inferences.sort(); partitioner.inferences.dedup(); partitioner.inferences.into_iter() .map(|CaseId(case_id)| case_id) .collect() } #[test] fn test_solve_basic4() { let solution = fully_partition("1 _ _ _\n\ _ 2 _ _\n\ 3 _ _ _\n\
{ let i = v.binary_search(&e) .err().expect("Partitioner bug: Bookkeeping already had element."); v.insert(i, e); }
identifier_body
util.rs
/* Copyright (c) 2017 The swc Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use anyhow::{Context, Error}; use napi::{CallContext, JsBuffer, Status}; use serde::de::DeserializeOwned; use std::any::type_name; pub trait MapErr<T>: Into<Result<T, anyhow::Error>> { fn convert_err(self) -> napi::Result<T> { self.into() .map_err(|err| napi::Error::new(Status::GenericFailure, format!("{:?}", err))) } } impl<T> MapErr<T> for Result<T, anyhow::Error> {} pub trait CtxtExt { fn get_buffer_as_string(&self, index: usize) -> napi::Result<String>; /// Currently this uses JsBuffer fn get_deserialized<T>(&self, index: usize) -> napi::Result<T> where T: DeserializeOwned; } impl CtxtExt for CallContext<'_> { fn get_buffer_as_string(&self, index: usize) -> napi::Result<String> { let buffer = self.get::<JsBuffer>(index)?.into_value()?; Ok(String::from_utf8_lossy(buffer.as_ref()).to_string()) } fn
<T>(&self, index: usize) -> napi::Result<T> where T: DeserializeOwned, { let buffer = self.get::<JsBuffer>(index)?.into_value()?; let v = serde_json::from_slice(&buffer) .with_context(|| { format!( "Failed to deserialize argument at `{}` as {}\nJSON: {}", index, type_name::<T>(), String::from_utf8_lossy(&buffer) ) }) .convert_err()?; Ok(v) } } pub(crate) fn deserialize_json<T>(s: &str) -> Result<T, Error> where T: DeserializeOwned, { serde_json::from_str(s) .with_context(|| format!("failed to deserialize as {}\nJSON: {}", type_name::<T>(), s)) }
get_deserialized
identifier_name
util.rs
/* Copyright (c) 2017 The swc Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use anyhow::{Context, Error}; use napi::{CallContext, JsBuffer, Status}; use serde::de::DeserializeOwned; use std::any::type_name; pub trait MapErr<T>: Into<Result<T, anyhow::Error>> { fn convert_err(self) -> napi::Result<T> { self.into() .map_err(|err| napi::Error::new(Status::GenericFailure, format!("{:?}", err))) } } impl<T> MapErr<T> for Result<T, anyhow::Error> {} pub trait CtxtExt { fn get_buffer_as_string(&self, index: usize) -> napi::Result<String>; /// Currently this uses JsBuffer fn get_deserialized<T>(&self, index: usize) -> napi::Result<T> where T: DeserializeOwned; } impl CtxtExt for CallContext<'_> { fn get_buffer_as_string(&self, index: usize) -> napi::Result<String> { let buffer = self.get::<JsBuffer>(index)?.into_value()?; Ok(String::from_utf8_lossy(buffer.as_ref()).to_string()) } fn get_deserialized<T>(&self, index: usize) -> napi::Result<T> where
.with_context(|| { format!( "Failed to deserialize argument at `{}` as {}\nJSON: {}", index, type_name::<T>(), String::from_utf8_lossy(&buffer) ) }) .convert_err()?; Ok(v) } } pub(crate) fn deserialize_json<T>(s: &str) -> Result<T, Error> where T: DeserializeOwned, { serde_json::from_str(s) .with_context(|| format!("failed to deserialize as {}\nJSON: {}", type_name::<T>(), s)) }
T: DeserializeOwned, { let buffer = self.get::<JsBuffer>(index)?.into_value()?; let v = serde_json::from_slice(&buffer)
random_line_split
util.rs
/* Copyright (c) 2017 The swc Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use anyhow::{Context, Error}; use napi::{CallContext, JsBuffer, Status}; use serde::de::DeserializeOwned; use std::any::type_name; pub trait MapErr<T>: Into<Result<T, anyhow::Error>> { fn convert_err(self) -> napi::Result<T> { self.into() .map_err(|err| napi::Error::new(Status::GenericFailure, format!("{:?}", err))) } } impl<T> MapErr<T> for Result<T, anyhow::Error> {} pub trait CtxtExt { fn get_buffer_as_string(&self, index: usize) -> napi::Result<String>; /// Currently this uses JsBuffer fn get_deserialized<T>(&self, index: usize) -> napi::Result<T> where T: DeserializeOwned; } impl CtxtExt for CallContext<'_> { fn get_buffer_as_string(&self, index: usize) -> napi::Result<String>
fn get_deserialized<T>(&self, index: usize) -> napi::Result<T> where T: DeserializeOwned, { let buffer = self.get::<JsBuffer>(index)?.into_value()?; let v = serde_json::from_slice(&buffer) .with_context(|| { format!( "Failed to deserialize argument at `{}` as {}\nJSON: {}", index, type_name::<T>(), String::from_utf8_lossy(&buffer) ) }) .convert_err()?; Ok(v) } } pub(crate) fn deserialize_json<T>(s: &str) -> Result<T, Error> where T: DeserializeOwned, { serde_json::from_str(s) .with_context(|| format!("failed to deserialize as {}\nJSON: {}", type_name::<T>(), s)) }
{ let buffer = self.get::<JsBuffer>(index)?.into_value()?; Ok(String::from_utf8_lossy(buffer.as_ref()).to_string()) }
identifier_body
basic.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![cfg(not(target_arch = "arm"))] use libc::{c_char, ioctl, open, O_RDWR}; use kvm_sys::*; const KVM_PATH: &str = "/dev/kvm\0"; #[test] fn get_version() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let ret = unsafe { ioctl(sys_fd, KVM_GET_API_VERSION(), 0) }; assert_eq!(ret as u32, KVM_API_VERSION); } #[test] fn create_vm_fd()
#[test] fn check_vm_extension() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let has_user_memory = unsafe { ioctl(sys_fd, KVM_CHECK_EXTENSION(), KVM_CAP_USER_MEMORY) }; assert_eq!(has_user_memory, 1); }
{ let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let vm_fd = unsafe { ioctl(sys_fd, KVM_CREATE_VM(), 0) }; assert!(vm_fd >= 0); }
identifier_body
basic.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![cfg(not(target_arch = "arm"))] use libc::{c_char, ioctl, open, O_RDWR}; use kvm_sys::*; const KVM_PATH: &str = "/dev/kvm\0"; #[test] fn get_version() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let ret = unsafe { ioctl(sys_fd, KVM_GET_API_VERSION(), 0) }; assert_eq!(ret as u32, KVM_API_VERSION); } #[test] fn create_vm_fd() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let vm_fd = unsafe { ioctl(sys_fd, KVM_CREATE_VM(), 0) }; assert!(vm_fd >= 0); } #[test] fn
() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let has_user_memory = unsafe { ioctl(sys_fd, KVM_CHECK_EXTENSION(), KVM_CAP_USER_MEMORY) }; assert_eq!(has_user_memory, 1); }
check_vm_extension
identifier_name
basic.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file.
use kvm_sys::*; const KVM_PATH: &str = "/dev/kvm\0"; #[test] fn get_version() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let ret = unsafe { ioctl(sys_fd, KVM_GET_API_VERSION(), 0) }; assert_eq!(ret as u32, KVM_API_VERSION); } #[test] fn create_vm_fd() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let vm_fd = unsafe { ioctl(sys_fd, KVM_CREATE_VM(), 0) }; assert!(vm_fd >= 0); } #[test] fn check_vm_extension() { let sys_fd = unsafe { open(KVM_PATH.as_ptr() as *const c_char, O_RDWR) }; assert!(sys_fd >= 0); let has_user_memory = unsafe { ioctl(sys_fd, KVM_CHECK_EXTENSION(), KVM_CAP_USER_MEMORY) }; assert_eq!(has_user_memory, 1); }
#![cfg(not(target_arch = "arm"))] use libc::{c_char, ioctl, open, O_RDWR};
random_line_split
request.rs
/*! Functions to make requests against the planets.nu API. */ extern crate curl; extern crate flate2; extern crate url; use self::curl::http; use self::flate2::reader::GzDecoder; use std::io::BufReader; use std::str; use std::vec; use error; use builders::game; use builders::load_turn; use builders::login; use parse; // Public pub use builders::game::Game; pub use builders::load_turn::LoadTurnResult; pub use builders::login::LoginResult; bitflags! { flags GameStatusFlags: u8 { const STATUS_DEFAULT = 0x00, const STATUS_JOINING = 0x01, const STATUS_RUNNING = 0x02, const STATUS_FINISHED = 0x04, const STATUS_HOLD = 0x08, } } bitflags! { flags GameTypeFlags: u8 { const GAME_TYPE_DEFAULT = 0x00, const GAME_TYPE_TRAINING = 0x01, const GAME_TYPE_STANDARD = 0x02, const GAME_TYPE_TEAM = 0x04, const GAME_TYPE_MELEE = 0x08, const GAME_TYPE_BLITZ = 0x10, } } pub enum GameScope { DefaultScope, PublicScope, CustomScope, } /// Make a call to the login API. /// /// The purpose of this call is to retrieve an API key that can be passed along in other API /// requests. It also retrieves the settings for the user. pub fn login(username: &str, password: &str) -> Result<login::LoginResult, error::Error> { let url = format!( "http://api.planets.nu/login?username={0}&password={1}", percent_encode(username.to_string()), percent_encode(password.to_string())); let response = try!(http_get(url.as_slice())); parse::login(try!(decode_response(&response)).as_slice()) } /// Make a call to the games list API. /// /// This call retrieves the list of all games, which can be filtered by several criteria. /// /// status: Retrieve only games with the specified statuses. /// game_type: Retrieve only games with the specified game types. /// scope: Retrieve only games with the specified scope. /// ids: Retrieve only games with the specified IDs. /// username: Username of account to list games. /// /// Will list all games for this user regardless of settings. /// The maximum number of records to return. // TODO: document the parameters better pub fn list_games( status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> Result<Vec<game::Game>, error::Error> { let url = build_games_list_url(status, game_type, scope, ids, username, limit); let response = try!(http_get(url.as_slice())); parse::list_games(try!(decode_response(&response)).as_slice()) } /// Make a call to the load turn API. /// /// This call retrieves all information relating to a single turn of a game. /// game_id: The game ID for which the turn is requested. /// turn: The turn number requested (if unspecified, the latest turn is used). /// api_key: The API key from the login API call. Used to authenticate calls for active games. /// player_id: The player to request a turn for. /// /// In an active game this must be the ID of the player to which the API key belongs. /// for_save: Indicates if the client intends to make a call to the save turn API. // TODO: document the parameters better pub fn load_turn( game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> Result<load_turn::LoadTurnResult, error::Error> { let url = build_load_turn_url(game_id, turn, api_key, player_id, for_save); let response = try!(http_get(url.as_slice())); parse::load_turn(try!(decode_response(&response)).as_slice()) } // Private fn status_flags_to_str(flags: GameStatusFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut statuses = vec::Vec::new(); if flags.contains(STATUS_JOINING) { statuses.push("1"); } if flags.contains(STATUS_RUNNING) { statuses.push("2"); } if flags.contains(STATUS_FINISHED) { statuses.push("3"); } if flags.contains(STATUS_HOLD) { statuses.push("4"); } Some(statuses.connect(",")) }, } } fn type_flags_to_str(flags: GameTypeFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut types = vec::Vec::new(); if flags.contains(GAME_TYPE_TRAINING) { types.push("1"); } if flags.contains(GAME_TYPE_STANDARD) { types.push("2"); } if flags.contains(GAME_TYPE_TEAM) { types.push("3"); } if flags.contains(GAME_TYPE_MELEE) { types.push("4"); } if flags.contains(GAME_TYPE_BLITZ) { types.push("5"); } Some(types.connect(",")) }, } } /// Builds the URL used for the games list API. fn build_games_list_url(status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> String { let mut url = "http://api.planets.nu/games/list".to_string(); let mut prepend_char = "?".to_string(); match status_flags_to_str(status) { Some(s) => { url = url + prepend_char + "status=" + s; prepend_char = "&".to_string(); }, None => (), }; match type_flags_to_str(game_type) { Some(s) => { url = url + prepend_char + "type=" + s; prepend_char = "&".to_string(); }, None => (), }; match scope { DefaultScope => (), PublicScope => { url = url + prepend_char + "scope=0"; prepend_char = "&".to_string(); }, CustomScope => { url = url + prepend_char + "scope=1"; prepend_char = "&".to_string(); }, }; let ids_as_str: Vec<String> = ids.iter().map(|x| format!("{}", x)).collect(); if ids_as_str.len() > 0 { url = url + prepend_char + "ids=" + ids_as_str.connect(","); prepend_char = "&".to_string(); } match username { Some(s) => { url = url + prepend_char + "username=" + percent_encode(s); prepend_char = "&".to_string(); }, None => (), }; match limit { Some(i) => { url = url + prepend_char + "limit=" + i.to_string(); }, None => (), }; url } /// Builds the URL used for the load turn API. fn build_load_turn_url(game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> String { let mut url = "http://api.planets.nu/game/loadturn?gameid=".to_string() + game_id.to_string(); match turn { Some(i) => url = url + "&turn=" + i.to_string(), None => (), }; match api_key { Some(s) => url = url + "&apikey=" + s, None => (), }; match player_id { Some(i) => url = url + "&playerid=" + i.to_string(), None => (), }; url + "&forsave=" + for_save.to_string() } /// Performs an HTTP GET request, returning the response (or an error). fn http_get(url: &str) -> Result<http::Response, error::Error> { match http::handle().get(url).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl GET request failed with error code {}", code))), } } // This works, but currently there is no need for POSTs. /* /// Performs an HTTP POST request, returning the response (or an error). fn http_post(url: &str, data: &str) -> Result<http::Response, error::Error> { match http::handle().post(url, data).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl POST request failed with error code {}", code))), } } */ /// Returns the body of the response, decoding it if it is compressed. fn decode_response(response: &http::Response) -> Result<String, error::Error> { let enc_headers = response.get_header("content-encoding"); if enc_headers.len() == 0 { return Ok(try!(bytes_to_str(response.get_body())).to_string()); } match enc_headers[0].as_slice() { "gzip" => { let mut decoder = GzDecoder::new(BufReader::new(response.get_body())); match decoder.read_to_string() { Ok(s) => Ok(s.clone()), Err(error) => Err(error::Error::new( error::NetworkError, format!("Unable to decode the GZIP-compressed response: {}", error))), } }, _ => Ok(try!(bytes_to_str(response.get_body())).to_string()), } } /// Converts a byte slice into a string, returning an error on failure. fn bytes_to_str<'a>(bytes: &'a [u8]) -> Result<&'a str, error::Error> { match str::from_utf8(bytes) { Some(s) => Ok(s), None => Err(error::Error::new( error::NetworkError, "Response body is not valid UTF-8.".to_string())), } } /// Percent encodes a string. fn percent_encode(input: String) -> String { url::percent_encode(input.into_bytes().as_slice(), url::DEFAULT_ENCODE_SET) } // Tests #[cfg(test)] mod tests { use super::*; use super::build_games_list_url; use super::build_load_turn_url; use request; #[test] fn test_build_games_list_url_defaults() { assert_eq!( "http://api.planets.nu/games/list", build_games_list_url( request::STATUS_DEFAULT, request::GAME_TYPE_DEFAULT, request::DefaultScope, &Vec::new(), None, None).as_slice()); } #[test] fn test_build_games_list_url() { assert_eq!( "http://api.planets.nu/games/list\ ?status=1,3&type=1,4&scope=1&ids=12,13371337&username=theuser&limit=123", build_games_list_url( request::STATUS_JOINING | request::STATUS_FINISHED, request::GAME_TYPE_TRAINING | request::GAME_TYPE_MELEE, request::CustomScope, &vec![12,13371337], Some("theuser".to_string()), Some(123)).as_slice()); } #[test] fn
() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&forsave=false", build_load_turn_url(1337, None, None, None, false).as_slice()); } #[test] fn test_build_load_turn_url() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&turn=5&apikey=theapikey&playerid=123&forsave=true", build_load_turn_url(1337, Some(5), Some("theapikey".to_string()), Some(123), true).as_slice()); } }
test_build_load_turn_url_defaults
identifier_name
request.rs
/*! Functions to make requests against the planets.nu API. */ extern crate curl; extern crate flate2; extern crate url; use self::curl::http; use self::flate2::reader::GzDecoder; use std::io::BufReader; use std::str; use std::vec; use error; use builders::game; use builders::load_turn; use builders::login; use parse; // Public pub use builders::game::Game; pub use builders::load_turn::LoadTurnResult; pub use builders::login::LoginResult; bitflags! { flags GameStatusFlags: u8 { const STATUS_DEFAULT = 0x00, const STATUS_JOINING = 0x01, const STATUS_RUNNING = 0x02, const STATUS_FINISHED = 0x04, const STATUS_HOLD = 0x08, } } bitflags! { flags GameTypeFlags: u8 { const GAME_TYPE_DEFAULT = 0x00, const GAME_TYPE_TRAINING = 0x01, const GAME_TYPE_STANDARD = 0x02, const GAME_TYPE_TEAM = 0x04, const GAME_TYPE_MELEE = 0x08, const GAME_TYPE_BLITZ = 0x10, } } pub enum GameScope { DefaultScope, PublicScope, CustomScope, } /// Make a call to the login API. /// /// The purpose of this call is to retrieve an API key that can be passed along in other API /// requests. It also retrieves the settings for the user. pub fn login(username: &str, password: &str) -> Result<login::LoginResult, error::Error> { let url = format!( "http://api.planets.nu/login?username={0}&password={1}", percent_encode(username.to_string()), percent_encode(password.to_string())); let response = try!(http_get(url.as_slice())); parse::login(try!(decode_response(&response)).as_slice()) } /// Make a call to the games list API. /// /// This call retrieves the list of all games, which can be filtered by several criteria. /// /// status: Retrieve only games with the specified statuses. /// game_type: Retrieve only games with the specified game types. /// scope: Retrieve only games with the specified scope. /// ids: Retrieve only games with the specified IDs. /// username: Username of account to list games. /// /// Will list all games for this user regardless of settings. /// The maximum number of records to return. // TODO: document the parameters better pub fn list_games( status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> Result<Vec<game::Game>, error::Error> { let url = build_games_list_url(status, game_type, scope, ids, username, limit); let response = try!(http_get(url.as_slice())); parse::list_games(try!(decode_response(&response)).as_slice()) } /// Make a call to the load turn API. /// /// This call retrieves all information relating to a single turn of a game. /// game_id: The game ID for which the turn is requested. /// turn: The turn number requested (if unspecified, the latest turn is used). /// api_key: The API key from the login API call. Used to authenticate calls for active games. /// player_id: The player to request a turn for. /// /// In an active game this must be the ID of the player to which the API key belongs. /// for_save: Indicates if the client intends to make a call to the save turn API. // TODO: document the parameters better pub fn load_turn( game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> Result<load_turn::LoadTurnResult, error::Error> { let url = build_load_turn_url(game_id, turn, api_key, player_id, for_save); let response = try!(http_get(url.as_slice())); parse::load_turn(try!(decode_response(&response)).as_slice()) } // Private fn status_flags_to_str(flags: GameStatusFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut statuses = vec::Vec::new(); if flags.contains(STATUS_JOINING) { statuses.push("1"); } if flags.contains(STATUS_RUNNING) { statuses.push("2"); } if flags.contains(STATUS_FINISHED) { statuses.push("3"); } if flags.contains(STATUS_HOLD) { statuses.push("4"); } Some(statuses.connect(",")) }, } } fn type_flags_to_str(flags: GameTypeFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut types = vec::Vec::new(); if flags.contains(GAME_TYPE_TRAINING) { types.push("1"); } if flags.contains(GAME_TYPE_STANDARD) { types.push("2"); } if flags.contains(GAME_TYPE_TEAM) { types.push("3"); } if flags.contains(GAME_TYPE_MELEE) { types.push("4"); } if flags.contains(GAME_TYPE_BLITZ) { types.push("5"); } Some(types.connect(",")) }, } } /// Builds the URL used for the games list API. fn build_games_list_url(status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> String { let mut url = "http://api.planets.nu/games/list".to_string(); let mut prepend_char = "?".to_string(); match status_flags_to_str(status) { Some(s) => { url = url + prepend_char + "status=" + s; prepend_char = "&".to_string(); }, None => (), }; match type_flags_to_str(game_type) { Some(s) => { url = url + prepend_char + "type=" + s; prepend_char = "&".to_string(); }, None => (), }; match scope {
DefaultScope => (), PublicScope => { url = url + prepend_char + "scope=0"; prepend_char = "&".to_string(); }, CustomScope => { url = url + prepend_char + "scope=1"; prepend_char = "&".to_string(); }, }; let ids_as_str: Vec<String> = ids.iter().map(|x| format!("{}", x)).collect(); if ids_as_str.len() > 0 { url = url + prepend_char + "ids=" + ids_as_str.connect(","); prepend_char = "&".to_string(); } match username { Some(s) => { url = url + prepend_char + "username=" + percent_encode(s); prepend_char = "&".to_string(); }, None => (), }; match limit { Some(i) => { url = url + prepend_char + "limit=" + i.to_string(); }, None => (), }; url } /// Builds the URL used for the load turn API. fn build_load_turn_url(game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> String { let mut url = "http://api.planets.nu/game/loadturn?gameid=".to_string() + game_id.to_string(); match turn { Some(i) => url = url + "&turn=" + i.to_string(), None => (), }; match api_key { Some(s) => url = url + "&apikey=" + s, None => (), }; match player_id { Some(i) => url = url + "&playerid=" + i.to_string(), None => (), }; url + "&forsave=" + for_save.to_string() } /// Performs an HTTP GET request, returning the response (or an error). fn http_get(url: &str) -> Result<http::Response, error::Error> { match http::handle().get(url).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl GET request failed with error code {}", code))), } } // This works, but currently there is no need for POSTs. /* /// Performs an HTTP POST request, returning the response (or an error). fn http_post(url: &str, data: &str) -> Result<http::Response, error::Error> { match http::handle().post(url, data).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl POST request failed with error code {}", code))), } } */ /// Returns the body of the response, decoding it if it is compressed. fn decode_response(response: &http::Response) -> Result<String, error::Error> { let enc_headers = response.get_header("content-encoding"); if enc_headers.len() == 0 { return Ok(try!(bytes_to_str(response.get_body())).to_string()); } match enc_headers[0].as_slice() { "gzip" => { let mut decoder = GzDecoder::new(BufReader::new(response.get_body())); match decoder.read_to_string() { Ok(s) => Ok(s.clone()), Err(error) => Err(error::Error::new( error::NetworkError, format!("Unable to decode the GZIP-compressed response: {}", error))), } }, _ => Ok(try!(bytes_to_str(response.get_body())).to_string()), } } /// Converts a byte slice into a string, returning an error on failure. fn bytes_to_str<'a>(bytes: &'a [u8]) -> Result<&'a str, error::Error> { match str::from_utf8(bytes) { Some(s) => Ok(s), None => Err(error::Error::new( error::NetworkError, "Response body is not valid UTF-8.".to_string())), } } /// Percent encodes a string. fn percent_encode(input: String) -> String { url::percent_encode(input.into_bytes().as_slice(), url::DEFAULT_ENCODE_SET) } // Tests #[cfg(test)] mod tests { use super::*; use super::build_games_list_url; use super::build_load_turn_url; use request; #[test] fn test_build_games_list_url_defaults() { assert_eq!( "http://api.planets.nu/games/list", build_games_list_url( request::STATUS_DEFAULT, request::GAME_TYPE_DEFAULT, request::DefaultScope, &Vec::new(), None, None).as_slice()); } #[test] fn test_build_games_list_url() { assert_eq!( "http://api.planets.nu/games/list\ ?status=1,3&type=1,4&scope=1&ids=12,13371337&username=theuser&limit=123", build_games_list_url( request::STATUS_JOINING | request::STATUS_FINISHED, request::GAME_TYPE_TRAINING | request::GAME_TYPE_MELEE, request::CustomScope, &vec![12,13371337], Some("theuser".to_string()), Some(123)).as_slice()); } #[test] fn test_build_load_turn_url_defaults() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&forsave=false", build_load_turn_url(1337, None, None, None, false).as_slice()); } #[test] fn test_build_load_turn_url() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&turn=5&apikey=theapikey&playerid=123&forsave=true", build_load_turn_url(1337, Some(5), Some("theapikey".to_string()), Some(123), true).as_slice()); } }
random_line_split
request.rs
/*! Functions to make requests against the planets.nu API. */ extern crate curl; extern crate flate2; extern crate url; use self::curl::http; use self::flate2::reader::GzDecoder; use std::io::BufReader; use std::str; use std::vec; use error; use builders::game; use builders::load_turn; use builders::login; use parse; // Public pub use builders::game::Game; pub use builders::load_turn::LoadTurnResult; pub use builders::login::LoginResult; bitflags! { flags GameStatusFlags: u8 { const STATUS_DEFAULT = 0x00, const STATUS_JOINING = 0x01, const STATUS_RUNNING = 0x02, const STATUS_FINISHED = 0x04, const STATUS_HOLD = 0x08, } } bitflags! { flags GameTypeFlags: u8 { const GAME_TYPE_DEFAULT = 0x00, const GAME_TYPE_TRAINING = 0x01, const GAME_TYPE_STANDARD = 0x02, const GAME_TYPE_TEAM = 0x04, const GAME_TYPE_MELEE = 0x08, const GAME_TYPE_BLITZ = 0x10, } } pub enum GameScope { DefaultScope, PublicScope, CustomScope, } /// Make a call to the login API. /// /// The purpose of this call is to retrieve an API key that can be passed along in other API /// requests. It also retrieves the settings for the user. pub fn login(username: &str, password: &str) -> Result<login::LoginResult, error::Error> { let url = format!( "http://api.planets.nu/login?username={0}&password={1}", percent_encode(username.to_string()), percent_encode(password.to_string())); let response = try!(http_get(url.as_slice())); parse::login(try!(decode_response(&response)).as_slice()) } /// Make a call to the games list API. /// /// This call retrieves the list of all games, which can be filtered by several criteria. /// /// status: Retrieve only games with the specified statuses. /// game_type: Retrieve only games with the specified game types. /// scope: Retrieve only games with the specified scope. /// ids: Retrieve only games with the specified IDs. /// username: Username of account to list games. /// /// Will list all games for this user regardless of settings. /// The maximum number of records to return. // TODO: document the parameters better pub fn list_games( status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> Result<Vec<game::Game>, error::Error> { let url = build_games_list_url(status, game_type, scope, ids, username, limit); let response = try!(http_get(url.as_slice())); parse::list_games(try!(decode_response(&response)).as_slice()) } /// Make a call to the load turn API. /// /// This call retrieves all information relating to a single turn of a game. /// game_id: The game ID for which the turn is requested. /// turn: The turn number requested (if unspecified, the latest turn is used). /// api_key: The API key from the login API call. Used to authenticate calls for active games. /// player_id: The player to request a turn for. /// /// In an active game this must be the ID of the player to which the API key belongs. /// for_save: Indicates if the client intends to make a call to the save turn API. // TODO: document the parameters better pub fn load_turn( game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> Result<load_turn::LoadTurnResult, error::Error> { let url = build_load_turn_url(game_id, turn, api_key, player_id, for_save); let response = try!(http_get(url.as_slice())); parse::load_turn(try!(decode_response(&response)).as_slice()) } // Private fn status_flags_to_str(flags: GameStatusFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut statuses = vec::Vec::new(); if flags.contains(STATUS_JOINING) { statuses.push("1"); } if flags.contains(STATUS_RUNNING) { statuses.push("2"); } if flags.contains(STATUS_FINISHED) { statuses.push("3"); } if flags.contains(STATUS_HOLD) { statuses.push("4"); } Some(statuses.connect(",")) }, } } fn type_flags_to_str(flags: GameTypeFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut types = vec::Vec::new(); if flags.contains(GAME_TYPE_TRAINING) { types.push("1"); } if flags.contains(GAME_TYPE_STANDARD) { types.push("2"); } if flags.contains(GAME_TYPE_TEAM) { types.push("3"); } if flags.contains(GAME_TYPE_MELEE) { types.push("4"); } if flags.contains(GAME_TYPE_BLITZ) { types.push("5"); } Some(types.connect(",")) }, } } /// Builds the URL used for the games list API. fn build_games_list_url(status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> String { let mut url = "http://api.planets.nu/games/list".to_string(); let mut prepend_char = "?".to_string(); match status_flags_to_str(status) { Some(s) => { url = url + prepend_char + "status=" + s; prepend_char = "&".to_string(); }, None => (), }; match type_flags_to_str(game_type) { Some(s) => { url = url + prepend_char + "type=" + s; prepend_char = "&".to_string(); }, None => (), }; match scope { DefaultScope => (), PublicScope => { url = url + prepend_char + "scope=0"; prepend_char = "&".to_string(); }, CustomScope => { url = url + prepend_char + "scope=1"; prepend_char = "&".to_string(); }, }; let ids_as_str: Vec<String> = ids.iter().map(|x| format!("{}", x)).collect(); if ids_as_str.len() > 0 { url = url + prepend_char + "ids=" + ids_as_str.connect(","); prepend_char = "&".to_string(); } match username { Some(s) => { url = url + prepend_char + "username=" + percent_encode(s); prepend_char = "&".to_string(); }, None => (), }; match limit { Some(i) =>
, None => (), }; url } /// Builds the URL used for the load turn API. fn build_load_turn_url(game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> String { let mut url = "http://api.planets.nu/game/loadturn?gameid=".to_string() + game_id.to_string(); match turn { Some(i) => url = url + "&turn=" + i.to_string(), None => (), }; match api_key { Some(s) => url = url + "&apikey=" + s, None => (), }; match player_id { Some(i) => url = url + "&playerid=" + i.to_string(), None => (), }; url + "&forsave=" + for_save.to_string() } /// Performs an HTTP GET request, returning the response (or an error). fn http_get(url: &str) -> Result<http::Response, error::Error> { match http::handle().get(url).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl GET request failed with error code {}", code))), } } // This works, but currently there is no need for POSTs. /* /// Performs an HTTP POST request, returning the response (or an error). fn http_post(url: &str, data: &str) -> Result<http::Response, error::Error> { match http::handle().post(url, data).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl POST request failed with error code {}", code))), } } */ /// Returns the body of the response, decoding it if it is compressed. fn decode_response(response: &http::Response) -> Result<String, error::Error> { let enc_headers = response.get_header("content-encoding"); if enc_headers.len() == 0 { return Ok(try!(bytes_to_str(response.get_body())).to_string()); } match enc_headers[0].as_slice() { "gzip" => { let mut decoder = GzDecoder::new(BufReader::new(response.get_body())); match decoder.read_to_string() { Ok(s) => Ok(s.clone()), Err(error) => Err(error::Error::new( error::NetworkError, format!("Unable to decode the GZIP-compressed response: {}", error))), } }, _ => Ok(try!(bytes_to_str(response.get_body())).to_string()), } } /// Converts a byte slice into a string, returning an error on failure. fn bytes_to_str<'a>(bytes: &'a [u8]) -> Result<&'a str, error::Error> { match str::from_utf8(bytes) { Some(s) => Ok(s), None => Err(error::Error::new( error::NetworkError, "Response body is not valid UTF-8.".to_string())), } } /// Percent encodes a string. fn percent_encode(input: String) -> String { url::percent_encode(input.into_bytes().as_slice(), url::DEFAULT_ENCODE_SET) } // Tests #[cfg(test)] mod tests { use super::*; use super::build_games_list_url; use super::build_load_turn_url; use request; #[test] fn test_build_games_list_url_defaults() { assert_eq!( "http://api.planets.nu/games/list", build_games_list_url( request::STATUS_DEFAULT, request::GAME_TYPE_DEFAULT, request::DefaultScope, &Vec::new(), None, None).as_slice()); } #[test] fn test_build_games_list_url() { assert_eq!( "http://api.planets.nu/games/list\ ?status=1,3&type=1,4&scope=1&ids=12,13371337&username=theuser&limit=123", build_games_list_url( request::STATUS_JOINING | request::STATUS_FINISHED, request::GAME_TYPE_TRAINING | request::GAME_TYPE_MELEE, request::CustomScope, &vec![12,13371337], Some("theuser".to_string()), Some(123)).as_slice()); } #[test] fn test_build_load_turn_url_defaults() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&forsave=false", build_load_turn_url(1337, None, None, None, false).as_slice()); } #[test] fn test_build_load_turn_url() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&turn=5&apikey=theapikey&playerid=123&forsave=true", build_load_turn_url(1337, Some(5), Some("theapikey".to_string()), Some(123), true).as_slice()); } }
{ url = url + prepend_char + "limit=" + i.to_string(); }
conditional_block
request.rs
/*! Functions to make requests against the planets.nu API. */ extern crate curl; extern crate flate2; extern crate url; use self::curl::http; use self::flate2::reader::GzDecoder; use std::io::BufReader; use std::str; use std::vec; use error; use builders::game; use builders::load_turn; use builders::login; use parse; // Public pub use builders::game::Game; pub use builders::load_turn::LoadTurnResult; pub use builders::login::LoginResult; bitflags! { flags GameStatusFlags: u8 { const STATUS_DEFAULT = 0x00, const STATUS_JOINING = 0x01, const STATUS_RUNNING = 0x02, const STATUS_FINISHED = 0x04, const STATUS_HOLD = 0x08, } } bitflags! { flags GameTypeFlags: u8 { const GAME_TYPE_DEFAULT = 0x00, const GAME_TYPE_TRAINING = 0x01, const GAME_TYPE_STANDARD = 0x02, const GAME_TYPE_TEAM = 0x04, const GAME_TYPE_MELEE = 0x08, const GAME_TYPE_BLITZ = 0x10, } } pub enum GameScope { DefaultScope, PublicScope, CustomScope, } /// Make a call to the login API. /// /// The purpose of this call is to retrieve an API key that can be passed along in other API /// requests. It also retrieves the settings for the user. pub fn login(username: &str, password: &str) -> Result<login::LoginResult, error::Error> { let url = format!( "http://api.planets.nu/login?username={0}&password={1}", percent_encode(username.to_string()), percent_encode(password.to_string())); let response = try!(http_get(url.as_slice())); parse::login(try!(decode_response(&response)).as_slice()) } /// Make a call to the games list API. /// /// This call retrieves the list of all games, which can be filtered by several criteria. /// /// status: Retrieve only games with the specified statuses. /// game_type: Retrieve only games with the specified game types. /// scope: Retrieve only games with the specified scope. /// ids: Retrieve only games with the specified IDs. /// username: Username of account to list games. /// /// Will list all games for this user regardless of settings. /// The maximum number of records to return. // TODO: document the parameters better pub fn list_games( status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> Result<Vec<game::Game>, error::Error> { let url = build_games_list_url(status, game_type, scope, ids, username, limit); let response = try!(http_get(url.as_slice())); parse::list_games(try!(decode_response(&response)).as_slice()) } /// Make a call to the load turn API. /// /// This call retrieves all information relating to a single turn of a game. /// game_id: The game ID for which the turn is requested. /// turn: The turn number requested (if unspecified, the latest turn is used). /// api_key: The API key from the login API call. Used to authenticate calls for active games. /// player_id: The player to request a turn for. /// /// In an active game this must be the ID of the player to which the API key belongs. /// for_save: Indicates if the client intends to make a call to the save turn API. // TODO: document the parameters better pub fn load_turn( game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> Result<load_turn::LoadTurnResult, error::Error> { let url = build_load_turn_url(game_id, turn, api_key, player_id, for_save); let response = try!(http_get(url.as_slice())); parse::load_turn(try!(decode_response(&response)).as_slice()) } // Private fn status_flags_to_str(flags: GameStatusFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut statuses = vec::Vec::new(); if flags.contains(STATUS_JOINING) { statuses.push("1"); } if flags.contains(STATUS_RUNNING) { statuses.push("2"); } if flags.contains(STATUS_FINISHED) { statuses.push("3"); } if flags.contains(STATUS_HOLD) { statuses.push("4"); } Some(statuses.connect(",")) }, } } fn type_flags_to_str(flags: GameTypeFlags) -> Option<String> { match flags.is_empty() { true => None, false => { let mut types = vec::Vec::new(); if flags.contains(GAME_TYPE_TRAINING) { types.push("1"); } if flags.contains(GAME_TYPE_STANDARD) { types.push("2"); } if flags.contains(GAME_TYPE_TEAM) { types.push("3"); } if flags.contains(GAME_TYPE_MELEE) { types.push("4"); } if flags.contains(GAME_TYPE_BLITZ) { types.push("5"); } Some(types.connect(",")) }, } } /// Builds the URL used for the games list API. fn build_games_list_url(status: GameStatusFlags, game_type: GameTypeFlags, scope: GameScope, ids: &Vec<i32>, username: Option<String>, limit: Option<i32>) -> String { let mut url = "http://api.planets.nu/games/list".to_string(); let mut prepend_char = "?".to_string(); match status_flags_to_str(status) { Some(s) => { url = url + prepend_char + "status=" + s; prepend_char = "&".to_string(); }, None => (), }; match type_flags_to_str(game_type) { Some(s) => { url = url + prepend_char + "type=" + s; prepend_char = "&".to_string(); }, None => (), }; match scope { DefaultScope => (), PublicScope => { url = url + prepend_char + "scope=0"; prepend_char = "&".to_string(); }, CustomScope => { url = url + prepend_char + "scope=1"; prepend_char = "&".to_string(); }, }; let ids_as_str: Vec<String> = ids.iter().map(|x| format!("{}", x)).collect(); if ids_as_str.len() > 0 { url = url + prepend_char + "ids=" + ids_as_str.connect(","); prepend_char = "&".to_string(); } match username { Some(s) => { url = url + prepend_char + "username=" + percent_encode(s); prepend_char = "&".to_string(); }, None => (), }; match limit { Some(i) => { url = url + prepend_char + "limit=" + i.to_string(); }, None => (), }; url } /// Builds the URL used for the load turn API. fn build_load_turn_url(game_id: i32, turn: Option<i32>, api_key: Option<String>, player_id: Option<i32>, for_save: bool) -> String { let mut url = "http://api.planets.nu/game/loadturn?gameid=".to_string() + game_id.to_string(); match turn { Some(i) => url = url + "&turn=" + i.to_string(), None => (), }; match api_key { Some(s) => url = url + "&apikey=" + s, None => (), }; match player_id { Some(i) => url = url + "&playerid=" + i.to_string(), None => (), }; url + "&forsave=" + for_save.to_string() } /// Performs an HTTP GET request, returning the response (or an error). fn http_get(url: &str) -> Result<http::Response, error::Error> { match http::handle().get(url).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl GET request failed with error code {}", code))), } } // This works, but currently there is no need for POSTs. /* /// Performs an HTTP POST request, returning the response (or an error). fn http_post(url: &str, data: &str) -> Result<http::Response, error::Error> { match http::handle().post(url, data).exec() { Ok(x) => Ok(x), Err(code) => Err(error::Error::new( error::NetworkError, format!("curl POST request failed with error code {}", code))), } } */ /// Returns the body of the response, decoding it if it is compressed. fn decode_response(response: &http::Response) -> Result<String, error::Error> { let enc_headers = response.get_header("content-encoding"); if enc_headers.len() == 0 { return Ok(try!(bytes_to_str(response.get_body())).to_string()); } match enc_headers[0].as_slice() { "gzip" => { let mut decoder = GzDecoder::new(BufReader::new(response.get_body())); match decoder.read_to_string() { Ok(s) => Ok(s.clone()), Err(error) => Err(error::Error::new( error::NetworkError, format!("Unable to decode the GZIP-compressed response: {}", error))), } }, _ => Ok(try!(bytes_to_str(response.get_body())).to_string()), } } /// Converts a byte slice into a string, returning an error on failure. fn bytes_to_str<'a>(bytes: &'a [u8]) -> Result<&'a str, error::Error> { match str::from_utf8(bytes) { Some(s) => Ok(s), None => Err(error::Error::new( error::NetworkError, "Response body is not valid UTF-8.".to_string())), } } /// Percent encodes a string. fn percent_encode(input: String) -> String { url::percent_encode(input.into_bytes().as_slice(), url::DEFAULT_ENCODE_SET) } // Tests #[cfg(test)] mod tests { use super::*; use super::build_games_list_url; use super::build_load_turn_url; use request; #[test] fn test_build_games_list_url_defaults()
#[test] fn test_build_games_list_url() { assert_eq!( "http://api.planets.nu/games/list\ ?status=1,3&type=1,4&scope=1&ids=12,13371337&username=theuser&limit=123", build_games_list_url( request::STATUS_JOINING | request::STATUS_FINISHED, request::GAME_TYPE_TRAINING | request::GAME_TYPE_MELEE, request::CustomScope, &vec![12,13371337], Some("theuser".to_string()), Some(123)).as_slice()); } #[test] fn test_build_load_turn_url_defaults() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&forsave=false", build_load_turn_url(1337, None, None, None, false).as_slice()); } #[test] fn test_build_load_turn_url() { assert_eq!( "http://api.planets.nu/game/loadturn?gameid=1337&turn=5&apikey=theapikey&playerid=123&forsave=true", build_load_turn_url(1337, Some(5), Some("theapikey".to_string()), Some(123), true).as_slice()); } }
{ assert_eq!( "http://api.planets.nu/games/list", build_games_list_url( request::STATUS_DEFAULT, request::GAME_TYPE_DEFAULT, request::DefaultScope, &Vec::new(), None, None).as_slice()); }
identifier_body
lib.rs
//! Maman is a Rust Web Crawler saving pages on Redis. //! //! # Default environment variables //! //! * `MAMAN_ENV`=development //! * `REDIS_URL`="redis://127.0.0.1/" #![doc(html_root_url = "https://docs.rs/maman/0.13.1")] #![deny(warnings)] #![crate_name = "maman"] extern crate html5ever; #[macro_use] extern crate log; extern crate mime; extern crate reqwest; extern crate robotparser; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; extern crate sidekiq; extern crate url; #[macro_export] macro_rules! maman_name { () => { "Maman" }; } #[macro_export] macro_rules! maman_version { () => { env!("CARGO_PKG_VERSION") }; } #[macro_export] macro_rules! maman_version_string { () => { concat!(maman_name!(), " v", maman_version!()) }; } #[macro_export] macro_rules! maman_user_agent { () => {
pub use crate::maman::{Page, Spider}; pub mod maman;
concat!(maman_version_string!(), " (https://crates.io/crates/maman)") }; }
random_line_split
chester.rs
use std::io::BufRead; struct Point { x: f64, y: f64, } fn square(x: f64) -> f64 { x*x } impl Point { fn distance(&self, p: &Point) -> f64 { self.distance_squared(p).sqrt() } fn distance_squared(&self, p: &Point) -> f64 { square(self.x - p.x) + square(self.y - p.y) } } fn read_input() -> Vec<Point> { let stdin = std::io::stdin(); let mut input = stdin.lock().lines(); let n_treats = input.next().unwrap().unwrap().parse().unwrap(); let mut treats = Vec::with_capacity(n_treats); for _ in 0..n_treats { let numbers: Vec<f64> = input.next().unwrap().unwrap().split(' ') .filter_map(|s| s.parse().ok()) .collect(); treats.push(Point { x: numbers[0], y: numbers[1] } ); } treats } // Remove the point closest to `p` and return it. fn pop_closest(p: &Point, ps: &mut Vec<Point>) -> Option<Point> { if ps.is_empty() { return None; } let len = ps.len(); let mut closest = (0, p.distance_squared(&ps[0])); for i in 1..len { let d = p.distance_squared(&ps[i]); if d < closest.1 { closest = (i, d); } } Some(ps.swap_remove(closest.0)) } fn main() {
let mut position = Point { x:0.5, y:0.5 }; let mut total_distance = 0f64; while let Some(next_position) = pop_closest(&position, &mut treats) { total_distance += position.distance(&next_position); position = next_position; } println!("{:.16}", total_distance); }
let mut treats = read_input();
random_line_split
chester.rs
use std::io::BufRead; struct Point { x: f64, y: f64, } fn square(x: f64) -> f64 { x*x } impl Point { fn distance(&self, p: &Point) -> f64 { self.distance_squared(p).sqrt() } fn distance_squared(&self, p: &Point) -> f64 { square(self.x - p.x) + square(self.y - p.y) } } fn
() -> Vec<Point> { let stdin = std::io::stdin(); let mut input = stdin.lock().lines(); let n_treats = input.next().unwrap().unwrap().parse().unwrap(); let mut treats = Vec::with_capacity(n_treats); for _ in 0..n_treats { let numbers: Vec<f64> = input.next().unwrap().unwrap().split(' ') .filter_map(|s| s.parse().ok()) .collect(); treats.push(Point { x: numbers[0], y: numbers[1] } ); } treats } // Remove the point closest to `p` and return it. fn pop_closest(p: &Point, ps: &mut Vec<Point>) -> Option<Point> { if ps.is_empty() { return None; } let len = ps.len(); let mut closest = (0, p.distance_squared(&ps[0])); for i in 1..len { let d = p.distance_squared(&ps[i]); if d < closest.1 { closest = (i, d); } } Some(ps.swap_remove(closest.0)) } fn main() { let mut treats = read_input(); let mut position = Point { x:0.5, y:0.5 }; let mut total_distance = 0f64; while let Some(next_position) = pop_closest(&position, &mut treats) { total_distance += position.distance(&next_position); position = next_position; } println!("{:.16}", total_distance); }
read_input
identifier_name
chester.rs
use std::io::BufRead; struct Point { x: f64, y: f64, } fn square(x: f64) -> f64 { x*x } impl Point { fn distance(&self, p: &Point) -> f64 { self.distance_squared(p).sqrt() } fn distance_squared(&self, p: &Point) -> f64 { square(self.x - p.x) + square(self.y - p.y) } } fn read_input() -> Vec<Point> { let stdin = std::io::stdin(); let mut input = stdin.lock().lines(); let n_treats = input.next().unwrap().unwrap().parse().unwrap(); let mut treats = Vec::with_capacity(n_treats); for _ in 0..n_treats { let numbers: Vec<f64> = input.next().unwrap().unwrap().split(' ') .filter_map(|s| s.parse().ok()) .collect(); treats.push(Point { x: numbers[0], y: numbers[1] } ); } treats } // Remove the point closest to `p` and return it. fn pop_closest(p: &Point, ps: &mut Vec<Point>) -> Option<Point> { if ps.is_empty()
let len = ps.len(); let mut closest = (0, p.distance_squared(&ps[0])); for i in 1..len { let d = p.distance_squared(&ps[i]); if d < closest.1 { closest = (i, d); } } Some(ps.swap_remove(closest.0)) } fn main() { let mut treats = read_input(); let mut position = Point { x:0.5, y:0.5 }; let mut total_distance = 0f64; while let Some(next_position) = pop_closest(&position, &mut treats) { total_distance += position.distance(&next_position); position = next_position; } println!("{:.16}", total_distance); }
{ return None; }
conditional_block
markdown.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. //! Markdown formatting for rustdoc //! //! This module implements markdown formatting through the sundown C-library //! (bundled into the rust runtime). This module self-contains the C bindings //! and necessary legwork to render markdown, and exposes all of the //! functionality through a unit-struct, `Markdown`, which has an implementation //! of `fmt::Default`. Example usage: //! //! ```rust //! let s = "My *markdown* _text_"; //! let html = format!("{}", Markdown(s)); //! //... something using html //! ``` use std::fmt; use std::libc; use std::io; use std::vec; /// A unit struct which has the `fmt::Default` trait implemented. When /// formatted, this struct will emit the HTML corresponding to the rendered /// version of the contained markdown string. pub struct Markdown<'a>(&'a str); static OUTPUT_UNIT: libc::size_t = 64; static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0; static MKDEXT_TABLES: libc::c_uint = 1 << 1; static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2; static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3; static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4; type sd_markdown = libc::c_void; // this is opaque to us // this is a large struct of callbacks we don't use type sd_callbacks = [libc::size_t,..26]; struct html_toc_data { header_count: libc::c_int, current_level: libc::c_int, level_offset: libc::c_int, } struct html_renderopt { toc_data: html_toc_data,
data: *u8, size: libc::size_t, asize: libc::size_t, unit: libc::size_t, } // sundown FFI #[link(name = "sundown", kind = "static")] extern { fn sdhtml_renderer(callbacks: *sd_callbacks, options_ptr: *html_renderopt, render_flags: libc::c_uint); fn sd_markdown_new(extensions: libc::c_uint, max_nesting: libc::size_t, callbacks: *sd_callbacks, opaque: *libc::c_void) -> *sd_markdown; fn sd_markdown_render(ob: *buf, document: *u8, doc_size: libc::size_t, md: *sd_markdown); fn sd_markdown_free(md: *sd_markdown); fn bufnew(unit: libc::size_t) -> *buf; fn bufrelease(b: *buf); } fn render(w: &mut io::Writer, s: &str) { // This code is all lifted from examples/sundown.c in the sundown repo unsafe { let ob = bufnew(OUTPUT_UNIT); let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES | MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK | MKDEXT_STRIKETHROUGH; let options = html_renderopt { toc_data: html_toc_data { header_count: 0, current_level: 0, level_offset: 0, }, flags: 0, link_attributes: None, }; let callbacks: sd_callbacks = [0,..26]; sdhtml_renderer(&callbacks, &options, 0); let markdown = sd_markdown_new(extensions, 16, &callbacks, &options as *html_renderopt as *libc::c_void); s.as_imm_buf(|data, len| { sd_markdown_render(ob, data, len as libc::size_t, markdown); }); sd_markdown_free(markdown); vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| { w.write(buf); }); bufrelease(ob); } } impl<'a> fmt::Default for Markdown<'a> { fn fmt(md: &Markdown<'a>, fmt: &mut fmt::Formatter) { // This is actually common enough to special-case if md.len() == 0 { return; } render(fmt.buf, md.as_slice()); } }
flags: libc::c_uint, link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>, } struct buf {
random_line_split
markdown.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. //! Markdown formatting for rustdoc //! //! This module implements markdown formatting through the sundown C-library //! (bundled into the rust runtime). This module self-contains the C bindings //! and necessary legwork to render markdown, and exposes all of the //! functionality through a unit-struct, `Markdown`, which has an implementation //! of `fmt::Default`. Example usage: //! //! ```rust //! let s = "My *markdown* _text_"; //! let html = format!("{}", Markdown(s)); //! //... something using html //! ``` use std::fmt; use std::libc; use std::io; use std::vec; /// A unit struct which has the `fmt::Default` trait implemented. When /// formatted, this struct will emit the HTML corresponding to the rendered /// version of the contained markdown string. pub struct
<'a>(&'a str); static OUTPUT_UNIT: libc::size_t = 64; static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0; static MKDEXT_TABLES: libc::c_uint = 1 << 1; static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2; static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3; static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4; type sd_markdown = libc::c_void; // this is opaque to us // this is a large struct of callbacks we don't use type sd_callbacks = [libc::size_t,..26]; struct html_toc_data { header_count: libc::c_int, current_level: libc::c_int, level_offset: libc::c_int, } struct html_renderopt { toc_data: html_toc_data, flags: libc::c_uint, link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>, } struct buf { data: *u8, size: libc::size_t, asize: libc::size_t, unit: libc::size_t, } // sundown FFI #[link(name = "sundown", kind = "static")] extern { fn sdhtml_renderer(callbacks: *sd_callbacks, options_ptr: *html_renderopt, render_flags: libc::c_uint); fn sd_markdown_new(extensions: libc::c_uint, max_nesting: libc::size_t, callbacks: *sd_callbacks, opaque: *libc::c_void) -> *sd_markdown; fn sd_markdown_render(ob: *buf, document: *u8, doc_size: libc::size_t, md: *sd_markdown); fn sd_markdown_free(md: *sd_markdown); fn bufnew(unit: libc::size_t) -> *buf; fn bufrelease(b: *buf); } fn render(w: &mut io::Writer, s: &str) { // This code is all lifted from examples/sundown.c in the sundown repo unsafe { let ob = bufnew(OUTPUT_UNIT); let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES | MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK | MKDEXT_STRIKETHROUGH; let options = html_renderopt { toc_data: html_toc_data { header_count: 0, current_level: 0, level_offset: 0, }, flags: 0, link_attributes: None, }; let callbacks: sd_callbacks = [0,..26]; sdhtml_renderer(&callbacks, &options, 0); let markdown = sd_markdown_new(extensions, 16, &callbacks, &options as *html_renderopt as *libc::c_void); s.as_imm_buf(|data, len| { sd_markdown_render(ob, data, len as libc::size_t, markdown); }); sd_markdown_free(markdown); vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| { w.write(buf); }); bufrelease(ob); } } impl<'a> fmt::Default for Markdown<'a> { fn fmt(md: &Markdown<'a>, fmt: &mut fmt::Formatter) { // This is actually common enough to special-case if md.len() == 0 { return; } render(fmt.buf, md.as_slice()); } }
Markdown
identifier_name
markdown.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. //! Markdown formatting for rustdoc //! //! This module implements markdown formatting through the sundown C-library //! (bundled into the rust runtime). This module self-contains the C bindings //! and necessary legwork to render markdown, and exposes all of the //! functionality through a unit-struct, `Markdown`, which has an implementation //! of `fmt::Default`. Example usage: //! //! ```rust //! let s = "My *markdown* _text_"; //! let html = format!("{}", Markdown(s)); //! //... something using html //! ``` use std::fmt; use std::libc; use std::io; use std::vec; /// A unit struct which has the `fmt::Default` trait implemented. When /// formatted, this struct will emit the HTML corresponding to the rendered /// version of the contained markdown string. pub struct Markdown<'a>(&'a str); static OUTPUT_UNIT: libc::size_t = 64; static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0; static MKDEXT_TABLES: libc::c_uint = 1 << 1; static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2; static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3; static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4; type sd_markdown = libc::c_void; // this is opaque to us // this is a large struct of callbacks we don't use type sd_callbacks = [libc::size_t,..26]; struct html_toc_data { header_count: libc::c_int, current_level: libc::c_int, level_offset: libc::c_int, } struct html_renderopt { toc_data: html_toc_data, flags: libc::c_uint, link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>, } struct buf { data: *u8, size: libc::size_t, asize: libc::size_t, unit: libc::size_t, } // sundown FFI #[link(name = "sundown", kind = "static")] extern { fn sdhtml_renderer(callbacks: *sd_callbacks, options_ptr: *html_renderopt, render_flags: libc::c_uint); fn sd_markdown_new(extensions: libc::c_uint, max_nesting: libc::size_t, callbacks: *sd_callbacks, opaque: *libc::c_void) -> *sd_markdown; fn sd_markdown_render(ob: *buf, document: *u8, doc_size: libc::size_t, md: *sd_markdown); fn sd_markdown_free(md: *sd_markdown); fn bufnew(unit: libc::size_t) -> *buf; fn bufrelease(b: *buf); } fn render(w: &mut io::Writer, s: &str) { // This code is all lifted from examples/sundown.c in the sundown repo unsafe { let ob = bufnew(OUTPUT_UNIT); let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES | MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK | MKDEXT_STRIKETHROUGH; let options = html_renderopt { toc_data: html_toc_data { header_count: 0, current_level: 0, level_offset: 0, }, flags: 0, link_attributes: None, }; let callbacks: sd_callbacks = [0,..26]; sdhtml_renderer(&callbacks, &options, 0); let markdown = sd_markdown_new(extensions, 16, &callbacks, &options as *html_renderopt as *libc::c_void); s.as_imm_buf(|data, len| { sd_markdown_render(ob, data, len as libc::size_t, markdown); }); sd_markdown_free(markdown); vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| { w.write(buf); }); bufrelease(ob); } } impl<'a> fmt::Default for Markdown<'a> { fn fmt(md: &Markdown<'a>, fmt: &mut fmt::Formatter) { // This is actually common enough to special-case if md.len() == 0
render(fmt.buf, md.as_slice()); } }
{ return; }
conditional_block
htmlbrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document;
use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLBRElement { htmlelement: HTMLElement, } impl HTMLBRElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLBRElement { HTMLBRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLBRElement> { Node::reflect_node( Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), document, ) } }
use crate::dom::htmlelement::HTMLElement;
random_line_split
htmlbrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct
{ htmlelement: HTMLElement, } impl HTMLBRElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLBRElement { HTMLBRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLBRElement> { Node::reflect_node( Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), document, ) } }
HTMLBRElement
identifier_name
htmlbrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLBRElement { htmlelement: HTMLElement, } impl HTMLBRElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLBRElement
#[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLBRElement> { Node::reflect_node( Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), document, ) } }
{ HTMLBRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } }
identifier_body
aeabi_memcpy.rs
#![cfg(all( target_arch = "arm", not(any(target_env = "gnu", target_env = "musl")), target_os = "linux", feature = "mem" ))] #![feature(compiler_builtins_lib)] #![feature(lang_items)] #![no_std] extern crate compiler_builtins; // test runner extern crate utest_cortex_m_qemu; // overrides `panic!` #[macro_use] extern crate utest_macros; macro_rules! panic { ($($tt:tt)*) => {
fn __aeabi_memcpy(dest: *mut u8, src: *const u8, n: usize); fn __aeabi_memcpy4(dest: *mut u8, src: *const u8, n: usize); } struct Aligned { array: [u8; 8], _alignment: [u32; 0], } impl Aligned { fn new(array: [u8; 8]) -> Self { Aligned { array: array, _alignment: [], } } } #[test] fn memcpy() { let mut dest = [0; 4]; let src = [0xde, 0xad, 0xbe, 0xef]; for n in 0..dest.len() { dest.copy_from_slice(&[0; 4]); unsafe { __aeabi_memcpy(dest.as_mut_ptr(), src.as_ptr(), n) } assert_eq!(&dest[0..n], &src[0..n]) } } #[test] fn memcpy4() { let mut aligned = Aligned::new([0; 8]); let dest = &mut aligned.array; let src = [0xde, 0xad, 0xbe, 0xef, 0xba, 0xad, 0xf0, 0x0d]; for n in 0..dest.len() { dest.copy_from_slice(&[0; 8]); unsafe { __aeabi_memcpy4(dest.as_mut_ptr(), src.as_ptr(), n) } assert_eq!(&dest[0..n], &src[0..n]) } }
upanic!($($tt)*); }; } extern "C" {
random_line_split
aeabi_memcpy.rs
#![cfg(all( target_arch = "arm", not(any(target_env = "gnu", target_env = "musl")), target_os = "linux", feature = "mem" ))] #![feature(compiler_builtins_lib)] #![feature(lang_items)] #![no_std] extern crate compiler_builtins; // test runner extern crate utest_cortex_m_qemu; // overrides `panic!` #[macro_use] extern crate utest_macros; macro_rules! panic { ($($tt:tt)*) => { upanic!($($tt)*); }; } extern "C" { fn __aeabi_memcpy(dest: *mut u8, src: *const u8, n: usize); fn __aeabi_memcpy4(dest: *mut u8, src: *const u8, n: usize); } struct Aligned { array: [u8; 8], _alignment: [u32; 0], } impl Aligned { fn new(array: [u8; 8]) -> Self
} #[test] fn memcpy() { let mut dest = [0; 4]; let src = [0xde, 0xad, 0xbe, 0xef]; for n in 0..dest.len() { dest.copy_from_slice(&[0; 4]); unsafe { __aeabi_memcpy(dest.as_mut_ptr(), src.as_ptr(), n) } assert_eq!(&dest[0..n], &src[0..n]) } } #[test] fn memcpy4() { let mut aligned = Aligned::new([0; 8]); let dest = &mut aligned.array; let src = [0xde, 0xad, 0xbe, 0xef, 0xba, 0xad, 0xf0, 0x0d]; for n in 0..dest.len() { dest.copy_from_slice(&[0; 8]); unsafe { __aeabi_memcpy4(dest.as_mut_ptr(), src.as_ptr(), n) } assert_eq!(&dest[0..n], &src[0..n]) } }
{ Aligned { array: array, _alignment: [], } }
identifier_body
aeabi_memcpy.rs
#![cfg(all( target_arch = "arm", not(any(target_env = "gnu", target_env = "musl")), target_os = "linux", feature = "mem" ))] #![feature(compiler_builtins_lib)] #![feature(lang_items)] #![no_std] extern crate compiler_builtins; // test runner extern crate utest_cortex_m_qemu; // overrides `panic!` #[macro_use] extern crate utest_macros; macro_rules! panic { ($($tt:tt)*) => { upanic!($($tt)*); }; } extern "C" { fn __aeabi_memcpy(dest: *mut u8, src: *const u8, n: usize); fn __aeabi_memcpy4(dest: *mut u8, src: *const u8, n: usize); } struct Aligned { array: [u8; 8], _alignment: [u32; 0], } impl Aligned { fn
(array: [u8; 8]) -> Self { Aligned { array: array, _alignment: [], } } } #[test] fn memcpy() { let mut dest = [0; 4]; let src = [0xde, 0xad, 0xbe, 0xef]; for n in 0..dest.len() { dest.copy_from_slice(&[0; 4]); unsafe { __aeabi_memcpy(dest.as_mut_ptr(), src.as_ptr(), n) } assert_eq!(&dest[0..n], &src[0..n]) } } #[test] fn memcpy4() { let mut aligned = Aligned::new([0; 8]); let dest = &mut aligned.array; let src = [0xde, 0xad, 0xbe, 0xef, 0xba, 0xad, 0xf0, 0x0d]; for n in 0..dest.len() { dest.copy_from_slice(&[0; 8]); unsafe { __aeabi_memcpy4(dest.as_mut_ptr(), src.as_ptr(), n) } assert_eq!(&dest[0..n], &src[0..n]) } }
new
identifier_name
io.rs
/*! # Input and Output This module holds a single struct (`FC`) that keeps what would otherwise be global state of the running process. All the open file handles and sockets are stored here as well as helper functions to properly initialize the program and all the necessary packing and work to receive, log, and send any data. In many ways this is the guts of the flight computer. */ extern crate byteorder; use std::net::UdpSocket; use std::net::SocketAddrV4; use std::net::Ipv4Addr; use std::io::Error; use std::io::Cursor; use std::fs::File; use std::io::Write; use std::time; use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; /// Ports for data const PSAS_LISTEN_UDP_PORT: u16 = 36000; /// Port for outgoing telemetry const PSAS_TELEMETRY_UDP_PORT: u16 = 35001; /// Expected port for ADIS messages pub const PSAS_ADIS_PORT: u16 = 35020; /// Maximum size of single telemetry packet const P_LIMIT: usize = 1432; /// Size of PSAS Packet header const HEADER_SIZE: usize = 12; /// Message name (ASCII: SEQN) const SEQN_NAME: [u8;4] = [83, 69, 81, 78]; /// Sequence Error message size (bytes) pub const SIZE_OF_SEQE: usize = 10; /// Sequence Error message name (ASCII: SEQE) pub const SEQE_NAME: [u8;4] = [83, 69, 81, 69]; /// Flight Computer IO. /// /// Internally holds state for this implementation of the flight computer. /// This includes time (nanosecond counter from startup), a socket for /// listening for incoming data, a socket for sending data over the telemetry /// link, a log file, a running count of telemetry messages sent and a buffer /// for partly built telemetry messages. /// /// To initialize use the Default trait: /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// ``` pub struct FC { /// Instant we started boot_time: time::Instant, /// Socket to listen on for messages. fc_listen_socket: UdpSocket, /// Socket to send telemetry. telemetry_socket: UdpSocket, /// File to write data to. fc_log_file: File, /// Current count of telemetry messages sent. sequence_number: u32, /// Buffer of messages to build a telemetry Packet. telemetry_buffer: Vec<u8>, } // Reusable code for packing header into bytes fn pack_header(name: [u8; 4], time: time::Duration, message_size: usize) -> [u8; HEADER_SIZE] { let mut buffer = [0u8; HEADER_SIZE]; { let mut header = Cursor::<&mut [u8]>::new(&mut buffer); // Fields: // ID (Four character code) header.write(&name).unwrap(); // Timestamp, 6 bytes nanoseconds from boot let nanos: u64 = (time.as_secs() * 1000000000) + time.subsec_nanos() as u64; let mut time_buffer = [0u8; 8]; { let mut t = Cursor::<&mut [u8]>::new(&mut time_buffer); t.write_u64::<BigEndian>(nanos).unwrap(); } // Truncate to 6 least significant bytes header.write(&time_buffer[2..8]).unwrap(); // Size: header.write_u16::<BigEndian>(message_size as u16).unwrap(); } buffer } impl Default for FC { fn default () -> FC { // Boot time let boot_time = time::Instant::now(); let fc_listen_socket: UdpSocket; let telemetry_socket: UdpSocket; let fc_log_file: File; // Try and open listen socket match UdpSocket::bind(("0.0.0.0", PSAS_LISTEN_UDP_PORT)) { Ok(socket) =>
, Err(e) => { panic!(e) }, } // Try and open telemetry socket match UdpSocket::bind("0.0.0.0:0") { Ok(socket) => { telemetry_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open log file, loop until we find a name that's not taken let mut newfilenum = 0; loop { let filename = format!("logfile-{:03}", newfilenum); match File::open(filename) { // If this works, keep going Ok(_) => { newfilenum += 1; }, // If this fails, make a new file Err(_) => { break; } } } // We got here, so open the file match File::create(format!("logfile-{:03}", newfilenum)) { Ok(file) => { fc_log_file = file; }, Err(e) => { panic!(e) }, } // Put first sequence number (always 0) in the telemetry buffer. let mut telemetry_buffer = Vec::with_capacity(P_LIMIT); telemetry_buffer.extend_from_slice(&[0, 0, 0, 0]); // Initialise let mut fc = FC { boot_time: boot_time, fc_listen_socket: fc_listen_socket, telemetry_socket: telemetry_socket, fc_log_file: fc_log_file, sequence_number: 0, telemetry_buffer: telemetry_buffer, }; // Write log header fc.log_message(&[0, 0, 0, 0], SEQN_NAME, time::Duration::new(0, 0), 4).unwrap(); fc } } impl FC { /// Listen for messages from the network. /// /// This makes a blocking `read` call on the `fc_listen_socket`, waiting /// for any message from the outside world. Once received, it will deal /// with the sequence numbers in the header of the data and write the raw /// message to the passed in buffer. /// /// # Returns: /// /// An Option containing a tuple of data from the socket. The tuple /// contains: /// /// - **Sequence Number**: Sequence number from the header of the data packet /// - **Port**: Which port the data was sent _from_ /// - **Time**: The time that the message was received /// - **Message**: A message buffer that has raw bytes off the wire /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// /// if let Some((seqn, recv_port, recv_time, message)) = flight_computer.listen() { /// // Do something here with received data /// } /// ``` pub fn listen(&self) -> Option<(u32, u16, time::Duration, [u8; P_LIMIT - 4])> { // A buffer to put data in from the port. // Should at least be the size of telemetry message. let mut message_buffer = [0u8; P_LIMIT]; // Read from the socket (blocking!) // message_buffer gets filled and we get the number of bytes read // along with and address that the message came from match self.fc_listen_socket.recv_from(&mut message_buffer) { Ok((_, recv_addr)) => { // Get time for incoming data let recv_time = time::Instant::now().duration_since(self.boot_time); // First 4 bytes are the sequence number let mut buf = Cursor::new(&message_buffer[..4]); let seqn = buf.read_u32::<BigEndian>().unwrap(); // Rest of the bytes may be part of a message let mut message = [0u8; P_LIMIT - 4]; message.clone_from_slice(&message_buffer[4..P_LIMIT]); Some((seqn, recv_addr.port(), recv_time, message)) }, Err(_) => { None }, // continue } } /// Log a message to disk. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and writes it to /// disk. /// /// ## Parameters: /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// /// ## Returns: /// /// A Result with any errors. But we hope to never deal with a failure here /// (Greater care was taken in the original flight computer to not crash /// because of disk errors). pub fn log_message(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) -> Result<(), Error> { // Header: let header = pack_header(name, time, message_size); try!(self.fc_log_file.write(&header)); // message: try!(self.fc_log_file.write(&message[0..message_size])); Ok(()) } /// Send a message to the ground. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and queues it to /// be send out over the network once will fill the maximum size of a UDP /// packet. /// /// ## Parameters /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// pub fn telemetry(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) { // If we won't have room in the current packet, flush if (self.telemetry_buffer.len() + HEADER_SIZE + message_size) > P_LIMIT { self.flush_telemetry(); } // Header: let header = pack_header(name, time, message_size); self.telemetry_buffer.extend_from_slice(&header); // Message: self.telemetry_buffer.extend_from_slice(&message[0..message_size]); } /// This will actually send the now full and packed telemetry packet, /// and set us up for the next one. fn flush_telemetry(&mut self) { // Push out the door let telemetry_addr: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), PSAS_TELEMETRY_UDP_PORT); // When did we send this packet let send_time = time::Instant::now().duration_since(self.boot_time); self.telemetry_socket.send_to(&self.telemetry_buffer, telemetry_addr).unwrap(); // Increment SEQN self.sequence_number += 1; // Start telemetry buffer over self.telemetry_buffer.clear(); // Prepend with next sequence number let mut seqn = Vec::with_capacity(4); seqn.write_u32::<BigEndian>(self.sequence_number).unwrap(); self.telemetry_buffer.extend_from_slice(&mut seqn); // Keep track of sequence numbers in the flight computer log too self.log_message(&seqn, SEQN_NAME, send_time, 4).unwrap(); } } /// A sequence error message. /// /// When we miss a packet or get an out of order packet we should log that /// for future analysis. This stores a error and builds a log-able message. /// /// # Example /// /// ``` /// use rust_fc::io; /// /// let seqerror = io::SequenceError { /// port: 35020, /// expected: 12345, /// received: 12349, /// }; /// /// // Now you can log or send the message somewhere /// ``` pub struct SequenceError { /// Which port the packet error is from pub port: u16, /// Expected packet sequence number pub expected: u32, /// Actual received packet sequence number pub received: u32, } impl SequenceError { /// Return a copy of this struct as a byte array. /// /// The PSAS file and message type is always a byte array with big-endian /// representation of fields in a struct. pub fn as_message(&self) -> [u8; SIZE_OF_SEQE] { let mut buffer = [0u8; SIZE_OF_SEQE]; { let mut message = Cursor::<&mut [u8]>::new(&mut buffer); // Struct Fields: message.write_u16::<BigEndian>(self.port).unwrap(); message.write_u32::<BigEndian>(self.expected).unwrap(); message.write_u32::<BigEndian>(self.received).unwrap(); } buffer } }
{ fc_listen_socket = socket; }
conditional_block
io.rs
/*! # Input and Output This module holds a single struct (`FC`) that keeps what would otherwise be global state of the running process. All the open file handles and sockets are stored here as well as helper functions to properly initialize the program and all the necessary packing and work to receive, log, and send any data. In many ways this is the guts of the flight computer. */ extern crate byteorder; use std::net::UdpSocket; use std::net::SocketAddrV4; use std::net::Ipv4Addr; use std::io::Error; use std::io::Cursor; use std::fs::File; use std::io::Write; use std::time; use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; /// Ports for data const PSAS_LISTEN_UDP_PORT: u16 = 36000; /// Port for outgoing telemetry const PSAS_TELEMETRY_UDP_PORT: u16 = 35001; /// Expected port for ADIS messages pub const PSAS_ADIS_PORT: u16 = 35020; /// Maximum size of single telemetry packet const P_LIMIT: usize = 1432; /// Size of PSAS Packet header const HEADER_SIZE: usize = 12; /// Message name (ASCII: SEQN) const SEQN_NAME: [u8;4] = [83, 69, 81, 78]; /// Sequence Error message size (bytes) pub const SIZE_OF_SEQE: usize = 10; /// Sequence Error message name (ASCII: SEQE) pub const SEQE_NAME: [u8;4] = [83, 69, 81, 69]; /// Flight Computer IO. /// /// Internally holds state for this implementation of the flight computer. /// This includes time (nanosecond counter from startup), a socket for /// listening for incoming data, a socket for sending data over the telemetry /// link, a log file, a running count of telemetry messages sent and a buffer /// for partly built telemetry messages. /// /// To initialize use the Default trait: /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// ``` pub struct
{ /// Instant we started boot_time: time::Instant, /// Socket to listen on for messages. fc_listen_socket: UdpSocket, /// Socket to send telemetry. telemetry_socket: UdpSocket, /// File to write data to. fc_log_file: File, /// Current count of telemetry messages sent. sequence_number: u32, /// Buffer of messages to build a telemetry Packet. telemetry_buffer: Vec<u8>, } // Reusable code for packing header into bytes fn pack_header(name: [u8; 4], time: time::Duration, message_size: usize) -> [u8; HEADER_SIZE] { let mut buffer = [0u8; HEADER_SIZE]; { let mut header = Cursor::<&mut [u8]>::new(&mut buffer); // Fields: // ID (Four character code) header.write(&name).unwrap(); // Timestamp, 6 bytes nanoseconds from boot let nanos: u64 = (time.as_secs() * 1000000000) + time.subsec_nanos() as u64; let mut time_buffer = [0u8; 8]; { let mut t = Cursor::<&mut [u8]>::new(&mut time_buffer); t.write_u64::<BigEndian>(nanos).unwrap(); } // Truncate to 6 least significant bytes header.write(&time_buffer[2..8]).unwrap(); // Size: header.write_u16::<BigEndian>(message_size as u16).unwrap(); } buffer } impl Default for FC { fn default () -> FC { // Boot time let boot_time = time::Instant::now(); let fc_listen_socket: UdpSocket; let telemetry_socket: UdpSocket; let fc_log_file: File; // Try and open listen socket match UdpSocket::bind(("0.0.0.0", PSAS_LISTEN_UDP_PORT)) { Ok(socket) => { fc_listen_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open telemetry socket match UdpSocket::bind("0.0.0.0:0") { Ok(socket) => { telemetry_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open log file, loop until we find a name that's not taken let mut newfilenum = 0; loop { let filename = format!("logfile-{:03}", newfilenum); match File::open(filename) { // If this works, keep going Ok(_) => { newfilenum += 1; }, // If this fails, make a new file Err(_) => { break; } } } // We got here, so open the file match File::create(format!("logfile-{:03}", newfilenum)) { Ok(file) => { fc_log_file = file; }, Err(e) => { panic!(e) }, } // Put first sequence number (always 0) in the telemetry buffer. let mut telemetry_buffer = Vec::with_capacity(P_LIMIT); telemetry_buffer.extend_from_slice(&[0, 0, 0, 0]); // Initialise let mut fc = FC { boot_time: boot_time, fc_listen_socket: fc_listen_socket, telemetry_socket: telemetry_socket, fc_log_file: fc_log_file, sequence_number: 0, telemetry_buffer: telemetry_buffer, }; // Write log header fc.log_message(&[0, 0, 0, 0], SEQN_NAME, time::Duration::new(0, 0), 4).unwrap(); fc } } impl FC { /// Listen for messages from the network. /// /// This makes a blocking `read` call on the `fc_listen_socket`, waiting /// for any message from the outside world. Once received, it will deal /// with the sequence numbers in the header of the data and write the raw /// message to the passed in buffer. /// /// # Returns: /// /// An Option containing a tuple of data from the socket. The tuple /// contains: /// /// - **Sequence Number**: Sequence number from the header of the data packet /// - **Port**: Which port the data was sent _from_ /// - **Time**: The time that the message was received /// - **Message**: A message buffer that has raw bytes off the wire /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// /// if let Some((seqn, recv_port, recv_time, message)) = flight_computer.listen() { /// // Do something here with received data /// } /// ``` pub fn listen(&self) -> Option<(u32, u16, time::Duration, [u8; P_LIMIT - 4])> { // A buffer to put data in from the port. // Should at least be the size of telemetry message. let mut message_buffer = [0u8; P_LIMIT]; // Read from the socket (blocking!) // message_buffer gets filled and we get the number of bytes read // along with and address that the message came from match self.fc_listen_socket.recv_from(&mut message_buffer) { Ok((_, recv_addr)) => { // Get time for incoming data let recv_time = time::Instant::now().duration_since(self.boot_time); // First 4 bytes are the sequence number let mut buf = Cursor::new(&message_buffer[..4]); let seqn = buf.read_u32::<BigEndian>().unwrap(); // Rest of the bytes may be part of a message let mut message = [0u8; P_LIMIT - 4]; message.clone_from_slice(&message_buffer[4..P_LIMIT]); Some((seqn, recv_addr.port(), recv_time, message)) }, Err(_) => { None }, // continue } } /// Log a message to disk. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and writes it to /// disk. /// /// ## Parameters: /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// /// ## Returns: /// /// A Result with any errors. But we hope to never deal with a failure here /// (Greater care was taken in the original flight computer to not crash /// because of disk errors). pub fn log_message(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) -> Result<(), Error> { // Header: let header = pack_header(name, time, message_size); try!(self.fc_log_file.write(&header)); // message: try!(self.fc_log_file.write(&message[0..message_size])); Ok(()) } /// Send a message to the ground. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and queues it to /// be send out over the network once will fill the maximum size of a UDP /// packet. /// /// ## Parameters /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// pub fn telemetry(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) { // If we won't have room in the current packet, flush if (self.telemetry_buffer.len() + HEADER_SIZE + message_size) > P_LIMIT { self.flush_telemetry(); } // Header: let header = pack_header(name, time, message_size); self.telemetry_buffer.extend_from_slice(&header); // Message: self.telemetry_buffer.extend_from_slice(&message[0..message_size]); } /// This will actually send the now full and packed telemetry packet, /// and set us up for the next one. fn flush_telemetry(&mut self) { // Push out the door let telemetry_addr: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), PSAS_TELEMETRY_UDP_PORT); // When did we send this packet let send_time = time::Instant::now().duration_since(self.boot_time); self.telemetry_socket.send_to(&self.telemetry_buffer, telemetry_addr).unwrap(); // Increment SEQN self.sequence_number += 1; // Start telemetry buffer over self.telemetry_buffer.clear(); // Prepend with next sequence number let mut seqn = Vec::with_capacity(4); seqn.write_u32::<BigEndian>(self.sequence_number).unwrap(); self.telemetry_buffer.extend_from_slice(&mut seqn); // Keep track of sequence numbers in the flight computer log too self.log_message(&seqn, SEQN_NAME, send_time, 4).unwrap(); } } /// A sequence error message. /// /// When we miss a packet or get an out of order packet we should log that /// for future analysis. This stores a error and builds a log-able message. /// /// # Example /// /// ``` /// use rust_fc::io; /// /// let seqerror = io::SequenceError { /// port: 35020, /// expected: 12345, /// received: 12349, /// }; /// /// // Now you can log or send the message somewhere /// ``` pub struct SequenceError { /// Which port the packet error is from pub port: u16, /// Expected packet sequence number pub expected: u32, /// Actual received packet sequence number pub received: u32, } impl SequenceError { /// Return a copy of this struct as a byte array. /// /// The PSAS file and message type is always a byte array with big-endian /// representation of fields in a struct. pub fn as_message(&self) -> [u8; SIZE_OF_SEQE] { let mut buffer = [0u8; SIZE_OF_SEQE]; { let mut message = Cursor::<&mut [u8]>::new(&mut buffer); // Struct Fields: message.write_u16::<BigEndian>(self.port).unwrap(); message.write_u32::<BigEndian>(self.expected).unwrap(); message.write_u32::<BigEndian>(self.received).unwrap(); } buffer } }
FC
identifier_name
io.rs
/*! # Input and Output This module holds a single struct (`FC`) that keeps what would otherwise be global state of the running process. All the open file handles and sockets are stored here as well as helper functions to properly initialize the program and all the necessary packing and work to receive, log, and send any data. In many ways this is the guts of the flight computer. */ extern crate byteorder; use std::net::UdpSocket; use std::net::SocketAddrV4; use std::net::Ipv4Addr; use std::io::Error; use std::io::Cursor; use std::fs::File; use std::io::Write; use std::time; use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; /// Ports for data const PSAS_LISTEN_UDP_PORT: u16 = 36000; /// Port for outgoing telemetry const PSAS_TELEMETRY_UDP_PORT: u16 = 35001; /// Expected port for ADIS messages pub const PSAS_ADIS_PORT: u16 = 35020; /// Maximum size of single telemetry packet const P_LIMIT: usize = 1432; /// Size of PSAS Packet header const HEADER_SIZE: usize = 12; /// Message name (ASCII: SEQN) const SEQN_NAME: [u8;4] = [83, 69, 81, 78]; /// Sequence Error message size (bytes) pub const SIZE_OF_SEQE: usize = 10; /// Sequence Error message name (ASCII: SEQE) pub const SEQE_NAME: [u8;4] = [83, 69, 81, 69]; /// Flight Computer IO. /// /// Internally holds state for this implementation of the flight computer. /// This includes time (nanosecond counter from startup), a socket for /// listening for incoming data, a socket for sending data over the telemetry /// link, a log file, a running count of telemetry messages sent and a buffer /// for partly built telemetry messages. /// /// To initialize use the Default trait: /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// ``` pub struct FC { /// Instant we started boot_time: time::Instant, /// Socket to listen on for messages. fc_listen_socket: UdpSocket, /// Socket to send telemetry. telemetry_socket: UdpSocket, /// File to write data to. fc_log_file: File, /// Current count of telemetry messages sent. sequence_number: u32, /// Buffer of messages to build a telemetry Packet. telemetry_buffer: Vec<u8>, } // Reusable code for packing header into bytes fn pack_header(name: [u8; 4], time: time::Duration, message_size: usize) -> [u8; HEADER_SIZE] { let mut buffer = [0u8; HEADER_SIZE]; { let mut header = Cursor::<&mut [u8]>::new(&mut buffer); // Fields: // ID (Four character code) header.write(&name).unwrap(); // Timestamp, 6 bytes nanoseconds from boot let nanos: u64 = (time.as_secs() * 1000000000) + time.subsec_nanos() as u64; let mut time_buffer = [0u8; 8]; { let mut t = Cursor::<&mut [u8]>::new(&mut time_buffer); t.write_u64::<BigEndian>(nanos).unwrap(); } // Truncate to 6 least significant bytes header.write(&time_buffer[2..8]).unwrap(); // Size: header.write_u16::<BigEndian>(message_size as u16).unwrap(); } buffer } impl Default for FC { fn default () -> FC { // Boot time let boot_time = time::Instant::now(); let fc_listen_socket: UdpSocket; let telemetry_socket: UdpSocket; let fc_log_file: File; // Try and open listen socket match UdpSocket::bind(("0.0.0.0", PSAS_LISTEN_UDP_PORT)) { Ok(socket) => { fc_listen_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open telemetry socket match UdpSocket::bind("0.0.0.0:0") { Ok(socket) => { telemetry_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open log file, loop until we find a name that's not taken let mut newfilenum = 0; loop { let filename = format!("logfile-{:03}", newfilenum); match File::open(filename) { // If this works, keep going Ok(_) => { newfilenum += 1; }, // If this fails, make a new file Err(_) => { break; } } } // We got here, so open the file match File::create(format!("logfile-{:03}", newfilenum)) { Ok(file) => { fc_log_file = file; }, Err(e) => { panic!(e) }, } // Put first sequence number (always 0) in the telemetry buffer. let mut telemetry_buffer = Vec::with_capacity(P_LIMIT); telemetry_buffer.extend_from_slice(&[0, 0, 0, 0]); // Initialise let mut fc = FC { boot_time: boot_time, fc_listen_socket: fc_listen_socket, telemetry_socket: telemetry_socket, fc_log_file: fc_log_file, sequence_number: 0, telemetry_buffer: telemetry_buffer, }; // Write log header fc.log_message(&[0, 0, 0, 0], SEQN_NAME, time::Duration::new(0, 0), 4).unwrap(); fc } } impl FC { /// Listen for messages from the network. /// /// This makes a blocking `read` call on the `fc_listen_socket`, waiting /// for any message from the outside world. Once received, it will deal /// with the sequence numbers in the header of the data and write the raw /// message to the passed in buffer. /// /// # Returns: /// /// An Option containing a tuple of data from the socket. The tuple /// contains: /// /// - **Sequence Number**: Sequence number from the header of the data packet /// - **Port**: Which port the data was sent _from_ /// - **Time**: The time that the message was received /// - **Message**: A message buffer that has raw bytes off the wire /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// /// if let Some((seqn, recv_port, recv_time, message)) = flight_computer.listen() { /// // Do something here with received data /// } /// ``` pub fn listen(&self) -> Option<(u32, u16, time::Duration, [u8; P_LIMIT - 4])> { // A buffer to put data in from the port. // Should at least be the size of telemetry message. let mut message_buffer = [0u8; P_LIMIT]; // Read from the socket (blocking!) // message_buffer gets filled and we get the number of bytes read // along with and address that the message came from match self.fc_listen_socket.recv_from(&mut message_buffer) { Ok((_, recv_addr)) => { // Get time for incoming data let recv_time = time::Instant::now().duration_since(self.boot_time); // First 4 bytes are the sequence number let mut buf = Cursor::new(&message_buffer[..4]); let seqn = buf.read_u32::<BigEndian>().unwrap(); // Rest of the bytes may be part of a message let mut message = [0u8; P_LIMIT - 4]; message.clone_from_slice(&message_buffer[4..P_LIMIT]); Some((seqn, recv_addr.port(), recv_time, message)) }, Err(_) => { None }, // continue } } /// Log a message to disk. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and writes it to /// disk. /// /// ## Parameters: /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// /// ## Returns: /// /// A Result with any errors. But we hope to never deal with a failure here /// (Greater care was taken in the original flight computer to not crash /// because of disk errors). pub fn log_message(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) -> Result<(), Error> { // Header: let header = pack_header(name, time, message_size); try!(self.fc_log_file.write(&header)); // message: try!(self.fc_log_file.write(&message[0..message_size])); Ok(()) } /// Send a message to the ground. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and queues it to /// be send out over the network once will fill the maximum size of a UDP /// packet. /// /// ## Parameters /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// pub fn telemetry(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) { // If we won't have room in the current packet, flush if (self.telemetry_buffer.len() + HEADER_SIZE + message_size) > P_LIMIT { self.flush_telemetry(); } // Header: let header = pack_header(name, time, message_size); self.telemetry_buffer.extend_from_slice(&header); // Message: self.telemetry_buffer.extend_from_slice(&message[0..message_size]); } /// This will actually send the now full and packed telemetry packet, /// and set us up for the next one. fn flush_telemetry(&mut self) { // Push out the door let telemetry_addr: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), PSAS_TELEMETRY_UDP_PORT); // When did we send this packet let send_time = time::Instant::now().duration_since(self.boot_time); self.telemetry_socket.send_to(&self.telemetry_buffer, telemetry_addr).unwrap(); // Increment SEQN self.sequence_number += 1; // Start telemetry buffer over self.telemetry_buffer.clear(); // Prepend with next sequence number let mut seqn = Vec::with_capacity(4); seqn.write_u32::<BigEndian>(self.sequence_number).unwrap(); self.telemetry_buffer.extend_from_slice(&mut seqn); // Keep track of sequence numbers in the flight computer log too self.log_message(&seqn, SEQN_NAME, send_time, 4).unwrap(); } } /// A sequence error message. /// /// When we miss a packet or get an out of order packet we should log that /// for future analysis. This stores a error and builds a log-able message. /// /// # Example /// /// ``` /// use rust_fc::io; /// /// let seqerror = io::SequenceError { /// port: 35020, /// expected: 12345, /// received: 12349, /// }; /// /// // Now you can log or send the message somewhere /// ``` pub struct SequenceError { /// Which port the packet error is from pub port: u16, /// Expected packet sequence number pub expected: u32, /// Actual received packet sequence number pub received: u32, } impl SequenceError { /// Return a copy of this struct as a byte array. /// /// The PSAS file and message type is always a byte array with big-endian /// representation of fields in a struct. pub fn as_message(&self) -> [u8; SIZE_OF_SEQE]
}
{ let mut buffer = [0u8; SIZE_OF_SEQE]; { let mut message = Cursor::<&mut [u8]>::new(&mut buffer); // Struct Fields: message.write_u16::<BigEndian>(self.port).unwrap(); message.write_u32::<BigEndian>(self.expected).unwrap(); message.write_u32::<BigEndian>(self.received).unwrap(); } buffer }
identifier_body
io.rs
/*! # Input and Output This module holds a single struct (`FC`) that keeps what would otherwise be global
here as well as helper functions to properly initialize the program and all the necessary packing and work to receive, log, and send any data. In many ways this is the guts of the flight computer. */ extern crate byteorder; use std::net::UdpSocket; use std::net::SocketAddrV4; use std::net::Ipv4Addr; use std::io::Error; use std::io::Cursor; use std::fs::File; use std::io::Write; use std::time; use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; /// Ports for data const PSAS_LISTEN_UDP_PORT: u16 = 36000; /// Port for outgoing telemetry const PSAS_TELEMETRY_UDP_PORT: u16 = 35001; /// Expected port for ADIS messages pub const PSAS_ADIS_PORT: u16 = 35020; /// Maximum size of single telemetry packet const P_LIMIT: usize = 1432; /// Size of PSAS Packet header const HEADER_SIZE: usize = 12; /// Message name (ASCII: SEQN) const SEQN_NAME: [u8;4] = [83, 69, 81, 78]; /// Sequence Error message size (bytes) pub const SIZE_OF_SEQE: usize = 10; /// Sequence Error message name (ASCII: SEQE) pub const SEQE_NAME: [u8;4] = [83, 69, 81, 69]; /// Flight Computer IO. /// /// Internally holds state for this implementation of the flight computer. /// This includes time (nanosecond counter from startup), a socket for /// listening for incoming data, a socket for sending data over the telemetry /// link, a log file, a running count of telemetry messages sent and a buffer /// for partly built telemetry messages. /// /// To initialize use the Default trait: /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// ``` pub struct FC { /// Instant we started boot_time: time::Instant, /// Socket to listen on for messages. fc_listen_socket: UdpSocket, /// Socket to send telemetry. telemetry_socket: UdpSocket, /// File to write data to. fc_log_file: File, /// Current count of telemetry messages sent. sequence_number: u32, /// Buffer of messages to build a telemetry Packet. telemetry_buffer: Vec<u8>, } // Reusable code for packing header into bytes fn pack_header(name: [u8; 4], time: time::Duration, message_size: usize) -> [u8; HEADER_SIZE] { let mut buffer = [0u8; HEADER_SIZE]; { let mut header = Cursor::<&mut [u8]>::new(&mut buffer); // Fields: // ID (Four character code) header.write(&name).unwrap(); // Timestamp, 6 bytes nanoseconds from boot let nanos: u64 = (time.as_secs() * 1000000000) + time.subsec_nanos() as u64; let mut time_buffer = [0u8; 8]; { let mut t = Cursor::<&mut [u8]>::new(&mut time_buffer); t.write_u64::<BigEndian>(nanos).unwrap(); } // Truncate to 6 least significant bytes header.write(&time_buffer[2..8]).unwrap(); // Size: header.write_u16::<BigEndian>(message_size as u16).unwrap(); } buffer } impl Default for FC { fn default () -> FC { // Boot time let boot_time = time::Instant::now(); let fc_listen_socket: UdpSocket; let telemetry_socket: UdpSocket; let fc_log_file: File; // Try and open listen socket match UdpSocket::bind(("0.0.0.0", PSAS_LISTEN_UDP_PORT)) { Ok(socket) => { fc_listen_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open telemetry socket match UdpSocket::bind("0.0.0.0:0") { Ok(socket) => { telemetry_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open log file, loop until we find a name that's not taken let mut newfilenum = 0; loop { let filename = format!("logfile-{:03}", newfilenum); match File::open(filename) { // If this works, keep going Ok(_) => { newfilenum += 1; }, // If this fails, make a new file Err(_) => { break; } } } // We got here, so open the file match File::create(format!("logfile-{:03}", newfilenum)) { Ok(file) => { fc_log_file = file; }, Err(e) => { panic!(e) }, } // Put first sequence number (always 0) in the telemetry buffer. let mut telemetry_buffer = Vec::with_capacity(P_LIMIT); telemetry_buffer.extend_from_slice(&[0, 0, 0, 0]); // Initialise let mut fc = FC { boot_time: boot_time, fc_listen_socket: fc_listen_socket, telemetry_socket: telemetry_socket, fc_log_file: fc_log_file, sequence_number: 0, telemetry_buffer: telemetry_buffer, }; // Write log header fc.log_message(&[0, 0, 0, 0], SEQN_NAME, time::Duration::new(0, 0), 4).unwrap(); fc } } impl FC { /// Listen for messages from the network. /// /// This makes a blocking `read` call on the `fc_listen_socket`, waiting /// for any message from the outside world. Once received, it will deal /// with the sequence numbers in the header of the data and write the raw /// message to the passed in buffer. /// /// # Returns: /// /// An Option containing a tuple of data from the socket. The tuple /// contains: /// /// - **Sequence Number**: Sequence number from the header of the data packet /// - **Port**: Which port the data was sent _from_ /// - **Time**: The time that the message was received /// - **Message**: A message buffer that has raw bytes off the wire /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// /// if let Some((seqn, recv_port, recv_time, message)) = flight_computer.listen() { /// // Do something here with received data /// } /// ``` pub fn listen(&self) -> Option<(u32, u16, time::Duration, [u8; P_LIMIT - 4])> { // A buffer to put data in from the port. // Should at least be the size of telemetry message. let mut message_buffer = [0u8; P_LIMIT]; // Read from the socket (blocking!) // message_buffer gets filled and we get the number of bytes read // along with and address that the message came from match self.fc_listen_socket.recv_from(&mut message_buffer) { Ok((_, recv_addr)) => { // Get time for incoming data let recv_time = time::Instant::now().duration_since(self.boot_time); // First 4 bytes are the sequence number let mut buf = Cursor::new(&message_buffer[..4]); let seqn = buf.read_u32::<BigEndian>().unwrap(); // Rest of the bytes may be part of a message let mut message = [0u8; P_LIMIT - 4]; message.clone_from_slice(&message_buffer[4..P_LIMIT]); Some((seqn, recv_addr.port(), recv_time, message)) }, Err(_) => { None }, // continue } } /// Log a message to disk. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and writes it to /// disk. /// /// ## Parameters: /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// /// ## Returns: /// /// A Result with any errors. But we hope to never deal with a failure here /// (Greater care was taken in the original flight computer to not crash /// because of disk errors). pub fn log_message(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) -> Result<(), Error> { // Header: let header = pack_header(name, time, message_size); try!(self.fc_log_file.write(&header)); // message: try!(self.fc_log_file.write(&message[0..message_size])); Ok(()) } /// Send a message to the ground. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and queues it to /// be send out over the network once will fill the maximum size of a UDP /// packet. /// /// ## Parameters /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// pub fn telemetry(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) { // If we won't have room in the current packet, flush if (self.telemetry_buffer.len() + HEADER_SIZE + message_size) > P_LIMIT { self.flush_telemetry(); } // Header: let header = pack_header(name, time, message_size); self.telemetry_buffer.extend_from_slice(&header); // Message: self.telemetry_buffer.extend_from_slice(&message[0..message_size]); } /// This will actually send the now full and packed telemetry packet, /// and set us up for the next one. fn flush_telemetry(&mut self) { // Push out the door let telemetry_addr: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), PSAS_TELEMETRY_UDP_PORT); // When did we send this packet let send_time = time::Instant::now().duration_since(self.boot_time); self.telemetry_socket.send_to(&self.telemetry_buffer, telemetry_addr).unwrap(); // Increment SEQN self.sequence_number += 1; // Start telemetry buffer over self.telemetry_buffer.clear(); // Prepend with next sequence number let mut seqn = Vec::with_capacity(4); seqn.write_u32::<BigEndian>(self.sequence_number).unwrap(); self.telemetry_buffer.extend_from_slice(&mut seqn); // Keep track of sequence numbers in the flight computer log too self.log_message(&seqn, SEQN_NAME, send_time, 4).unwrap(); } } /// A sequence error message. /// /// When we miss a packet or get an out of order packet we should log that /// for future analysis. This stores a error and builds a log-able message. /// /// # Example /// /// ``` /// use rust_fc::io; /// /// let seqerror = io::SequenceError { /// port: 35020, /// expected: 12345, /// received: 12349, /// }; /// /// // Now you can log or send the message somewhere /// ``` pub struct SequenceError { /// Which port the packet error is from pub port: u16, /// Expected packet sequence number pub expected: u32, /// Actual received packet sequence number pub received: u32, } impl SequenceError { /// Return a copy of this struct as a byte array. /// /// The PSAS file and message type is always a byte array with big-endian /// representation of fields in a struct. pub fn as_message(&self) -> [u8; SIZE_OF_SEQE] { let mut buffer = [0u8; SIZE_OF_SEQE]; { let mut message = Cursor::<&mut [u8]>::new(&mut buffer); // Struct Fields: message.write_u16::<BigEndian>(self.port).unwrap(); message.write_u32::<BigEndian>(self.expected).unwrap(); message.write_u32::<BigEndian>(self.received).unwrap(); } buffer } }
state of the running process. All the open file handles and sockets are stored
random_line_split
row.rs
use blas::{Copy, Gemv}; use Forward; use onezero::{One, Zero}; use ops::{set, self}; use traits::Transpose as _0; use traits::{Matrix, Set, Slice, SliceMut}; use {Product, RowMut, Row, RowVec, Scaled, SubMat, Transposed}; // NOTE Core impl<'a, T> Set<T> for RowMut<'a, T> where T: Copy { fn set(&mut self, value: T) { let RowMut(Row(ref mut y)) = *self; let ref x = value; set::strided(x, y) } } // NOTE Core impl<'a, 'b, T> Set<Row<'a, T>> for RowMut<'b, T> where T: Copy { fn set(&mut self, rhs: Row<T>) { unsafe { assert_eq!(self.ncols(), rhs.ncols()); let RowMut(Row(ref mut y)) = *self; let Row(ref x) = rhs; ops::copy_strided(x, y) } } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Scaled<Product<Row<'b, T>, SubMat<'a, T>>>> for RowMut<'c, T> where T: Gemv + Zero, { fn
(&mut self, rhs: Scaled<Product<Row<T>, SubMat<T>>>) { self.slice_mut(..).t().set(rhs.t()) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Scaled<Product<Row<'b, T>, Transposed<SubMat<'a, T>>>>> for RowMut<'c, T> where T: Gemv + Zero, { fn set(&mut self, rhs: Scaled<Product<Row<T>, Transposed<SubMat<T>>>>) { self.slice_mut(..).t().set(rhs.t()) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Product<Row<'b, T>, SubMat<'a, T>>> for RowMut<'c, T> where T: Gemv + One + Zero, { fn set(&mut self, rhs: Product<Row<T>, SubMat<T>>) { self.set(Scaled(T::one(), rhs)) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Product<Row<'b, T>, Transposed<SubMat<'a, T>>>> for RowMut<'c, T> where T: Gemv + One + Zero, { fn set(&mut self, rhs: Product<Row<T>, Transposed<SubMat<T>>>) { self.set(Scaled(T::one(), rhs)) } } // NOTE Forward impl<T> Set<T> for RowVec<T> where T: Copy { fn set(&mut self, value: T) { self.slice_mut(..).set(value) } } macro_rules! forward { ($lhs:ty { $($rhs:ty { $($bound:ident),+ }),+, }) => { $( // NOTE Forward impl<'a, 'b, 'c, T> Set<$rhs> for $lhs where $(T: $bound),+ { fn set(&mut self, rhs: $rhs) { self.slice_mut(..).set(rhs.slice(..)) } } )+ } } forward!(RowMut<'a, T> { &'b RowMut<'c, T> { Copy }, &'b RowVec<T> { Copy }, }); forward!(RowVec<T> { &'a RowMut<'b, T> { Copy }, &'a RowVec<T> { Copy }, Product<Row<'a, T>, SubMat<'b, T>> { Gemv, One, Zero }, Product<Row<'a, T>, Transposed<SubMat<'b, T>>> { Gemv, One, Zero }, Scaled<Product<Row<'a, T>, SubMat<'b, T>>> { Gemv, Zero }, Scaled<Product<Row<'a, T>, Transposed<SubMat<'b, T>>>> { Gemv, Zero }, });
set
identifier_name
row.rs
use blas::{Copy, Gemv}; use Forward; use onezero::{One, Zero}; use ops::{set, self}; use traits::Transpose as _0; use traits::{Matrix, Set, Slice, SliceMut}; use {Product, RowMut, Row, RowVec, Scaled, SubMat, Transposed}; // NOTE Core impl<'a, T> Set<T> for RowMut<'a, T> where T: Copy { fn set(&mut self, value: T) { let RowMut(Row(ref mut y)) = *self; let ref x = value; set::strided(x, y) } } // NOTE Core impl<'a, 'b, T> Set<Row<'a, T>> for RowMut<'b, T> where T: Copy { fn set(&mut self, rhs: Row<T>) { unsafe { assert_eq!(self.ncols(), rhs.ncols()); let RowMut(Row(ref mut y)) = *self; let Row(ref x) = rhs; ops::copy_strided(x, y) } } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Scaled<Product<Row<'b, T>, SubMat<'a, T>>>> for RowMut<'c, T> where T: Gemv + Zero, { fn set(&mut self, rhs: Scaled<Product<Row<T>, SubMat<T>>>)
} // NOTE Secondary impl<'a, 'b, 'c, T> Set<Scaled<Product<Row<'b, T>, Transposed<SubMat<'a, T>>>>> for RowMut<'c, T> where T: Gemv + Zero, { fn set(&mut self, rhs: Scaled<Product<Row<T>, Transposed<SubMat<T>>>>) { self.slice_mut(..).t().set(rhs.t()) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Product<Row<'b, T>, SubMat<'a, T>>> for RowMut<'c, T> where T: Gemv + One + Zero, { fn set(&mut self, rhs: Product<Row<T>, SubMat<T>>) { self.set(Scaled(T::one(), rhs)) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Product<Row<'b, T>, Transposed<SubMat<'a, T>>>> for RowMut<'c, T> where T: Gemv + One + Zero, { fn set(&mut self, rhs: Product<Row<T>, Transposed<SubMat<T>>>) { self.set(Scaled(T::one(), rhs)) } } // NOTE Forward impl<T> Set<T> for RowVec<T> where T: Copy { fn set(&mut self, value: T) { self.slice_mut(..).set(value) } } macro_rules! forward { ($lhs:ty { $($rhs:ty { $($bound:ident),+ }),+, }) => { $( // NOTE Forward impl<'a, 'b, 'c, T> Set<$rhs> for $lhs where $(T: $bound),+ { fn set(&mut self, rhs: $rhs) { self.slice_mut(..).set(rhs.slice(..)) } } )+ } } forward!(RowMut<'a, T> { &'b RowMut<'c, T> { Copy }, &'b RowVec<T> { Copy }, }); forward!(RowVec<T> { &'a RowMut<'b, T> { Copy }, &'a RowVec<T> { Copy }, Product<Row<'a, T>, SubMat<'b, T>> { Gemv, One, Zero }, Product<Row<'a, T>, Transposed<SubMat<'b, T>>> { Gemv, One, Zero }, Scaled<Product<Row<'a, T>, SubMat<'b, T>>> { Gemv, Zero }, Scaled<Product<Row<'a, T>, Transposed<SubMat<'b, T>>>> { Gemv, Zero }, });
{ self.slice_mut(..).t().set(rhs.t()) }
identifier_body
row.rs
use blas::{Copy, Gemv}; use Forward; use onezero::{One, Zero}; use ops::{set, self}; use traits::Transpose as _0; use traits::{Matrix, Set, Slice, SliceMut}; use {Product, RowMut, Row, RowVec, Scaled, SubMat, Transposed}; // NOTE Core impl<'a, T> Set<T> for RowMut<'a, T> where T: Copy { fn set(&mut self, value: T) { let RowMut(Row(ref mut y)) = *self; let ref x = value; set::strided(x, y) } } // NOTE Core impl<'a, 'b, T> Set<Row<'a, T>> for RowMut<'b, T> where T: Copy { fn set(&mut self, rhs: Row<T>) { unsafe { assert_eq!(self.ncols(), rhs.ncols()); let RowMut(Row(ref mut y)) = *self; let Row(ref x) = rhs; ops::copy_strided(x, y) } }
// NOTE Secondary impl<'a, 'b, 'c, T> Set<Scaled<Product<Row<'b, T>, SubMat<'a, T>>>> for RowMut<'c, T> where T: Gemv + Zero, { fn set(&mut self, rhs: Scaled<Product<Row<T>, SubMat<T>>>) { self.slice_mut(..).t().set(rhs.t()) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Scaled<Product<Row<'b, T>, Transposed<SubMat<'a, T>>>>> for RowMut<'c, T> where T: Gemv + Zero, { fn set(&mut self, rhs: Scaled<Product<Row<T>, Transposed<SubMat<T>>>>) { self.slice_mut(..).t().set(rhs.t()) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Product<Row<'b, T>, SubMat<'a, T>>> for RowMut<'c, T> where T: Gemv + One + Zero, { fn set(&mut self, rhs: Product<Row<T>, SubMat<T>>) { self.set(Scaled(T::one(), rhs)) } } // NOTE Secondary impl<'a, 'b, 'c, T> Set<Product<Row<'b, T>, Transposed<SubMat<'a, T>>>> for RowMut<'c, T> where T: Gemv + One + Zero, { fn set(&mut self, rhs: Product<Row<T>, Transposed<SubMat<T>>>) { self.set(Scaled(T::one(), rhs)) } } // NOTE Forward impl<T> Set<T> for RowVec<T> where T: Copy { fn set(&mut self, value: T) { self.slice_mut(..).set(value) } } macro_rules! forward { ($lhs:ty { $($rhs:ty { $($bound:ident),+ }),+, }) => { $( // NOTE Forward impl<'a, 'b, 'c, T> Set<$rhs> for $lhs where $(T: $bound),+ { fn set(&mut self, rhs: $rhs) { self.slice_mut(..).set(rhs.slice(..)) } } )+ } } forward!(RowMut<'a, T> { &'b RowMut<'c, T> { Copy }, &'b RowVec<T> { Copy }, }); forward!(RowVec<T> { &'a RowMut<'b, T> { Copy }, &'a RowVec<T> { Copy }, Product<Row<'a, T>, SubMat<'b, T>> { Gemv, One, Zero }, Product<Row<'a, T>, Transposed<SubMat<'b, T>>> { Gemv, One, Zero }, Scaled<Product<Row<'a, T>, SubMat<'b, T>>> { Gemv, Zero }, Scaled<Product<Row<'a, T>, Transposed<SubMat<'b, T>>>> { Gemv, Zero }, });
}
random_line_split
lib.rs
#![allow(non_upper_case_globals)] #![deny(missing_docs)] // Copyright 2015 Adrien Champion. See the COPYRIGHT file at the top-level // directory of this distribution. // // 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. /*! Transition system library. ## Hash consing [`Sym`][sym type] and [`Term`][term type] come from the kinō [`term`][term crate] crate and are hash consed. Remember that one should **never** create more that one [Factory][factory struct] for these. It is thread-safe and can be cloned. [`Context`][context struct] holds one for parsing. ## Thread-safety All constructions related to systems (`Sys`, `Prop`, `Args`, *etc.*) are wrapped in an `Arc` and thus are thread-safe. ## To do * more clever input consumption in [`Context`][context struct] * less copy in [`Context`][context struct] * more informative parse error (depency checking) * spanned parse errors * integrate type checking in parser * support for `stdin`-like input [sym type]:../term/type.Sym.html (Sym type) [term type]:../term/type.Term.html (Term type) [term crate]:../term/index.html (term crate) [factory struct]:../term/struct.Factory.html (Factory struct) [context struct]: ctxt/struct.Context.html (Context struct) */ #[macro_use] extern crate nom ; #[macro_use] extern crate error_chain ; #[macro_use] extern crate term ; use std::sync::Arc ; use std::fmt ; /// A line with a line number, a sub line indicating something in the line, /// and a column number. #[derive(Debug)] pub struct Line { /// The line. pub line: String, /// The subline showing something in the line above. pub subline: String, /// The line number of the line. pub l: usize, /// The column of the token of interest in the line. pub c: usize, } impl Line { /// Creates a line. #[inline] pub fn mk(line: String, subline: String, l: usize, c: usize) -> Self { Line { line: line, subline: subline, l: l, c: c } } } impl fmt::Display for Line { fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result { write!(fmt, "[{}:{}] `{}`", self.line, self.l, self.c) } } /// Errors. #[derive(Debug)] pub enum Error { /// Parse error. Parse { /// Line of the error. line: Line, /// Description of the error. blah: String, /// Optional notes about the error. notes: Vec<(Line, String)> }, /// IO error. Io(::std::io::Error) } impl Error { /// Creates a parsing error. #[inline] pub fn parse_mk( line: Line, blah: String, notes: Vec<(Line, String)> ) -> Self { Error::Parse { line: line, blah: blah, notes: notes } } /// Prints an internal parse error. #[cfg(test)] pub fn print(& self) { match * self { Error::Parse { ref line, ref blah, ref notes } => { println!("parse error {}: {}", line, blah) ; for & (ref line, ref blah) in notes { println!("| {}: {}", line, blah) } }, Error::Io(ref e) => println!("io error: {:?}", e) } } } impl fmt::Display for Error { fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result { match * self { Error::Parse { ref line, ref blah,.. } => write!( fmt, "{} in line {}", blah, line ), Error::Io(ref e) => write!(fmt, "io error: {:?}", e), } } } mod base ; mod type_check ; mod parse ; /// Real types of the elements of a context.
} /// Parses, type checks and remembers the input. pub mod ctxt { pub use super::base::Callable ; pub use super::parse::{ Res, Context } ; pub use super::parse::check::CheckError ; pub use type_check::type_check ; } pub use base::{ CallSet, PropStatus } ; pub use parse::Cex ; /// A signature, a list of types. Used only in `Uf`. pub type Sig = Arc<base::Sig> ; /// A list of typed formal parameters. pub type Args = Arc<base::Args> ; /// An uninterpreted function. pub type Uf = Arc<base::Uf> ; /// A function (actually a macro in SMT-LIB). pub type Fun = Arc<base::Fun> ; /// Wraps an (uninterpreted) function. pub type Callable = Arc<base::Callable> ; /// A property. pub type Prop = Arc<base::Prop> ; /// A transition system. pub type Sys = Arc<base::Sys> ;
pub mod real_sys { pub use base::{ Sig, Args, Uf, Fun, Prop, Sys, Callable } ;
random_line_split
lib.rs
#![allow(non_upper_case_globals)] #![deny(missing_docs)] // Copyright 2015 Adrien Champion. See the COPYRIGHT file at the top-level // directory of this distribution. // // 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. /*! Transition system library. ## Hash consing [`Sym`][sym type] and [`Term`][term type] come from the kinō [`term`][term crate] crate and are hash consed. Remember that one should **never** create more that one [Factory][factory struct] for these. It is thread-safe and can be cloned. [`Context`][context struct] holds one for parsing. ## Thread-safety All constructions related to systems (`Sys`, `Prop`, `Args`, *etc.*) are wrapped in an `Arc` and thus are thread-safe. ## To do * more clever input consumption in [`Context`][context struct] * less copy in [`Context`][context struct] * more informative parse error (depency checking) * spanned parse errors * integrate type checking in parser * support for `stdin`-like input [sym type]:../term/type.Sym.html (Sym type) [term type]:../term/type.Term.html (Term type) [term crate]:../term/index.html (term crate) [factory struct]:../term/struct.Factory.html (Factory struct) [context struct]: ctxt/struct.Context.html (Context struct) */ #[macro_use] extern crate nom ; #[macro_use] extern crate error_chain ; #[macro_use] extern crate term ; use std::sync::Arc ; use std::fmt ; /// A line with a line number, a sub line indicating something in the line, /// and a column number. #[derive(Debug)] pub struct Line { /// The line. pub line: String, /// The subline showing something in the line above. pub subline: String, /// The line number of the line. pub l: usize, /// The column of the token of interest in the line. pub c: usize, } impl Line { /// Creates a line. #[inline] pub fn mk(line: String, subline: String, l: usize, c: usize) -> Self { Line { line: line, subline: subline, l: l, c: c } } } impl fmt::Display for Line { fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result { write!(fmt, "[{}:{}] `{}`", self.line, self.l, self.c) } } /// Errors. #[derive(Debug)] pub enum Error { /// Parse error. Parse { /// Line of the error. line: Line, /// Description of the error. blah: String, /// Optional notes about the error. notes: Vec<(Line, String)> }, /// IO error. Io(::std::io::Error) } impl Error { /// Creates a parsing error. #[inline] pub fn parse_mk( line: Line, blah: String, notes: Vec<(Line, String)> ) -> Self { Error::Parse { line: line, blah: blah, notes: notes } } /// Prints an internal parse error. #[cfg(test)] pub fn p
& self) { match * self { Error::Parse { ref line, ref blah, ref notes } => { println!("parse error {}: {}", line, blah) ; for & (ref line, ref blah) in notes { println!("| {}: {}", line, blah) } }, Error::Io(ref e) => println!("io error: {:?}", e) } } } impl fmt::Display for Error { fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result { match * self { Error::Parse { ref line, ref blah,.. } => write!( fmt, "{} in line {}", blah, line ), Error::Io(ref e) => write!(fmt, "io error: {:?}", e), } } } mod base ; mod type_check ; mod parse ; /// Real types of the elements of a context. pub mod real_sys { pub use base::{ Sig, Args, Uf, Fun, Prop, Sys, Callable } ; } /// Parses, type checks and remembers the input. pub mod ctxt { pub use super::base::Callable ; pub use super::parse::{ Res, Context } ; pub use super::parse::check::CheckError ; pub use type_check::type_check ; } pub use base::{ CallSet, PropStatus } ; pub use parse::Cex ; /// A signature, a list of types. Used only in `Uf`. pub type Sig = Arc<base::Sig> ; /// A list of typed formal parameters. pub type Args = Arc<base::Args> ; /// An uninterpreted function. pub type Uf = Arc<base::Uf> ; /// A function (actually a macro in SMT-LIB). pub type Fun = Arc<base::Fun> ; /// Wraps an (uninterpreted) function. pub type Callable = Arc<base::Callable> ; /// A property. pub type Prop = Arc<base::Prop> ; /// A transition system. pub type Sys = Arc<base::Sys> ;
rint(
identifier_name
domainxover.rs
use super::{lerp, PVocDescriptor, PVocPlugin}; use ladspa::{DefaultValue, Plugin, PluginDescriptor, Port, PortConnection, PortDescriptor}; use pvoc::{Bin, PhaseVocoder}; plugin!(DomainXOver); struct DomainXOver; impl PVocPlugin for DomainXOver { fn
() -> PVocDescriptor { PVocDescriptor { name: "pvoc domain crossover", author: "Noah Weninger", channels: 1, ports: vec![ Port { name: "Add", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Value0), lower_bound: Some(0.0), upper_bound: Some(25.0), }, Port { name: "Shift", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Value0), lower_bound: Some(0.0), upper_bound: Some(1.0), }, Port { name: "Alpha", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Middle), lower_bound: Some(0.0), upper_bound: Some(1.0), }, ], } } fn new(_: usize, _: f64, _: usize, _: usize) -> DomainXOver { DomainXOver } fn process( &mut self, ports: &[f64], sample_rate: f64, channels: usize, bins: usize, input: &[Vec<Bin>], output: &mut [Vec<Bin>], ) { let freq_per_bin = sample_rate / (bins as f64); let add = ports[0]; let shift = ports[1]; let alpha = ports[2]; for i in 0..channels { let mut avg = input[i][0].amp; for j in 0..bins { output[i][j].freq = input[i][j].freq + shift * freq_per_bin + ((avg - input[i][j].amp) * add); output[i][j].amp = input[i][j].amp; avg = lerp(avg, input[i][j].amp, alpha); } } } }
descriptor
identifier_name
domainxover.rs
use super::{lerp, PVocDescriptor, PVocPlugin}; use ladspa::{DefaultValue, Plugin, PluginDescriptor, Port, PortConnection, PortDescriptor}; use pvoc::{Bin, PhaseVocoder}; plugin!(DomainXOver); struct DomainXOver; impl PVocPlugin for DomainXOver { fn descriptor() -> PVocDescriptor { PVocDescriptor { name: "pvoc domain crossover", author: "Noah Weninger", channels: 1, ports: vec![ Port { name: "Add", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Value0), lower_bound: Some(0.0), upper_bound: Some(25.0), }, Port { name: "Shift", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Value0), lower_bound: Some(0.0), upper_bound: Some(1.0), }, Port { name: "Alpha", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Middle), lower_bound: Some(0.0), upper_bound: Some(1.0), }, ], }
DomainXOver } fn process( &mut self, ports: &[f64], sample_rate: f64, channels: usize, bins: usize, input: &[Vec<Bin>], output: &mut [Vec<Bin>], ) { let freq_per_bin = sample_rate / (bins as f64); let add = ports[0]; let shift = ports[1]; let alpha = ports[2]; for i in 0..channels { let mut avg = input[i][0].amp; for j in 0..bins { output[i][j].freq = input[i][j].freq + shift * freq_per_bin + ((avg - input[i][j].amp) * add); output[i][j].amp = input[i][j].amp; avg = lerp(avg, input[i][j].amp, alpha); } } } }
} fn new(_: usize, _: f64, _: usize, _: usize) -> DomainXOver {
random_line_split
domainxover.rs
use super::{lerp, PVocDescriptor, PVocPlugin}; use ladspa::{DefaultValue, Plugin, PluginDescriptor, Port, PortConnection, PortDescriptor}; use pvoc::{Bin, PhaseVocoder}; plugin!(DomainXOver); struct DomainXOver; impl PVocPlugin for DomainXOver { fn descriptor() -> PVocDescriptor { PVocDescriptor { name: "pvoc domain crossover", author: "Noah Weninger", channels: 1, ports: vec![ Port { name: "Add", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Value0), lower_bound: Some(0.0), upper_bound: Some(25.0), }, Port { name: "Shift", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Value0), lower_bound: Some(0.0), upper_bound: Some(1.0), }, Port { name: "Alpha", desc: PortDescriptor::ControlInput, hint: None, default: Some(DefaultValue::Middle), lower_bound: Some(0.0), upper_bound: Some(1.0), }, ], } } fn new(_: usize, _: f64, _: usize, _: usize) -> DomainXOver { DomainXOver } fn process( &mut self, ports: &[f64], sample_rate: f64, channels: usize, bins: usize, input: &[Vec<Bin>], output: &mut [Vec<Bin>], )
}
{ let freq_per_bin = sample_rate / (bins as f64); let add = ports[0]; let shift = ports[1]; let alpha = ports[2]; for i in 0..channels { let mut avg = input[i][0].amp; for j in 0..bins { output[i][j].freq = input[i][j].freq + shift * freq_per_bin + ((avg - input[i][j].amp) * add); output[i][j].amp = input[i][j].amp; avg = lerp(avg, input[i][j].amp, alpha); } } }
identifier_body
private-type-alias.rs
type MyResultPriv<T> = Result<T, u16>; pub type MyResultPub<T> = Result<T, u64>; // @has private_type_alias/fn.get_result_priv.html '//pre' 'Result<u8, u16>' pub fn get_result_priv() -> MyResultPriv<u8> { panic!(); } // @has private_type_alias/fn.get_result_pub.html '//pre' 'MyResultPub<u32>' pub fn
() -> MyResultPub<u32> { panic!(); } pub type PubRecursive = u16; type PrivRecursive3 = u8; type PrivRecursive2 = PubRecursive; type PrivRecursive1 = PrivRecursive3; // PrivRecursive1 is expanded twice and stops at u8 // PrivRecursive2 is expanded once and stops at public type alias PubRecursive // @has private_type_alias/fn.get_result_recursive.html '//pre' '(u8, PubRecursive)' pub fn get_result_recursive() -> (PrivRecursive1, PrivRecursive2) { panic!(); } type MyLifetimePriv<'a> = &'a isize; // @has private_type_alias/fn.get_lifetime_priv.html '//pre' "&'static isize" pub fn get_lifetime_priv() -> MyLifetimePriv<'static> { panic!(); }
get_result_pub
identifier_name
private-type-alias.rs
type MyResultPriv<T> = Result<T, u16>; pub type MyResultPub<T> = Result<T, u64>; // @has private_type_alias/fn.get_result_priv.html '//pre' 'Result<u8, u16>' pub fn get_result_priv() -> MyResultPriv<u8> { panic!();
} // @has private_type_alias/fn.get_result_pub.html '//pre' 'MyResultPub<u32>' pub fn get_result_pub() -> MyResultPub<u32> { panic!(); } pub type PubRecursive = u16; type PrivRecursive3 = u8; type PrivRecursive2 = PubRecursive; type PrivRecursive1 = PrivRecursive3; // PrivRecursive1 is expanded twice and stops at u8 // PrivRecursive2 is expanded once and stops at public type alias PubRecursive // @has private_type_alias/fn.get_result_recursive.html '//pre' '(u8, PubRecursive)' pub fn get_result_recursive() -> (PrivRecursive1, PrivRecursive2) { panic!(); } type MyLifetimePriv<'a> = &'a isize; // @has private_type_alias/fn.get_lifetime_priv.html '//pre' "&'static isize" pub fn get_lifetime_priv() -> MyLifetimePriv<'static> { panic!(); }
random_line_split
private-type-alias.rs
type MyResultPriv<T> = Result<T, u16>; pub type MyResultPub<T> = Result<T, u64>; // @has private_type_alias/fn.get_result_priv.html '//pre' 'Result<u8, u16>' pub fn get_result_priv() -> MyResultPriv<u8> { panic!(); } // @has private_type_alias/fn.get_result_pub.html '//pre' 'MyResultPub<u32>' pub fn get_result_pub() -> MyResultPub<u32> { panic!(); } pub type PubRecursive = u16; type PrivRecursive3 = u8; type PrivRecursive2 = PubRecursive; type PrivRecursive1 = PrivRecursive3; // PrivRecursive1 is expanded twice and stops at u8 // PrivRecursive2 is expanded once and stops at public type alias PubRecursive // @has private_type_alias/fn.get_result_recursive.html '//pre' '(u8, PubRecursive)' pub fn get_result_recursive() -> (PrivRecursive1, PrivRecursive2)
type MyLifetimePriv<'a> = &'a isize; // @has private_type_alias/fn.get_lifetime_priv.html '//pre' "&'static isize" pub fn get_lifetime_priv() -> MyLifetimePriv<'static> { panic!(); }
{ panic!(); }
identifier_body
signature.rs
use bytes; use {Error, FileType}; use std::io::Read; const SIGNATURE_FILE: u32 = 0x9AA2D903; const SIGNATURE_KEEPASS1: u32 = 0xB54BFB65; const SIGNATURE_KEEPASS2_PRE_RELEASE: u32 = 0xB54BFB66; const SIGNATURE_KEEPASS2: u32 = 0xB54BFB67; pub fn read_file_type(reader: &mut Read) -> Result<FileType, Error> { let signature = try!(bytes::read_u32(reader)); try!(check_file_signature(signature)); let file_type = try!(bytes::read_u32(reader)); match_file_type(file_type) } fn check_file_signature(sig: u32) -> Result<(), Error> { if sig == SIGNATURE_FILE { Ok(()) } else { Err(Error::InvalidSignature(sig)) } } fn match_file_type(file_type: u32) -> Result<FileType, Error> { match file_type { SIGNATURE_KEEPASS1 => Ok(FileType::KeePass1), SIGNATURE_KEEPASS2_PRE_RELEASE => Ok(FileType::KeePass2PreRelease), SIGNATURE_KEEPASS2 => Ok(FileType::KeePass2), _ => Err(Error::InvalidFileType(file_type)), } } #[cfg(test)] mod test { use super::*; use {Error, FileType}; use byteorder::{LittleEndian, WriteBytesExt};
bytes.write_u32::<LittleEndian>(super::SIGNATURE_FILE).unwrap(); bytes.write_u32::<LittleEndian>(super::SIGNATURE_KEEPASS2).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Ok(FileType::KeePass2) => (), _ => panic!("Invalid result: {:#?}", result), } } #[test] pub fn should_return_error_if_wrong_signature() { let signature = super::SIGNATURE_FILE + 1; let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(signature).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Err(Error::InvalidSignature(s)) => assert_eq!(s, signature), _ => panic!("Invalid result: {:#?}", result), } } #[test] pub fn should_return_error_if_invalid_type() { let file_type = super::SIGNATURE_KEEPASS2 + 1; let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(super::SIGNATURE_FILE).unwrap(); bytes.write_u32::<LittleEndian>(file_type).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Err(Error::InvalidFileType(t)) => assert_eq!(t, file_type), _ => panic!("Invalid result: {:#?}", result), } } }
#[test] pub fn should_return_file_type() { let mut bytes = vec![];
random_line_split
signature.rs
use bytes; use {Error, FileType}; use std::io::Read; const SIGNATURE_FILE: u32 = 0x9AA2D903; const SIGNATURE_KEEPASS1: u32 = 0xB54BFB65; const SIGNATURE_KEEPASS2_PRE_RELEASE: u32 = 0xB54BFB66; const SIGNATURE_KEEPASS2: u32 = 0xB54BFB67; pub fn read_file_type(reader: &mut Read) -> Result<FileType, Error> { let signature = try!(bytes::read_u32(reader)); try!(check_file_signature(signature)); let file_type = try!(bytes::read_u32(reader)); match_file_type(file_type) } fn check_file_signature(sig: u32) -> Result<(), Error> { if sig == SIGNATURE_FILE { Ok(()) } else { Err(Error::InvalidSignature(sig)) } } fn
(file_type: u32) -> Result<FileType, Error> { match file_type { SIGNATURE_KEEPASS1 => Ok(FileType::KeePass1), SIGNATURE_KEEPASS2_PRE_RELEASE => Ok(FileType::KeePass2PreRelease), SIGNATURE_KEEPASS2 => Ok(FileType::KeePass2), _ => Err(Error::InvalidFileType(file_type)), } } #[cfg(test)] mod test { use super::*; use {Error, FileType}; use byteorder::{LittleEndian, WriteBytesExt}; #[test] pub fn should_return_file_type() { let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(super::SIGNATURE_FILE).unwrap(); bytes.write_u32::<LittleEndian>(super::SIGNATURE_KEEPASS2).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Ok(FileType::KeePass2) => (), _ => panic!("Invalid result: {:#?}", result), } } #[test] pub fn should_return_error_if_wrong_signature() { let signature = super::SIGNATURE_FILE + 1; let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(signature).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Err(Error::InvalidSignature(s)) => assert_eq!(s, signature), _ => panic!("Invalid result: {:#?}", result), } } #[test] pub fn should_return_error_if_invalid_type() { let file_type = super::SIGNATURE_KEEPASS2 + 1; let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(super::SIGNATURE_FILE).unwrap(); bytes.write_u32::<LittleEndian>(file_type).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Err(Error::InvalidFileType(t)) => assert_eq!(t, file_type), _ => panic!("Invalid result: {:#?}", result), } } }
match_file_type
identifier_name
signature.rs
use bytes; use {Error, FileType}; use std::io::Read; const SIGNATURE_FILE: u32 = 0x9AA2D903; const SIGNATURE_KEEPASS1: u32 = 0xB54BFB65; const SIGNATURE_KEEPASS2_PRE_RELEASE: u32 = 0xB54BFB66; const SIGNATURE_KEEPASS2: u32 = 0xB54BFB67; pub fn read_file_type(reader: &mut Read) -> Result<FileType, Error> { let signature = try!(bytes::read_u32(reader)); try!(check_file_signature(signature)); let file_type = try!(bytes::read_u32(reader)); match_file_type(file_type) } fn check_file_signature(sig: u32) -> Result<(), Error> { if sig == SIGNATURE_FILE { Ok(()) } else { Err(Error::InvalidSignature(sig)) } } fn match_file_type(file_type: u32) -> Result<FileType, Error> { match file_type { SIGNATURE_KEEPASS1 => Ok(FileType::KeePass1), SIGNATURE_KEEPASS2_PRE_RELEASE => Ok(FileType::KeePass2PreRelease), SIGNATURE_KEEPASS2 => Ok(FileType::KeePass2), _ => Err(Error::InvalidFileType(file_type)), } } #[cfg(test)] mod test { use super::*; use {Error, FileType}; use byteorder::{LittleEndian, WriteBytesExt}; #[test] pub fn should_return_file_type() { let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(super::SIGNATURE_FILE).unwrap(); bytes.write_u32::<LittleEndian>(super::SIGNATURE_KEEPASS2).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Ok(FileType::KeePass2) => (), _ => panic!("Invalid result: {:#?}", result), } } #[test] pub fn should_return_error_if_wrong_signature() { let signature = super::SIGNATURE_FILE + 1; let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(signature).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Err(Error::InvalidSignature(s)) => assert_eq!(s, signature), _ => panic!("Invalid result: {:#?}", result), } } #[test] pub fn should_return_error_if_invalid_type()
}
{ let file_type = super::SIGNATURE_KEEPASS2 + 1; let mut bytes = vec![]; bytes.write_u32::<LittleEndian>(super::SIGNATURE_FILE).unwrap(); bytes.write_u32::<LittleEndian>(file_type).unwrap(); let result = read_file_type(&mut &bytes[..]); match result { Err(Error::InvalidFileType(t)) => assert_eq!(t, file_type), _ => panic!("Invalid result: {:#?}", result), } }
identifier_body
class-methods-cross-crate.rs
// Copyright 2012-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. // aux-build:cci_class_3.rs extern crate cci_class_3; use cci_class_3::kitties::cat; pub fn
() { let mut nyan : cat = cat(52u, 99); let kitty = cat(1000u, 2); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(); assert_eq!(nyan.meow_count(), 53u); }
main
identifier_name
class-methods-cross-crate.rs
// Copyright 2012-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
// option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:cci_class_3.rs extern crate cci_class_3; use cci_class_3::kitties::cat; pub fn main() { let mut nyan : cat = cat(52u, 99); let kitty = cat(1000u, 2); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(); assert_eq!(nyan.meow_count(), 53u); }
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
class-methods-cross-crate.rs
// Copyright 2012-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. // aux-build:cci_class_3.rs extern crate cci_class_3; use cci_class_3::kitties::cat; pub fn main()
{ let mut nyan : cat = cat(52u, 99); let kitty = cat(1000u, 2); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(); assert_eq!(nyan.meow_count(), 53u); }
identifier_body
winusbio.rs
// 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.
pub const SHORT_PACKET_TERMINATE: ULONG = 0x01; pub const AUTO_CLEAR_STALL: ULONG = 0x02; pub const PIPE_TRANSFER_TIMEOUT: ULONG = 0x03; pub const IGNORE_SHORT_PACKETS: ULONG = 0x04; pub const ALLOW_PARTIAL_READS: ULONG = 0x05; pub const AUTO_FLUSH: ULONG = 0x06; pub const RAW_IO: ULONG = 0x07; pub const MAXIMUM_TRANSFER_SIZE: ULONG = 0x08; pub const RESET_PIPE_ON_RESUME: ULONG = 0x09; pub const DEVICE_SPEED: ULONG = 0x01; pub const LowSpeed: ULONG = 0x01; pub const FullSpeed: ULONG = 0x02; pub const HighSpeed: ULONG = 0x03; DEFINE_GUID!{WinUSB_TestGuid, 0xda812bff, 0x12c3, 0x46a2, 0x8e, 0x2b, 0xdb, 0xd3, 0xb7, 0x83, 0x4c, 0x43} STRUCT!{struct WINUSB_PIPE_INFORMATION { PipeType: USBD_PIPE_TYPE, PipeId: UCHAR, MaximumPacketSize: USHORT, Interval: UCHAR, }} pub type PWINUSB_PIPE_INFORMATION = *mut WINUSB_PIPE_INFORMATION; STRUCT!{struct WINUSB_PIPE_INFORMATION_EX { PipeType: USBD_PIPE_TYPE, PipeId: UCHAR, MaximumPacketSize: USHORT, Interval: UCHAR, MaximumBytesPerInterval: ULONG, }} pub type PWINUSB_PIPE_INFORMATION_EX = *mut WINUSB_PIPE_INFORMATION_EX;
// All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! Public header for WINUSB use shared::minwindef::{UCHAR, ULONG, USHORT}; use shared::usb::USBD_PIPE_TYPE;
random_line_split
pixmap.rs
//! Custom pixmaps which can handle kinds of data that the `image` library //! doesn't support. use cast; use common_failures::prelude::*; use image::{ImageBuffer, Rgba, RgbaImage}; use std::fmt; use std::slice; #[cfg(test)] use test_util::rgba_hex; /// A type which can be used as a pixel in a `Pixmap`. pub trait Pixel: Clone + Copy + fmt::Debug +'static { /// This is basically just `Default::default`. We would normally just /// base this trait on `Default`, but we also want to implement this /// trait for `image::Rgba`, which doesn't implement `Default`. fn default_color() -> Self; /// Is this pixel transparent? fn is_transparent(self) -> bool; /// Return a RGBA color for this pixel. Used for visualizing images /// with pixel types that aren't ordinary colors. fn to_rgba(self) -> Rgba<u8>; } impl Pixel for bool { fn default_color() -> Self { false } fn is_transparent(self) -> bool { !self } fn to_rgba(self) -> Rgba<u8> { match self { false => Rgba { data: [0, 0, 0, 0] }, true => Rgba { data: [0, 0, 0, 0xff] }, } } } #[test] fn bool_implements_pixel() { assert_eq!(bool::default_color(), false); assert_eq!(true.is_transparent(), false); assert_eq!(false.is_transparent(), true); assert_eq!(true.to_rgba(), rgba_hex(0x000000ff)); assert_eq!(false.to_rgba(), rgba_hex(0x00000000)); } impl Pixel for Rgba<u8> { fn default_color() -> Self { Rgba { data: [0, 0, 0, 0] } } fn is_transparent(self) -> bool { self.data[3] < 0xff } fn to_rgba(self) -> Rgba<u8> { self } } #[test] fn rgba_implements_pixel() { assert_eq!(Rgba::<u8>::default_color(), rgba_hex(0x00000000)); assert_eq!(rgba_hex(0x000000ff).is_transparent(), false); assert_eq!(rgba_hex(0x00000000).is_transparent(), true); assert_eq!(rgba_hex(0xff0000ff).to_rgba(), rgba_hex(0xff0000ff)); } /// A fully generic image type, which can hold non-graphical data. pub struct Pixmap<P: Pixel = Rgba<u8>> { data: Vec<P>, width: usize, height: usize, } impl<P: Pixel> Pixmap<P> { /// Make sure that these specified image size is legal. fn size_check(width: usize, height: usize) { let max_dim = isize::max_value() as usize; if width > max_dim || height > max_dim { panic!("image dimensions {}x{} are too large", width, height); } if width.checked_mul(height).is_none() { panic!("image area {}x{} is too large", width, height); } } /// Create a new `Pixmap` filled with `P::default_color()`. pub fn blank(width: usize, height: usize) -> Pixmap<P> { Pixmap::<P>::size_check(width, height); Pixmap { data: vec![P::default_color(); width * height], width: width, height: height, } } /// If `x` and `y` do not fit within the pixmap, panic. fn bounds_check(&self, x: usize, y: usize) { if x >= self.width { panic!("out of bounds x: {} width: {}", x, self.width); } if y >= self.height { panic!("out of bounds y: {} height: {}", y, self.height); } } /// The width of the `Pixmap`. pub fn width(&self) -> usize { self.width } /// The height of the `Pixmap`. pub fn height(&self) -> usize { self.height } /// Get the pixel at `x` and `y`, or panic if out of bounds. pub fn get(&self, x: usize, y: usize) -> P { self.bounds_check(x, y); self.data[y*self.width + x] } /// Get the pixel at `x` and `y`, or return `P::default_color()` if out /// of bounds. pub fn get_default(&self, x: isize, y: isize) -> P { if x < 0 || y < 0 { return P::default_color(); } // `as usize` is safe here because we're verified x and y are // non-negative. let x = x as usize; let y = y as usize; if x >= self.width || y >= self.height { P::default_color() } else { self.data[y*self.width + x] } } /// Get a mutable reference to the pixel at `x` and `y`, or panic if /// out of bounds. pub fn get_mut(&mut self, x: usize, y: usize) -> &mut P { self.bounds_check(x, y); &mut self.data[y*self.width + x] } /// Iterate over all the pixels in an image. pub fn pixels(&self) -> Pixels<P> { Pixels { iter: self.data.iter() } } /// Iterate over `(x, y, value)` for all the pixels in an image. pub fn enumerate_pixels(&self) -> EnumeratePixels<P> { EnumeratePixels { pixmap: self, x: 0, y: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// out-of-bounds pixels. pub fn all_neighbors(&self, x: usize, y: usize) -> AllNeighbors { AllNeighbors { x: cast::isize(x).expect("x outside maximum image size"), y: cast::isize(y).expect("y outside maximum image size"), i: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// only in-bounds pixels. pub fn real_neighbors(&self, x: usize, y: usize) -> RealNeighbors { RealNeighbors { width: self.width, height: self.height, x: x, y: y, i: 0, } } /// Transform each pixel of the image. pub fn map<F, P2>(&self, f: F) -> Pixmap<P2> where F: Fn(P) -> P2, P2: Pixel { Pixmap { data: self.data.iter().map(|p| f(*p)).collect(), width: self.width, height: self.height, } } /// Convert this `Pixmap` into a `RgbaImage`, for easy output. pub fn to_image(&self) -> Result<RgbaImage> { let mut raw: Vec<_> = Vec::with_capacity(self.data.len() * 4); for px in &self.data { let rgba = px.to_rgba().data; raw.extend_from_slice(&[rgba[0], rgba[1], rgba[2], rgba[3]]); } Ok(ImageBuffer::from_raw(u32_from_usize(self.width)?, u32_from_usize(self.height)?, raw).expect("image bounds mismatch")) } } #[cfg(target_pointer_width = "64")] fn u32_from_usize(i: usize) -> Result<u32> { // This can fail on 64-bit platforms. Ok(cast::u32(i)?) } #[cfg(target_pointer_width = "32")] fn u32_from_usize(i: usize) -> Result<u32> { // This will always succeed on 32-bit platforms. Ok(cast::u32(i)) } /// An iterator over all the pixels in an image. pub struct Pixels<'a, P: Pixel> { iter: slice::Iter<'a, P>, } impl<'a, P: Pixel> Iterator for Pixels<'a, P> { type Item = P; fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|v| *v) } } /// An iterator over `(x, y, value)` for all the pixels in an image. pub struct EnumeratePixels<'a, P: Pixel> { pixmap: &'a Pixmap<P>, x: usize, y: usize, } impl<'a, P: Pixel> Iterator for EnumeratePixels<'a, P> { type Item = (usize, usize, P); fn next(&mut self) -> Option<Self::Item> { if self.pixmap.width == 0 || self.pixmap.height == 0 { return None; } if self.x >= self.pixmap.width { self.x = 0; self.y += 1; } if self.y >= self.pixmap.height { return None; } assert!(self.x < self.pixmap.width); assert!(self.y < self.pixmap.height); let px = self.pixmap.data[self.y*self.pixmap.width + self.x]; let result = Some((self.x, self.y, px)); self.x += 1; result } } /// Delta coordinates for neighboring pixels. const NEIGHBORS: &'static [(isize, isize)] = &[(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including out-of-bounds pixels. pub struct AllNeighbors { x: isize, y: isize, i: usize, } impl Iterator for AllNeighbors { type Item = (isize, isize); fn next(&mut self) -> Option<Self::Item> { if let Some(&(dx, dy)) = NEIGHBORS.get(self.i)
else { None } } } /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including only in-bounds pixels. pub struct RealNeighbors { width: usize, height: usize, x: usize, y: usize, i: usize, } impl Iterator for RealNeighbors { type Item = (usize, usize); fn next(&mut self) -> Option<Self::Item> { while let Some(&(dx, dy)) = NEIGHBORS.get(self.i) { self.i += 1; if self.x == 0 && dx == -1 || self.y == 0 && dy == -1 { continue; } // `as isize` is safe because of `size_check`, `as usize` is // safe because we eliminated sums of -1 above. let x = ((self.x as isize) + dx) as usize; let y = ((self.y as isize) + dy) as usize; if x == self.width || y == self.height { continue; } return Some((x, y)) } None } } impl From<RgbaImage> for Pixmap<Rgba<u8>> { fn from(image: RgbaImage) -> Pixmap<Rgba<u8>> { let width = cast::usize(image.width()); let height = cast::usize(image.height()); let channels = image.into_raw(); assert_eq!(channels.len(), width * height * 4); let mut data = Vec::with_capacity(width * height); for chunk in channels.chunks(4) { data.push(Rgba { data: [chunk[0], chunk[1], chunk[2], chunk[3]] }); } Pixmap { data: data, width: width, height: height, } } } impl<P: Pixel> fmt::Debug for Pixmap<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Pixmap") .field("width", &self.width) .field("height", &self.height) .finish() } } #[test] fn blank_fills_image_with_default() { let pixmap = Pixmap::<bool>::blank(1, 2); assert_eq!(pixmap.width(), 1); assert_eq!(pixmap.height(), 2); assert_eq!(pixmap.get(0, 0), false); } #[test] fn get_and_get_mut_provide_access_to_pixels() { let mut pixmap = Pixmap::<bool>::blank(1, 1); assert_eq!(pixmap.get(0, 0), false); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get(0, 0), true); } #[test] #[should_panic] fn get_panics_when_out_of_bounds() { let pixmap = Pixmap::<bool>::blank(1, 1); pixmap.get(1, 1); } #[test] fn get_default_returns_default_color_when_out_of_bounds() { let mut pixmap = Pixmap::<bool>::blank(1, 1); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get_default(0, -1), false); assert_eq!(pixmap.get_default(-1, 0), false); assert_eq!(pixmap.get_default(0, 1), false); assert_eq!(pixmap.get_default(1, 0), false); } #[test] fn pixels_iterates_over_all_pixel_values() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let pixels = pixmap.pixels().collect::<Vec<_>>(); assert_eq!(pixels, &[true, false]); } #[test] fn enumerate_pixels_iterates_over_pixel_values_and_coordinates() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let output = pixmap.enumerate_pixels().collect::<Vec<_>>(); assert_eq!(output, &[(0, 0, true), (1, 0, false)]); } #[test] fn all_neighbors_iterates_over_all_neighbor_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.all_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, -1), (1, -1), (2, -1), (0, 0), (2, 0), (0, 1), (1, 1), (2, 1)]); } #[test] fn real_neighbors_iterates_over_in_bounds_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.real_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, 0)]); } #[test] fn map_creates_a_new_image_by_applying_a_function() { let mut pixmap = Pixmap::<bool>::blank(1, 2); *pixmap.get_mut(0, 0) = true; let mapped = pixmap.map(|p| { match p { true => rgba_hex(0xff0000ff), false => rgba_hex(0x00ff00ff), } }); assert_eq!(mapped.get(0, 0), rgba_hex(0xff0000ff)); assert_eq!(mapped.get(0, 1), rgba_hex(0x00ff00ff)); } #[test] fn to_image_converts_to_image() { let mut pixmap = Pixmap::<bool>::blank(1, 2); *pixmap.get_mut(0, 0) = true; let image = pixmap.to_image().unwrap(); assert_eq!(image.width(), 1); assert_eq!(image.height(), 2); assert_eq!(image[(0, 0)], rgba_hex(0x000000ff)); assert_eq!(image[(0, 1)], rgba_hex(0x00000000)); } #[test] fn from_image_constructs_from_rgba_image() { let image: RgbaImage = ImageBuffer::from_pixel(2, 1, rgba_hex(0xff0000ff)); let pixmap = Pixmap::from(image); assert_eq!(pixmap.width(), 2); assert_eq!(pixmap.height(), 1); assert_eq!(pixmap.get(0, 0), rgba_hex(0xff0000ff)); }
{ self.i += 1; Some((self.x + dx, self.y + dy)) }
conditional_block
pixmap.rs
//! Custom pixmaps which can handle kinds of data that the `image` library //! doesn't support. use cast; use common_failures::prelude::*; use image::{ImageBuffer, Rgba, RgbaImage}; use std::fmt; use std::slice; #[cfg(test)] use test_util::rgba_hex; /// A type which can be used as a pixel in a `Pixmap`. pub trait Pixel: Clone + Copy + fmt::Debug +'static { /// This is basically just `Default::default`. We would normally just /// base this trait on `Default`, but we also want to implement this /// trait for `image::Rgba`, which doesn't implement `Default`. fn default_color() -> Self; /// Is this pixel transparent? fn is_transparent(self) -> bool; /// Return a RGBA color for this pixel. Used for visualizing images /// with pixel types that aren't ordinary colors. fn to_rgba(self) -> Rgba<u8>; } impl Pixel for bool { fn default_color() -> Self { false } fn is_transparent(self) -> bool { !self } fn to_rgba(self) -> Rgba<u8> { match self { false => Rgba { data: [0, 0, 0, 0] }, true => Rgba { data: [0, 0, 0, 0xff] }, } } } #[test] fn bool_implements_pixel() { assert_eq!(bool::default_color(), false); assert_eq!(true.is_transparent(), false); assert_eq!(false.is_transparent(), true); assert_eq!(true.to_rgba(), rgba_hex(0x000000ff)); assert_eq!(false.to_rgba(), rgba_hex(0x00000000)); } impl Pixel for Rgba<u8> { fn default_color() -> Self { Rgba { data: [0, 0, 0, 0] } } fn is_transparent(self) -> bool { self.data[3] < 0xff } fn to_rgba(self) -> Rgba<u8> { self } } #[test] fn rgba_implements_pixel() { assert_eq!(Rgba::<u8>::default_color(), rgba_hex(0x00000000)); assert_eq!(rgba_hex(0x000000ff).is_transparent(), false); assert_eq!(rgba_hex(0x00000000).is_transparent(), true); assert_eq!(rgba_hex(0xff0000ff).to_rgba(), rgba_hex(0xff0000ff)); } /// A fully generic image type, which can hold non-graphical data. pub struct Pixmap<P: Pixel = Rgba<u8>> { data: Vec<P>, width: usize, height: usize, } impl<P: Pixel> Pixmap<P> { /// Make sure that these specified image size is legal. fn size_check(width: usize, height: usize) { let max_dim = isize::max_value() as usize; if width > max_dim || height > max_dim { panic!("image dimensions {}x{} are too large", width, height); } if width.checked_mul(height).is_none() { panic!("image area {}x{} is too large", width, height); } } /// Create a new `Pixmap` filled with `P::default_color()`. pub fn blank(width: usize, height: usize) -> Pixmap<P> { Pixmap::<P>::size_check(width, height); Pixmap { data: vec![P::default_color(); width * height], width: width, height: height, } } /// If `x` and `y` do not fit within the pixmap, panic. fn bounds_check(&self, x: usize, y: usize) { if x >= self.width { panic!("out of bounds x: {} width: {}", x, self.width); } if y >= self.height { panic!("out of bounds y: {} height: {}", y, self.height); } } /// The width of the `Pixmap`. pub fn width(&self) -> usize { self.width } /// The height of the `Pixmap`. pub fn height(&self) -> usize { self.height } /// Get the pixel at `x` and `y`, or panic if out of bounds. pub fn get(&self, x: usize, y: usize) -> P { self.bounds_check(x, y); self.data[y*self.width + x] } /// Get the pixel at `x` and `y`, or return `P::default_color()` if out /// of bounds. pub fn get_default(&self, x: isize, y: isize) -> P { if x < 0 || y < 0 { return P::default_color(); } // `as usize` is safe here because we're verified x and y are // non-negative. let x = x as usize; let y = y as usize; if x >= self.width || y >= self.height { P::default_color() } else { self.data[y*self.width + x] } } /// Get a mutable reference to the pixel at `x` and `y`, or panic if /// out of bounds. pub fn get_mut(&mut self, x: usize, y: usize) -> &mut P { self.bounds_check(x, y); &mut self.data[y*self.width + x] } /// Iterate over all the pixels in an image. pub fn pixels(&self) -> Pixels<P> { Pixels { iter: self.data.iter() } } /// Iterate over `(x, y, value)` for all the pixels in an image. pub fn enumerate_pixels(&self) -> EnumeratePixels<P> { EnumeratePixels { pixmap: self, x: 0, y: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// out-of-bounds pixels. pub fn all_neighbors(&self, x: usize, y: usize) -> AllNeighbors { AllNeighbors { x: cast::isize(x).expect("x outside maximum image size"), y: cast::isize(y).expect("y outside maximum image size"), i: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// only in-bounds pixels. pub fn real_neighbors(&self, x: usize, y: usize) -> RealNeighbors { RealNeighbors { width: self.width, height: self.height, x: x, y: y, i: 0, } } /// Transform each pixel of the image. pub fn map<F, P2>(&self, f: F) -> Pixmap<P2> where F: Fn(P) -> P2, P2: Pixel { Pixmap { data: self.data.iter().map(|p| f(*p)).collect(), width: self.width, height: self.height, } } /// Convert this `Pixmap` into a `RgbaImage`, for easy output. pub fn to_image(&self) -> Result<RgbaImage> { let mut raw: Vec<_> = Vec::with_capacity(self.data.len() * 4); for px in &self.data { let rgba = px.to_rgba().data; raw.extend_from_slice(&[rgba[0], rgba[1], rgba[2], rgba[3]]); } Ok(ImageBuffer::from_raw(u32_from_usize(self.width)?, u32_from_usize(self.height)?, raw).expect("image bounds mismatch")) } } #[cfg(target_pointer_width = "64")] fn u32_from_usize(i: usize) -> Result<u32> { // This can fail on 64-bit platforms. Ok(cast::u32(i)?) } #[cfg(target_pointer_width = "32")] fn u32_from_usize(i: usize) -> Result<u32> { // This will always succeed on 32-bit platforms. Ok(cast::u32(i)) } /// An iterator over all the pixels in an image. pub struct Pixels<'a, P: Pixel> { iter: slice::Iter<'a, P>, } impl<'a, P: Pixel> Iterator for Pixels<'a, P> { type Item = P; fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|v| *v) } } /// An iterator over `(x, y, value)` for all the pixels in an image. pub struct EnumeratePixels<'a, P: Pixel> { pixmap: &'a Pixmap<P>, x: usize, y: usize, } impl<'a, P: Pixel> Iterator for EnumeratePixels<'a, P> { type Item = (usize, usize, P); fn next(&mut self) -> Option<Self::Item> { if self.pixmap.width == 0 || self.pixmap.height == 0 { return None; } if self.x >= self.pixmap.width { self.x = 0; self.y += 1; } if self.y >= self.pixmap.height { return None; } assert!(self.x < self.pixmap.width); assert!(self.y < self.pixmap.height); let px = self.pixmap.data[self.y*self.pixmap.width + self.x]; let result = Some((self.x, self.y, px)); self.x += 1; result } } /// Delta coordinates for neighboring pixels. const NEIGHBORS: &'static [(isize, isize)] = &[(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including out-of-bounds pixels. pub struct AllNeighbors { x: isize, y: isize, i: usize, } impl Iterator for AllNeighbors { type Item = (isize, isize); fn next(&mut self) -> Option<Self::Item> { if let Some(&(dx, dy)) = NEIGHBORS.get(self.i) { self.i += 1; Some((self.x + dx, self.y + dy)) } else { None } } } /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including only in-bounds pixels. pub struct RealNeighbors { width: usize, height: usize, x: usize, y: usize, i: usize, } impl Iterator for RealNeighbors { type Item = (usize, usize); fn next(&mut self) -> Option<Self::Item> { while let Some(&(dx, dy)) = NEIGHBORS.get(self.i) { self.i += 1; if self.x == 0 && dx == -1 || self.y == 0 && dy == -1 { continue; } // `as isize` is safe because of `size_check`, `as usize` is // safe because we eliminated sums of -1 above. let x = ((self.x as isize) + dx) as usize; let y = ((self.y as isize) + dy) as usize; if x == self.width || y == self.height { continue; } return Some((x, y)) } None } } impl From<RgbaImage> for Pixmap<Rgba<u8>> { fn from(image: RgbaImage) -> Pixmap<Rgba<u8>> { let width = cast::usize(image.width()); let height = cast::usize(image.height()); let channels = image.into_raw(); assert_eq!(channels.len(), width * height * 4); let mut data = Vec::with_capacity(width * height); for chunk in channels.chunks(4) { data.push(Rgba { data: [chunk[0], chunk[1], chunk[2], chunk[3]] }); } Pixmap { data: data, width: width, height: height, } } } impl<P: Pixel> fmt::Debug for Pixmap<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Pixmap") .field("width", &self.width) .field("height", &self.height) .finish() } } #[test] fn blank_fills_image_with_default() { let pixmap = Pixmap::<bool>::blank(1, 2); assert_eq!(pixmap.width(), 1); assert_eq!(pixmap.height(), 2); assert_eq!(pixmap.get(0, 0), false); } #[test] fn get_and_get_mut_provide_access_to_pixels() { let mut pixmap = Pixmap::<bool>::blank(1, 1); assert_eq!(pixmap.get(0, 0), false); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get(0, 0), true); } #[test] #[should_panic] fn get_panics_when_out_of_bounds() { let pixmap = Pixmap::<bool>::blank(1, 1); pixmap.get(1, 1); } #[test] fn get_default_returns_default_color_when_out_of_bounds() { let mut pixmap = Pixmap::<bool>::blank(1, 1); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get_default(0, -1), false); assert_eq!(pixmap.get_default(-1, 0), false); assert_eq!(pixmap.get_default(0, 1), false); assert_eq!(pixmap.get_default(1, 0), false); } #[test] fn pixels_iterates_over_all_pixel_values() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let pixels = pixmap.pixels().collect::<Vec<_>>(); assert_eq!(pixels, &[true, false]); } #[test] fn enumerate_pixels_iterates_over_pixel_values_and_coordinates() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let output = pixmap.enumerate_pixels().collect::<Vec<_>>(); assert_eq!(output, &[(0, 0, true), (1, 0, false)]); } #[test] fn all_neighbors_iterates_over_all_neighbor_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.all_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, -1), (1, -1), (2, -1), (0, 0), (2, 0), (0, 1), (1, 1), (2, 1)]); } #[test] fn real_neighbors_iterates_over_in_bounds_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.real_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, 0)]); } #[test] fn map_creates_a_new_image_by_applying_a_function() { let mut pixmap = Pixmap::<bool>::blank(1, 2);
false => rgba_hex(0x00ff00ff), } }); assert_eq!(mapped.get(0, 0), rgba_hex(0xff0000ff)); assert_eq!(mapped.get(0, 1), rgba_hex(0x00ff00ff)); } #[test] fn to_image_converts_to_image() { let mut pixmap = Pixmap::<bool>::blank(1, 2); *pixmap.get_mut(0, 0) = true; let image = pixmap.to_image().unwrap(); assert_eq!(image.width(), 1); assert_eq!(image.height(), 2); assert_eq!(image[(0, 0)], rgba_hex(0x000000ff)); assert_eq!(image[(0, 1)], rgba_hex(0x00000000)); } #[test] fn from_image_constructs_from_rgba_image() { let image: RgbaImage = ImageBuffer::from_pixel(2, 1, rgba_hex(0xff0000ff)); let pixmap = Pixmap::from(image); assert_eq!(pixmap.width(), 2); assert_eq!(pixmap.height(), 1); assert_eq!(pixmap.get(0, 0), rgba_hex(0xff0000ff)); }
*pixmap.get_mut(0, 0) = true; let mapped = pixmap.map(|p| { match p { true => rgba_hex(0xff0000ff),
random_line_split
pixmap.rs
//! Custom pixmaps which can handle kinds of data that the `image` library //! doesn't support. use cast; use common_failures::prelude::*; use image::{ImageBuffer, Rgba, RgbaImage}; use std::fmt; use std::slice; #[cfg(test)] use test_util::rgba_hex; /// A type which can be used as a pixel in a `Pixmap`. pub trait Pixel: Clone + Copy + fmt::Debug +'static { /// This is basically just `Default::default`. We would normally just /// base this trait on `Default`, but we also want to implement this /// trait for `image::Rgba`, which doesn't implement `Default`. fn default_color() -> Self; /// Is this pixel transparent? fn is_transparent(self) -> bool; /// Return a RGBA color for this pixel. Used for visualizing images /// with pixel types that aren't ordinary colors. fn to_rgba(self) -> Rgba<u8>; } impl Pixel for bool { fn default_color() -> Self { false } fn is_transparent(self) -> bool { !self } fn to_rgba(self) -> Rgba<u8> { match self { false => Rgba { data: [0, 0, 0, 0] }, true => Rgba { data: [0, 0, 0, 0xff] }, } } } #[test] fn bool_implements_pixel() { assert_eq!(bool::default_color(), false); assert_eq!(true.is_transparent(), false); assert_eq!(false.is_transparent(), true); assert_eq!(true.to_rgba(), rgba_hex(0x000000ff)); assert_eq!(false.to_rgba(), rgba_hex(0x00000000)); } impl Pixel for Rgba<u8> { fn default_color() -> Self { Rgba { data: [0, 0, 0, 0] } } fn is_transparent(self) -> bool { self.data[3] < 0xff } fn to_rgba(self) -> Rgba<u8> { self } } #[test] fn rgba_implements_pixel() { assert_eq!(Rgba::<u8>::default_color(), rgba_hex(0x00000000)); assert_eq!(rgba_hex(0x000000ff).is_transparent(), false); assert_eq!(rgba_hex(0x00000000).is_transparent(), true); assert_eq!(rgba_hex(0xff0000ff).to_rgba(), rgba_hex(0xff0000ff)); } /// A fully generic image type, which can hold non-graphical data. pub struct Pixmap<P: Pixel = Rgba<u8>> { data: Vec<P>, width: usize, height: usize, } impl<P: Pixel> Pixmap<P> { /// Make sure that these specified image size is legal. fn size_check(width: usize, height: usize) { let max_dim = isize::max_value() as usize; if width > max_dim || height > max_dim { panic!("image dimensions {}x{} are too large", width, height); } if width.checked_mul(height).is_none() { panic!("image area {}x{} is too large", width, height); } } /// Create a new `Pixmap` filled with `P::default_color()`. pub fn blank(width: usize, height: usize) -> Pixmap<P> { Pixmap::<P>::size_check(width, height); Pixmap { data: vec![P::default_color(); width * height], width: width, height: height, } } /// If `x` and `y` do not fit within the pixmap, panic. fn bounds_check(&self, x: usize, y: usize) { if x >= self.width { panic!("out of bounds x: {} width: {}", x, self.width); } if y >= self.height { panic!("out of bounds y: {} height: {}", y, self.height); } } /// The width of the `Pixmap`. pub fn width(&self) -> usize { self.width } /// The height of the `Pixmap`. pub fn height(&self) -> usize { self.height } /// Get the pixel at `x` and `y`, or panic if out of bounds. pub fn get(&self, x: usize, y: usize) -> P { self.bounds_check(x, y); self.data[y*self.width + x] } /// Get the pixel at `x` and `y`, or return `P::default_color()` if out /// of bounds. pub fn get_default(&self, x: isize, y: isize) -> P { if x < 0 || y < 0 { return P::default_color(); } // `as usize` is safe here because we're verified x and y are // non-negative. let x = x as usize; let y = y as usize; if x >= self.width || y >= self.height { P::default_color() } else { self.data[y*self.width + x] } } /// Get a mutable reference to the pixel at `x` and `y`, or panic if /// out of bounds. pub fn get_mut(&mut self, x: usize, y: usize) -> &mut P { self.bounds_check(x, y); &mut self.data[y*self.width + x] } /// Iterate over all the pixels in an image. pub fn pixels(&self) -> Pixels<P> { Pixels { iter: self.data.iter() } } /// Iterate over `(x, y, value)` for all the pixels in an image. pub fn enumerate_pixels(&self) -> EnumeratePixels<P> { EnumeratePixels { pixmap: self, x: 0, y: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// out-of-bounds pixels. pub fn all_neighbors(&self, x: usize, y: usize) -> AllNeighbors { AllNeighbors { x: cast::isize(x).expect("x outside maximum image size"), y: cast::isize(y).expect("y outside maximum image size"), i: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// only in-bounds pixels. pub fn real_neighbors(&self, x: usize, y: usize) -> RealNeighbors { RealNeighbors { width: self.width, height: self.height, x: x, y: y, i: 0, } } /// Transform each pixel of the image. pub fn map<F, P2>(&self, f: F) -> Pixmap<P2> where F: Fn(P) -> P2, P2: Pixel { Pixmap { data: self.data.iter().map(|p| f(*p)).collect(), width: self.width, height: self.height, } } /// Convert this `Pixmap` into a `RgbaImage`, for easy output. pub fn to_image(&self) -> Result<RgbaImage> { let mut raw: Vec<_> = Vec::with_capacity(self.data.len() * 4); for px in &self.data { let rgba = px.to_rgba().data; raw.extend_from_slice(&[rgba[0], rgba[1], rgba[2], rgba[3]]); } Ok(ImageBuffer::from_raw(u32_from_usize(self.width)?, u32_from_usize(self.height)?, raw).expect("image bounds mismatch")) } } #[cfg(target_pointer_width = "64")] fn u32_from_usize(i: usize) -> Result<u32> { // This can fail on 64-bit platforms. Ok(cast::u32(i)?) } #[cfg(target_pointer_width = "32")] fn u32_from_usize(i: usize) -> Result<u32>
/// An iterator over all the pixels in an image. pub struct Pixels<'a, P: Pixel> { iter: slice::Iter<'a, P>, } impl<'a, P: Pixel> Iterator for Pixels<'a, P> { type Item = P; fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|v| *v) } } /// An iterator over `(x, y, value)` for all the pixels in an image. pub struct EnumeratePixels<'a, P: Pixel> { pixmap: &'a Pixmap<P>, x: usize, y: usize, } impl<'a, P: Pixel> Iterator for EnumeratePixels<'a, P> { type Item = (usize, usize, P); fn next(&mut self) -> Option<Self::Item> { if self.pixmap.width == 0 || self.pixmap.height == 0 { return None; } if self.x >= self.pixmap.width { self.x = 0; self.y += 1; } if self.y >= self.pixmap.height { return None; } assert!(self.x < self.pixmap.width); assert!(self.y < self.pixmap.height); let px = self.pixmap.data[self.y*self.pixmap.width + self.x]; let result = Some((self.x, self.y, px)); self.x += 1; result } } /// Delta coordinates for neighboring pixels. const NEIGHBORS: &'static [(isize, isize)] = &[(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including out-of-bounds pixels. pub struct AllNeighbors { x: isize, y: isize, i: usize, } impl Iterator for AllNeighbors { type Item = (isize, isize); fn next(&mut self) -> Option<Self::Item> { if let Some(&(dx, dy)) = NEIGHBORS.get(self.i) { self.i += 1; Some((self.x + dx, self.y + dy)) } else { None } } } /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including only in-bounds pixels. pub struct RealNeighbors { width: usize, height: usize, x: usize, y: usize, i: usize, } impl Iterator for RealNeighbors { type Item = (usize, usize); fn next(&mut self) -> Option<Self::Item> { while let Some(&(dx, dy)) = NEIGHBORS.get(self.i) { self.i += 1; if self.x == 0 && dx == -1 || self.y == 0 && dy == -1 { continue; } // `as isize` is safe because of `size_check`, `as usize` is // safe because we eliminated sums of -1 above. let x = ((self.x as isize) + dx) as usize; let y = ((self.y as isize) + dy) as usize; if x == self.width || y == self.height { continue; } return Some((x, y)) } None } } impl From<RgbaImage> for Pixmap<Rgba<u8>> { fn from(image: RgbaImage) -> Pixmap<Rgba<u8>> { let width = cast::usize(image.width()); let height = cast::usize(image.height()); let channels = image.into_raw(); assert_eq!(channels.len(), width * height * 4); let mut data = Vec::with_capacity(width * height); for chunk in channels.chunks(4) { data.push(Rgba { data: [chunk[0], chunk[1], chunk[2], chunk[3]] }); } Pixmap { data: data, width: width, height: height, } } } impl<P: Pixel> fmt::Debug for Pixmap<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Pixmap") .field("width", &self.width) .field("height", &self.height) .finish() } } #[test] fn blank_fills_image_with_default() { let pixmap = Pixmap::<bool>::blank(1, 2); assert_eq!(pixmap.width(), 1); assert_eq!(pixmap.height(), 2); assert_eq!(pixmap.get(0, 0), false); } #[test] fn get_and_get_mut_provide_access_to_pixels() { let mut pixmap = Pixmap::<bool>::blank(1, 1); assert_eq!(pixmap.get(0, 0), false); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get(0, 0), true); } #[test] #[should_panic] fn get_panics_when_out_of_bounds() { let pixmap = Pixmap::<bool>::blank(1, 1); pixmap.get(1, 1); } #[test] fn get_default_returns_default_color_when_out_of_bounds() { let mut pixmap = Pixmap::<bool>::blank(1, 1); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get_default(0, -1), false); assert_eq!(pixmap.get_default(-1, 0), false); assert_eq!(pixmap.get_default(0, 1), false); assert_eq!(pixmap.get_default(1, 0), false); } #[test] fn pixels_iterates_over_all_pixel_values() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let pixels = pixmap.pixels().collect::<Vec<_>>(); assert_eq!(pixels, &[true, false]); } #[test] fn enumerate_pixels_iterates_over_pixel_values_and_coordinates() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let output = pixmap.enumerate_pixels().collect::<Vec<_>>(); assert_eq!(output, &[(0, 0, true), (1, 0, false)]); } #[test] fn all_neighbors_iterates_over_all_neighbor_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.all_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, -1), (1, -1), (2, -1), (0, 0), (2, 0), (0, 1), (1, 1), (2, 1)]); } #[test] fn real_neighbors_iterates_over_in_bounds_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.real_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, 0)]); } #[test] fn map_creates_a_new_image_by_applying_a_function() { let mut pixmap = Pixmap::<bool>::blank(1, 2); *pixmap.get_mut(0, 0) = true; let mapped = pixmap.map(|p| { match p { true => rgba_hex(0xff0000ff), false => rgba_hex(0x00ff00ff), } }); assert_eq!(mapped.get(0, 0), rgba_hex(0xff0000ff)); assert_eq!(mapped.get(0, 1), rgba_hex(0x00ff00ff)); } #[test] fn to_image_converts_to_image() { let mut pixmap = Pixmap::<bool>::blank(1, 2); *pixmap.get_mut(0, 0) = true; let image = pixmap.to_image().unwrap(); assert_eq!(image.width(), 1); assert_eq!(image.height(), 2); assert_eq!(image[(0, 0)], rgba_hex(0x000000ff)); assert_eq!(image[(0, 1)], rgba_hex(0x00000000)); } #[test] fn from_image_constructs_from_rgba_image() { let image: RgbaImage = ImageBuffer::from_pixel(2, 1, rgba_hex(0xff0000ff)); let pixmap = Pixmap::from(image); assert_eq!(pixmap.width(), 2); assert_eq!(pixmap.height(), 1); assert_eq!(pixmap.get(0, 0), rgba_hex(0xff0000ff)); }
{ // This will always succeed on 32-bit platforms. Ok(cast::u32(i)) }
identifier_body
pixmap.rs
//! Custom pixmaps which can handle kinds of data that the `image` library //! doesn't support. use cast; use common_failures::prelude::*; use image::{ImageBuffer, Rgba, RgbaImage}; use std::fmt; use std::slice; #[cfg(test)] use test_util::rgba_hex; /// A type which can be used as a pixel in a `Pixmap`. pub trait Pixel: Clone + Copy + fmt::Debug +'static { /// This is basically just `Default::default`. We would normally just /// base this trait on `Default`, but we also want to implement this /// trait for `image::Rgba`, which doesn't implement `Default`. fn default_color() -> Self; /// Is this pixel transparent? fn is_transparent(self) -> bool; /// Return a RGBA color for this pixel. Used for visualizing images /// with pixel types that aren't ordinary colors. fn to_rgba(self) -> Rgba<u8>; } impl Pixel for bool { fn default_color() -> Self { false } fn is_transparent(self) -> bool { !self } fn to_rgba(self) -> Rgba<u8> { match self { false => Rgba { data: [0, 0, 0, 0] }, true => Rgba { data: [0, 0, 0, 0xff] }, } } } #[test] fn bool_implements_pixel() { assert_eq!(bool::default_color(), false); assert_eq!(true.is_transparent(), false); assert_eq!(false.is_transparent(), true); assert_eq!(true.to_rgba(), rgba_hex(0x000000ff)); assert_eq!(false.to_rgba(), rgba_hex(0x00000000)); } impl Pixel for Rgba<u8> { fn default_color() -> Self { Rgba { data: [0, 0, 0, 0] } } fn is_transparent(self) -> bool { self.data[3] < 0xff } fn to_rgba(self) -> Rgba<u8> { self } } #[test] fn rgba_implements_pixel() { assert_eq!(Rgba::<u8>::default_color(), rgba_hex(0x00000000)); assert_eq!(rgba_hex(0x000000ff).is_transparent(), false); assert_eq!(rgba_hex(0x00000000).is_transparent(), true); assert_eq!(rgba_hex(0xff0000ff).to_rgba(), rgba_hex(0xff0000ff)); } /// A fully generic image type, which can hold non-graphical data. pub struct Pixmap<P: Pixel = Rgba<u8>> { data: Vec<P>, width: usize, height: usize, } impl<P: Pixel> Pixmap<P> { /// Make sure that these specified image size is legal. fn size_check(width: usize, height: usize) { let max_dim = isize::max_value() as usize; if width > max_dim || height > max_dim { panic!("image dimensions {}x{} are too large", width, height); } if width.checked_mul(height).is_none() { panic!("image area {}x{} is too large", width, height); } } /// Create a new `Pixmap` filled with `P::default_color()`. pub fn blank(width: usize, height: usize) -> Pixmap<P> { Pixmap::<P>::size_check(width, height); Pixmap { data: vec![P::default_color(); width * height], width: width, height: height, } } /// If `x` and `y` do not fit within the pixmap, panic. fn bounds_check(&self, x: usize, y: usize) { if x >= self.width { panic!("out of bounds x: {} width: {}", x, self.width); } if y >= self.height { panic!("out of bounds y: {} height: {}", y, self.height); } } /// The width of the `Pixmap`. pub fn width(&self) -> usize { self.width } /// The height of the `Pixmap`. pub fn height(&self) -> usize { self.height } /// Get the pixel at `x` and `y`, or panic if out of bounds. pub fn get(&self, x: usize, y: usize) -> P { self.bounds_check(x, y); self.data[y*self.width + x] } /// Get the pixel at `x` and `y`, or return `P::default_color()` if out /// of bounds. pub fn get_default(&self, x: isize, y: isize) -> P { if x < 0 || y < 0 { return P::default_color(); } // `as usize` is safe here because we're verified x and y are // non-negative. let x = x as usize; let y = y as usize; if x >= self.width || y >= self.height { P::default_color() } else { self.data[y*self.width + x] } } /// Get a mutable reference to the pixel at `x` and `y`, or panic if /// out of bounds. pub fn get_mut(&mut self, x: usize, y: usize) -> &mut P { self.bounds_check(x, y); &mut self.data[y*self.width + x] } /// Iterate over all the pixels in an image. pub fn pixels(&self) -> Pixels<P> { Pixels { iter: self.data.iter() } } /// Iterate over `(x, y, value)` for all the pixels in an image. pub fn enumerate_pixels(&self) -> EnumeratePixels<P> { EnumeratePixels { pixmap: self, x: 0, y: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// out-of-bounds pixels. pub fn all_neighbors(&self, x: usize, y: usize) -> AllNeighbors { AllNeighbors { x: cast::isize(x).expect("x outside maximum image size"), y: cast::isize(y).expect("y outside maximum image size"), i: 0, } } /// The coordinates `(x, y)` of all neighboring pixels, including /// only in-bounds pixels. pub fn real_neighbors(&self, x: usize, y: usize) -> RealNeighbors { RealNeighbors { width: self.width, height: self.height, x: x, y: y, i: 0, } } /// Transform each pixel of the image. pub fn map<F, P2>(&self, f: F) -> Pixmap<P2> where F: Fn(P) -> P2, P2: Pixel { Pixmap { data: self.data.iter().map(|p| f(*p)).collect(), width: self.width, height: self.height, } } /// Convert this `Pixmap` into a `RgbaImage`, for easy output. pub fn to_image(&self) -> Result<RgbaImage> { let mut raw: Vec<_> = Vec::with_capacity(self.data.len() * 4); for px in &self.data { let rgba = px.to_rgba().data; raw.extend_from_slice(&[rgba[0], rgba[1], rgba[2], rgba[3]]); } Ok(ImageBuffer::from_raw(u32_from_usize(self.width)?, u32_from_usize(self.height)?, raw).expect("image bounds mismatch")) } } #[cfg(target_pointer_width = "64")] fn u32_from_usize(i: usize) -> Result<u32> { // This can fail on 64-bit platforms. Ok(cast::u32(i)?) } #[cfg(target_pointer_width = "32")] fn
(i: usize) -> Result<u32> { // This will always succeed on 32-bit platforms. Ok(cast::u32(i)) } /// An iterator over all the pixels in an image. pub struct Pixels<'a, P: Pixel> { iter: slice::Iter<'a, P>, } impl<'a, P: Pixel> Iterator for Pixels<'a, P> { type Item = P; fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|v| *v) } } /// An iterator over `(x, y, value)` for all the pixels in an image. pub struct EnumeratePixels<'a, P: Pixel> { pixmap: &'a Pixmap<P>, x: usize, y: usize, } impl<'a, P: Pixel> Iterator for EnumeratePixels<'a, P> { type Item = (usize, usize, P); fn next(&mut self) -> Option<Self::Item> { if self.pixmap.width == 0 || self.pixmap.height == 0 { return None; } if self.x >= self.pixmap.width { self.x = 0; self.y += 1; } if self.y >= self.pixmap.height { return None; } assert!(self.x < self.pixmap.width); assert!(self.y < self.pixmap.height); let px = self.pixmap.data[self.y*self.pixmap.width + self.x]; let result = Some((self.x, self.y, px)); self.x += 1; result } } /// Delta coordinates for neighboring pixels. const NEIGHBORS: &'static [(isize, isize)] = &[(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including out-of-bounds pixels. pub struct AllNeighbors { x: isize, y: isize, i: usize, } impl Iterator for AllNeighbors { type Item = (isize, isize); fn next(&mut self) -> Option<Self::Item> { if let Some(&(dx, dy)) = NEIGHBORS.get(self.i) { self.i += 1; Some((self.x + dx, self.y + dy)) } else { None } } } /// An iterator over the coordinates `(x, y)` of all neighboring pixels, /// including only in-bounds pixels. pub struct RealNeighbors { width: usize, height: usize, x: usize, y: usize, i: usize, } impl Iterator for RealNeighbors { type Item = (usize, usize); fn next(&mut self) -> Option<Self::Item> { while let Some(&(dx, dy)) = NEIGHBORS.get(self.i) { self.i += 1; if self.x == 0 && dx == -1 || self.y == 0 && dy == -1 { continue; } // `as isize` is safe because of `size_check`, `as usize` is // safe because we eliminated sums of -1 above. let x = ((self.x as isize) + dx) as usize; let y = ((self.y as isize) + dy) as usize; if x == self.width || y == self.height { continue; } return Some((x, y)) } None } } impl From<RgbaImage> for Pixmap<Rgba<u8>> { fn from(image: RgbaImage) -> Pixmap<Rgba<u8>> { let width = cast::usize(image.width()); let height = cast::usize(image.height()); let channels = image.into_raw(); assert_eq!(channels.len(), width * height * 4); let mut data = Vec::with_capacity(width * height); for chunk in channels.chunks(4) { data.push(Rgba { data: [chunk[0], chunk[1], chunk[2], chunk[3]] }); } Pixmap { data: data, width: width, height: height, } } } impl<P: Pixel> fmt::Debug for Pixmap<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Pixmap") .field("width", &self.width) .field("height", &self.height) .finish() } } #[test] fn blank_fills_image_with_default() { let pixmap = Pixmap::<bool>::blank(1, 2); assert_eq!(pixmap.width(), 1); assert_eq!(pixmap.height(), 2); assert_eq!(pixmap.get(0, 0), false); } #[test] fn get_and_get_mut_provide_access_to_pixels() { let mut pixmap = Pixmap::<bool>::blank(1, 1); assert_eq!(pixmap.get(0, 0), false); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get(0, 0), true); } #[test] #[should_panic] fn get_panics_when_out_of_bounds() { let pixmap = Pixmap::<bool>::blank(1, 1); pixmap.get(1, 1); } #[test] fn get_default_returns_default_color_when_out_of_bounds() { let mut pixmap = Pixmap::<bool>::blank(1, 1); *pixmap.get_mut(0, 0) = true; assert_eq!(pixmap.get_default(0, -1), false); assert_eq!(pixmap.get_default(-1, 0), false); assert_eq!(pixmap.get_default(0, 1), false); assert_eq!(pixmap.get_default(1, 0), false); } #[test] fn pixels_iterates_over_all_pixel_values() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let pixels = pixmap.pixels().collect::<Vec<_>>(); assert_eq!(pixels, &[true, false]); } #[test] fn enumerate_pixels_iterates_over_pixel_values_and_coordinates() { let mut pixmap = Pixmap::<bool>::blank(2, 1); *pixmap.get_mut(0, 0) = true; let output = pixmap.enumerate_pixels().collect::<Vec<_>>(); assert_eq!(output, &[(0, 0, true), (1, 0, false)]); } #[test] fn all_neighbors_iterates_over_all_neighbor_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.all_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, -1), (1, -1), (2, -1), (0, 0), (2, 0), (0, 1), (1, 1), (2, 1)]); } #[test] fn real_neighbors_iterates_over_in_bounds_coordinates() { let pixmap = Pixmap::<bool>::blank(2, 1); let output = pixmap.real_neighbors(1, 0).collect::<Vec<_>>(); assert_eq!(output, &[(0, 0)]); } #[test] fn map_creates_a_new_image_by_applying_a_function() { let mut pixmap = Pixmap::<bool>::blank(1, 2); *pixmap.get_mut(0, 0) = true; let mapped = pixmap.map(|p| { match p { true => rgba_hex(0xff0000ff), false => rgba_hex(0x00ff00ff), } }); assert_eq!(mapped.get(0, 0), rgba_hex(0xff0000ff)); assert_eq!(mapped.get(0, 1), rgba_hex(0x00ff00ff)); } #[test] fn to_image_converts_to_image() { let mut pixmap = Pixmap::<bool>::blank(1, 2); *pixmap.get_mut(0, 0) = true; let image = pixmap.to_image().unwrap(); assert_eq!(image.width(), 1); assert_eq!(image.height(), 2); assert_eq!(image[(0, 0)], rgba_hex(0x000000ff)); assert_eq!(image[(0, 1)], rgba_hex(0x00000000)); } #[test] fn from_image_constructs_from_rgba_image() { let image: RgbaImage = ImageBuffer::from_pixel(2, 1, rgba_hex(0xff0000ff)); let pixmap = Pixmap::from(image); assert_eq!(pixmap.width(), 2); assert_eq!(pixmap.height(), 1); assert_eq!(pixmap.get(0, 0), rgba_hex(0xff0000ff)); }
u32_from_usize
identifier_name
mutex.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. //! A native mutex and condition variable type //! //! This module contains bindings to the platform's native mutex/condition //! variable primitives. It provides a single type, `Mutex`, which can be //! statically initialized via the `MUTEX_INIT` value. This object serves as both a //! mutex and a condition variable simultaneously. //! //! The lock is lazily initialized, but it can only be unsafely destroyed. A //! statically initialized lock doesn't necessarily have a time at which it can //! get deallocated. For this reason, there is no `Drop` implementation of the //! mutex, but rather the `destroy()` method must be invoked manually if //! destruction of the mutex is desired. //! //! It is not recommended to use this type for idiomatic rust use. This type is //! appropriate where no other options are available, but other rust concurrency //! primitives should be used before this type. //! //! # Example //! //! use std::unstable::mutex::{Mutex, MUTEX_INIT}; //! //! // Use a statically initialized mutex //! static mut lock: Mutex = MUTEX_INIT; //! //! unsafe { //! lock.lock(); //! lock.unlock(); //! } //! //! // Use a normally initialied mutex //! let mut lock = Mutex::new(); //! unsafe { //! lock.lock(); //! lock.unlock(); //! lock.destroy(); //! } #[allow(non_camel_case_types)]; use libc::c_void; use unstable::atomics; pub struct Mutex { // pointers for the lock/cond handles, atomically updated priv lock: atomics::AtomicUint, priv cond: atomics::AtomicUint, } pub static MUTEX_INIT: Mutex = Mutex { lock: atomics::INIT_ATOMIC_UINT, cond: atomics::INIT_ATOMIC_UINT, }; impl Mutex { /// Creates a new mutex, with the lock/condition variable pre-initialized pub unsafe fn new() -> Mutex { Mutex { lock: atomics::AtomicUint::new(imp::init_lock() as uint), cond: atomics::AtomicUint::new(imp::init_cond() as uint), } } /// Creates a new mutex, with the lock/condition variable not initialized. /// This is the same as initializing from the MUTEX_INIT static. pub unsafe fn empty() -> Mutex { Mutex { lock: atomics::AtomicUint::new(0), cond: atomics::AtomicUint::new(0), } } /// Creates a new copy of this mutex. This is an unsafe operation because /// there is no reference counting performed on this type. /// /// This function may only be called on mutexes which have had both the /// internal condition variable and lock initialized. This means that the /// mutex must have been created via `new`, or usage of it has already /// initialized the internal handles. /// /// This is a dangerous function to call as both this mutex and the returned /// mutex will share the same handles to the underlying mutex/condition /// variable. Care must be taken to ensure that deallocation happens /// accordingly. pub unsafe fn clone(&self) -> Mutex { let lock = self.lock.load(atomics::Relaxed); let cond = self.cond.load(atomics::Relaxed); assert!(lock!= 0); assert!(cond!= 0); Mutex { lock: atomics::AtomicUint::new(lock), cond: atomics::AtomicUint::new(cond), } } /// Acquires this lock. This assumes that the current thread does not /// already hold the lock. pub unsafe fn lock(&mut self)
/// Attempts to acquire the lock. The value returned is whether the lock was /// acquired or not pub unsafe fn trylock(&mut self) -> bool { imp::trylock(self.getlock()) } /// Unlocks the lock. This assumes that the current thread already holds the /// lock. pub unsafe fn unlock(&mut self) { imp::unlock(self.getlock()) } /// Block on the internal condition variable. /// /// This function assumes that the lock is already held pub unsafe fn wait(&mut self) { imp::wait(self.getcond(), self.getlock()) } /// Signals a thread in `wait` to wake up pub unsafe fn signal(&mut self) { imp::signal(self.getcond()) } /// This function is especially unsafe because there are no guarantees made /// that no other thread is currently holding the lock or waiting on the /// condition variable contained inside. pub unsafe fn destroy(&mut self) { let lock = self.lock.swap(0, atomics::Relaxed); let cond = self.cond.swap(0, atomics::Relaxed); if lock!= 0 { imp::free_lock(lock) } if cond!= 0 { imp::free_cond(cond) } } unsafe fn getlock(&mut self) -> *c_void { match self.lock.load(atomics::Relaxed) { 0 => {} n => return n as *c_void } let lock = imp::init_lock(); match self.lock.compare_and_swap(0, lock, atomics::SeqCst) { 0 => return lock as *c_void, _ => {} } imp::free_lock(lock); return self.lock.load(atomics::Relaxed) as *c_void; } unsafe fn getcond(&mut self) -> *c_void { match self.cond.load(atomics::Relaxed) { 0 => {} n => return n as *c_void } let cond = imp::init_cond(); match self.cond.compare_and_swap(0, cond, atomics::SeqCst) { 0 => return cond as *c_void, _ => {} } imp::free_cond(cond); return self.cond.load(atomics::Relaxed) as *c_void; } } #[cfg(unix)] mod imp { use libc::c_void; use libc; use ptr; type pthread_mutex_t = libc::c_void; type pthread_mutexattr_t = libc::c_void; type pthread_cond_t = libc::c_void; type pthread_condattr_t = libc::c_void; pub unsafe fn init_lock() -> uint { let block = libc::malloc(rust_pthread_mutex_t_size() as libc::size_t); assert!(!block.is_null()); let n = pthread_mutex_init(block, ptr::null()); assert_eq!(n, 0); return block as uint; } pub unsafe fn init_cond() -> uint { let block = libc::malloc(rust_pthread_cond_t_size() as libc::size_t); assert!(!block.is_null()); let n = pthread_cond_init(block, ptr::null()); assert_eq!(n, 0); return block as uint; } pub unsafe fn free_lock(h: uint) { let block = h as *c_void; assert_eq!(pthread_mutex_destroy(block), 0); libc::free(block); } pub unsafe fn free_cond(h: uint) { let block = h as *c_void; assert_eq!(pthread_cond_destroy(block), 0); libc::free(block); } pub unsafe fn lock(l: *pthread_mutex_t) { assert_eq!(pthread_mutex_lock(l), 0); } pub unsafe fn trylock(l: *c_void) -> bool { pthread_mutex_trylock(l) == 0 } pub unsafe fn unlock(l: *pthread_mutex_t) { assert_eq!(pthread_mutex_unlock(l), 0); } pub unsafe fn wait(cond: *pthread_cond_t, m: *pthread_mutex_t) { assert_eq!(pthread_cond_wait(cond, m), 0); } pub unsafe fn signal(cond: *pthread_cond_t) { assert_eq!(pthread_cond_signal(cond), 0); } extern { fn rust_pthread_mutex_t_size() -> libc::c_int; fn rust_pthread_cond_t_size() -> libc::c_int; } extern { fn pthread_mutex_init(lock: *pthread_mutex_t, attr: *pthread_mutexattr_t) -> libc::c_int; fn pthread_mutex_destroy(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_init(cond: *pthread_cond_t, attr: *pthread_condattr_t) -> libc::c_int; fn pthread_cond_destroy(cond: *pthread_cond_t) -> libc::c_int; fn pthread_mutex_lock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_mutex_trylock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_mutex_unlock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_wait(cond: *pthread_cond_t, lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_signal(cond: *pthread_cond_t) -> libc::c_int; } } #[cfg(windows)] mod imp { use libc; use libc::{HANDLE, BOOL, LPSECURITY_ATTRIBUTES, c_void, DWORD, LPCSTR}; use ptr; type LPCRITICAL_SECTION = *c_void; static SPIN_COUNT: DWORD = 4000; pub unsafe fn init_lock() -> uint { let block = libc::malloc(rust_crit_section_size() as libc::size_t); assert!(!block.is_null()); InitializeCriticalSectionAndSpinCount(block, SPIN_COUNT); return block as uint; } pub unsafe fn init_cond() -> uint { return CreateEventA(ptr::mut_null(), libc::FALSE, libc::FALSE, ptr::null()) as uint; } pub unsafe fn free_lock(h: uint) { DeleteCriticalSection(h as LPCRITICAL_SECTION); libc::free(h as *c_void); } pub unsafe fn free_cond(h: uint) { let block = h as HANDLE; libc::CloseHandle(block); } pub unsafe fn lock(l: *c_void) { EnterCriticalSection(l as LPCRITICAL_SECTION) } pub unsafe fn trylock(l: *c_void) -> bool { TryEnterCriticalSection(l as LPCRITICAL_SECTION)!= 0 } pub unsafe fn unlock(l: *c_void) { LeaveCriticalSection(l as LPCRITICAL_SECTION) } pub unsafe fn wait(cond: *c_void, m: *c_void) { unlock(m); WaitForSingleObject(cond as HANDLE, 0); lock(m); } pub unsafe fn signal(cond: *c_void) { assert!(SetEvent(cond as HANDLE)!= 0); } extern { fn rust_crit_section_size() -> libc::c_int; } extern "system" { fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, bInitialState: BOOL, lpName: LPCSTR) -> HANDLE; fn InitializeCriticalSectionAndSpinCount( lpCriticalSection: LPCRITICAL_SECTION, dwSpinCount: DWORD) -> BOOL; fn DeleteCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn EnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn LeaveCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn TryEnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION) -> BOOL; fn SetEvent(hEvent: HANDLE) -> BOOL; fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; } } #[cfg(test)] mod test { use super::{Mutex, MUTEX_INIT}; use rt::thread::Thread; #[test] fn somke_lock() { static mut lock: Mutex = MUTEX_INIT; unsafe { lock.lock(); lock.unlock(); } } #[test] fn somke_cond() { static mut lock: Mutex = MUTEX_INIT; unsafe { let t = do Thread::start { lock.lock(); lock.signal(); lock.unlock(); }; lock.lock(); lock.wait(); lock.unlock(); t.join(); } } #[test] fn destroy_immediately() { unsafe { let mut m = Mutex::empty(); m.destroy(); } } }
{ imp::lock(self.getlock()) }
identifier_body
mutex.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. //! A native mutex and condition variable type //! //! This module contains bindings to the platform's native mutex/condition //! variable primitives. It provides a single type, `Mutex`, which can be //! statically initialized via the `MUTEX_INIT` value. This object serves as both a //! mutex and a condition variable simultaneously. //! //! The lock is lazily initialized, but it can only be unsafely destroyed. A //! statically initialized lock doesn't necessarily have a time at which it can //! get deallocated. For this reason, there is no `Drop` implementation of the //! mutex, but rather the `destroy()` method must be invoked manually if //! destruction of the mutex is desired. //! //! It is not recommended to use this type for idiomatic rust use. This type is //! appropriate where no other options are available, but other rust concurrency //! primitives should be used before this type. //! //! # Example //! //! use std::unstable::mutex::{Mutex, MUTEX_INIT}; //! //! // Use a statically initialized mutex //! static mut lock: Mutex = MUTEX_INIT; //! //! unsafe { //! lock.lock(); //! lock.unlock(); //! } //! //! // Use a normally initialied mutex //! let mut lock = Mutex::new(); //! unsafe { //! lock.lock(); //! lock.unlock(); //! lock.destroy(); //! } #[allow(non_camel_case_types)]; use libc::c_void; use unstable::atomics; pub struct Mutex { // pointers for the lock/cond handles, atomically updated priv lock: atomics::AtomicUint, priv cond: atomics::AtomicUint, } pub static MUTEX_INIT: Mutex = Mutex { lock: atomics::INIT_ATOMIC_UINT, cond: atomics::INIT_ATOMIC_UINT, }; impl Mutex { /// Creates a new mutex, with the lock/condition variable pre-initialized pub unsafe fn new() -> Mutex { Mutex { lock: atomics::AtomicUint::new(imp::init_lock() as uint), cond: atomics::AtomicUint::new(imp::init_cond() as uint), } } /// Creates a new mutex, with the lock/condition variable not initialized. /// This is the same as initializing from the MUTEX_INIT static. pub unsafe fn empty() -> Mutex { Mutex { lock: atomics::AtomicUint::new(0), cond: atomics::AtomicUint::new(0), } } /// Creates a new copy of this mutex. This is an unsafe operation because /// there is no reference counting performed on this type. /// /// This function may only be called on mutexes which have had both the /// internal condition variable and lock initialized. This means that the /// mutex must have been created via `new`, or usage of it has already /// initialized the internal handles. /// /// This is a dangerous function to call as both this mutex and the returned /// mutex will share the same handles to the underlying mutex/condition /// variable. Care must be taken to ensure that deallocation happens /// accordingly. pub unsafe fn clone(&self) -> Mutex { let lock = self.lock.load(atomics::Relaxed); let cond = self.cond.load(atomics::Relaxed); assert!(lock!= 0); assert!(cond!= 0); Mutex { lock: atomics::AtomicUint::new(lock), cond: atomics::AtomicUint::new(cond), } } /// Acquires this lock. This assumes that the current thread does not /// already hold the lock. pub unsafe fn lock(&mut self) { imp::lock(self.getlock()) } /// Attempts to acquire the lock. The value returned is whether the lock was /// acquired or not pub unsafe fn trylock(&mut self) -> bool { imp::trylock(self.getlock()) } /// Unlocks the lock. This assumes that the current thread already holds the /// lock. pub unsafe fn unlock(&mut self) { imp::unlock(self.getlock()) } /// Block on the internal condition variable. /// /// This function assumes that the lock is already held pub unsafe fn wait(&mut self) { imp::wait(self.getcond(), self.getlock()) } /// Signals a thread in `wait` to wake up pub unsafe fn signal(&mut self) { imp::signal(self.getcond()) } /// This function is especially unsafe because there are no guarantees made /// that no other thread is currently holding the lock or waiting on the /// condition variable contained inside. pub unsafe fn destroy(&mut self) { let lock = self.lock.swap(0, atomics::Relaxed); let cond = self.cond.swap(0, atomics::Relaxed); if lock!= 0 { imp::free_lock(lock) } if cond!= 0 { imp::free_cond(cond) } } unsafe fn getlock(&mut self) -> *c_void { match self.lock.load(atomics::Relaxed) { 0 => {} n => return n as *c_void } let lock = imp::init_lock(); match self.lock.compare_and_swap(0, lock, atomics::SeqCst) { 0 => return lock as *c_void, _ => {} } imp::free_lock(lock); return self.lock.load(atomics::Relaxed) as *c_void; } unsafe fn getcond(&mut self) -> *c_void { match self.cond.load(atomics::Relaxed) { 0 => {} n => return n as *c_void } let cond = imp::init_cond(); match self.cond.compare_and_swap(0, cond, atomics::SeqCst) { 0 => return cond as *c_void, _ => {} } imp::free_cond(cond); return self.cond.load(atomics::Relaxed) as *c_void; } } #[cfg(unix)] mod imp { use libc::c_void; use libc; use ptr; type pthread_mutex_t = libc::c_void; type pthread_mutexattr_t = libc::c_void; type pthread_cond_t = libc::c_void; type pthread_condattr_t = libc::c_void; pub unsafe fn init_lock() -> uint { let block = libc::malloc(rust_pthread_mutex_t_size() as libc::size_t); assert!(!block.is_null()); let n = pthread_mutex_init(block, ptr::null()); assert_eq!(n, 0); return block as uint; } pub unsafe fn init_cond() -> uint { let block = libc::malloc(rust_pthread_cond_t_size() as libc::size_t); assert!(!block.is_null()); let n = pthread_cond_init(block, ptr::null()); assert_eq!(n, 0); return block as uint; } pub unsafe fn free_lock(h: uint) { let block = h as *c_void; assert_eq!(pthread_mutex_destroy(block), 0); libc::free(block); } pub unsafe fn free_cond(h: uint) { let block = h as *c_void; assert_eq!(pthread_cond_destroy(block), 0); libc::free(block); } pub unsafe fn lock(l: *pthread_mutex_t) { assert_eq!(pthread_mutex_lock(l), 0); } pub unsafe fn trylock(l: *c_void) -> bool { pthread_mutex_trylock(l) == 0 } pub unsafe fn unlock(l: *pthread_mutex_t) { assert_eq!(pthread_mutex_unlock(l), 0); } pub unsafe fn wait(cond: *pthread_cond_t, m: *pthread_mutex_t) { assert_eq!(pthread_cond_wait(cond, m), 0); } pub unsafe fn signal(cond: *pthread_cond_t) { assert_eq!(pthread_cond_signal(cond), 0); } extern { fn rust_pthread_mutex_t_size() -> libc::c_int; fn rust_pthread_cond_t_size() -> libc::c_int; } extern { fn pthread_mutex_init(lock: *pthread_mutex_t, attr: *pthread_mutexattr_t) -> libc::c_int; fn pthread_mutex_destroy(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_init(cond: *pthread_cond_t, attr: *pthread_condattr_t) -> libc::c_int; fn pthread_cond_destroy(cond: *pthread_cond_t) -> libc::c_int; fn pthread_mutex_lock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_mutex_trylock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_mutex_unlock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_wait(cond: *pthread_cond_t, lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_signal(cond: *pthread_cond_t) -> libc::c_int; } } #[cfg(windows)] mod imp { use libc; use libc::{HANDLE, BOOL, LPSECURITY_ATTRIBUTES, c_void, DWORD, LPCSTR}; use ptr; type LPCRITICAL_SECTION = *c_void; static SPIN_COUNT: DWORD = 4000; pub unsafe fn init_lock() -> uint { let block = libc::malloc(rust_crit_section_size() as libc::size_t); assert!(!block.is_null()); InitializeCriticalSectionAndSpinCount(block, SPIN_COUNT); return block as uint; } pub unsafe fn init_cond() -> uint { return CreateEventA(ptr::mut_null(), libc::FALSE, libc::FALSE, ptr::null()) as uint; } pub unsafe fn free_lock(h: uint) { DeleteCriticalSection(h as LPCRITICAL_SECTION); libc::free(h as *c_void); } pub unsafe fn free_cond(h: uint) { let block = h as HANDLE; libc::CloseHandle(block); } pub unsafe fn lock(l: *c_void) { EnterCriticalSection(l as LPCRITICAL_SECTION) } pub unsafe fn trylock(l: *c_void) -> bool {
} pub unsafe fn unlock(l: *c_void) { LeaveCriticalSection(l as LPCRITICAL_SECTION) } pub unsafe fn wait(cond: *c_void, m: *c_void) { unlock(m); WaitForSingleObject(cond as HANDLE, 0); lock(m); } pub unsafe fn signal(cond: *c_void) { assert!(SetEvent(cond as HANDLE)!= 0); } extern { fn rust_crit_section_size() -> libc::c_int; } extern "system" { fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, bInitialState: BOOL, lpName: LPCSTR) -> HANDLE; fn InitializeCriticalSectionAndSpinCount( lpCriticalSection: LPCRITICAL_SECTION, dwSpinCount: DWORD) -> BOOL; fn DeleteCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn EnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn LeaveCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn TryEnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION) -> BOOL; fn SetEvent(hEvent: HANDLE) -> BOOL; fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; } } #[cfg(test)] mod test { use super::{Mutex, MUTEX_INIT}; use rt::thread::Thread; #[test] fn somke_lock() { static mut lock: Mutex = MUTEX_INIT; unsafe { lock.lock(); lock.unlock(); } } #[test] fn somke_cond() { static mut lock: Mutex = MUTEX_INIT; unsafe { let t = do Thread::start { lock.lock(); lock.signal(); lock.unlock(); }; lock.lock(); lock.wait(); lock.unlock(); t.join(); } } #[test] fn destroy_immediately() { unsafe { let mut m = Mutex::empty(); m.destroy(); } } }
TryEnterCriticalSection(l as LPCRITICAL_SECTION) != 0
random_line_split
mutex.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. //! A native mutex and condition variable type //! //! This module contains bindings to the platform's native mutex/condition //! variable primitives. It provides a single type, `Mutex`, which can be //! statically initialized via the `MUTEX_INIT` value. This object serves as both a //! mutex and a condition variable simultaneously. //! //! The lock is lazily initialized, but it can only be unsafely destroyed. A //! statically initialized lock doesn't necessarily have a time at which it can //! get deallocated. For this reason, there is no `Drop` implementation of the //! mutex, but rather the `destroy()` method must be invoked manually if //! destruction of the mutex is desired. //! //! It is not recommended to use this type for idiomatic rust use. This type is //! appropriate where no other options are available, but other rust concurrency //! primitives should be used before this type. //! //! # Example //! //! use std::unstable::mutex::{Mutex, MUTEX_INIT}; //! //! // Use a statically initialized mutex //! static mut lock: Mutex = MUTEX_INIT; //! //! unsafe { //! lock.lock(); //! lock.unlock(); //! } //! //! // Use a normally initialied mutex //! let mut lock = Mutex::new(); //! unsafe { //! lock.lock(); //! lock.unlock(); //! lock.destroy(); //! } #[allow(non_camel_case_types)]; use libc::c_void; use unstable::atomics; pub struct Mutex { // pointers for the lock/cond handles, atomically updated priv lock: atomics::AtomicUint, priv cond: atomics::AtomicUint, } pub static MUTEX_INIT: Mutex = Mutex { lock: atomics::INIT_ATOMIC_UINT, cond: atomics::INIT_ATOMIC_UINT, }; impl Mutex { /// Creates a new mutex, with the lock/condition variable pre-initialized pub unsafe fn new() -> Mutex { Mutex { lock: atomics::AtomicUint::new(imp::init_lock() as uint), cond: atomics::AtomicUint::new(imp::init_cond() as uint), } } /// Creates a new mutex, with the lock/condition variable not initialized. /// This is the same as initializing from the MUTEX_INIT static. pub unsafe fn empty() -> Mutex { Mutex { lock: atomics::AtomicUint::new(0), cond: atomics::AtomicUint::new(0), } } /// Creates a new copy of this mutex. This is an unsafe operation because /// there is no reference counting performed on this type. /// /// This function may only be called on mutexes which have had both the /// internal condition variable and lock initialized. This means that the /// mutex must have been created via `new`, or usage of it has already /// initialized the internal handles. /// /// This is a dangerous function to call as both this mutex and the returned /// mutex will share the same handles to the underlying mutex/condition /// variable. Care must be taken to ensure that deallocation happens /// accordingly. pub unsafe fn clone(&self) -> Mutex { let lock = self.lock.load(atomics::Relaxed); let cond = self.cond.load(atomics::Relaxed); assert!(lock!= 0); assert!(cond!= 0); Mutex { lock: atomics::AtomicUint::new(lock), cond: atomics::AtomicUint::new(cond), } } /// Acquires this lock. This assumes that the current thread does not /// already hold the lock. pub unsafe fn lock(&mut self) { imp::lock(self.getlock()) } /// Attempts to acquire the lock. The value returned is whether the lock was /// acquired or not pub unsafe fn trylock(&mut self) -> bool { imp::trylock(self.getlock()) } /// Unlocks the lock. This assumes that the current thread already holds the /// lock. pub unsafe fn unlock(&mut self) { imp::unlock(self.getlock()) } /// Block on the internal condition variable. /// /// This function assumes that the lock is already held pub unsafe fn wait(&mut self) { imp::wait(self.getcond(), self.getlock()) } /// Signals a thread in `wait` to wake up pub unsafe fn signal(&mut self) { imp::signal(self.getcond()) } /// This function is especially unsafe because there are no guarantees made /// that no other thread is currently holding the lock or waiting on the /// condition variable contained inside. pub unsafe fn destroy(&mut self) { let lock = self.lock.swap(0, atomics::Relaxed); let cond = self.cond.swap(0, atomics::Relaxed); if lock!= 0 { imp::free_lock(lock) } if cond!= 0 { imp::free_cond(cond) } } unsafe fn getlock(&mut self) -> *c_void { match self.lock.load(atomics::Relaxed) { 0 => {} n => return n as *c_void } let lock = imp::init_lock(); match self.lock.compare_and_swap(0, lock, atomics::SeqCst) { 0 => return lock as *c_void, _ => {} } imp::free_lock(lock); return self.lock.load(atomics::Relaxed) as *c_void; } unsafe fn getcond(&mut self) -> *c_void { match self.cond.load(atomics::Relaxed) { 0 => {} n => return n as *c_void } let cond = imp::init_cond(); match self.cond.compare_and_swap(0, cond, atomics::SeqCst) { 0 => return cond as *c_void, _ => {} } imp::free_cond(cond); return self.cond.load(atomics::Relaxed) as *c_void; } } #[cfg(unix)] mod imp { use libc::c_void; use libc; use ptr; type pthread_mutex_t = libc::c_void; type pthread_mutexattr_t = libc::c_void; type pthread_cond_t = libc::c_void; type pthread_condattr_t = libc::c_void; pub unsafe fn init_lock() -> uint { let block = libc::malloc(rust_pthread_mutex_t_size() as libc::size_t); assert!(!block.is_null()); let n = pthread_mutex_init(block, ptr::null()); assert_eq!(n, 0); return block as uint; } pub unsafe fn init_cond() -> uint { let block = libc::malloc(rust_pthread_cond_t_size() as libc::size_t); assert!(!block.is_null()); let n = pthread_cond_init(block, ptr::null()); assert_eq!(n, 0); return block as uint; } pub unsafe fn free_lock(h: uint) { let block = h as *c_void; assert_eq!(pthread_mutex_destroy(block), 0); libc::free(block); } pub unsafe fn
(h: uint) { let block = h as *c_void; assert_eq!(pthread_cond_destroy(block), 0); libc::free(block); } pub unsafe fn lock(l: *pthread_mutex_t) { assert_eq!(pthread_mutex_lock(l), 0); } pub unsafe fn trylock(l: *c_void) -> bool { pthread_mutex_trylock(l) == 0 } pub unsafe fn unlock(l: *pthread_mutex_t) { assert_eq!(pthread_mutex_unlock(l), 0); } pub unsafe fn wait(cond: *pthread_cond_t, m: *pthread_mutex_t) { assert_eq!(pthread_cond_wait(cond, m), 0); } pub unsafe fn signal(cond: *pthread_cond_t) { assert_eq!(pthread_cond_signal(cond), 0); } extern { fn rust_pthread_mutex_t_size() -> libc::c_int; fn rust_pthread_cond_t_size() -> libc::c_int; } extern { fn pthread_mutex_init(lock: *pthread_mutex_t, attr: *pthread_mutexattr_t) -> libc::c_int; fn pthread_mutex_destroy(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_init(cond: *pthread_cond_t, attr: *pthread_condattr_t) -> libc::c_int; fn pthread_cond_destroy(cond: *pthread_cond_t) -> libc::c_int; fn pthread_mutex_lock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_mutex_trylock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_mutex_unlock(lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_wait(cond: *pthread_cond_t, lock: *pthread_mutex_t) -> libc::c_int; fn pthread_cond_signal(cond: *pthread_cond_t) -> libc::c_int; } } #[cfg(windows)] mod imp { use libc; use libc::{HANDLE, BOOL, LPSECURITY_ATTRIBUTES, c_void, DWORD, LPCSTR}; use ptr; type LPCRITICAL_SECTION = *c_void; static SPIN_COUNT: DWORD = 4000; pub unsafe fn init_lock() -> uint { let block = libc::malloc(rust_crit_section_size() as libc::size_t); assert!(!block.is_null()); InitializeCriticalSectionAndSpinCount(block, SPIN_COUNT); return block as uint; } pub unsafe fn init_cond() -> uint { return CreateEventA(ptr::mut_null(), libc::FALSE, libc::FALSE, ptr::null()) as uint; } pub unsafe fn free_lock(h: uint) { DeleteCriticalSection(h as LPCRITICAL_SECTION); libc::free(h as *c_void); } pub unsafe fn free_cond(h: uint) { let block = h as HANDLE; libc::CloseHandle(block); } pub unsafe fn lock(l: *c_void) { EnterCriticalSection(l as LPCRITICAL_SECTION) } pub unsafe fn trylock(l: *c_void) -> bool { TryEnterCriticalSection(l as LPCRITICAL_SECTION)!= 0 } pub unsafe fn unlock(l: *c_void) { LeaveCriticalSection(l as LPCRITICAL_SECTION) } pub unsafe fn wait(cond: *c_void, m: *c_void) { unlock(m); WaitForSingleObject(cond as HANDLE, 0); lock(m); } pub unsafe fn signal(cond: *c_void) { assert!(SetEvent(cond as HANDLE)!= 0); } extern { fn rust_crit_section_size() -> libc::c_int; } extern "system" { fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, bInitialState: BOOL, lpName: LPCSTR) -> HANDLE; fn InitializeCriticalSectionAndSpinCount( lpCriticalSection: LPCRITICAL_SECTION, dwSpinCount: DWORD) -> BOOL; fn DeleteCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn EnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn LeaveCriticalSection(lpCriticalSection: LPCRITICAL_SECTION); fn TryEnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION) -> BOOL; fn SetEvent(hEvent: HANDLE) -> BOOL; fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; } } #[cfg(test)] mod test { use super::{Mutex, MUTEX_INIT}; use rt::thread::Thread; #[test] fn somke_lock() { static mut lock: Mutex = MUTEX_INIT; unsafe { lock.lock(); lock.unlock(); } } #[test] fn somke_cond() { static mut lock: Mutex = MUTEX_INIT; unsafe { let t = do Thread::start { lock.lock(); lock.signal(); lock.unlock(); }; lock.lock(); lock.wait(); lock.unlock(); t.join(); } } #[test] fn destroy_immediately() { unsafe { let mut m = Mutex::empty(); m.destroy(); } } }
free_cond
identifier_name
ex_1.rs
/* Copyright © 2013 Free Software Foundation, Inc See licensing in LICENSE file File: examples/ex_1.rs Author: Jesse 'Jeaye' Wilkerson Description: Simple "Hello, world" example. */ extern crate ncurses; use ncurses::*; fn main() { /* If your locale env is unicode, you should use `setlocale`. */ // let locale_conf = LcCategory::all; // setlocale(locale_conf, "zh_CN.UTF-8"); // if your locale is like mine(zh_CN.UTF-8).
initscr(); /* Print to the back buffer. */ printw("Hello, world!"); /* Print some unicode(Chinese) string. */ // printw("Great Firewall dislike VPN protocol.\nGFW 不喜欢 VPN 协议。"; /* Update the screen. */ refresh(); /* Wait for a key press. */ getch(); /* Terminate ncurses. */ endwin(); }
/* Start ncurses. */
random_line_split
ex_1.rs
/* Copyright © 2013 Free Software Foundation, Inc See licensing in LICENSE file File: examples/ex_1.rs Author: Jesse 'Jeaye' Wilkerson Description: Simple "Hello, world" example. */ extern crate ncurses; use ncurses::*; fn main() {
/* Terminate ncurses. */ endwin(); }
/* If your locale env is unicode, you should use `setlocale`. */ // let locale_conf = LcCategory::all; // setlocale(locale_conf, "zh_CN.UTF-8"); // if your locale is like mine(zh_CN.UTF-8). /* Start ncurses. */ initscr(); /* Print to the back buffer. */ printw("Hello, world!"); /* Print some unicode(Chinese) string. */ // printw("Great Firewall dislike VPN protocol.\nGFW 不喜欢 VPN 协议。"; /* Update the screen. */ refresh(); /* Wait for a key press. */ getch();
identifier_body
ex_1.rs
/* Copyright © 2013 Free Software Foundation, Inc See licensing in LICENSE file File: examples/ex_1.rs Author: Jesse 'Jeaye' Wilkerson Description: Simple "Hello, world" example. */ extern crate ncurses; use ncurses::*; fn m
) { /* If your locale env is unicode, you should use `setlocale`. */ // let locale_conf = LcCategory::all; // setlocale(locale_conf, "zh_CN.UTF-8"); // if your locale is like mine(zh_CN.UTF-8). /* Start ncurses. */ initscr(); /* Print to the back buffer. */ printw("Hello, world!"); /* Print some unicode(Chinese) string. */ // printw("Great Firewall dislike VPN protocol.\nGFW 不喜欢 VPN 协议。"; /* Update the screen. */ refresh(); /* Wait for a key press. */ getch(); /* Terminate ncurses. */ endwin(); }
ain(
identifier_name
pipeline.rs
fn parse_cluster(record: csv::StringRecord) -> Result<Vec<usize>> { let seqids = &record[2]; Ok(csv::ReaderBuilder::new() .delimiter(b',') .has_headers(false) .from_reader(seqids.as_bytes()) .deserialize() .next() .unwrap()?) } /// Calculates the median hamming distance for all records by deriving the overlap from insert size fn median_hamming_distance( insert_size: usize, f_recs: &[fastq::Record], r_recs: &[fastq::Record], ) -> Option<f64> { let distances = f_recs.iter().zip(r_recs).filter_map(|(f_rec, r_rec)| { // check if reads overlap within insert size if (insert_size < f_rec.seq().len()) | (insert_size < r_rec.seq().len()) { return None; } if insert_size >= (f_rec.seq().len() + r_rec.seq().len()) { return None; } let overlap = (f_rec.seq().len() + r_rec.seq().len()) - insert_size; let suffix_start_idx: usize = f_rec.seq().len() - overlap; Some(bio::alignment::distance::hamming( &f_rec.seq()[suffix_start_idx..], &bio::alphabets::dna::revcomp(r_rec.seq())[..overlap], )) }); stats::median(distances) } /// as shown in http://www.milefoot.com/math/stat/pdfc-normaldisc.htm fn isize_pmf(value: f64, mean: f64, sd: f64) -> LogProb { LogProb((ugaussian_P((value + 0.5 - mean) / sd) - ugaussian_P((value - 0.5 - mean) / sd)).ln()) } /// Used to store a mapping of read index to read sequence #[derive(Debug)] struct FastqStorage { db: DB, } impl FastqStorage { /// Create a new FASTQStorage using a Rocksdb database /// that maps read indices to read seqeunces. pub fn new() -> Result<Self> { // Save storage_dir to prevent it from leaving scope and // in turn deleting the tempdir let storage_dir = tempdir()?.path().join("db"); Ok(FastqStorage { db: DB::open_default(storage_dir)?, }) } #[allow(clippy::wrong_self_convention)] fn as_key(i: u64) -> [u8; 8] { unsafe { mem::transmute::<u64, [u8; 8]>(i) } } /// Enter a (read index, read sequence) pair into the database. pub fn put(&mut self, i: usize, f_rec: &fastq::Record, r_rec: &fastq::Record) -> Result<()> { Ok(self.db.put( &Self::as_key(i as u64), serde_json::to_string(&(f_rec, r_rec))?.as_bytes(), )?) } /// Retrieve the read sequence of the read with index `i`. pub fn get(&self, i: usize) -> Result<(fastq::Record, fastq::Record)> { Ok(serde_json::from_str( str::from_utf8(&self.db.get(&Self::as_key(i as u64))?.unwrap()).unwrap(), )?) } } pub struct OverlappingConsensus { record: Record, likelihood: LogProb, } pub struct NonOverlappingConsensus { f_record: Record, r_record: Record, likelihood: LogProb, } pub trait CallConsensusReads<'a, R: io::Read + io::BufRead + 'a, W: io::Write + 'a> { /// Cluster reads from fastq readers according to their sequence /// and UMI, then compute a consensus sequence. /// /// Cluster the reads in the input file according to their sequence /// (concatenated p5 and p7 reads without UMI). Read the /// identified clusters, and cluster all reds in a cluster by UMI, /// creating groups of very likely PCR duplicates. /// Next, compute a consensus read for each unique read, /// i.e. a cluster with similar sequences and identical UMI, /// and write it into the output files. fn call_consensus_reads(&'a mut self) -> Result<()> { let spinner_style = indicatif::ProgressStyle::default_spinner() .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ") .template("{prefix:.bold.dim} {spinner} {wide_msg}"); // cluster by umi // Note: If starcode is not installed, this throws a // hard to interpret error: // (No such file or directory (os error 2)) // The expect added below should make this more clear. let mut umi_cluster = Command::new("starcode") .arg("--dist") .arg(format!("{}", self.umi_dist())) .arg("--seq-id") .arg("-s") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("Error in starcode call. Starcode might not be installed."); let mut f_rec = fastq::Record::new(); let mut r_rec = fastq::Record::new(); // init temp storage for reads let mut read_storage = FastqStorage::new()?; let mut i = 0; // prepare spinner for user feedback let pb = indicatif::ProgressBar::new_spinner(); pb.set_style(spinner_style.clone()); pb.set_prefix("[1/2] Clustering input reads by UMI using starcode."); loop { // update spinner pb.set_message(&format!(" Processed {:>10} reads", i)); pb.inc(1); self.fq1_reader().read(&mut f_rec)?; self.fq2_reader().read(&mut r_rec)?; match (f_rec.is_empty(), r_rec.is_empty()) { (true, true) => break, (false, false) => (), (true, false) => { let error_message = format!("Given FASTQ files have unequal lengths. Forward file returned record {} as empty, reverse record is not: id:'{}' seq:'{:?}'.", i, r_rec.id(), str::from_utf8(r_rec.seq())); panic!("{}", error_message); } (false, true) => { let error_message = format!("Given FASTQ files have unequal lengths. Reverse file returned record {} as empty, forward record is not: id:'{}' seq:'{:?}'.", i, f_rec.id(), str::from_utf8(f_rec.seq())); panic!("{}", error_message); } } // extract umi for clustering let umi = if self.reverse_umi() { r_rec.seq()[..self.umi_len()].to_owned() } else { f_rec.seq()[..self.umi_len()].to_owned() }; umi_cluster.stdin.as_mut().unwrap().write_all(&umi)?; umi_cluster.stdin.as_mut().unwrap().write_all(b"\n")?; // remove umi from read sequence for all further clustering steps if self.reverse_umi() { r_rec = self.strip_umi_from_record(&r_rec) } else { f_rec = self.strip_umi_from_record(&f_rec) } // store read sequences in an on-disk key value store for random access read_storage.put(i, &f_rec, &r_rec)?; i += 1; } umi_cluster.stdin.as_mut().unwrap().flush()?; drop(umi_cluster.stdin.take()); pb.finish_with_message(&format!("Done. Analyzed {} reads.", i)); // prepare user feedback let mut j = 0; let pb = indicatif::ProgressBar::new_spinner(); pb.set_style(spinner_style); pb.set_prefix("[1/2] Clustering input reads by UMI using starcode."); // read clusters identified by the first starcode run // the first run clustered by UMI, hence all reads in // the clusters handled here had similar UMIs for record in csv::ReaderBuilder::new() .delimiter(b'\t') .has_headers(false) .from_reader(umi_cluster.stdout.as_mut().unwrap()) .records() { // update spinner pb.inc(1); pb.set_message(&format!("Processed {:>10} cluster", j)); let seqids = parse_cluster(record?)?; // cluster within in this cluster by read sequence let mut seq_cluster = Command::new("starcode") .arg("--dist") .arg(format!("{}", self.seq_dist())) .arg("--seq-id") .arg("-s") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; for &seqid in &seqids { // get sequences from rocksdb (key value store) let (f_rec, r_rec) = read_storage.get(seqid - 1).unwrap(); // perform clustering using the concatenated read sequences // without the UMIs (remove in the first clustering step) seq_cluster .stdin .as_mut() .unwrap() .write_all(&[f_rec.seq(), r_rec.seq()].concat())?; seq_cluster.stdin.as_mut().unwrap().write_all(b"\n")?; } seq_cluster.stdin.as_mut().unwrap().flush()?; drop(seq_cluster.stdin.take()); // handle each potential unique read, i.e. clusters with similar // UMI and similar sequence for record in csv::ReaderBuilder::new() .delimiter(b'\t') .has_headers(false) .from_reader(seq_cluster.stdout.as_mut().unwrap()) .records() { let inner_seqids = parse_cluster(record?)?; // this is a proper cluster // calculate consensus reads and write to output FASTQs let mut f_recs = Vec::new(); let mut r_recs = Vec::new(); let mut outer_seqids = Vec::new(); for inner_seqid in inner_seqids { let seqid = seqids[inner_seqid - 1]; let (f_rec, r_rec) = read_storage.get(seqid - 1)?; f_recs.push(f_rec); r_recs.push(r_rec); outer_seqids.push(seqid); } self.write_records(f_recs, r_recs, outer_seqids)?; } match seq_cluster .wait() .expect("process did not even start") .code() { Some(0) => (), Some(s) => eprintln!("Starcode failed with error code {}", s), None => eprintln!("Starcode was terminated by signal"), } j += 1; } pb.finish_with_message(&format!("Done. Processed {} cluster.", j)); Ok(()) } fn strip_umi_from_record(&mut self, record: &Record) -> Record { let rec_seq = &record.seq()[self.umi_len()..]; let rec_qual = &record.qual()[self.umi_len()..]; Record::with_attrs(record.id(), record.desc(), rec_seq, rec_qual) } fn write_records( &mut self, f_recs: Vec<Record>, r_recs: Vec<Record>, outer_seqids: Vec<usize>, ) -> Result<()>; fn fq1_reader(&mut self) -> &mut fastq::Reader<R>; fn fq2_reader(&mut self) -> &mut fastq::Reader<R>; fn umi_len(&self) -> usize; fn seq_dist(&self) -> usize; fn umi_dist(&self) -> usize; fn reverse_umi(&self) -> bool; } /// Struct for calling non-overlapping consensus reads /// Implements Trait CallConsensusReads #[allow(clippy::too_many_arguments)] #[derive(new)] pub struct CallNonOverlappingConsensusRead<'a, R: io::Read, W: io::Write> { fq1_reader: &'a mut fastq::Reader<R>, fq2_reader: &'a mut fastq::Reader<R>, fq1_writer: &'a mut fastq::Writer<W>, fq2_writer: &'a mut fastq::Writer<W>, umi_len: usize, seq_dist: usize, umi_dist: usize, reverse_umi: bool, verbose_read_names: bool, } impl<'a, R: io::Read + io::BufRead, W: io::Write> CallConsensusReads<'a, R, W> for CallNonOverlappingConsensusRead<'a, R, W> { fn write_records( &mut self, f_recs: Vec<Record>, r_recs: Vec<Record>, outer_seqids: Vec<usize>, ) -> Result<()> { if f_recs.len() > 1 { let uuid = &Uuid::new_v4().to_hyphenated().to_string(); self.fq1_writer.write_record( &CalcNonOverlappingConsensus::new( &f_recs, &outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus() .0, )?; self.fq2_writer.write_record( &CalcNonOverlappingConsensus::new( &r_recs, &outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus() .0, )?; } else { self.fq1_writer.write_record(&f_recs[0])?; self.fq2_writer.write_record(&r_recs[0])?; } Ok(()) } fn fq1_reader(&mut self) -> &mut fastq::Reader<R> { self.fq1_reader } fn fq2_reader(&mut self) -> &mut fastq::Reader<R> { self.fq2_reader } fn umi_len(&self) -> usize { self.umi_len } fn seq_dist(&self) -> usize { self.seq_dist } fn umi_dist(&self) -> usize { self.umi_dist } fn reverse_umi(&self) -> bool { self.reverse_umi } } ///Clusters fastq reads by UMIs and calls consensus for overlapping reads #[allow(clippy::too_many_arguments)] #[derive(new)] pub struct CallOverlappingConsensusRead<'a, R: io::Read, W: io::Write> { fq1_reader: &'a mut fastq::Reader<R>, fq2_reader: &'a mut fastq::Reader<R>, fq1_writer: &'a mut fastq::Writer<W>, fq2_writer: &'a mut fastq::Writer<W>, fq3_writer: &'a mut fastq::Writer<W>, umi_len: usize, seq_dist: usize, umi_dist: usize, insert_size: usize, std_dev: usize, reverse_umi: bool, verbose_read_names: bool, } impl<'a, R: io::Read, W: io::Write> CallOverlappingConsensusRead<'a, R, W> { fn isize_highest_probability(&mut self, f_seq_len: usize, r_seq_len: usize) -> f64 { if f_seq_len + f_seq_len < self.insert_size { self.insert_size as f64 } else if f_seq_len + r_seq_len > self.insert_size + 2 * self.std_dev { (self.insert_size + 2 * self.std_dev) as f64 } else { (f_seq_len + r_seq_len) as f64 } } fn maximum_likelihood_overlapping_consensus( &mut self, f_recs: &[Record], r_recs: &[Record], outer_seqids: &[usize], uuid: &str, ) -> OverlappingConsensus { //Returns consensus record by filtering overlaps with lowest hamming distance. //For these overlaps(insert sizes) the consensus reads and their likelihoods are calculated. //The read with maximum likelihood will be returned. let insert_sizes = ((self.insert_size - 2 * self.std_dev) ..(self.insert_size + 2 * self.std_dev)) .filter_map(|insert_size| { median_hamming_distance(insert_size, f_recs, r_recs) .filter(|&median_distance| median_distance < HAMMING_THRESHOLD) .map(|_| insert_size) }); insert_sizes .map(|insert_size| { let overlap = (f_recs[0].seq().len() + r_recs[0].seq().len()) - insert_size; let (consensus_record, lh_isize) = CalcOverlappingConsensus::new( f_recs, r_recs, overlap, outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus(); let likelihood = lh_isize + isize_pmf( insert_size as f64, self.insert_size as f64, self.std_dev as f64, ); OverlappingConsensus { record: consensus_record, likelihood, } }) .max_by_key(|consensus| NotNaN::new(*consensus.likelihood).unwrap()) .unwrap() } fn maximum_likelihood_nonoverlapping_consensus( &mut self, f_recs: &[Record], r_recs: &[Record], outer_seqids: &[usize], uuid: &str, ) -> NonOverlappingConsensus { //Calculate non-overlapping consensus records and shared lh let (f_consensus_rec, f_lh) = CalcNonOverlappingConsensus::new(f_recs, outer_seqids, uuid, self.verbose_read_names) .calc_consensus(); let (r_consensus_rec, r_lh) = CalcNonOverlappingConsensus::new(r_recs, outer_seqids, uuid, self.verbose_read_names) .calc_consensus(); let overall_lh_isize = f_lh + r_lh; //Determine insert size with highest probability for non-overlapping records based on expected insert size let likeliest_isize = self.isize_highest_probability(f_recs[0].seq().len(), r_recs[0].seq().len()); let overall_lh = overall_lh_isize + isize_pmf( likeliest_isize, self.insert_size as f64, self.std_dev as f64
/// Interpret a cluster returned by starcode
random_line_split
pipeline.rs
next() .unwrap()?) } /// Calculates the median hamming distance for all records by deriving the overlap from insert size fn median_hamming_distance( insert_size: usize, f_recs: &[fastq::Record], r_recs: &[fastq::Record], ) -> Option<f64> { let distances = f_recs.iter().zip(r_recs).filter_map(|(f_rec, r_rec)| { // check if reads overlap within insert size if (insert_size < f_rec.seq().len()) | (insert_size < r_rec.seq().len()) { return None; } if insert_size >= (f_rec.seq().len() + r_rec.seq().len()) { return None; } let overlap = (f_rec.seq().len() + r_rec.seq().len()) - insert_size; let suffix_start_idx: usize = f_rec.seq().len() - overlap; Some(bio::alignment::distance::hamming( &f_rec.seq()[suffix_start_idx..], &bio::alphabets::dna::revcomp(r_rec.seq())[..overlap], )) }); stats::median(distances) } /// as shown in http://www.milefoot.com/math/stat/pdfc-normaldisc.htm fn isize_pmf(value: f64, mean: f64, sd: f64) -> LogProb { LogProb((ugaussian_P((value + 0.5 - mean) / sd) - ugaussian_P((value - 0.5 - mean) / sd)).ln()) } /// Used to store a mapping of read index to read sequence #[derive(Debug)] struct FastqStorage { db: DB, } impl FastqStorage { /// Create a new FASTQStorage using a Rocksdb database /// that maps read indices to read seqeunces. pub fn new() -> Result<Self> { // Save storage_dir to prevent it from leaving scope and // in turn deleting the tempdir let storage_dir = tempdir()?.path().join("db"); Ok(FastqStorage { db: DB::open_default(storage_dir)?, }) } #[allow(clippy::wrong_self_convention)] fn as_key(i: u64) -> [u8; 8] { unsafe { mem::transmute::<u64, [u8; 8]>(i) } } /// Enter a (read index, read sequence) pair into the database. pub fn put(&mut self, i: usize, f_rec: &fastq::Record, r_rec: &fastq::Record) -> Result<()> { Ok(self.db.put( &Self::as_key(i as u64), serde_json::to_string(&(f_rec, r_rec))?.as_bytes(), )?) } /// Retrieve the read sequence of the read with index `i`. pub fn get(&self, i: usize) -> Result<(fastq::Record, fastq::Record)> { Ok(serde_json::from_str( str::from_utf8(&self.db.get(&Self::as_key(i as u64))?.unwrap()).unwrap(), )?) } } pub struct OverlappingConsensus { record: Record, likelihood: LogProb, } pub struct NonOverlappingConsensus { f_record: Record, r_record: Record, likelihood: LogProb, } pub trait CallConsensusReads<'a, R: io::Read + io::BufRead + 'a, W: io::Write + 'a> { /// Cluster reads from fastq readers according to their sequence /// and UMI, then compute a consensus sequence. /// /// Cluster the reads in the input file according to their sequence /// (concatenated p5 and p7 reads without UMI). Read the /// identified clusters, and cluster all reds in a cluster by UMI, /// creating groups of very likely PCR duplicates. /// Next, compute a consensus read for each unique read, /// i.e. a cluster with similar sequences and identical UMI, /// and write it into the output files. fn call_consensus_reads(&'a mut self) -> Result<()> { let spinner_style = indicatif::ProgressStyle::default_spinner() .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ") .template("{prefix:.bold.dim} {spinner} {wide_msg}"); // cluster by umi // Note: If starcode is not installed, this throws a // hard to interpret error: // (No such file or directory (os error 2)) // The expect added below should make this more clear. let mut umi_cluster = Command::new("starcode") .arg("--dist") .arg(format!("{}", self.umi_dist())) .arg("--seq-id") .arg("-s") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("Error in starcode call. Starcode might not be installed."); let mut f_rec = fastq::Record::new(); let mut r_rec = fastq::Record::new(); // init temp storage for reads let mut read_storage = FastqStorage::new()?; let mut i = 0; // prepare spinner for user feedback let pb = indicatif::ProgressBar::new_spinner(); pb.set_style(spinner_style.clone()); pb.set_prefix("[1/2] Clustering input reads by UMI using starcode."); loop { // update spinner pb.set_message(&format!(" Processed {:>10} reads", i)); pb.inc(1); self.fq1_reader().read(&mut f_rec)?; self.fq2_reader().read(&mut r_rec)?; match (f_rec.is_empty(), r_rec.is_empty()) { (true, true) => break, (false, false) => (), (true, false) => { let error_message = format!("Given FASTQ files have unequal lengths. Forward file returned record {} as empty, reverse record is not: id:'{}' seq:'{:?}'.", i, r_rec.id(), str::from_utf8(r_rec.seq())); panic!("{}", error_message); } (false, true) => { let error_message = format!("Given FASTQ files have unequal lengths. Reverse file returned record {} as empty, forward record is not: id:'{}' seq:'{:?}'.", i, f_rec.id(), str::from_utf8(f_rec.seq())); panic!("{}", error_message); } } // extract umi for clustering let umi = if self.reverse_umi() { r_rec.seq()[..self.umi_len()].to_owned() } else { f_rec.seq()[..self.umi_len()].to_owned() }; umi_cluster.stdin.as_mut().unwrap().write_all(&umi)?; umi_cluster.stdin.as_mut().unwrap().write_all(b"\n")?; // remove umi from read sequence for all further clustering steps if self.reverse_umi() { r_rec = self.strip_umi_from_record(&r_rec) } else { f_rec = self.strip_umi_from_record(&f_rec) } // store read sequences in an on-disk key value store for random access read_storage.put(i, &f_rec, &r_rec)?; i += 1; } umi_cluster.stdin.as_mut().unwrap().flush()?; drop(umi_cluster.stdin.take()); pb.finish_with_message(&format!("Done. Analyzed {} reads.", i)); // prepare user feedback let mut j = 0; let pb = indicatif::ProgressBar::new_spinner(); pb.set_style(spinner_style); pb.set_prefix("[1/2] Clustering input reads by UMI using starcode."); // read clusters identified by the first starcode run // the first run clustered by UMI, hence all reads in // the clusters handled here had similar UMIs for record in csv::ReaderBuilder::new() .delimiter(b'\t') .has_headers(false) .from_reader(umi_cluster.stdout.as_mut().unwrap()) .records() { // update spinner pb.inc(1); pb.set_message(&format!("Processed {:>10} cluster", j)); let seqids = parse_cluster(record?)?; // cluster within in this cluster by read sequence let mut seq_cluster = Command::new("starcode") .arg("--dist") .arg(format!("{}", self.seq_dist())) .arg("--seq-id") .arg("-s") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; for &seqid in &seqids { // get sequences from rocksdb (key value store) let (f_rec, r_rec) = read_storage.get(seqid - 1).unwrap(); // perform clustering using the concatenated read sequences // without the UMIs (remove in the first clustering step) seq_cluster .stdin .as_mut() .unwrap() .write_all(&[f_rec.seq(), r_rec.seq()].concat())?; seq_cluster.stdin.as_mut().unwrap().write_all(b"\n")?; } seq_cluster.stdin.as_mut().unwrap().flush()?; drop(seq_cluster.stdin.take()); // handle each potential unique read, i.e. clusters with similar // UMI and similar sequence for record in csv::ReaderBuilder::new() .delimiter(b'\t') .has_headers(false) .from_reader(seq_cluster.stdout.as_mut().unwrap()) .records() { let inner_seqids = parse_cluster(record?)?; // this is a proper cluster // calculate consensus reads and write to output FASTQs let mut f_recs = Vec::new(); let mut r_recs = Vec::new(); let mut outer_seqids = Vec::new(); for inner_seqid in inner_seqids { let seqid = seqids[inner_seqid - 1]; let (f_rec, r_rec) = read_storage.get(seqid - 1)?; f_recs.push(f_rec); r_recs.push(r_rec); outer_seqids.push(seqid); } self.write_records(f_recs, r_recs, outer_seqids)?; } match seq_cluster .wait() .expect("process did not even start") .code() { Some(0) => (), Some(s) => eprintln!("Starcode failed with error code {}", s), None => eprintln!("Starcode was terminated by signal"), } j += 1; } pb.finish_with_message(&format!("Done. Processed {} cluster.", j)); Ok(()) } fn strip_umi_from_record(&mut self, record: &Record) -> Record { let rec_seq = &record.seq()[self.umi_len()..]; let rec_qual = &record.qual()[self.umi_len()..]; Record::with_attrs(record.id(), record.desc(), rec_seq, rec_qual) } fn write_records( &mut self, f_recs: Vec<Record>, r_recs: Vec<Record>, outer_seqids: Vec<usize>, ) -> Result<()>; fn fq1_reader(&mut self) -> &mut fastq::Reader<R>; fn fq2_reader(&mut self) -> &mut fastq::Reader<R>; fn umi_len(&self) -> usize; fn seq_dist(&self) -> usize; fn umi_dist(&self) -> usize; fn reverse_umi(&self) -> bool; } /// Struct for calling non-overlapping consensus reads /// Implements Trait CallConsensusReads #[allow(clippy::too_many_arguments)] #[derive(new)] pub struct CallNonOverlappingConsensusRead<'a, R: io::Read, W: io::Write> { fq1_reader: &'a mut fastq::Reader<R>, fq2_reader: &'a mut fastq::Reader<R>, fq1_writer: &'a mut fastq::Writer<W>, fq2_writer: &'a mut fastq::Writer<W>, umi_len: usize, seq_dist: usize, umi_dist: usize, reverse_umi: bool, verbose_read_names: bool, } impl<'a, R: io::Read + io::BufRead, W: io::Write> CallConsensusReads<'a, R, W> for CallNonOverlappingConsensusRead<'a, R, W> { fn write_records( &mut self, f_recs: Vec<Record>, r_recs: Vec<Record>, outer_seqids: Vec<usize>, ) -> Result<()> { if f_recs.len() > 1 { let uuid = &Uuid::new_v4().to_hyphenated().to_string(); self.fq1_writer.write_record( &CalcNonOverlappingConsensus::new( &f_recs, &outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus() .0, )?; self.fq2_writer.write_record( &CalcNonOverlappingConsensus::new( &r_recs, &outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus() .0, )?; } else { self.fq1_writer.write_record(&f_recs[0])?; self.fq2_writer.write_record(&r_recs[0])?; } Ok(()) } fn fq1_reader(&mut self) -> &mut fastq::Reader<R> { self.fq1_reader } fn fq2_reader(&mut self) -> &mut fastq::Reader<R> { self.fq2_reader } fn umi_len(&self) -> usize { self.umi_len } fn seq_dist(&self) -> usize { self.seq_dist } fn umi_dist(&self) -> usize { self.umi_dist } fn reverse_umi(&self) -> bool { self.reverse_umi } } ///Clusters fastq reads by UMIs and calls consensus for overlapping reads #[allow(clippy::too_many_arguments)] #[derive(new)] pub struct CallOverlappingConsensusRead<'a, R: io::Read, W: io::Write> { fq1_reader: &'a mut fastq::Reader<R>, fq2_reader: &'a mut fastq::Reader<R>, fq1_writer: &'a mut fastq::Writer<W>, fq2_writer: &'a mut fastq::Writer<W>, fq3_writer: &'a mut fastq::Writer<W>, umi_len: usize, seq_dist: usize, umi_dist: usize, insert_size: usize, std_dev: usize, reverse_umi: bool, verbose_read_names: bool, } impl<'a, R: io::Read, W: io::Write> CallOverlappingConsensusRead<'a, R, W> { fn isize_highest_probability(&mut self, f_seq_len: usize, r_seq_len: usize) -> f64 { if f_seq_len + f_seq_len < self.insert_size { self.insert_size as f64 } else if f_seq_len + r_seq_len > self.insert_size + 2 * self.std_dev { (self.insert_size + 2 * self.std_dev) as f64 } else { (f_seq_len + r_seq_len) as f64 } } fn maximum_likeliho
elf, f_recs: &[Record], r_recs: &[Record], outer_seqids: &[usize], uuid: &str, ) -> OverlappingConsensus { //Returns consensus record by filtering overlaps with lowest hamming distance. //For these overlaps(insert sizes) the consensus reads and their likelihoods are calculated. //The read with maximum likelihood will be returned. let insert_sizes = ((self.insert_size - 2 * self.std_dev) ..(self.insert_size + 2 * self.std_dev)) .filter_map(|insert_size| { median_hamming_distance(insert_size, f_recs, r_recs) .filter(|&median_distance| median_distance < HAMMING_THRESHOLD) .map(|_| insert_size) }); insert_sizes .map(|insert_size| { let overlap = (f_recs[0].seq().len() + r_recs[0].seq().len()) - insert_size; let (consensus_record, lh_isize) = CalcOverlappingConsensus::new( f_recs, r_recs, overlap, outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus(); let likelihood = lh_isize + isize_pmf( insert_size as f64, self.insert_size as f64, self.std_dev as f64, ); OverlappingConsensus { record: consensus_record, likelihood, } }) .max_by_key(|consensus| NotNaN::new(*consensus.likelihood).unwrap()) .unwrap() } fn maximum_likelihood_nonoverlapping_consensus( &mut self, f_recs: &[Record], r_recs: &[Record], outer_seqids: &[usize], uuid: &str, ) -> NonOverlappingConsensus { //Calculate non-overlapping consensus records and shared lh let (f_consensus_rec, f_lh) = CalcNonOverlappingConsensus::new(f_recs, outer_seqids, uuid, self.verbose_read_names) .calc_consensus(); let (r_consensus_rec, r_lh) = CalcNonOverlappingConsensus::new(r_recs, outer_seqids, uuid, self.verbose_read_names) .calc_consensus(); let overall_lh_isize = f_lh + r_lh; //Determine insert size with highest probability for non-overlapping records based on expected insert size let likeliest_isize = self.isize_highest_probability(f_recs[0].seq().len(), r_recs[0].seq().len()); let overall_lh = overall_lh_isize + isize_pmf( likeliest_isize, self.insert_size as f64, self.std_dev as f64, ); NonOverlappingConsensus { f_record: f_consensus_rec, r_record: r_consensus_rec, likelihood: overall_lh, } } } impl<'a, R: io::Read + io::BufRead,
od_overlapping_consensus( &mut s
identifier_name
pipeline.rs
.next() .unwrap()?) } /// Calculates the median hamming distance for all records by deriving the overlap from insert size fn median_hamming_distance( insert_size: usize, f_recs: &[fastq::Record], r_recs: &[fastq::Record], ) -> Option<f64> { let distances = f_recs.iter().zip(r_recs).filter_map(|(f_rec, r_rec)| { // check if reads overlap within insert size if (insert_size < f_rec.seq().len()) | (insert_size < r_rec.seq().len()) { return None; } if insert_size >= (f_rec.seq().len() + r_rec.seq().len()) { return None; } let overlap = (f_rec.seq().len() + r_rec.seq().len()) - insert_size; let suffix_start_idx: usize = f_rec.seq().len() - overlap; Some(bio::alignment::distance::hamming( &f_rec.seq()[suffix_start_idx..], &bio::alphabets::dna::revcomp(r_rec.seq())[..overlap], )) }); stats::median(distances) } /// as shown in http://www.milefoot.com/math/stat/pdfc-normaldisc.htm fn isize_pmf(value: f64, mean: f64, sd: f64) -> LogProb { LogProb((ugaussian_P((value + 0.5 - mean) / sd) - ugaussian_P((value - 0.5 - mean) / sd)).ln()) } /// Used to store a mapping of read index to read sequence #[derive(Debug)] struct FastqStorage { db: DB, } impl FastqStorage { /// Create a new FASTQStorage using a Rocksdb database /// that maps read indices to read seqeunces. pub fn new() -> Result<Self> { // Save storage_dir to prevent it from leaving scope and // in turn deleting the tempdir let storage_dir = tempdir()?.path().join("db"); Ok(FastqStorage { db: DB::open_default(storage_dir)?, }) } #[allow(clippy::wrong_self_convention)] fn as_key(i: u64) -> [u8; 8] { unsafe { mem::transmute::<u64, [u8; 8]>(i) } } /// Enter a (read index, read sequence) pair into the database. pub fn put(&mut self, i: usize, f_rec: &fastq::Record, r_rec: &fastq::Record) -> Result<()> { Ok(self.db.put( &Self::as_key(i as u64), serde_json::to_string(&(f_rec, r_rec))?.as_bytes(), )?) } /// Retrieve the read sequence of the read with index `i`. pub fn get(&self, i: usize) -> Result<(fastq::Record, fastq::Record)> { Ok(serde_json::from_str( str::from_utf8(&self.db.get(&Self::as_key(i as u64))?.unwrap()).unwrap(), )?) } } pub struct OverlappingConsensus { record: Record, likelihood: LogProb, } pub struct NonOverlappingConsensus { f_record: Record, r_record: Record, likelihood: LogProb, } pub trait CallConsensusReads<'a, R: io::Read + io::BufRead + 'a, W: io::Write + 'a> { /// Cluster reads from fastq readers according to their sequence /// and UMI, then compute a consensus sequence. /// /// Cluster the reads in the input file according to their sequence /// (concatenated p5 and p7 reads without UMI). Read the /// identified clusters, and cluster all reds in a cluster by UMI, /// creating groups of very likely PCR duplicates. /// Next, compute a consensus read for each unique read, /// i.e. a cluster with similar sequences and identical UMI, /// and write it into the output files. fn call_consensus_reads(&'a mut self) -> Result<()> { let spinner_style = indicatif::ProgressStyle::default_spinner() .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ") .template("{prefix:.bold.dim} {spinner} {wide_msg}"); // cluster by umi // Note: If starcode is not installed, this throws a // hard to interpret error: // (No such file or directory (os error 2)) // The expect added below should make this more clear. let mut umi_cluster = Command::new("starcode") .arg("--dist") .arg(format!("{}", self.umi_dist())) .arg("--seq-id") .arg("-s") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("Error in starcode call. Starcode might not be installed."); let mut f_rec = fastq::Record::new(); let mut r_rec = fastq::Record::new(); // init temp storage for reads let mut read_storage = FastqStorage::new()?; let mut i = 0; // prepare spinner for user feedback let pb = indicatif::ProgressBar::new_spinner(); pb.set_style(spinner_style.clone()); pb.set_prefix("[1/2] Clustering input reads by UMI using starcode."); loop { // update spinner pb.set_message(&format!(" Processed {:>10} reads", i)); pb.inc(1); self.fq1_reader().read(&mut f_rec)?; self.fq2_reader().read(&mut r_rec)?; match (f_rec.is_empty(), r_rec.is_empty()) { (true, true) => break, (false, false) => (), (true, false) => { let error_message = format!("Given FASTQ files have unequal lengths. Forward file returned record {} as empty, reverse record is not: id:'{}' seq:'{:?}'.", i, r_rec.id(), str::from_utf8(r_rec.seq())); panic!("{}", error_message); } (false, true) => { let error_message = format!("Given FASTQ files have unequal lengths. Reverse file returned record {} as empty, forward record is not: id:'{}' seq:'{:?}'.", i, f_rec.id(), str::from_utf8(f_rec.seq())); panic!("{}", error_message); } } // extract umi for clustering let umi = if self.reverse_umi() { r_rec.seq()[..self.umi_len()].to_owned() } else { f_rec.seq()[..self.umi_len()].to_owned() }; umi_cluster.stdin.as_mut().unwrap().write_all(&umi)?; umi_cluster.stdin.as_mut().unwrap().write_all(b"\n")?; // remove umi from read sequence for all further clustering steps if self.reverse_umi() { r_rec = self.strip_umi_from_record(&r_rec) } else { f_rec = self.strip_umi_from_record(&f_rec) } // store read sequences in an on-disk key value store for random access read_storage.put(i, &f_rec, &r_rec)?; i += 1; } umi_cluster.stdin.as_mut().unwrap().flush()?; drop(umi_cluster.stdin.take()); pb.finish_with_message(&format!("Done. Analyzed {} reads.", i)); // prepare user feedback let mut j = 0; let pb = indicatif::ProgressBar::new_spinner(); pb.set_style(spinner_style); pb.set_prefix("[1/2] Clustering input reads by UMI using starcode."); // read clusters identified by the first starcode run // the first run clustered by UMI, hence all reads in // the clusters handled here had similar UMIs for record in csv::ReaderBuilder::new() .delimiter(b'\t') .has_headers(false) .from_reader(umi_cluster.stdout.as_mut().unwrap()) .records() { // update spinner pb.inc(1); pb.set_message(&format!("Processed {:>10} cluster", j)); let seqids = parse_cluster(record?)?; // cluster within in this cluster by read sequence let mut seq_cluster = Command::new("starcode") .arg("--dist") .arg(format!("{}", self.seq_dist())) .arg("--seq-id") .arg("-s") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; for &seqid in &seqids { // get sequences from rocksdb (key value store) let (f_rec, r_rec) = read_storage.get(seqid - 1).unwrap(); // perform clustering using the concatenated read sequences // without the UMIs (remove in the first clustering step) seq_cluster .stdin .as_mut() .unwrap() .write_all(&[f_rec.seq(), r_rec.seq()].concat())?; seq_cluster.stdin.as_mut().unwrap().write_all(b"\n")?; } seq_cluster.stdin.as_mut().unwrap().flush()?; drop(seq_cluster.stdin.take()); // handle each potential unique read, i.e. clusters with similar // UMI and similar sequence for record in csv::ReaderBuilder::new() .delimiter(b'\t') .has_headers(false) .from_reader(seq_cluster.stdout.as_mut().unwrap()) .records() { let inner_seqids = parse_cluster(record?)?; // this is a proper cluster // calculate consensus reads and write to output FASTQs let mut f_recs = Vec::new(); let mut r_recs = Vec::new(); let mut outer_seqids = Vec::new(); for inner_seqid in inner_seqids { let seqid = seqids[inner_seqid - 1]; let (f_rec, r_rec) = read_storage.get(seqid - 1)?; f_recs.push(f_rec); r_recs.push(r_rec); outer_seqids.push(seqid); } self.write_records(f_recs, r_recs, outer_seqids)?; } match seq_cluster .wait() .expect("process did not even start") .code() { Some(0) => (), Some(s) => eprintln!("Starcode failed with error code {}", s), None => eprintln!("Starcode was terminated by signal"), } j += 1; } pb.finish_with_message(&format!("Done. Processed {} cluster.", j)); Ok(()) } fn strip_umi_from_record(&mut self, record: &Record) -> Record { let rec_seq = &record.seq()[self.umi_len()..]; let rec_qual = &record.qual()[self.umi_len()..]; Record::with_attrs(record.id(), record.desc(), rec_seq, rec_qual) } fn write_records( &mut self, f_recs: Vec<Record>, r_recs: Vec<Record>, outer_seqids: Vec<usize>, ) -> Result<()>; fn fq1_reader(&mut self) -> &mut fastq::Reader<R>; fn fq2_reader(&mut self) -> &mut fastq::Reader<R>; fn umi_len(&self) -> usize; fn seq_dist(&self) -> usize; fn umi_dist(&self) -> usize; fn reverse_umi(&self) -> bool; } /// Struct for calling non-overlapping consensus reads /// Implements Trait CallConsensusReads #[allow(clippy::too_many_arguments)] #[derive(new)] pub struct CallNonOverlappingConsensusRead<'a, R: io::Read, W: io::Write> { fq1_reader: &'a mut fastq::Reader<R>, fq2_reader: &'a mut fastq::Reader<R>, fq1_writer: &'a mut fastq::Writer<W>, fq2_writer: &'a mut fastq::Writer<W>, umi_len: usize, seq_dist: usize, umi_dist: usize, reverse_umi: bool, verbose_read_names: bool, } impl<'a, R: io::Read + io::BufRead, W: io::Write> CallConsensusReads<'a, R, W> for CallNonOverlappingConsensusRead<'a, R, W> { fn write_records( &mut self, f_recs: Vec<Record>, r_recs: Vec<Record>, outer_seqids: Vec<usize>, ) -> Result<()> { if f_r
.0, )?; } else { self.fq1_writer.write_record(&f_recs[0])?; self.fq2_writer.write_record(&r_recs[0])?; } Ok(()) } fn fq1_rea der(&mut self) -> &mut fastq::Reader<R> { self.fq1_reader } fn fq2_reader(&mut self) -> &mut fastq::Reader<R> { self.fq2_reader } fn umi_len(&self) -> usize { self.umi_len } fn seq_dist(&self) -> usize { self.seq_dist } fn umi_dist(&self) -> usize { self.umi_dist } fn reverse_umi(&self) -> bool { self.reverse_umi } } ///Clusters fastq reads by UMIs and calls consensus for overlapping reads #[allow(clippy::too_many_arguments)] #[derive(new)] pub struct CallOverlappingConsensusRead<'a, R: io::Read, W: io::Write> { fq1_reader: &'a mut fastq::Reader<R>, fq2_reader: &'a mut fastq::Reader<R>, fq1_writer: &'a mut fastq::Writer<W>, fq2_writer: &'a mut fastq::Writer<W>, fq3_writer: &'a mut fastq::Writer<W>, umi_len: usize, seq_dist: usize, umi_dist: usize, insert_size: usize, std_dev: usize, reverse_umi: bool, verbose_read_names: bool, } impl<'a, R: io::Read, W: io::Write> CallOverlappingConsensusRead<'a, R, W> { fn isize_highest_probability(&mut self, f_seq_len: usize, r_seq_len: usize) -> f64 { if f_seq_len + f_seq_len < self.insert_size { self.insert_size as f64 } else if f_seq_len + r_seq_len > self.insert_size + 2 * self.std_dev { (self.insert_size + 2 * self.std_dev) as f64 } else { (f_seq_len + r_seq_len) as f64 } } fn maximum_likelihood_overlapping_consensus( &mut self, f_recs: &[Record], r_recs: &[Record], outer_seqids: &[usize], uuid: &str, ) -> OverlappingConsensus { //Returns consensus record by filtering overlaps with lowest hamming distance. //For these overlaps(insert sizes) the consensus reads and their likelihoods are calculated. //The read with maximum likelihood will be returned. let insert_sizes = ((self.insert_size - 2 * self.std_dev) ..(self.insert_size + 2 * self.std_dev)) .filter_map(|insert_size| { median_hamming_distance(insert_size, f_recs, r_recs) .filter(|&median_distance| median_distance < HAMMING_THRESHOLD) .map(|_| insert_size) }); insert_sizes .map(|insert_size| { let overlap = (f_recs[0].seq().len() + r_recs[0].seq().len()) - insert_size; let (consensus_record, lh_isize) = CalcOverlappingConsensus::new( f_recs, r_recs, overlap, outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus(); let likelihood = lh_isize + isize_pmf( insert_size as f64, self.insert_size as f64, self.std_dev as f64, ); OverlappingConsensus { record: consensus_record, likelihood, } }) .max_by_key(|consensus| NotNaN::new(*consensus.likelihood).unwrap()) .unwrap() } fn maximum_likelihood_nonoverlapping_consensus( &mut self, f_recs: &[Record], r_recs: &[Record], outer_seqids: &[usize], uuid: &str, ) -> NonOverlappingConsensus { //Calculate non-overlapping consensus records and shared lh let (f_consensus_rec, f_lh) = CalcNonOverlappingConsensus::new(f_recs, outer_seqids, uuid, self.verbose_read_names) .calc_consensus(); let (r_consensus_rec, r_lh) = CalcNonOverlappingConsensus::new(r_recs, outer_seqids, uuid, self.verbose_read_names) .calc_consensus(); let overall_lh_isize = f_lh + r_lh; //Determine insert size with highest probability for non-overlapping records based on expected insert size let likeliest_isize = self.isize_highest_probability(f_recs[0].seq().len(), r_recs[0].seq().len()); let overall_lh = overall_lh_isize + isize_pmf( likeliest_isize, self.insert_size as f64, self.std_dev as f64, ); NonOverlappingConsensus { f_record: f_consensus_rec, r_record: r_consensus_rec, likelihood: overall_lh, } } } impl<'a, R: io::Read + io::BufRead, W
ecs.len() > 1 { let uuid = &Uuid::new_v4().to_hyphenated().to_string(); self.fq1_writer.write_record( &CalcNonOverlappingConsensus::new( &f_recs, &outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus() .0, )?; self.fq2_writer.write_record( &CalcNonOverlappingConsensus::new( &r_recs, &outer_seqids, uuid, self.verbose_read_names, ) .calc_consensus()
identifier_body
cli.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use clap::{App, Arg}; use std::result; use export_docker as docker; /// A Kubernetes-specific clap:App wrapper /// /// The API here is provided to make it possible to reuse the CLI code of the Kubernetes exporter. /// The CLI argument addition is divided between multiple methods to allow you to only pick the /// parts of the CLI that you need. #[derive(Clone)] pub struct Cli<'a, 'b> where 'a: 'b, { pub app: App<'a, 'b>, } impl<'a, 'b> Cli<'a, 'b> { /// Create a `Cli` /// /// # Arguments /// /// * `name` - The name of the CLI application to show in `--help' output. /// * `about` - The long description of the CLi to show in `--help' output. pub fn new(name: &str, about: &'a str) -> Self { let app = docker::Cli::new(name, about).app; Cli { app: app } } /// Convenient method to add all known arguments to the CLI. pub fn add_all_args(self) -> Self { self.add_docker_args() .add_output_args() .add_runtime_args() .add_secret_names_args() .add_bind_args() } pub fn add_docker_args(self) -> Self { let cli = docker::Cli { app: self.app }; let app = cli.add_base_packages_args() .add_builder_args() .add_tagging_args() .add_publishing_args() .add_pkg_ident_arg(docker::PkgIdentArgOptions { multiple: false }) .app .arg( Arg::with_name("NO_DOCKER_IMAGE") .long("no-docker-image") .short("d") .help( "Disable creation of the Docker image and only create a Kubernetes \ manifest", ), ); Cli { app: app } } pub fn add_output_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("OUTPUT") .value_name("OUTPUT") .long("output") .short("o") .help("Name of manifest file to create. Pass '-' for stdout (default: -)"), ), } } /// Add Habitat (operator) runtime arguments to the CLI. pub fn add_runtime_args(self) -> Self { Cli { app: self.app .arg( Arg::with_name("K8S_NAME") .value_name("K8S_NAME") .long("k8s-name") .help( "The Kubernetes resource name \ (default: {{pkg_name}}-{{pkg_version}}-{{pkg_release}})", ), ) .arg( Arg::with_name("COUNT") .value_name("COUNT") .long("count") .validator(valid_natural_number) .help("Count is the number of desired instances"), ) .arg( Arg::with_name("TOPOLOGY") .value_name("TOPOLOGY") .long("topology") .short("t") .possible_values(&["standalone", "leader"]) .help( "A topology describes the intended relationship between peers \ within a Habitat service group. Specify either standalone or leader \ topology (default: standalone)", ), ) .arg( Arg::with_name("GROUP") .value_name("GROUP") .long("service-group") .short("g") .help( "group is a logical grouping of services with the same package and \ topology type connected together in a ring (default: default)", ), ) .arg( Arg::with_name("CONFIG") .value_name("CONFIG") .long("config") .short("n") .help( "The path to Habitat configuration file in user.toml format. Habitat \ will use it for initial configuration of the service running in a \ Kubernetes cluster", ), ), } } pub fn add_secret_names_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("RING_SECRET_NAME") .value_name("RING_SECRET_NAME") .long("ring-secret-name") .short("r") .help( "name of the Kubernetes Secret that contains the ring key, which \ encrypts the communication between Habitat supervisors", ), ), } } pub fn add_bind_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("BIND") .value_name("BIND") .long("bind") .short("b") .multiple(true) .number_of_values(1) .help( "Bind to another service to form a producer/consumer relationship, \ specified as name:service:group", ), ), } } } fn valid_natural_number(val: String) -> result::Result<(), String> { match val.parse::<u32>() {
Ok(_) => Ok(()), Err(_) => Err(format!("{} is not a natural number", val)), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_valid_natural_number() { valid_natural_number("99".to_owned()).unwrap(); for &s in ["x", "", "#####", "0x11", "ab"].iter() { assert!(valid_natural_number(s.to_owned()).is_err()); } } }
random_line_split
cli.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use clap::{App, Arg}; use std::result; use export_docker as docker; /// A Kubernetes-specific clap:App wrapper /// /// The API here is provided to make it possible to reuse the CLI code of the Kubernetes exporter. /// The CLI argument addition is divided between multiple methods to allow you to only pick the /// parts of the CLI that you need. #[derive(Clone)] pub struct Cli<'a, 'b> where 'a: 'b, { pub app: App<'a, 'b>, } impl<'a, 'b> Cli<'a, 'b> { /// Create a `Cli` /// /// # Arguments /// /// * `name` - The name of the CLI application to show in `--help' output. /// * `about` - The long description of the CLi to show in `--help' output. pub fn new(name: &str, about: &'a str) -> Self { let app = docker::Cli::new(name, about).app; Cli { app: app } } /// Convenient method to add all known arguments to the CLI. pub fn add_all_args(self) -> Self
pub fn add_docker_args(self) -> Self { let cli = docker::Cli { app: self.app }; let app = cli.add_base_packages_args() .add_builder_args() .add_tagging_args() .add_publishing_args() .add_pkg_ident_arg(docker::PkgIdentArgOptions { multiple: false }) .app .arg( Arg::with_name("NO_DOCKER_IMAGE") .long("no-docker-image") .short("d") .help( "Disable creation of the Docker image and only create a Kubernetes \ manifest", ), ); Cli { app: app } } pub fn add_output_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("OUTPUT") .value_name("OUTPUT") .long("output") .short("o") .help("Name of manifest file to create. Pass '-' for stdout (default: -)"), ), } } /// Add Habitat (operator) runtime arguments to the CLI. pub fn add_runtime_args(self) -> Self { Cli { app: self.app .arg( Arg::with_name("K8S_NAME") .value_name("K8S_NAME") .long("k8s-name") .help( "The Kubernetes resource name \ (default: {{pkg_name}}-{{pkg_version}}-{{pkg_release}})", ), ) .arg( Arg::with_name("COUNT") .value_name("COUNT") .long("count") .validator(valid_natural_number) .help("Count is the number of desired instances"), ) .arg( Arg::with_name("TOPOLOGY") .value_name("TOPOLOGY") .long("topology") .short("t") .possible_values(&["standalone", "leader"]) .help( "A topology describes the intended relationship between peers \ within a Habitat service group. Specify either standalone or leader \ topology (default: standalone)", ), ) .arg( Arg::with_name("GROUP") .value_name("GROUP") .long("service-group") .short("g") .help( "group is a logical grouping of services with the same package and \ topology type connected together in a ring (default: default)", ), ) .arg( Arg::with_name("CONFIG") .value_name("CONFIG") .long("config") .short("n") .help( "The path to Habitat configuration file in user.toml format. Habitat \ will use it for initial configuration of the service running in a \ Kubernetes cluster", ), ), } } pub fn add_secret_names_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("RING_SECRET_NAME") .value_name("RING_SECRET_NAME") .long("ring-secret-name") .short("r") .help( "name of the Kubernetes Secret that contains the ring key, which \ encrypts the communication between Habitat supervisors", ), ), } } pub fn add_bind_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("BIND") .value_name("BIND") .long("bind") .short("b") .multiple(true) .number_of_values(1) .help( "Bind to another service to form a producer/consumer relationship, \ specified as name:service:group", ), ), } } } fn valid_natural_number(val: String) -> result::Result<(), String> { match val.parse::<u32>() { Ok(_) => Ok(()), Err(_) => Err(format!("{} is not a natural number", val)), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_valid_natural_number() { valid_natural_number("99".to_owned()).unwrap(); for &s in ["x", "", "#####", "0x11", "ab"].iter() { assert!(valid_natural_number(s.to_owned()).is_err()); } } }
{ self.add_docker_args() .add_output_args() .add_runtime_args() .add_secret_names_args() .add_bind_args() }
identifier_body
cli.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use clap::{App, Arg}; use std::result; use export_docker as docker; /// A Kubernetes-specific clap:App wrapper /// /// The API here is provided to make it possible to reuse the CLI code of the Kubernetes exporter. /// The CLI argument addition is divided between multiple methods to allow you to only pick the /// parts of the CLI that you need. #[derive(Clone)] pub struct Cli<'a, 'b> where 'a: 'b, { pub app: App<'a, 'b>, } impl<'a, 'b> Cli<'a, 'b> { /// Create a `Cli` /// /// # Arguments /// /// * `name` - The name of the CLI application to show in `--help' output. /// * `about` - The long description of the CLi to show in `--help' output. pub fn new(name: &str, about: &'a str) -> Self { let app = docker::Cli::new(name, about).app; Cli { app: app } } /// Convenient method to add all known arguments to the CLI. pub fn add_all_args(self) -> Self { self.add_docker_args() .add_output_args() .add_runtime_args() .add_secret_names_args() .add_bind_args() } pub fn add_docker_args(self) -> Self { let cli = docker::Cli { app: self.app }; let app = cli.add_base_packages_args() .add_builder_args() .add_tagging_args() .add_publishing_args() .add_pkg_ident_arg(docker::PkgIdentArgOptions { multiple: false }) .app .arg( Arg::with_name("NO_DOCKER_IMAGE") .long("no-docker-image") .short("d") .help( "Disable creation of the Docker image and only create a Kubernetes \ manifest", ), ); Cli { app: app } } pub fn add_output_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("OUTPUT") .value_name("OUTPUT") .long("output") .short("o") .help("Name of manifest file to create. Pass '-' for stdout (default: -)"), ), } } /// Add Habitat (operator) runtime arguments to the CLI. pub fn add_runtime_args(self) -> Self { Cli { app: self.app .arg( Arg::with_name("K8S_NAME") .value_name("K8S_NAME") .long("k8s-name") .help( "The Kubernetes resource name \ (default: {{pkg_name}}-{{pkg_version}}-{{pkg_release}})", ), ) .arg( Arg::with_name("COUNT") .value_name("COUNT") .long("count") .validator(valid_natural_number) .help("Count is the number of desired instances"), ) .arg( Arg::with_name("TOPOLOGY") .value_name("TOPOLOGY") .long("topology") .short("t") .possible_values(&["standalone", "leader"]) .help( "A topology describes the intended relationship between peers \ within a Habitat service group. Specify either standalone or leader \ topology (default: standalone)", ), ) .arg( Arg::with_name("GROUP") .value_name("GROUP") .long("service-group") .short("g") .help( "group is a logical grouping of services with the same package and \ topology type connected together in a ring (default: default)", ), ) .arg( Arg::with_name("CONFIG") .value_name("CONFIG") .long("config") .short("n") .help( "The path to Habitat configuration file in user.toml format. Habitat \ will use it for initial configuration of the service running in a \ Kubernetes cluster", ), ), } } pub fn add_secret_names_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("RING_SECRET_NAME") .value_name("RING_SECRET_NAME") .long("ring-secret-name") .short("r") .help( "name of the Kubernetes Secret that contains the ring key, which \ encrypts the communication between Habitat supervisors", ), ), } } pub fn add_bind_args(self) -> Self { Cli { app: self.app.arg( Arg::with_name("BIND") .value_name("BIND") .long("bind") .short("b") .multiple(true) .number_of_values(1) .help( "Bind to another service to form a producer/consumer relationship, \ specified as name:service:group", ), ), } } } fn
(val: String) -> result::Result<(), String> { match val.parse::<u32>() { Ok(_) => Ok(()), Err(_) => Err(format!("{} is not a natural number", val)), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_valid_natural_number() { valid_natural_number("99".to_owned()).unwrap(); for &s in ["x", "", "#####", "0x11", "ab"].iter() { assert!(valid_natural_number(s.to_owned()).is_err()); } } }
valid_natural_number
identifier_name
macro-input-future-proofing.rs
// Copyright 2015 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. macro_rules! errors_everywhere { ($ty:ty <) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty < foo,) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty, ) => (); ( ( $ty:ty ) ) => (); ( { $ty:ty } ) => (); ( [ $ty:ty ] ) => (); ($bl:block < ) => (); ($pa:pat >) => (); //~ ERROR `$pa:pat` is followed by `>`, which is not allowed for `pat` ($pa:pat, ) => (); ($pa:pat | ) => (); //~ ERROR `$pa:pat` is followed by `|` ($pa:pat $pb:pat $ty:ty,) => (); //~^ ERROR `$pa:pat` is followed by `$pb:pat`, which is not allowed //~^^ ERROR `$pb:pat` is followed by `$ty:ty`, which is not allowed ($($ty:ty)* -) => (); //~ ERROR `$ty:ty` is followed by `-` ($($a:ty, $b:ty)* -) => (); //~ ERROR `$b:ty` is followed by `-` ($($ty:ty)-+) => (); //~ ERROR `$ty:ty` is followed by `-`, which is not allowed for `ty` } fn main()
{ }
identifier_body
macro-input-future-proofing.rs
// Copyright 2015 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. macro_rules! errors_everywhere { ($ty:ty <) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty < foo,) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty, ) => (); ( ( $ty:ty ) ) => (); ( { $ty:ty } ) => (); ( [ $ty:ty ] ) => (); ($bl:block < ) => (); ($pa:pat >) => (); //~ ERROR `$pa:pat` is followed by `>`, which is not allowed for `pat` ($pa:pat, ) => (); ($pa:pat | ) => (); //~ ERROR `$pa:pat` is followed by `|`
($pa:pat $pb:pat $ty:ty,) => (); //~^ ERROR `$pa:pat` is followed by `$pb:pat`, which is not allowed //~^^ ERROR `$pb:pat` is followed by `$ty:ty`, which is not allowed ($($ty:ty)* -) => (); //~ ERROR `$ty:ty` is followed by `-` ($($a:ty, $b:ty)* -) => (); //~ ERROR `$b:ty` is followed by `-` ($($ty:ty)-+) => (); //~ ERROR `$ty:ty` is followed by `-`, which is not allowed for `ty` } fn main() { }
random_line_split
macro-input-future-proofing.rs
// Copyright 2015 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. macro_rules! errors_everywhere { ($ty:ty <) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty < foo,) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty, ) => (); ( ( $ty:ty ) ) => (); ( { $ty:ty } ) => (); ( [ $ty:ty ] ) => (); ($bl:block < ) => (); ($pa:pat >) => (); //~ ERROR `$pa:pat` is followed by `>`, which is not allowed for `pat` ($pa:pat, ) => (); ($pa:pat | ) => (); //~ ERROR `$pa:pat` is followed by `|` ($pa:pat $pb:pat $ty:ty,) => (); //~^ ERROR `$pa:pat` is followed by `$pb:pat`, which is not allowed //~^^ ERROR `$pb:pat` is followed by `$ty:ty`, which is not allowed ($($ty:ty)* -) => (); //~ ERROR `$ty:ty` is followed by `-` ($($a:ty, $b:ty)* -) => (); //~ ERROR `$b:ty` is followed by `-` ($($ty:ty)-+) => (); //~ ERROR `$ty:ty` is followed by `-`, which is not allowed for `ty` } fn
() { }
main
identifier_name
box-of-array-of-drop-2.rs
// Copyright 2015 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 #![allow(overflowing_literals)] // Test that we cleanup dynamic sized Box<[D]> properly when D has a // destructor. // ignore-emscripten no threads support use std::thread; use std::sync::atomic::{AtomicUsize, Ordering}; static LOG: AtomicUsize = AtomicUsize::new(0); struct D(u8); impl Drop for D { fn drop(&mut self) { println!("Dropping {}", self.0); let old = LOG.load(Ordering::SeqCst); LOG.compare_and_swap(old, old << 4 | self.0 as usize, Ordering::SeqCst); } } fn main() { fn die() -> D { panic!("Oh no"); } let g = thread::spawn(|| { let _b1: Box<[D; 4]> = Box::new([D( 1), D( 2), D( 3), D( 4)]); let _b2: Box<[D; 4]> = Box::new([D( 5), D( 6), D( 7), D( 8)]); let _b3: Box<[D; 4]> = Box::new([D( 9), D(10), die(), D(12)]); let _b4: Box<[D; 4]> = Box::new([D(13), D(14), D(15), D(16)]); }); assert!(g.join().is_err());
// Issue 23222: The order in which the elements actually get // dropped is a little funky. See similar notes in nested-vec-3; // in essence, I would not be surprised if we change the ordering // given in `expect` in the future. let expect = 0x__A_9__5_6_7_8__1_2_3_4; let actual = LOG.load(Ordering::SeqCst); assert!(actual == expect, "expect: 0x{:x} actual: 0x{:x}", expect, actual); }
// When the panic occurs, we will be in the midst of constructing // the input to `_b3`. Therefore, we drop the elements of the // partially filled array first, before we get around to dropping // the elements of `_b1` and _b2`.
random_line_split
box-of-array-of-drop-2.rs
// Copyright 2015 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 #![allow(overflowing_literals)] // Test that we cleanup dynamic sized Box<[D]> properly when D has a // destructor. // ignore-emscripten no threads support use std::thread; use std::sync::atomic::{AtomicUsize, Ordering}; static LOG: AtomicUsize = AtomicUsize::new(0); struct D(u8); impl Drop for D { fn
(&mut self) { println!("Dropping {}", self.0); let old = LOG.load(Ordering::SeqCst); LOG.compare_and_swap(old, old << 4 | self.0 as usize, Ordering::SeqCst); } } fn main() { fn die() -> D { panic!("Oh no"); } let g = thread::spawn(|| { let _b1: Box<[D; 4]> = Box::new([D( 1), D( 2), D( 3), D( 4)]); let _b2: Box<[D; 4]> = Box::new([D( 5), D( 6), D( 7), D( 8)]); let _b3: Box<[D; 4]> = Box::new([D( 9), D(10), die(), D(12)]); let _b4: Box<[D; 4]> = Box::new([D(13), D(14), D(15), D(16)]); }); assert!(g.join().is_err()); // When the panic occurs, we will be in the midst of constructing // the input to `_b3`. Therefore, we drop the elements of the // partially filled array first, before we get around to dropping // the elements of `_b1` and _b2`. // Issue 23222: The order in which the elements actually get // dropped is a little funky. See similar notes in nested-vec-3; // in essence, I would not be surprised if we change the ordering // given in `expect` in the future. let expect = 0x__A_9__5_6_7_8__1_2_3_4; let actual = LOG.load(Ordering::SeqCst); assert!(actual == expect, "expect: 0x{:x} actual: 0x{:x}", expect, actual); }
drop
identifier_name
box-of-array-of-drop-2.rs
// Copyright 2015 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 #![allow(overflowing_literals)] // Test that we cleanup dynamic sized Box<[D]> properly when D has a // destructor. // ignore-emscripten no threads support use std::thread; use std::sync::atomic::{AtomicUsize, Ordering}; static LOG: AtomicUsize = AtomicUsize::new(0); struct D(u8); impl Drop for D { fn drop(&mut self)
} fn main() { fn die() -> D { panic!("Oh no"); } let g = thread::spawn(|| { let _b1: Box<[D; 4]> = Box::new([D( 1), D( 2), D( 3), D( 4)]); let _b2: Box<[D; 4]> = Box::new([D( 5), D( 6), D( 7), D( 8)]); let _b3: Box<[D; 4]> = Box::new([D( 9), D(10), die(), D(12)]); let _b4: Box<[D; 4]> = Box::new([D(13), D(14), D(15), D(16)]); }); assert!(g.join().is_err()); // When the panic occurs, we will be in the midst of constructing // the input to `_b3`. Therefore, we drop the elements of the // partially filled array first, before we get around to dropping // the elements of `_b1` and _b2`. // Issue 23222: The order in which the elements actually get // dropped is a little funky. See similar notes in nested-vec-3; // in essence, I would not be surprised if we change the ordering // given in `expect` in the future. let expect = 0x__A_9__5_6_7_8__1_2_3_4; let actual = LOG.load(Ordering::SeqCst); assert!(actual == expect, "expect: 0x{:x} actual: 0x{:x}", expect, actual); }
{ println!("Dropping {}", self.0); let old = LOG.load(Ordering::SeqCst); LOG.compare_and_swap(old, old << 4 | self.0 as usize, Ordering::SeqCst); }
identifier_body
lib.rs
use std::collections::HashMap; pub fn get_sorted_chars(string : &str) -> String { let mut chars : Vec<char> = string.chars().collect(); chars.sort(); let mut sorted_string = String::new(); for c in chars { sorted_string.push(c); } sorted_string } pub fn get_anagrams<'a>(strings : &[&'a str]) -> HashMap<String, Vec<&'a str>> { let mut anagram_map = HashMap::new(); for string in strings { let sorted_string = get_sorted_chars(string); let string_vec = anagram_map.entry(sorted_string).or_insert(Vec::new()); string_vec.push(*string); } anagram_map } #[test] fn
() { let string = "waffles"; let sorted = get_sorted_chars(string); assert_eq!(sorted, "aefflsw"); } #[test] fn get_anagrams_works_on_simple_data() { let strings = ["ate", "eat"]; let mut expected_anagrams = Vec::new(); expected_anagrams.push("ate"); expected_anagrams.push("eat"); let anagram_map = get_anagrams(&strings); assert_eq!(anagram_map.keys().len(), 1); assert_eq!(anagram_map["aet"], expected_anagrams); }
get_sorted_chars_works
identifier_name
lib.rs
use std::collections::HashMap; pub fn get_sorted_chars(string : &str) -> String { let mut chars : Vec<char> = string.chars().collect(); chars.sort(); let mut sorted_string = String::new(); for c in chars { sorted_string.push(c); } sorted_string } pub fn get_anagrams<'a>(strings : &[&'a str]) -> HashMap<String, Vec<&'a str>> { let mut anagram_map = HashMap::new(); for string in strings { let sorted_string = get_sorted_chars(string); let string_vec = anagram_map.entry(sorted_string).or_insert(Vec::new()); string_vec.push(*string); } anagram_map } #[test] fn get_sorted_chars_works() { let string = "waffles"; let sorted = get_sorted_chars(string); assert_eq!(sorted, "aefflsw");
#[test] fn get_anagrams_works_on_simple_data() { let strings = ["ate", "eat"]; let mut expected_anagrams = Vec::new(); expected_anagrams.push("ate"); expected_anagrams.push("eat"); let anagram_map = get_anagrams(&strings); assert_eq!(anagram_map.keys().len(), 1); assert_eq!(anagram_map["aet"], expected_anagrams); }
}
random_line_split
lib.rs
use std::collections::HashMap; pub fn get_sorted_chars(string : &str) -> String { let mut chars : Vec<char> = string.chars().collect(); chars.sort(); let mut sorted_string = String::new(); for c in chars { sorted_string.push(c); } sorted_string } pub fn get_anagrams<'a>(strings : &[&'a str]) -> HashMap<String, Vec<&'a str>> { let mut anagram_map = HashMap::new(); for string in strings { let sorted_string = get_sorted_chars(string); let string_vec = anagram_map.entry(sorted_string).or_insert(Vec::new()); string_vec.push(*string); } anagram_map } #[test] fn get_sorted_chars_works()
#[test] fn get_anagrams_works_on_simple_data() { let strings = ["ate", "eat"]; let mut expected_anagrams = Vec::new(); expected_anagrams.push("ate"); expected_anagrams.push("eat"); let anagram_map = get_anagrams(&strings); assert_eq!(anagram_map.keys().len(), 1); assert_eq!(anagram_map["aet"], expected_anagrams); }
{ let string = "waffles"; let sorted = get_sorted_chars(string); assert_eq!(sorted, "aefflsw"); }
identifier_body
on_disk.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{CryptoKVStorage, Error, GetResponse, KVStorage}; use diem_temppath::TempPath; use diem_time_service::{TimeService, TimeServiceTrait}; use serde::{de::DeserializeOwned, Serialize}; use serde_json::Value; use std::{ collections::HashMap, fs::{self, File}, io::{Read, Write}, path::PathBuf, }; /// OnDiskStorage represents a key value store that is persisted to the local filesystem and is /// intended for single threads (or must be wrapped by a Arc<RwLock<>>). This provides no permission /// checks and simply offers a proof of concept to unblock building of applications without more /// complex data stores. Internally, it reads and writes all data to a file, which means that it /// must make copies of all key material which violates the Diem code base. It violates it because /// the anticipation is that data stores would securely handle key material. This should not be used /// in production. pub struct OnDiskStorage { file_path: PathBuf, temp_path: TempPath, time_service: TimeService, } impl OnDiskStorage { pub fn new(file_path: PathBuf) -> Self { Self::new_with_time_service(file_path, TimeService::real()) } fn new_with_time_service(file_path: PathBuf, time_service: TimeService) -> Self { if!file_path.exists() { File::create(&file_path).expect("Unable to create storage"); } // The parent will be one when only a filename is supplied. Therefore use the current // working directory provided by PathBuf::new(). let file_dir = file_path .parent() .map_or(PathBuf::new(), |p| p.to_path_buf()); Self { file_path, temp_path: TempPath::new_with_temp_dir(file_dir), time_service, } } fn read(&self) -> Result<HashMap<String, Value>, Error> { let mut file = File::open(&self.file_path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; if contents.is_empty() { return Ok(HashMap::new()); } let data = serde_json::from_str(&contents)?; Ok(data) } fn write(&self, data: &HashMap<String, Value>) -> Result<(), Error> { let contents = serde_json::to_vec(data)?; let mut file = File::create(self.temp_path.path())?; file.write_all(&contents)?; fs::rename(&self.temp_path, &self.file_path)?; Ok(()) } } impl KVStorage for OnDiskStorage { fn
(&self) -> Result<(), Error> { Ok(()) } fn get<V: DeserializeOwned>(&self, key: &str) -> Result<GetResponse<V>, Error> { let mut data = self.read()?; data.remove(key) .ok_or_else(|| Error::KeyNotSet(key.to_string())) .and_then(|value| serde_json::from_value(value).map_err(|e| e.into())) } fn set<V: Serialize>(&mut self, key: &str, value: V) -> Result<(), Error> { let now = self.time_service.now_secs(); let mut data = self.read()?; data.insert( key.to_string(), serde_json::to_value(&GetResponse::new(value, now))?, ); self.write(&data) } #[cfg(any(test, feature = "testing"))] fn reset_and_clear(&mut self) -> Result<(), Error> { self.write(&HashMap::new()) } } impl CryptoKVStorage for OnDiskStorage {}
available
identifier_name
on_disk.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{CryptoKVStorage, Error, GetResponse, KVStorage}; use diem_temppath::TempPath; use diem_time_service::{TimeService, TimeServiceTrait}; use serde::{de::DeserializeOwned, Serialize}; use serde_json::Value; use std::{ collections::HashMap, fs::{self, File}, io::{Read, Write}, path::PathBuf, }; /// OnDiskStorage represents a key value store that is persisted to the local filesystem and is /// intended for single threads (or must be wrapped by a Arc<RwLock<>>). This provides no permission /// checks and simply offers a proof of concept to unblock building of applications without more /// complex data stores. Internally, it reads and writes all data to a file, which means that it /// must make copies of all key material which violates the Diem code base. It violates it because /// the anticipation is that data stores would securely handle key material. This should not be used /// in production. pub struct OnDiskStorage { file_path: PathBuf, temp_path: TempPath, time_service: TimeService, } impl OnDiskStorage { pub fn new(file_path: PathBuf) -> Self { Self::new_with_time_service(file_path, TimeService::real()) } fn new_with_time_service(file_path: PathBuf, time_service: TimeService) -> Self { if!file_path.exists() { File::create(&file_path).expect("Unable to create storage"); } // The parent will be one when only a filename is supplied. Therefore use the current // working directory provided by PathBuf::new(). let file_dir = file_path .parent() .map_or(PathBuf::new(), |p| p.to_path_buf()); Self { file_path, temp_path: TempPath::new_with_temp_dir(file_dir), time_service, } } fn read(&self) -> Result<HashMap<String, Value>, Error> { let mut file = File::open(&self.file_path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; if contents.is_empty()
let data = serde_json::from_str(&contents)?; Ok(data) } fn write(&self, data: &HashMap<String, Value>) -> Result<(), Error> { let contents = serde_json::to_vec(data)?; let mut file = File::create(self.temp_path.path())?; file.write_all(&contents)?; fs::rename(&self.temp_path, &self.file_path)?; Ok(()) } } impl KVStorage for OnDiskStorage { fn available(&self) -> Result<(), Error> { Ok(()) } fn get<V: DeserializeOwned>(&self, key: &str) -> Result<GetResponse<V>, Error> { let mut data = self.read()?; data.remove(key) .ok_or_else(|| Error::KeyNotSet(key.to_string())) .and_then(|value| serde_json::from_value(value).map_err(|e| e.into())) } fn set<V: Serialize>(&mut self, key: &str, value: V) -> Result<(), Error> { let now = self.time_service.now_secs(); let mut data = self.read()?; data.insert( key.to_string(), serde_json::to_value(&GetResponse::new(value, now))?, ); self.write(&data) } #[cfg(any(test, feature = "testing"))] fn reset_and_clear(&mut self) -> Result<(), Error> { self.write(&HashMap::new()) } } impl CryptoKVStorage for OnDiskStorage {}
{ return Ok(HashMap::new()); }
conditional_block
on_disk.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{CryptoKVStorage, Error, GetResponse, KVStorage}; use diem_temppath::TempPath; use diem_time_service::{TimeService, TimeServiceTrait}; use serde::{de::DeserializeOwned, Serialize}; use serde_json::Value; use std::{ collections::HashMap, fs::{self, File}, io::{Read, Write}, path::PathBuf, }; /// OnDiskStorage represents a key value store that is persisted to the local filesystem and is /// intended for single threads (or must be wrapped by a Arc<RwLock<>>). This provides no permission /// checks and simply offers a proof of concept to unblock building of applications without more /// complex data stores. Internally, it reads and writes all data to a file, which means that it /// must make copies of all key material which violates the Diem code base. It violates it because /// the anticipation is that data stores would securely handle key material. This should not be used /// in production. pub struct OnDiskStorage { file_path: PathBuf, temp_path: TempPath, time_service: TimeService, } impl OnDiskStorage { pub fn new(file_path: PathBuf) -> Self { Self::new_with_time_service(file_path, TimeService::real()) } fn new_with_time_service(file_path: PathBuf, time_service: TimeService) -> Self { if!file_path.exists() { File::create(&file_path).expect("Unable to create storage"); } // The parent will be one when only a filename is supplied. Therefore use the current // working directory provided by PathBuf::new(). let file_dir = file_path .parent() .map_or(PathBuf::new(), |p| p.to_path_buf()); Self { file_path, temp_path: TempPath::new_with_temp_dir(file_dir), time_service, } } fn read(&self) -> Result<HashMap<String, Value>, Error> { let mut file = File::open(&self.file_path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; if contents.is_empty() { return Ok(HashMap::new()); } let data = serde_json::from_str(&contents)?; Ok(data) } fn write(&self, data: &HashMap<String, Value>) -> Result<(), Error> { let contents = serde_json::to_vec(data)?; let mut file = File::create(self.temp_path.path())?; file.write_all(&contents)?; fs::rename(&self.temp_path, &self.file_path)?; Ok(()) } } impl KVStorage for OnDiskStorage { fn available(&self) -> Result<(), Error> { Ok(()) } fn get<V: DeserializeOwned>(&self, key: &str) -> Result<GetResponse<V>, Error> { let mut data = self.read()?; data.remove(key) .ok_or_else(|| Error::KeyNotSet(key.to_string())) .and_then(|value| serde_json::from_value(value).map_err(|e| e.into())) } fn set<V: Serialize>(&mut self, key: &str, value: V) -> Result<(), Error> { let now = self.time_service.now_secs(); let mut data = self.read()?; data.insert( key.to_string(),
); self.write(&data) } #[cfg(any(test, feature = "testing"))] fn reset_and_clear(&mut self) -> Result<(), Error> { self.write(&HashMap::new()) } } impl CryptoKVStorage for OnDiskStorage {}
serde_json::to_value(&GetResponse::new(value, now))?,
random_line_split
callback.rs
use std::mem; use std::ptr; use std::cell::RefCell; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use CursorState; use Event; use super::event; use user32; use shell32; use winapi; /// There's no parameters passed to the callback function, so it needs to get /// its context (the HWND, the Sender for events, etc.) stashed in /// a thread-local variable. thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None)); pub struct ThreadLocalData { pub win: winapi::HWND, pub sender: Sender<Event>, pub cursor_state: Arc<Mutex<CursorState>> } /// Checks that the window is the good one, and if so send the event to it. fn send_event(input_window: winapi::HWND, event: Event) { CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win, ref sender,.. } = stored; if win!= &input_window { return; } sender.send(event).ok(); // ignoring if closed }); } /// This is the callback that is called by `DispatchMessage` in the events loop. /// /// Returning 0 tells the Win32 API that the message has been processed. // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT, wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> winapi::LRESULT { match msg { winapi::WM_DESTROY => { use events::Event::Closed; CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win,.. } = stored; if win == &window { user32::PostQuitMessage(0); } }); send_event(window, Closed); 0 }, winapi::WM_ERASEBKGND => { 1 }, winapi::WM_SIZE => { use events::Event::Resized; let w = winapi::LOWORD(lparam as winapi::DWORD) as u32; let h = winapi::HIWORD(lparam as winapi::DWORD) as u32; send_event(window, Resized(w, h)); 0 }, winapi::WM_MOVE => { use events::Event::Moved; let x = winapi::LOWORD(lparam as winapi::DWORD) as i32; let y = winapi::HIWORD(lparam as winapi::DWORD) as i32; send_event(window, Moved(x, y)); 0 }, winapi::WM_CHAR => { use std::mem; use events::Event::ReceivedCharacter; let chr: char = mem::transmute(wparam as u32); send_event(window, ReceivedCharacter(chr)); 0 }, // Prevents default windows menu hotkeys playing unwanted // "ding" sounds. Alternatively could check for WM_SYSCOMMAND // with wparam being SC_KEYMENU, but this may prevent some // other unwanted default hotkeys as well. winapi::WM_SYSCHAR => { 0 } winapi::WM_MOUSEMOVE => { use events::Event::MouseMoved; let x = winapi::GET_X_LPARAM(lparam) as i32; let y = winapi::GET_Y_LPARAM(lparam) as i32; send_event(window, MouseMoved((x, y)));
winapi::WM_MOUSEWHEEL => { use events::Event::MouseWheel; use events::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = value as f32 / winapi::WHEEL_DELTA as f32; send_event(window, MouseWheel(LineDelta(0.0, value))); 0 }, winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => { use events::Event::KeyboardInput; use events::ElementState::Pressed; if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 { user32::DefWindowProcW(window, msg, wparam, lparam) } else { let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Pressed, scancode, vkey)); 0 } }, winapi::WM_KEYUP | winapi::WM_SYSKEYUP => { use events::Event::KeyboardInput; use events::ElementState::Released; let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Released, scancode, vkey)); 0 }, winapi::WM_LBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Left)); 0 }, winapi::WM_LBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Released; send_event(window, MouseInput(Released, Left)); 0 }, winapi::WM_RBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Right)); 0 }, winapi::WM_RBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Released; send_event(window, MouseInput(Released, Right)); 0 }, winapi::WM_MBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Middle)); 0 }, winapi::WM_MBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Released; send_event(window, MouseInput(Released, Middle)); 0 }, winapi::WM_INPUT => { let mut data: winapi::RAWINPUT = mem::uninitialized(); let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT; user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT, mem::transmute(&mut data), &mut data_size, mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT); if data.header.dwType == winapi::RIM_TYPEMOUSE { let _x = data.mouse.lLastX; // FIXME: this is not always the relative movement let _y = data.mouse.lLastY; // TODO: //send_event(window, Event::MouseRawMovement { x: x, y: y }); 0 } else { user32::DefWindowProcW(window, msg, wparam, lparam) } }, winapi::WM_SETFOCUS => { use events::Event::Focused; send_event(window, Focused(true)); 0 }, winapi::WM_KILLFOCUS => { use events::Event::Focused; send_event(window, Focused(false)); 0 }, winapi::WM_SETCURSOR => { CONTEXT_STASH.with(|context_stash| { let cstash = context_stash.borrow(); let cstash = cstash.as_ref(); // there's a very bizarre borrow checker bug // possibly related to rust-lang/rust/#23338 let _cursor_state = if let Some(cstash) = cstash { if let Ok(cursor_state) = cstash.cursor_state.lock() { match *cursor_state { CursorState::Normal => { user32::SetCursor(user32::LoadCursorW( ptr::null_mut(), winapi::IDC_ARROW)); }, CursorState::Grab | CursorState::Hide => { user32::SetCursor(ptr::null_mut()); } } } } else { return }; // let &ThreadLocalData { ref cursor_state,.. } = stored; }); 0 }, winapi::WM_DROPFILES => { use events::Event::DroppedFile; let hdrop = wparam as winapi::HDROP; let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized(); let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); for i in 0..num_drops { let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), winapi::MAX_PATH as u32) as usize; if nch > 0 { send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into())); } } shell32::DragFinish(hdrop); 0 }, _ => { user32::DefWindowProcW(window, msg, wparam, lparam) } } }
0 },
random_line_split
callback.rs
use std::mem; use std::ptr; use std::cell::RefCell; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use CursorState; use Event; use super::event; use user32; use shell32; use winapi; /// There's no parameters passed to the callback function, so it needs to get /// its context (the HWND, the Sender for events, etc.) stashed in /// a thread-local variable. thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None)); pub struct ThreadLocalData { pub win: winapi::HWND, pub sender: Sender<Event>, pub cursor_state: Arc<Mutex<CursorState>> } /// Checks that the window is the good one, and if so send the event to it. fn send_event(input_window: winapi::HWND, event: Event) { CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win, ref sender,.. } = stored; if win!= &input_window { return; } sender.send(event).ok(); // ignoring if closed }); } /// This is the callback that is called by `DispatchMessage` in the events loop. /// /// Returning 0 tells the Win32 API that the message has been processed. // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT, wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> winapi::LRESULT
0 }, winapi::WM_ERASEBKGND => { 1 }, winapi::WM_SIZE => { use events::Event::Resized; let w = winapi::LOWORD(lparam as winapi::DWORD) as u32; let h = winapi::HIWORD(lparam as winapi::DWORD) as u32; send_event(window, Resized(w, h)); 0 }, winapi::WM_MOVE => { use events::Event::Moved; let x = winapi::LOWORD(lparam as winapi::DWORD) as i32; let y = winapi::HIWORD(lparam as winapi::DWORD) as i32; send_event(window, Moved(x, y)); 0 }, winapi::WM_CHAR => { use std::mem; use events::Event::ReceivedCharacter; let chr: char = mem::transmute(wparam as u32); send_event(window, ReceivedCharacter(chr)); 0 }, // Prevents default windows menu hotkeys playing unwanted // "ding" sounds. Alternatively could check for WM_SYSCOMMAND // with wparam being SC_KEYMENU, but this may prevent some // other unwanted default hotkeys as well. winapi::WM_SYSCHAR => { 0 } winapi::WM_MOUSEMOVE => { use events::Event::MouseMoved; let x = winapi::GET_X_LPARAM(lparam) as i32; let y = winapi::GET_Y_LPARAM(lparam) as i32; send_event(window, MouseMoved((x, y))); 0 }, winapi::WM_MOUSEWHEEL => { use events::Event::MouseWheel; use events::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = value as f32 / winapi::WHEEL_DELTA as f32; send_event(window, MouseWheel(LineDelta(0.0, value))); 0 }, winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => { use events::Event::KeyboardInput; use events::ElementState::Pressed; if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 { user32::DefWindowProcW(window, msg, wparam, lparam) } else { let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Pressed, scancode, vkey)); 0 } }, winapi::WM_KEYUP | winapi::WM_SYSKEYUP => { use events::Event::KeyboardInput; use events::ElementState::Released; let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Released, scancode, vkey)); 0 }, winapi::WM_LBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Left)); 0 }, winapi::WM_LBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Released; send_event(window, MouseInput(Released, Left)); 0 }, winapi::WM_RBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Right)); 0 }, winapi::WM_RBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Released; send_event(window, MouseInput(Released, Right)); 0 }, winapi::WM_MBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Middle)); 0 }, winapi::WM_MBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Released; send_event(window, MouseInput(Released, Middle)); 0 }, winapi::WM_INPUT => { let mut data: winapi::RAWINPUT = mem::uninitialized(); let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT; user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT, mem::transmute(&mut data), &mut data_size, mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT); if data.header.dwType == winapi::RIM_TYPEMOUSE { let _x = data.mouse.lLastX; // FIXME: this is not always the relative movement let _y = data.mouse.lLastY; // TODO: //send_event(window, Event::MouseRawMovement { x: x, y: y }); 0 } else { user32::DefWindowProcW(window, msg, wparam, lparam) } }, winapi::WM_SETFOCUS => { use events::Event::Focused; send_event(window, Focused(true)); 0 }, winapi::WM_KILLFOCUS => { use events::Event::Focused; send_event(window, Focused(false)); 0 }, winapi::WM_SETCURSOR => { CONTEXT_STASH.with(|context_stash| { let cstash = context_stash.borrow(); let cstash = cstash.as_ref(); // there's a very bizarre borrow checker bug // possibly related to rust-lang/rust/#23338 let _cursor_state = if let Some(cstash) = cstash { if let Ok(cursor_state) = cstash.cursor_state.lock() { match *cursor_state { CursorState::Normal => { user32::SetCursor(user32::LoadCursorW( ptr::null_mut(), winapi::IDC_ARROW)); }, CursorState::Grab | CursorState::Hide => { user32::SetCursor(ptr::null_mut()); } } } } else { return }; // let &ThreadLocalData { ref cursor_state,.. } = stored; }); 0 }, winapi::WM_DROPFILES => { use events::Event::DroppedFile; let hdrop = wparam as winapi::HDROP; let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized(); let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); for i in 0..num_drops { let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), winapi::MAX_PATH as u32) as usize; if nch > 0 { send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into())); } } shell32::DragFinish(hdrop); 0 }, _ => { user32::DefWindowProcW(window, msg, wparam, lparam) } } }
{ match msg { winapi::WM_DESTROY => { use events::Event::Closed; CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win, .. } = stored; if win == &window { user32::PostQuitMessage(0); } }); send_event(window, Closed);
identifier_body
callback.rs
use std::mem; use std::ptr; use std::cell::RefCell; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use CursorState; use Event; use super::event; use user32; use shell32; use winapi; /// There's no parameters passed to the callback function, so it needs to get /// its context (the HWND, the Sender for events, etc.) stashed in /// a thread-local variable. thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None)); pub struct ThreadLocalData { pub win: winapi::HWND, pub sender: Sender<Event>, pub cursor_state: Arc<Mutex<CursorState>> } /// Checks that the window is the good one, and if so send the event to it. fn send_event(input_window: winapi::HWND, event: Event) { CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win, ref sender,.. } = stored; if win!= &input_window { return; } sender.send(event).ok(); // ignoring if closed }); } /// This is the callback that is called by `DispatchMessage` in the events loop. /// /// Returning 0 tells the Win32 API that the message has been processed. // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary pub unsafe extern "system" fn
(window: winapi::HWND, msg: winapi::UINT, wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> winapi::LRESULT { match msg { winapi::WM_DESTROY => { use events::Event::Closed; CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win,.. } = stored; if win == &window { user32::PostQuitMessage(0); } }); send_event(window, Closed); 0 }, winapi::WM_ERASEBKGND => { 1 }, winapi::WM_SIZE => { use events::Event::Resized; let w = winapi::LOWORD(lparam as winapi::DWORD) as u32; let h = winapi::HIWORD(lparam as winapi::DWORD) as u32; send_event(window, Resized(w, h)); 0 }, winapi::WM_MOVE => { use events::Event::Moved; let x = winapi::LOWORD(lparam as winapi::DWORD) as i32; let y = winapi::HIWORD(lparam as winapi::DWORD) as i32; send_event(window, Moved(x, y)); 0 }, winapi::WM_CHAR => { use std::mem; use events::Event::ReceivedCharacter; let chr: char = mem::transmute(wparam as u32); send_event(window, ReceivedCharacter(chr)); 0 }, // Prevents default windows menu hotkeys playing unwanted // "ding" sounds. Alternatively could check for WM_SYSCOMMAND // with wparam being SC_KEYMENU, but this may prevent some // other unwanted default hotkeys as well. winapi::WM_SYSCHAR => { 0 } winapi::WM_MOUSEMOVE => { use events::Event::MouseMoved; let x = winapi::GET_X_LPARAM(lparam) as i32; let y = winapi::GET_Y_LPARAM(lparam) as i32; send_event(window, MouseMoved((x, y))); 0 }, winapi::WM_MOUSEWHEEL => { use events::Event::MouseWheel; use events::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = value as f32 / winapi::WHEEL_DELTA as f32; send_event(window, MouseWheel(LineDelta(0.0, value))); 0 }, winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => { use events::Event::KeyboardInput; use events::ElementState::Pressed; if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 { user32::DefWindowProcW(window, msg, wparam, lparam) } else { let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Pressed, scancode, vkey)); 0 } }, winapi::WM_KEYUP | winapi::WM_SYSKEYUP => { use events::Event::KeyboardInput; use events::ElementState::Released; let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Released, scancode, vkey)); 0 }, winapi::WM_LBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Left)); 0 }, winapi::WM_LBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Released; send_event(window, MouseInput(Released, Left)); 0 }, winapi::WM_RBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Right)); 0 }, winapi::WM_RBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Released; send_event(window, MouseInput(Released, Right)); 0 }, winapi::WM_MBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Middle)); 0 }, winapi::WM_MBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Released; send_event(window, MouseInput(Released, Middle)); 0 }, winapi::WM_INPUT => { let mut data: winapi::RAWINPUT = mem::uninitialized(); let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT; user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT, mem::transmute(&mut data), &mut data_size, mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT); if data.header.dwType == winapi::RIM_TYPEMOUSE { let _x = data.mouse.lLastX; // FIXME: this is not always the relative movement let _y = data.mouse.lLastY; // TODO: //send_event(window, Event::MouseRawMovement { x: x, y: y }); 0 } else { user32::DefWindowProcW(window, msg, wparam, lparam) } }, winapi::WM_SETFOCUS => { use events::Event::Focused; send_event(window, Focused(true)); 0 }, winapi::WM_KILLFOCUS => { use events::Event::Focused; send_event(window, Focused(false)); 0 }, winapi::WM_SETCURSOR => { CONTEXT_STASH.with(|context_stash| { let cstash = context_stash.borrow(); let cstash = cstash.as_ref(); // there's a very bizarre borrow checker bug // possibly related to rust-lang/rust/#23338 let _cursor_state = if let Some(cstash) = cstash { if let Ok(cursor_state) = cstash.cursor_state.lock() { match *cursor_state { CursorState::Normal => { user32::SetCursor(user32::LoadCursorW( ptr::null_mut(), winapi::IDC_ARROW)); }, CursorState::Grab | CursorState::Hide => { user32::SetCursor(ptr::null_mut()); } } } } else { return }; // let &ThreadLocalData { ref cursor_state,.. } = stored; }); 0 }, winapi::WM_DROPFILES => { use events::Event::DroppedFile; let hdrop = wparam as winapi::HDROP; let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized(); let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); for i in 0..num_drops { let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), winapi::MAX_PATH as u32) as usize; if nch > 0 { send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into())); } } shell32::DragFinish(hdrop); 0 }, _ => { user32::DefWindowProcW(window, msg, wparam, lparam) } } }
callback
identifier_name
test_select.rs
use nix::sys::select::{FdSet, FD_SETSIZE, select}; use nix::sys::time::TimeVal; use nix::unistd::{write, pipe}; #[test] fn test_fdset() { let mut fd_set = FdSet::new(); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } fd_set.insert(7);
assert!(!fd_set.contains(i)); } fd_set.insert(1); fd_set.insert(FD_SETSIZE / 2); fd_set.insert(FD_SETSIZE - 1); fd_set.clear(); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } } #[test] fn test_select() { let (r1, w1) = pipe().unwrap(); write(w1, b"hi!").unwrap(); let (r2, _w2) = pipe().unwrap(); let mut fd_set = FdSet::new(); fd_set.insert(r1); fd_set.insert(r2); let mut timeout = TimeVal::seconds(1); assert_eq!(1, select(r2 + 1, Some(&mut fd_set), None, None, Some(&mut timeout)).unwrap()); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); }
assert!(fd_set.contains(7)); fd_set.remove(7); for i in 0..FD_SETSIZE {
random_line_split
test_select.rs
use nix::sys::select::{FdSet, FD_SETSIZE, select}; use nix::sys::time::TimeVal; use nix::unistd::{write, pipe}; #[test] fn test_fdset() { let mut fd_set = FdSet::new(); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } fd_set.insert(7); assert!(fd_set.contains(7)); fd_set.remove(7); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } fd_set.insert(1); fd_set.insert(FD_SETSIZE / 2); fd_set.insert(FD_SETSIZE - 1); fd_set.clear(); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } } #[test] fn test_select()
{ let (r1, w1) = pipe().unwrap(); write(w1, b"hi!").unwrap(); let (r2, _w2) = pipe().unwrap(); let mut fd_set = FdSet::new(); fd_set.insert(r1); fd_set.insert(r2); let mut timeout = TimeVal::seconds(1); assert_eq!(1, select(r2 + 1, Some(&mut fd_set), None, None, Some(&mut timeout)).unwrap()); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); }
identifier_body
test_select.rs
use nix::sys::select::{FdSet, FD_SETSIZE, select}; use nix::sys::time::TimeVal; use nix::unistd::{write, pipe}; #[test] fn
() { let mut fd_set = FdSet::new(); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } fd_set.insert(7); assert!(fd_set.contains(7)); fd_set.remove(7); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } fd_set.insert(1); fd_set.insert(FD_SETSIZE / 2); fd_set.insert(FD_SETSIZE - 1); fd_set.clear(); for i in 0..FD_SETSIZE { assert!(!fd_set.contains(i)); } } #[test] fn test_select() { let (r1, w1) = pipe().unwrap(); write(w1, b"hi!").unwrap(); let (r2, _w2) = pipe().unwrap(); let mut fd_set = FdSet::new(); fd_set.insert(r1); fd_set.insert(r2); let mut timeout = TimeVal::seconds(1); assert_eq!(1, select(r2 + 1, Some(&mut fd_set), None, None, Some(&mut timeout)).unwrap()); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); }
test_fdset
identifier_name
svg.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/. */ //! Computed types for SVG properties. use app_units::Au; use values::RGBA; use values::computed::{LengthOrPercentage, NonNegativeLength}; use values::computed::{NonNegativeLengthOrPercentage, NonNegativeNumber, Number}; use values::computed::Opacity; use values::computed::url::ComputedUrl; use values::generics::svg as generic; pub use values::specified::SVGPaintOrder; pub use values::specified::MozContextProperties; /// Computed SVG Paint value pub type SVGPaint = generic::SVGPaint<RGBA, ComputedUrl>; /// Computed SVG Paint Kind value pub type SVGPaintKind = generic::SVGPaintKind<RGBA, ComputedUrl>; impl Default for SVGPaint { fn default() -> Self { SVGPaint { kind: generic::SVGPaintKind::None, fallback: None, } } } impl SVGPaint { /// Opaque black color pub fn black() -> Self { let rgba = RGBA::from_floats(0., 0., 0., 1.); SVGPaint { kind: generic::SVGPaintKind::Color(rgba), fallback: None, } } } /// A value of <length> | <percentage> | <number> for stroke-dashoffset. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type SvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>; /// <length> | <percentage> | <number> | context-value pub type SVGLength = generic::SVGLength<SvgLengthOrPercentageOrNumber>; impl From<Au> for SVGLength { fn from(length: Au) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type NonNegativeSvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<NonNegativeLengthOrPercentage, NonNegativeNumber>; impl Into<NonNegativeSvgLengthOrPercentageOrNumber> for SvgLengthOrPercentageOrNumber { fn into(self) -> NonNegativeSvgLengthOrPercentageOrNumber { match self { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop.into()) }, generic::SvgLengthOrPercentageOrNumber::Number(num) => { generic::SvgLengthOrPercentageOrNumber::Number(num.into()) }, } } } /// An non-negative wrapper of SVGLength. pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthOrPercentageOrNumber>; impl From<NonNegativeLength> for SVGWidth { fn from(length: NonNegativeLength) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// [ <length> | <percentage> | <number> ]# | context-value pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthOrPercentageOrNumber>; impl Default for SVGStrokeDashArray { fn default() -> Self { generic::SVGStrokeDashArray::Values(vec![]) } } /// <opacity-value> | context-fill-opacity | context-stroke-opacity pub type SVGOpacity = generic::SVGOpacity<Opacity>; impl Default for SVGOpacity { fn default() -> Self
}
{ generic::SVGOpacity::Opacity(1.) }
identifier_body
svg.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/. */ //! Computed types for SVG properties. use app_units::Au; use values::RGBA; use values::computed::{LengthOrPercentage, NonNegativeLength}; use values::computed::{NonNegativeLengthOrPercentage, NonNegativeNumber, Number}; use values::computed::Opacity; use values::computed::url::ComputedUrl; use values::generics::svg as generic; pub use values::specified::SVGPaintOrder; pub use values::specified::MozContextProperties; /// Computed SVG Paint value pub type SVGPaint = generic::SVGPaint<RGBA, ComputedUrl>; /// Computed SVG Paint Kind value pub type SVGPaintKind = generic::SVGPaintKind<RGBA, ComputedUrl>; impl Default for SVGPaint { fn default() -> Self { SVGPaint { kind: generic::SVGPaintKind::None, fallback: None, } } } impl SVGPaint { /// Opaque black color pub fn black() -> Self { let rgba = RGBA::from_floats(0., 0., 0., 1.); SVGPaint { kind: generic::SVGPaintKind::Color(rgba), fallback: None, } } } /// A value of <length> | <percentage> | <number> for stroke-dashoffset. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type SvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>; /// <length> | <percentage> | <number> | context-value pub type SVGLength = generic::SVGLength<SvgLengthOrPercentageOrNumber>; impl From<Au> for SVGLength { fn from(length: Au) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type NonNegativeSvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<NonNegativeLengthOrPercentage, NonNegativeNumber>; impl Into<NonNegativeSvgLengthOrPercentageOrNumber> for SvgLengthOrPercentageOrNumber { fn into(self) -> NonNegativeSvgLengthOrPercentageOrNumber { match self { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop.into()) }, generic::SvgLengthOrPercentageOrNumber::Number(num) =>
, } } } /// An non-negative wrapper of SVGLength. pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthOrPercentageOrNumber>; impl From<NonNegativeLength> for SVGWidth { fn from(length: NonNegativeLength) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// [ <length> | <percentage> | <number> ]# | context-value pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthOrPercentageOrNumber>; impl Default for SVGStrokeDashArray { fn default() -> Self { generic::SVGStrokeDashArray::Values(vec![]) } } /// <opacity-value> | context-fill-opacity | context-stroke-opacity pub type SVGOpacity = generic::SVGOpacity<Opacity>; impl Default for SVGOpacity { fn default() -> Self { generic::SVGOpacity::Opacity(1.) } }
{ generic::SvgLengthOrPercentageOrNumber::Number(num.into()) }
conditional_block
svg.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/. */ //! Computed types for SVG properties. use app_units::Au; use values::RGBA; use values::computed::{LengthOrPercentage, NonNegativeLength}; use values::computed::{NonNegativeLengthOrPercentage, NonNegativeNumber, Number}; use values::computed::Opacity; use values::computed::url::ComputedUrl; use values::generics::svg as generic; pub use values::specified::SVGPaintOrder; pub use values::specified::MozContextProperties;
/// Computed SVG Paint value pub type SVGPaint = generic::SVGPaint<RGBA, ComputedUrl>; /// Computed SVG Paint Kind value pub type SVGPaintKind = generic::SVGPaintKind<RGBA, ComputedUrl>; impl Default for SVGPaint { fn default() -> Self { SVGPaint { kind: generic::SVGPaintKind::None, fallback: None, } } } impl SVGPaint { /// Opaque black color pub fn black() -> Self { let rgba = RGBA::from_floats(0., 0., 0., 1.); SVGPaint { kind: generic::SVGPaintKind::Color(rgba), fallback: None, } } } /// A value of <length> | <percentage> | <number> for stroke-dashoffset. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type SvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>; /// <length> | <percentage> | <number> | context-value pub type SVGLength = generic::SVGLength<SvgLengthOrPercentageOrNumber>; impl From<Au> for SVGLength { fn from(length: Au) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type NonNegativeSvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<NonNegativeLengthOrPercentage, NonNegativeNumber>; impl Into<NonNegativeSvgLengthOrPercentageOrNumber> for SvgLengthOrPercentageOrNumber { fn into(self) -> NonNegativeSvgLengthOrPercentageOrNumber { match self { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop.into()) }, generic::SvgLengthOrPercentageOrNumber::Number(num) => { generic::SvgLengthOrPercentageOrNumber::Number(num.into()) }, } } } /// An non-negative wrapper of SVGLength. pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthOrPercentageOrNumber>; impl From<NonNegativeLength> for SVGWidth { fn from(length: NonNegativeLength) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// [ <length> | <percentage> | <number> ]# | context-value pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthOrPercentageOrNumber>; impl Default for SVGStrokeDashArray { fn default() -> Self { generic::SVGStrokeDashArray::Values(vec![]) } } /// <opacity-value> | context-fill-opacity | context-stroke-opacity pub type SVGOpacity = generic::SVGOpacity<Opacity>; impl Default for SVGOpacity { fn default() -> Self { generic::SVGOpacity::Opacity(1.) } }
random_line_split
svg.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/. */ //! Computed types for SVG properties. use app_units::Au; use values::RGBA; use values::computed::{LengthOrPercentage, NonNegativeLength}; use values::computed::{NonNegativeLengthOrPercentage, NonNegativeNumber, Number}; use values::computed::Opacity; use values::computed::url::ComputedUrl; use values::generics::svg as generic; pub use values::specified::SVGPaintOrder; pub use values::specified::MozContextProperties; /// Computed SVG Paint value pub type SVGPaint = generic::SVGPaint<RGBA, ComputedUrl>; /// Computed SVG Paint Kind value pub type SVGPaintKind = generic::SVGPaintKind<RGBA, ComputedUrl>; impl Default for SVGPaint { fn default() -> Self { SVGPaint { kind: generic::SVGPaintKind::None, fallback: None, } } } impl SVGPaint { /// Opaque black color pub fn black() -> Self { let rgba = RGBA::from_floats(0., 0., 0., 1.); SVGPaint { kind: generic::SVGPaintKind::Color(rgba), fallback: None, } } } /// A value of <length> | <percentage> | <number> for stroke-dashoffset. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type SvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>; /// <length> | <percentage> | <number> | context-value pub type SVGLength = generic::SVGLength<SvgLengthOrPercentageOrNumber>; impl From<Au> for SVGLength { fn from(length: Au) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> pub type NonNegativeSvgLengthOrPercentageOrNumber = generic::SvgLengthOrPercentageOrNumber<NonNegativeLengthOrPercentage, NonNegativeNumber>; impl Into<NonNegativeSvgLengthOrPercentageOrNumber> for SvgLengthOrPercentageOrNumber { fn into(self) -> NonNegativeSvgLengthOrPercentageOrNumber { match self { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => { generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop.into()) }, generic::SvgLengthOrPercentageOrNumber::Number(num) => { generic::SvgLengthOrPercentageOrNumber::Number(num.into()) }, } } } /// An non-negative wrapper of SVGLength. pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthOrPercentageOrNumber>; impl From<NonNegativeLength> for SVGWidth { fn from(length: NonNegativeLength) -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( length.into(), )) } } /// [ <length> | <percentage> | <number> ]# | context-value pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthOrPercentageOrNumber>; impl Default for SVGStrokeDashArray { fn
() -> Self { generic::SVGStrokeDashArray::Values(vec![]) } } /// <opacity-value> | context-fill-opacity | context-stroke-opacity pub type SVGOpacity = generic::SVGOpacity<Opacity>; impl Default for SVGOpacity { fn default() -> Self { generic::SVGOpacity::Opacity(1.) } }
default
identifier_name