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
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible. fn main() { let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y
else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; let d = if let Some(val) = turbo { "cool" } else { "beans" }; if cond() { statement(); } else { other_statement(); } if true { do_something() } let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; funk(if test() { 1 } else { 2 }, arg2); }
{ 2 }
conditional_block
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*\n\n" -> "" // normalize-stderr-test "note:.*unexpectedly panicked.*\n\n" -> "" // normalize-stderr-test "note: we would appreciate a bug report.*\n\n" -> "" // normalize-stderr-test "note: compiler flags.*\n\n" -> "" // normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" // normalize-stderr-test "query stack during panic:\n" -> "" // normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> "" // normalize-stderr-test "end of query stack\n" -> "" #[macro_use] extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked fn main()
{}
identifier_body
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*\n\n" -> "" // normalize-stderr-test "note:.*unexpectedly panicked.*\n\n" -> "" // normalize-stderr-test "note: we would appreciate a bug report.*\n\n" -> "" // normalize-stderr-test "note: compiler flags.*\n\n" -> "" // normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" // normalize-stderr-test "query stack during panic:\n" -> "" // normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> "" // normalize-stderr-test "end of query stack\n" -> "" #[macro_use] extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked fn
() {}
main
identifier_name
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*\n\n" -> "" // normalize-stderr-test "note:.*unexpectedly panicked.*\n\n" -> "" // normalize-stderr-test "note: we would appreciate a bug report.*\n\n" -> "" // normalize-stderr-test "note: compiler flags.*\n\n" -> ""
// normalize-stderr-test "end of query stack\n" -> "" #[macro_use] extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked fn main() {}
// normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" // normalize-stderr-test "query stack during panic:\n" -> "" // normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> ""
random_line_split
texture_draw.rs
#[macro_use] extern crate glium; use glium::Surface; mod support; macro_rules! texture_draw_test { ($test_name:ident, $tex_ty:ident, [$($dims:expr),+], $glsl_ty:expr, $glsl_value:expr, $rust_value:expr) => ( #[test]
let program = glium::Program::from_source(&display, " #version 110 attribute vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } ", &format!(" #version 130 out {} color; void main() {{ color = {}; }} ", $glsl_ty, $glsl_value), None); let program = match program { Ok(p) => p, Err(_) => return }; let texture = glium::texture::$tex_ty::empty(&display, $($dims),+).unwrap(); texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0); texture.as_surface().draw(&vb, &ib, &program, &uniform!{ texture: &texture }, &Default::default()).unwrap(); display.assert_no_error(None); let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read(); for row in data.iter() { for pixel in row.iter() { assert_eq!(pixel, &$rust_value); } } display.assert_no_error(None); } ); } texture_draw_test!(texture_2d_draw, Texture2d, [1024, 1024], "vec4", "vec4(1.0, 0.0, 1.0, 0.0)", (255, 0, 255, 0));
fn $test_name() { let display = support::build_display(); let (vb, ib) = support::build_rectangle_vb_ib(&display);
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args() { app.render(&r); } if let Some(u) = e.update_args() { app.update(&u); } } }
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct
{ gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args() { app.render(&r); } if let Some(u) = e.update_args() { app.update(&u); } } }
App
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args()
if let Some(u) = e.update_args() { app.update(&u); } } }
{ app.render(&r); }
conditional_block
import-crate-with-invalid-spans.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. // aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn main()
{ // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
identifier_body
import-crate-with-invalid-spans.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. // aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn
() { // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
main
identifier_name
import-crate-with-invalid-spans.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
// aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn main() { // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
// 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.
random_line_split
mod.rs
//! Simple Rust AST. This is what the various code generators create, //! which then gets serialized. use grammar::repr::Grammar; use grammar::parse_tree::Visibility; use tls::Tls; use std::fmt; use std::io::{self, Write}; macro_rules! rust { ($w:expr, $($args:tt)*) => { try!(($w).writeln(&::std::fmt::format(format_args!($($args)*)))) } } /// A wrapper around a Write instance that handles indentation for /// Rust code. It expects Rust code to be written in a stylized way, /// with lots of braces and newlines (example shown here with no /// indentation). Over time maybe we can extend this to make things /// look prettier, but seems like...meh, just run it through some /// rustfmt tool. /// /// ```ignore /// fn foo( /// arg1: Type1, /// arg2: Type2, /// arg3: Type3) /// -> ReturnType /// { /// match foo { /// Variant => { /// } /// } /// } /// ``` pub struct RustWrite<W: Write> { write: W, indent: usize, } const TAB: usize = 4; impl<W: Write> RustWrite<W> { pub fn new(w: W) -> RustWrite<W> { RustWrite { write: w, indent: 0, } } pub fn into_inner(self) -> W { self.write } fn write_indentation(&mut self) -> io::Result<()> { write!(self.write, "{0:1$}", "", self.indent) } fn write_indented(&mut self, out: &str) -> io::Result<()> { writeln!(self.write, "{0:1$}{2}", "", self.indent, out) } pub fn write_table_row<I, C>(&mut self, iterable: I) -> io::Result<()> where I: IntoIterator<Item = (i32, C)>, C: fmt::Display, { if Tls::session().emit_comments { for (i, comment) in iterable { try!(self.write_indentation()); try!(writeln!(self.write, "{}, {}", i, comment)); } } else { try!(self.write_indentation()); let mut first = true;
try!(write!(self.write, " ")); } try!(write!(self.write, "{},", i)); first = false; } } writeln!(self.write, "") } pub fn writeln(&mut self, out: &str) -> io::Result<()> { let buf = out.as_bytes(); // pass empty lines through with no indentation if buf.is_empty() { return self.write.write_all("\n".as_bytes()); } let n = buf.len() - 1; // If the line begins with a `}`, `]`, or `)`, first decrement the indentation. if buf[0] == ('}' as u8) || buf[0] == (']' as u8) || buf[0] == (')' as u8) { self.indent -= TAB; } try!(self.write_indented(out)); // Detect a line that ends in a `{` or `(` and increase indentation for future lines. if buf[n] == ('{' as u8) || buf[n] == ('[' as u8) || buf[n] == ('(' as u8) { self.indent += TAB; } Ok(()) } pub fn write_fn_header( &mut self, grammar: &Grammar, visibility: &Visibility, name: String, type_parameters: Vec<String>, first_parameter: Option<String>, parameters: Vec<String>, return_type: String, where_clauses: Vec<String>, ) -> io::Result<()> { rust!(self, "{}fn {}<", visibility, name); for type_parameter in &grammar.type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } for type_parameter in type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } rust!(self, ">("); if let Some(param) = first_parameter { rust!(self, "{},", param); } for parameter in &grammar.parameters { rust!(self, "{}: {},", parameter.name, parameter.ty); } for parameter in &parameters { rust!(self, "{},", parameter); } if!grammar.where_clauses.is_empty() ||!where_clauses.is_empty() { rust!(self, ") -> {} where", return_type); for where_clause in &grammar.where_clauses { rust!(self, " {},", where_clause); } for where_clause in &where_clauses { rust!(self, " {},", where_clause); } } else { rust!(self, ") -> {}", return_type); } Ok(()) } pub fn write_module_attributes(&mut self, grammar: &Grammar) -> io::Result<()> { for attribute in grammar.module_attributes.iter() { rust!(self, "{}", attribute); } Ok(()) } pub fn write_uses(&mut self, super_prefix: &str, grammar: &Grammar) -> io::Result<()> { // things the user wrote for u in &grammar.uses { if u.starts_with("super::") { rust!(self, "use {}{};", super_prefix, u); } else { rust!(self, "use {};", u); } } self.write_standard_uses(&grammar.prefix) } pub fn write_standard_uses(&mut self, prefix: &str) -> io::Result<()> { // Stuff that we plan to use. // Occasionally we happen to not use it after all, hence the allow. rust!(self, "#[allow(unused_extern_crates)]"); rust!(self, "extern crate lalrpop_util as {}lalrpop_util;", prefix); Ok(()) } }
for (i, _comment) in iterable { if !first {
random_line_split
mod.rs
//! Simple Rust AST. This is what the various code generators create, //! which then gets serialized. use grammar::repr::Grammar; use grammar::parse_tree::Visibility; use tls::Tls; use std::fmt; use std::io::{self, Write}; macro_rules! rust { ($w:expr, $($args:tt)*) => { try!(($w).writeln(&::std::fmt::format(format_args!($($args)*)))) } } /// A wrapper around a Write instance that handles indentation for /// Rust code. It expects Rust code to be written in a stylized way, /// with lots of braces and newlines (example shown here with no /// indentation). Over time maybe we can extend this to make things /// look prettier, but seems like...meh, just run it through some /// rustfmt tool. /// /// ```ignore /// fn foo( /// arg1: Type1, /// arg2: Type2, /// arg3: Type3) /// -> ReturnType /// { /// match foo { /// Variant => { /// } /// } /// } /// ``` pub struct RustWrite<W: Write> { write: W, indent: usize, } const TAB: usize = 4; impl<W: Write> RustWrite<W> { pub fn new(w: W) -> RustWrite<W> { RustWrite { write: w, indent: 0, } } pub fn into_inner(self) -> W { self.write } fn write_indentation(&mut self) -> io::Result<()> { write!(self.write, "{0:1$}", "", self.indent) } fn write_indented(&mut self, out: &str) -> io::Result<()> { writeln!(self.write, "{0:1$}{2}", "", self.indent, out) } pub fn write_table_row<I, C>(&mut self, iterable: I) -> io::Result<()> where I: IntoIterator<Item = (i32, C)>, C: fmt::Display, { if Tls::session().emit_comments { for (i, comment) in iterable { try!(self.write_indentation()); try!(writeln!(self.write, "{}, {}", i, comment)); } } else { try!(self.write_indentation()); let mut first = true; for (i, _comment) in iterable { if!first { try!(write!(self.write, " ")); } try!(write!(self.write, "{},", i)); first = false; } } writeln!(self.write, "") } pub fn writeln(&mut self, out: &str) -> io::Result<()> { let buf = out.as_bytes(); // pass empty lines through with no indentation if buf.is_empty() { return self.write.write_all("\n".as_bytes()); } let n = buf.len() - 1; // If the line begins with a `}`, `]`, or `)`, first decrement the indentation. if buf[0] == ('}' as u8) || buf[0] == (']' as u8) || buf[0] == (')' as u8) { self.indent -= TAB; } try!(self.write_indented(out)); // Detect a line that ends in a `{` or `(` and increase indentation for future lines. if buf[n] == ('{' as u8) || buf[n] == ('[' as u8) || buf[n] == ('(' as u8) { self.indent += TAB; } Ok(()) } pub fn write_fn_header( &mut self, grammar: &Grammar, visibility: &Visibility, name: String, type_parameters: Vec<String>, first_parameter: Option<String>, parameters: Vec<String>, return_type: String, where_clauses: Vec<String>, ) -> io::Result<()> { rust!(self, "{}fn {}<", visibility, name); for type_parameter in &grammar.type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } for type_parameter in type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } rust!(self, ">("); if let Some(param) = first_parameter { rust!(self, "{},", param); } for parameter in &grammar.parameters { rust!(self, "{}: {},", parameter.name, parameter.ty); } for parameter in &parameters { rust!(self, "{},", parameter); } if!grammar.where_clauses.is_empty() ||!where_clauses.is_empty() { rust!(self, ") -> {} where", return_type); for where_clause in &grammar.where_clauses { rust!(self, " {},", where_clause); } for where_clause in &where_clauses { rust!(self, " {},", where_clause); } } else { rust!(self, ") -> {}", return_type); } Ok(()) } pub fn write_module_attributes(&mut self, grammar: &Grammar) -> io::Result<()> { for attribute in grammar.module_attributes.iter() { rust!(self, "{}", attribute); } Ok(()) } pub fn write_uses(&mut self, super_prefix: &str, grammar: &Grammar) -> io::Result<()> { // things the user wrote for u in &grammar.uses { if u.starts_with("super::") { rust!(self, "use {}{};", super_prefix, u); } else { rust!(self, "use {};", u); } } self.write_standard_uses(&grammar.prefix) } pub fn write_standard_uses(&mut self, prefix: &str) -> io::Result<()>
}
{ // Stuff that we plan to use. // Occasionally we happen to not use it after all, hence the allow. rust!(self, "#[allow(unused_extern_crates)]"); rust!(self, "extern crate lalrpop_util as {}lalrpop_util;", prefix); Ok(()) }
identifier_body
mod.rs
//! Simple Rust AST. This is what the various code generators create, //! which then gets serialized. use grammar::repr::Grammar; use grammar::parse_tree::Visibility; use tls::Tls; use std::fmt; use std::io::{self, Write}; macro_rules! rust { ($w:expr, $($args:tt)*) => { try!(($w).writeln(&::std::fmt::format(format_args!($($args)*)))) } } /// A wrapper around a Write instance that handles indentation for /// Rust code. It expects Rust code to be written in a stylized way, /// with lots of braces and newlines (example shown here with no /// indentation). Over time maybe we can extend this to make things /// look prettier, but seems like...meh, just run it through some /// rustfmt tool. /// /// ```ignore /// fn foo( /// arg1: Type1, /// arg2: Type2, /// arg3: Type3) /// -> ReturnType /// { /// match foo { /// Variant => { /// } /// } /// } /// ``` pub struct RustWrite<W: Write> { write: W, indent: usize, } const TAB: usize = 4; impl<W: Write> RustWrite<W> { pub fn new(w: W) -> RustWrite<W> { RustWrite { write: w, indent: 0, } } pub fn into_inner(self) -> W { self.write } fn write_indentation(&mut self) -> io::Result<()> { write!(self.write, "{0:1$}", "", self.indent) } fn write_indented(&mut self, out: &str) -> io::Result<()> { writeln!(self.write, "{0:1$}{2}", "", self.indent, out) } pub fn write_table_row<I, C>(&mut self, iterable: I) -> io::Result<()> where I: IntoIterator<Item = (i32, C)>, C: fmt::Display, { if Tls::session().emit_comments { for (i, comment) in iterable { try!(self.write_indentation()); try!(writeln!(self.write, "{}, {}", i, comment)); } } else { try!(self.write_indentation()); let mut first = true; for (i, _comment) in iterable { if!first { try!(write!(self.write, " ")); } try!(write!(self.write, "{},", i)); first = false; } } writeln!(self.write, "") } pub fn writeln(&mut self, out: &str) -> io::Result<()> { let buf = out.as_bytes(); // pass empty lines through with no indentation if buf.is_empty() { return self.write.write_all("\n".as_bytes()); } let n = buf.len() - 1; // If the line begins with a `}`, `]`, or `)`, first decrement the indentation. if buf[0] == ('}' as u8) || buf[0] == (']' as u8) || buf[0] == (')' as u8) { self.indent -= TAB; } try!(self.write_indented(out)); // Detect a line that ends in a `{` or `(` and increase indentation for future lines. if buf[n] == ('{' as u8) || buf[n] == ('[' as u8) || buf[n] == ('(' as u8) { self.indent += TAB; } Ok(()) } pub fn write_fn_header( &mut self, grammar: &Grammar, visibility: &Visibility, name: String, type_parameters: Vec<String>, first_parameter: Option<String>, parameters: Vec<String>, return_type: String, where_clauses: Vec<String>, ) -> io::Result<()> { rust!(self, "{}fn {}<", visibility, name); for type_parameter in &grammar.type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } for type_parameter in type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } rust!(self, ">("); if let Some(param) = first_parameter { rust!(self, "{},", param); } for parameter in &grammar.parameters { rust!(self, "{}: {},", parameter.name, parameter.ty); } for parameter in &parameters { rust!(self, "{},", parameter); } if!grammar.where_clauses.is_empty() ||!where_clauses.is_empty() { rust!(self, ") -> {} where", return_type); for where_clause in &grammar.where_clauses { rust!(self, " {},", where_clause); } for where_clause in &where_clauses { rust!(self, " {},", where_clause); } } else
Ok(()) } pub fn write_module_attributes(&mut self, grammar: &Grammar) -> io::Result<()> { for attribute in grammar.module_attributes.iter() { rust!(self, "{}", attribute); } Ok(()) } pub fn write_uses(&mut self, super_prefix: &str, grammar: &Grammar) -> io::Result<()> { // things the user wrote for u in &grammar.uses { if u.starts_with("super::") { rust!(self, "use {}{};", super_prefix, u); } else { rust!(self, "use {};", u); } } self.write_standard_uses(&grammar.prefix) } pub fn write_standard_uses(&mut self, prefix: &str) -> io::Result<()> { // Stuff that we plan to use. // Occasionally we happen to not use it after all, hence the allow. rust!(self, "#[allow(unused_extern_crates)]"); rust!(self, "extern crate lalrpop_util as {}lalrpop_util;", prefix); Ok(()) } }
{ rust!(self, ") -> {}", return_type); }
conditional_block
mod.rs
//! Simple Rust AST. This is what the various code generators create, //! which then gets serialized. use grammar::repr::Grammar; use grammar::parse_tree::Visibility; use tls::Tls; use std::fmt; use std::io::{self, Write}; macro_rules! rust { ($w:expr, $($args:tt)*) => { try!(($w).writeln(&::std::fmt::format(format_args!($($args)*)))) } } /// A wrapper around a Write instance that handles indentation for /// Rust code. It expects Rust code to be written in a stylized way, /// with lots of braces and newlines (example shown here with no /// indentation). Over time maybe we can extend this to make things /// look prettier, but seems like...meh, just run it through some /// rustfmt tool. /// /// ```ignore /// fn foo( /// arg1: Type1, /// arg2: Type2, /// arg3: Type3) /// -> ReturnType /// { /// match foo { /// Variant => { /// } /// } /// } /// ``` pub struct RustWrite<W: Write> { write: W, indent: usize, } const TAB: usize = 4; impl<W: Write> RustWrite<W> { pub fn new(w: W) -> RustWrite<W> { RustWrite { write: w, indent: 0, } } pub fn into_inner(self) -> W { self.write } fn write_indentation(&mut self) -> io::Result<()> { write!(self.write, "{0:1$}", "", self.indent) } fn write_indented(&mut self, out: &str) -> io::Result<()> { writeln!(self.write, "{0:1$}{2}", "", self.indent, out) } pub fn write_table_row<I, C>(&mut self, iterable: I) -> io::Result<()> where I: IntoIterator<Item = (i32, C)>, C: fmt::Display, { if Tls::session().emit_comments { for (i, comment) in iterable { try!(self.write_indentation()); try!(writeln!(self.write, "{}, {}", i, comment)); } } else { try!(self.write_indentation()); let mut first = true; for (i, _comment) in iterable { if!first { try!(write!(self.write, " ")); } try!(write!(self.write, "{},", i)); first = false; } } writeln!(self.write, "") } pub fn writeln(&mut self, out: &str) -> io::Result<()> { let buf = out.as_bytes(); // pass empty lines through with no indentation if buf.is_empty() { return self.write.write_all("\n".as_bytes()); } let n = buf.len() - 1; // If the line begins with a `}`, `]`, or `)`, first decrement the indentation. if buf[0] == ('}' as u8) || buf[0] == (']' as u8) || buf[0] == (')' as u8) { self.indent -= TAB; } try!(self.write_indented(out)); // Detect a line that ends in a `{` or `(` and increase indentation for future lines. if buf[n] == ('{' as u8) || buf[n] == ('[' as u8) || buf[n] == ('(' as u8) { self.indent += TAB; } Ok(()) } pub fn write_fn_header( &mut self, grammar: &Grammar, visibility: &Visibility, name: String, type_parameters: Vec<String>, first_parameter: Option<String>, parameters: Vec<String>, return_type: String, where_clauses: Vec<String>, ) -> io::Result<()> { rust!(self, "{}fn {}<", visibility, name); for type_parameter in &grammar.type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } for type_parameter in type_parameters { rust!(self, "{0:1$}{2},", "", TAB, type_parameter); } rust!(self, ">("); if let Some(param) = first_parameter { rust!(self, "{},", param); } for parameter in &grammar.parameters { rust!(self, "{}: {},", parameter.name, parameter.ty); } for parameter in &parameters { rust!(self, "{},", parameter); } if!grammar.where_clauses.is_empty() ||!where_clauses.is_empty() { rust!(self, ") -> {} where", return_type); for where_clause in &grammar.where_clauses { rust!(self, " {},", where_clause); } for where_clause in &where_clauses { rust!(self, " {},", where_clause); } } else { rust!(self, ") -> {}", return_type); } Ok(()) } pub fn
(&mut self, grammar: &Grammar) -> io::Result<()> { for attribute in grammar.module_attributes.iter() { rust!(self, "{}", attribute); } Ok(()) } pub fn write_uses(&mut self, super_prefix: &str, grammar: &Grammar) -> io::Result<()> { // things the user wrote for u in &grammar.uses { if u.starts_with("super::") { rust!(self, "use {}{};", super_prefix, u); } else { rust!(self, "use {};", u); } } self.write_standard_uses(&grammar.prefix) } pub fn write_standard_uses(&mut self, prefix: &str) -> io::Result<()> { // Stuff that we plan to use. // Occasionally we happen to not use it after all, hence the allow. rust!(self, "#[allow(unused_extern_crates)]"); rust!(self, "extern crate lalrpop_util as {}lalrpop_util;", prefix); Ok(()) } }
write_module_attributes
identifier_name
create.rs
static LOREM_IPSUM: &'static str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. "; use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; fn
() { let path = Path::new("out/lorem_ipsum.txt"); let display = path.display(); // 以只写模式打开文件,返回 `io::Result<File>` let mut file = match File::create(&path) { Err(why) => panic!("couldn't create {}: {}", display, why.description()), Ok(file) => file, }; // 将 `LOREM_IPSUM` 字符串写进 `file`,返回 `io::Result<()>` match file.write_all(LOREM_IPSUM.as_bytes()) { Err(why) => { panic!("couldn't write to {}: {}", display, why.description()) }, Ok(_) => println!("successfully wrote to {}", display), } }
main
identifier_name
create.rs
static LOREM_IPSUM: &'static str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. "; use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; fn main()
}
{ let path = Path::new("out/lorem_ipsum.txt"); let display = path.display(); // 以只写模式打开文件,返回 `io::Result<File>` let mut file = match File::create(&path) { Err(why) => panic!("couldn't create {}: {}", display, why.description()), Ok(file) => file, }; // 将 `LOREM_IPSUM` 字符串写进 `file`,返回 `io::Result<()>` match file.write_all(LOREM_IPSUM.as_bytes()) { Err(why) => { panic!("couldn't write to {}: {}", display, why.description()) }, Ok(_) => println!("successfully wrote to {}", display), }
identifier_body
create.rs
static LOREM_IPSUM: &'static str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. "; use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; fn main() { let path = Path::new("out/lorem_ipsum.txt"); let display = path.display(); // 以只写模式打开文件,返回 `io::Result<File>` let mut file = match File::create(&path) { Err(why) => panic!("couldn't create {}: {}", display, why.description()), Ok(file) => file, }; // 将 `LOREM_IPSUM` 字符串写进 `file`,返回 `io::Result<()>` match file.write_all(LOREM_IPSUM.as_bytes()) { Err(why) => { panic!("couldn't write to {}: {}", display, why.description()) }, Ok(_) => println!("successfully wrote to {}", display), }
}
random_line_split
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn
() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_owned(); let mut i: int = 0; for c in s.bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } if i == 3 { assert!((c == 'l' as u8)); } if i == 4 { assert!((c == 'o' as u8)); } //... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
main
identifier_name
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn main() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_owned(); let mut i: int = 0; for c in s.bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1
if i == 2 { assert!((c == 'l' as u8)); } if i == 3 { assert!((c == 'l' as u8)); } if i == 4 { assert!((c == 'o' as u8)); } //... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
{ assert!((c == 'e' as u8)); }
conditional_block
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn main()
assert_eq!(i, 11); }
{ let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_owned(); let mut i: int = 0; for c in s.bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } if i == 3 { assert!((c == 'l' as u8)); } if i == 4 { assert!((c == 'o' as u8)); } // ... i += 1; println!("{:?}", i); println!("{:?}", c); }
identifier_body
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_owned(); let mut i: int = 0; for c in s.bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } if i == 3 { assert!((c == 'l' as u8)); } if i == 4 { assert!((c == 'o' as u8)); } //... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn main() {
random_line_split
serv.rs
// Copyright 2021 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs::File; use std::io; use std::net::{IpAddr, Shutdown, SocketAddr, SocketAddrV4, TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::Arc; use std::thread; use std::time::Duration; use crate::chain; use crate::chain::txhashset::BitmapChunk; use crate::core::core; use crate::core::core::hash::Hash; use crate::core::core::{OutputIdentifier, Segment, SegmentIdentifier, TxKernel}; use crate::core::global; use crate::core::pow::Difficulty; use crate::handshake::Handshake; use crate::peer::Peer; use crate::peers::Peers; use crate::store::PeerStore; use crate::types::{ Capabilities, ChainAdapter, Error, NetAdapter, P2PConfig, PeerAddr, PeerInfo, ReasonForBan, TxHashSetRead, }; use crate::util::secp::pedersen::RangeProof; use crate::util::StopState; use chrono::prelude::{DateTime, Utc}; /// P2P server implementation, handling bootstrapping to find and connect to /// peers, receiving connections from other peers and keep track of all of them. pub struct Server { pub config: P2PConfig, capabilities: Capabilities, handshake: Arc<Handshake>, pub peers: Arc<Peers>, stop_state: Arc<StopState>, } // TODO TLS impl Server { /// Creates a new idle p2p server with no peers pub fn new( db_root: &str, capabilities: Capabilities, config: P2PConfig, adapter: Arc<dyn ChainAdapter>, genesis: Hash, stop_state: Arc<StopState>, ) -> Result<Server, Error> { Ok(Server { config: config.clone(), capabilities, handshake: Arc::new(Handshake::new(genesis, config.clone())), peers: Arc::new(Peers::new(PeerStore::new(db_root)?, adapter, config)), stop_state, }) } /// Starts a new TCP server and listen to incoming connections. This is a /// blocking call until the TCP server stops. pub fn listen(&self) -> Result<(), Error> { // start TCP listener and handle incoming connections let addr = SocketAddr::new(self.config.host, self.config.port); let listener = TcpListener::bind(addr)?; listener.set_nonblocking(true)?; let sleep_time = Duration::from_millis(5); loop { // Pause peer ingress connection request. Only for tests. if self.stop_state.is_paused() { thread::sleep(Duration::from_secs(1)); continue; } match listener.accept() { Ok((stream, peer_addr)) => { // We want out TCP stream to be in blocking mode. // The TCP listener is in nonblocking mode so we *must* explicitly // move the accepted TCP stream into blocking mode (or all kinds of // bad things can and will happen). // A nonblocking TCP listener will accept nonblocking TCP streams which // we do not want. stream.set_nonblocking(false)?; let mut peer_addr = PeerAddr(peer_addr); // attempt to see if it an ipv4-mapped ipv6 // if yes convert to ipv4 if peer_addr.0.is_ipv6() { if let IpAddr::V6(ipv6) = peer_addr.0.ip() { if let Some(ipv4) = ipv6.to_ipv4() { peer_addr = PeerAddr(SocketAddr::V4(SocketAddrV4::new( ipv4, peer_addr.0.port(), ))) } } } if self.check_undesirable(&stream) { // Shutdown the incoming TCP connection if it is not desired if let Err(e) = stream.shutdown(Shutdown::Both) { debug!("Error shutting down conn: {:?}", e); } continue; } match self.handle_new_peer(stream) { Err(Error::ConnectionClose) => debug!("shutting down, ignoring a new peer"), Err(e) => { debug!("Error accepting peer {}: {:?}", peer_addr.to_string(), e); let _ = self.peers.add_banned(peer_addr, ReasonForBan::BadHandshake); } Ok(_) => {} } } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { // nothing to do, will retry in next iteration } Err(e) => { debug!("Couldn't establish new client connection: {:?}", e); } } if self.stop_state.is_stopped() { break; } thread::sleep(sleep_time); } Ok(()) } /// Asks the server to connect to a new peer. Directly returns the peer if /// we're already connected to the provided address. pub fn connect(&self, addr: PeerAddr) -> Result<Arc<Peer>, Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } if Peer::is_denied(&self.config, addr) { debug!("connect_peer: peer {} denied, not connecting.", addr); return Err(Error::ConnectionClose); } if global::is_production_mode() { let hs = self.handshake.clone(); let addrs = hs.addrs.read(); if addrs.contains(&addr) { debug!("connect: ignore connecting to PeerWithSelf, addr: {}", addr); return Err(Error::PeerWithSelf); } } if let Some(p) = self.peers.get_connected_peer(addr) { // if we're already connected to the addr, just return the peer trace!("connect_peer: already connected {}", addr); return Ok(p); } trace!( "connect_peer: on {}:{}. connecting to {}", self.config.host, self.config.port, addr ); match TcpStream::connect_timeout(&addr.0, Duration::from_secs(10)) { Ok(stream) => { let addr = SocketAddr::new(self.config.host, self.config.port); let total_diff = self.peers.total_difficulty()?; let peer = Peer::connect( stream, self.capabilities, total_diff, PeerAddr(addr), &self.handshake, self.peers.clone(), )?; let peer = Arc::new(peer); self.peers.add_connected(peer.clone())?; Ok(peer) } Err(e) => { trace!( "connect_peer: on {}:{}. Could not connect to {}: {:?}", self.config.host, self.config.port, addr, e ); Err(Error::Connection(e)) } } } fn handle_new_peer(&self, stream: TcpStream) -> Result<(), Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } let total_diff = self.peers.total_difficulty()?; // accept the peer and add it to the server map let peer = Peer::accept( stream, self.capabilities, total_diff, &self.handshake, self.peers.clone(), )?; self.peers.add_connected(Arc::new(peer))?; Ok(()) } /// Checks whether there's any reason we don't want to accept an incoming peer /// connection. There can be a few of them: /// 1. Accepting the peer connection would exceed the configured maximum allowed /// inbound peer count. Note that seed nodes may wish to increase the default /// value for PEER_LISTENER_BUFFER_COUNT to help with network bootstrapping. /// A default buffer of 8 peers is allowed to help with network growth. /// 2. The peer has been previously banned and the ban period hasn't /// expired yet. /// 3. We're already connected to a peer at the same IP. While there are /// many reasons multiple peers can legitimately share identical IP /// addresses (NAT), network distribution is improved if they choose /// different sets of peers themselves. In addition, it prevent potential /// duplicate connections, malicious or not. fn check_undesirable(&self, stream: &TcpStream) -> bool { if self.peers.iter().inbound().connected().count() as u32 >= self.config.peer_max_inbound_count() + self.config.peer_listener_buffer_count() { debug!("Accepting new connection will exceed peer limit, refusing connection."); return true; } if let Ok(peer_addr) = stream.peer_addr() { let peer_addr = PeerAddr(peer_addr); if self.peers.is_banned(peer_addr) { debug!("Peer {} banned, refusing connection.", peer_addr); return true; } // The call to is_known() can fail due to contention on the peers map. // If it fails we want to default to refusing the connection. match self.peers.is_known(peer_addr) { Ok(true) => { debug!("Peer {} already known, refusing connection.", peer_addr); return true; } Err(_) => { error!( "Peer {} is_known check failed, refusing connection.", peer_addr ); return true; } _ => (), } } false } pub fn stop(&self) { self.stop_state.stop(); self.peers.stop(); } /// Pause means: stop all the current peers connection, only for tests. /// Note: /// 1. must pause the'seed' thread also, to avoid the new egress peer connection /// 2. must pause the 'p2p-server' thread also, to avoid the new ingress peer connection. pub fn pause(&self) { self.peers.stop(); } } /// A no-op network adapter used for testing. pub struct DummyAdapter {} impl ChainAdapter for DummyAdapter { fn total_difficulty(&self) -> Result<Difficulty, chain::Error> { Ok(Difficulty::min_dma()) } fn total_height(&self) -> Result<u64, chain::Error> { Ok(0) } fn
(&self, _h: Hash) -> Option<core::Transaction> { None } fn tx_kernel_received(&self, _h: Hash, _peer_info: &PeerInfo) -> Result<bool, chain::Error> { Ok(true) } fn transaction_received( &self, _: core::Transaction, _stem: bool, ) -> Result<bool, chain::Error> { Ok(true) } fn compact_block_received( &self, _cb: core::CompactBlock, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn header_received( &self, _bh: core::BlockHeader, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn block_received( &self, _: core::Block, _: &PeerInfo, _: chain::Options, ) -> Result<bool, chain::Error> { Ok(true) } fn headers_received( &self, _: &[core::BlockHeader], _: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn locate_headers(&self, _: &[Hash]) -> Result<Vec<core::BlockHeader>, chain::Error> { Ok(vec![]) } fn get_block(&self, _: Hash, _: &PeerInfo) -> Option<core::Block> { None } fn txhashset_read(&self, _h: Hash) -> Option<TxHashSetRead> { unimplemented!() } fn txhashset_archive_header(&self) -> Result<core::BlockHeader, chain::Error> { unimplemented!() } fn txhashset_receive_ready(&self) -> bool { false } fn txhashset_write( &self, _h: Hash, _txhashset_data: File, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(false) } fn txhashset_download_update( &self, _start_time: DateTime<Utc>, _downloaded_size: u64, _total_size: u64, ) -> bool { false } fn get_tmp_dir(&self) -> PathBuf { unimplemented!() } fn get_tmpfile_pathname(&self, _tmpfile_name: String) -> PathBuf { unimplemented!() } fn get_kernel_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<TxKernel>, chain::Error> { unimplemented!() } fn get_bitmap_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<BitmapChunk>, Hash), chain::Error> { unimplemented!() } fn get_output_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<OutputIdentifier>, Hash), chain::Error> { unimplemented!() } fn get_rangeproof_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<RangeProof>, chain::Error> { unimplemented!() } } impl NetAdapter for DummyAdapter { fn find_peer_addrs(&self, _: Capabilities) -> Vec<PeerAddr> { vec![] } fn peer_addrs_received(&self, _: Vec<PeerAddr>) {} fn peer_difficulty(&self, _: PeerAddr, _: Difficulty, _: u64) {} fn is_banned(&self, _: PeerAddr) -> bool { false } }
get_transaction
identifier_name
serv.rs
// Copyright 2021 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs::File; use std::io; use std::net::{IpAddr, Shutdown, SocketAddr, SocketAddrV4, TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::Arc; use std::thread; use std::time::Duration; use crate::chain; use crate::chain::txhashset::BitmapChunk; use crate::core::core; use crate::core::core::hash::Hash; use crate::core::core::{OutputIdentifier, Segment, SegmentIdentifier, TxKernel}; use crate::core::global; use crate::core::pow::Difficulty; use crate::handshake::Handshake; use crate::peer::Peer; use crate::peers::Peers; use crate::store::PeerStore; use crate::types::{ Capabilities, ChainAdapter, Error, NetAdapter, P2PConfig, PeerAddr, PeerInfo, ReasonForBan, TxHashSetRead, }; use crate::util::secp::pedersen::RangeProof; use crate::util::StopState; use chrono::prelude::{DateTime, Utc}; /// P2P server implementation, handling bootstrapping to find and connect to /// peers, receiving connections from other peers and keep track of all of them. pub struct Server { pub config: P2PConfig, capabilities: Capabilities, handshake: Arc<Handshake>, pub peers: Arc<Peers>, stop_state: Arc<StopState>, } // TODO TLS impl Server { /// Creates a new idle p2p server with no peers pub fn new( db_root: &str, capabilities: Capabilities, config: P2PConfig, adapter: Arc<dyn ChainAdapter>, genesis: Hash, stop_state: Arc<StopState>, ) -> Result<Server, Error> { Ok(Server { config: config.clone(), capabilities, handshake: Arc::new(Handshake::new(genesis, config.clone())), peers: Arc::new(Peers::new(PeerStore::new(db_root)?, adapter, config)), stop_state, }) } /// Starts a new TCP server and listen to incoming connections. This is a /// blocking call until the TCP server stops. pub fn listen(&self) -> Result<(), Error> { // start TCP listener and handle incoming connections let addr = SocketAddr::new(self.config.host, self.config.port); let listener = TcpListener::bind(addr)?; listener.set_nonblocking(true)?; let sleep_time = Duration::from_millis(5); loop { // Pause peer ingress connection request. Only for tests. if self.stop_state.is_paused() { thread::sleep(Duration::from_secs(1)); continue; } match listener.accept() { Ok((stream, peer_addr)) => { // We want out TCP stream to be in blocking mode. // The TCP listener is in nonblocking mode so we *must* explicitly // move the accepted TCP stream into blocking mode (or all kinds of // bad things can and will happen). // A nonblocking TCP listener will accept nonblocking TCP streams which // we do not want. stream.set_nonblocking(false)?; let mut peer_addr = PeerAddr(peer_addr); // attempt to see if it an ipv4-mapped ipv6 // if yes convert to ipv4 if peer_addr.0.is_ipv6() { if let IpAddr::V6(ipv6) = peer_addr.0.ip() { if let Some(ipv4) = ipv6.to_ipv4() { peer_addr = PeerAddr(SocketAddr::V4(SocketAddrV4::new( ipv4, peer_addr.0.port(), ))) } } } if self.check_undesirable(&stream) { // Shutdown the incoming TCP connection if it is not desired if let Err(e) = stream.shutdown(Shutdown::Both) { debug!("Error shutting down conn: {:?}", e); } continue; } match self.handle_new_peer(stream) { Err(Error::ConnectionClose) => debug!("shutting down, ignoring a new peer"), Err(e) => { debug!("Error accepting peer {}: {:?}", peer_addr.to_string(), e); let _ = self.peers.add_banned(peer_addr, ReasonForBan::BadHandshake); } Ok(_) => {} } } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { // nothing to do, will retry in next iteration } Err(e) => { debug!("Couldn't establish new client connection: {:?}", e); } } if self.stop_state.is_stopped() { break; } thread::sleep(sleep_time); } Ok(()) } /// Asks the server to connect to a new peer. Directly returns the peer if /// we're already connected to the provided address. pub fn connect(&self, addr: PeerAddr) -> Result<Arc<Peer>, Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } if Peer::is_denied(&self.config, addr) { debug!("connect_peer: peer {} denied, not connecting.", addr); return Err(Error::ConnectionClose); } if global::is_production_mode() { let hs = self.handshake.clone(); let addrs = hs.addrs.read(); if addrs.contains(&addr) { debug!("connect: ignore connecting to PeerWithSelf, addr: {}", addr); return Err(Error::PeerWithSelf); } } if let Some(p) = self.peers.get_connected_peer(addr) { // if we're already connected to the addr, just return the peer trace!("connect_peer: already connected {}", addr); return Ok(p); } trace!( "connect_peer: on {}:{}. connecting to {}", self.config.host, self.config.port, addr ); match TcpStream::connect_timeout(&addr.0, Duration::from_secs(10)) { Ok(stream) => { let addr = SocketAddr::new(self.config.host, self.config.port); let total_diff = self.peers.total_difficulty()?; let peer = Peer::connect( stream, self.capabilities, total_diff, PeerAddr(addr), &self.handshake, self.peers.clone(), )?; let peer = Arc::new(peer); self.peers.add_connected(peer.clone())?; Ok(peer) } Err(e) => { trace!( "connect_peer: on {}:{}. Could not connect to {}: {:?}", self.config.host, self.config.port, addr, e ); Err(Error::Connection(e)) } } } fn handle_new_peer(&self, stream: TcpStream) -> Result<(), Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } let total_diff = self.peers.total_difficulty()?; // accept the peer and add it to the server map let peer = Peer::accept( stream, self.capabilities, total_diff, &self.handshake, self.peers.clone(), )?; self.peers.add_connected(Arc::new(peer))?; Ok(()) } /// Checks whether there's any reason we don't want to accept an incoming peer /// connection. There can be a few of them: /// 1. Accepting the peer connection would exceed the configured maximum allowed /// inbound peer count. Note that seed nodes may wish to increase the default /// value for PEER_LISTENER_BUFFER_COUNT to help with network bootstrapping. /// A default buffer of 8 peers is allowed to help with network growth. /// 2. The peer has been previously banned and the ban period hasn't /// expired yet. /// 3. We're already connected to a peer at the same IP. While there are /// many reasons multiple peers can legitimately share identical IP /// addresses (NAT), network distribution is improved if they choose /// different sets of peers themselves. In addition, it prevent potential /// duplicate connections, malicious or not. fn check_undesirable(&self, stream: &TcpStream) -> bool { if self.peers.iter().inbound().connected().count() as u32 >= self.config.peer_max_inbound_count() + self.config.peer_listener_buffer_count() { debug!("Accepting new connection will exceed peer limit, refusing connection."); return true; } if let Ok(peer_addr) = stream.peer_addr() { let peer_addr = PeerAddr(peer_addr); if self.peers.is_banned(peer_addr) { debug!("Peer {} banned, refusing connection.", peer_addr); return true; } // The call to is_known() can fail due to contention on the peers map. // If it fails we want to default to refusing the connection. match self.peers.is_known(peer_addr) { Ok(true) => { debug!("Peer {} already known, refusing connection.", peer_addr); return true; } Err(_) => { error!( "Peer {} is_known check failed, refusing connection.", peer_addr ); return true; } _ => (), } } false } pub fn stop(&self) { self.stop_state.stop(); self.peers.stop(); } /// Pause means: stop all the current peers connection, only for tests. /// Note: /// 1. must pause the'seed' thread also, to avoid the new egress peer connection /// 2. must pause the 'p2p-server' thread also, to avoid the new ingress peer connection. pub fn pause(&self) { self.peers.stop(); } } /// A no-op network adapter used for testing. pub struct DummyAdapter {} impl ChainAdapter for DummyAdapter { fn total_difficulty(&self) -> Result<Difficulty, chain::Error> { Ok(Difficulty::min_dma()) } fn total_height(&self) -> Result<u64, chain::Error> { Ok(0) } fn get_transaction(&self, _h: Hash) -> Option<core::Transaction> { None } fn tx_kernel_received(&self, _h: Hash, _peer_info: &PeerInfo) -> Result<bool, chain::Error> { Ok(true) } fn transaction_received( &self, _: core::Transaction, _stem: bool, ) -> Result<bool, chain::Error> { Ok(true) } fn compact_block_received( &self, _cb: core::CompactBlock, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn header_received( &self, _bh: core::BlockHeader, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn block_received( &self, _: core::Block, _: &PeerInfo, _: chain::Options, ) -> Result<bool, chain::Error> { Ok(true) } fn headers_received( &self, _: &[core::BlockHeader], _: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn locate_headers(&self, _: &[Hash]) -> Result<Vec<core::BlockHeader>, chain::Error> { Ok(vec![]) } fn get_block(&self, _: Hash, _: &PeerInfo) -> Option<core::Block> { None } fn txhashset_read(&self, _h: Hash) -> Option<TxHashSetRead> { unimplemented!() } fn txhashset_archive_header(&self) -> Result<core::BlockHeader, chain::Error> { unimplemented!() } fn txhashset_receive_ready(&self) -> bool { false } fn txhashset_write( &self, _h: Hash, _txhashset_data: File, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(false) } fn txhashset_download_update( &self, _start_time: DateTime<Utc>, _downloaded_size: u64, _total_size: u64, ) -> bool { false } fn get_tmp_dir(&self) -> PathBuf { unimplemented!() } fn get_tmpfile_pathname(&self, _tmpfile_name: String) -> PathBuf { unimplemented!() } fn get_kernel_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<TxKernel>, chain::Error> { unimplemented!() } fn get_bitmap_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<BitmapChunk>, Hash), chain::Error> { unimplemented!() } fn get_output_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<OutputIdentifier>, Hash), chain::Error> { unimplemented!() } fn get_rangeproof_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<RangeProof>, chain::Error> { unimplemented!() } } impl NetAdapter for DummyAdapter { fn find_peer_addrs(&self, _: Capabilities) -> Vec<PeerAddr> { vec![] } fn peer_addrs_received(&self, _: Vec<PeerAddr>) {} fn peer_difficulty(&self, _: PeerAddr, _: Difficulty, _: u64) {} fn is_banned(&self, _: PeerAddr) -> bool
}
{ false }
identifier_body
serv.rs
// Copyright 2021 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs::File; use std::io; use std::net::{IpAddr, Shutdown, SocketAddr, SocketAddrV4, TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::Arc; use std::thread; use std::time::Duration; use crate::chain; use crate::chain::txhashset::BitmapChunk; use crate::core::core; use crate::core::core::hash::Hash; use crate::core::core::{OutputIdentifier, Segment, SegmentIdentifier, TxKernel}; use crate::core::global; use crate::core::pow::Difficulty; use crate::handshake::Handshake; use crate::peer::Peer; use crate::peers::Peers; use crate::store::PeerStore; use crate::types::{ Capabilities, ChainAdapter, Error, NetAdapter, P2PConfig, PeerAddr, PeerInfo, ReasonForBan, TxHashSetRead, }; use crate::util::secp::pedersen::RangeProof; use crate::util::StopState; use chrono::prelude::{DateTime, Utc}; /// P2P server implementation, handling bootstrapping to find and connect to /// peers, receiving connections from other peers and keep track of all of them. pub struct Server { pub config: P2PConfig, capabilities: Capabilities, handshake: Arc<Handshake>, pub peers: Arc<Peers>, stop_state: Arc<StopState>, } // TODO TLS impl Server { /// Creates a new idle p2p server with no peers pub fn new( db_root: &str, capabilities: Capabilities, config: P2PConfig, adapter: Arc<dyn ChainAdapter>, genesis: Hash, stop_state: Arc<StopState>,
peers: Arc::new(Peers::new(PeerStore::new(db_root)?, adapter, config)), stop_state, }) } /// Starts a new TCP server and listen to incoming connections. This is a /// blocking call until the TCP server stops. pub fn listen(&self) -> Result<(), Error> { // start TCP listener and handle incoming connections let addr = SocketAddr::new(self.config.host, self.config.port); let listener = TcpListener::bind(addr)?; listener.set_nonblocking(true)?; let sleep_time = Duration::from_millis(5); loop { // Pause peer ingress connection request. Only for tests. if self.stop_state.is_paused() { thread::sleep(Duration::from_secs(1)); continue; } match listener.accept() { Ok((stream, peer_addr)) => { // We want out TCP stream to be in blocking mode. // The TCP listener is in nonblocking mode so we *must* explicitly // move the accepted TCP stream into blocking mode (or all kinds of // bad things can and will happen). // A nonblocking TCP listener will accept nonblocking TCP streams which // we do not want. stream.set_nonblocking(false)?; let mut peer_addr = PeerAddr(peer_addr); // attempt to see if it an ipv4-mapped ipv6 // if yes convert to ipv4 if peer_addr.0.is_ipv6() { if let IpAddr::V6(ipv6) = peer_addr.0.ip() { if let Some(ipv4) = ipv6.to_ipv4() { peer_addr = PeerAddr(SocketAddr::V4(SocketAddrV4::new( ipv4, peer_addr.0.port(), ))) } } } if self.check_undesirable(&stream) { // Shutdown the incoming TCP connection if it is not desired if let Err(e) = stream.shutdown(Shutdown::Both) { debug!("Error shutting down conn: {:?}", e); } continue; } match self.handle_new_peer(stream) { Err(Error::ConnectionClose) => debug!("shutting down, ignoring a new peer"), Err(e) => { debug!("Error accepting peer {}: {:?}", peer_addr.to_string(), e); let _ = self.peers.add_banned(peer_addr, ReasonForBan::BadHandshake); } Ok(_) => {} } } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { // nothing to do, will retry in next iteration } Err(e) => { debug!("Couldn't establish new client connection: {:?}", e); } } if self.stop_state.is_stopped() { break; } thread::sleep(sleep_time); } Ok(()) } /// Asks the server to connect to a new peer. Directly returns the peer if /// we're already connected to the provided address. pub fn connect(&self, addr: PeerAddr) -> Result<Arc<Peer>, Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } if Peer::is_denied(&self.config, addr) { debug!("connect_peer: peer {} denied, not connecting.", addr); return Err(Error::ConnectionClose); } if global::is_production_mode() { let hs = self.handshake.clone(); let addrs = hs.addrs.read(); if addrs.contains(&addr) { debug!("connect: ignore connecting to PeerWithSelf, addr: {}", addr); return Err(Error::PeerWithSelf); } } if let Some(p) = self.peers.get_connected_peer(addr) { // if we're already connected to the addr, just return the peer trace!("connect_peer: already connected {}", addr); return Ok(p); } trace!( "connect_peer: on {}:{}. connecting to {}", self.config.host, self.config.port, addr ); match TcpStream::connect_timeout(&addr.0, Duration::from_secs(10)) { Ok(stream) => { let addr = SocketAddr::new(self.config.host, self.config.port); let total_diff = self.peers.total_difficulty()?; let peer = Peer::connect( stream, self.capabilities, total_diff, PeerAddr(addr), &self.handshake, self.peers.clone(), )?; let peer = Arc::new(peer); self.peers.add_connected(peer.clone())?; Ok(peer) } Err(e) => { trace!( "connect_peer: on {}:{}. Could not connect to {}: {:?}", self.config.host, self.config.port, addr, e ); Err(Error::Connection(e)) } } } fn handle_new_peer(&self, stream: TcpStream) -> Result<(), Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } let total_diff = self.peers.total_difficulty()?; // accept the peer and add it to the server map let peer = Peer::accept( stream, self.capabilities, total_diff, &self.handshake, self.peers.clone(), )?; self.peers.add_connected(Arc::new(peer))?; Ok(()) } /// Checks whether there's any reason we don't want to accept an incoming peer /// connection. There can be a few of them: /// 1. Accepting the peer connection would exceed the configured maximum allowed /// inbound peer count. Note that seed nodes may wish to increase the default /// value for PEER_LISTENER_BUFFER_COUNT to help with network bootstrapping. /// A default buffer of 8 peers is allowed to help with network growth. /// 2. The peer has been previously banned and the ban period hasn't /// expired yet. /// 3. We're already connected to a peer at the same IP. While there are /// many reasons multiple peers can legitimately share identical IP /// addresses (NAT), network distribution is improved if they choose /// different sets of peers themselves. In addition, it prevent potential /// duplicate connections, malicious or not. fn check_undesirable(&self, stream: &TcpStream) -> bool { if self.peers.iter().inbound().connected().count() as u32 >= self.config.peer_max_inbound_count() + self.config.peer_listener_buffer_count() { debug!("Accepting new connection will exceed peer limit, refusing connection."); return true; } if let Ok(peer_addr) = stream.peer_addr() { let peer_addr = PeerAddr(peer_addr); if self.peers.is_banned(peer_addr) { debug!("Peer {} banned, refusing connection.", peer_addr); return true; } // The call to is_known() can fail due to contention on the peers map. // If it fails we want to default to refusing the connection. match self.peers.is_known(peer_addr) { Ok(true) => { debug!("Peer {} already known, refusing connection.", peer_addr); return true; } Err(_) => { error!( "Peer {} is_known check failed, refusing connection.", peer_addr ); return true; } _ => (), } } false } pub fn stop(&self) { self.stop_state.stop(); self.peers.stop(); } /// Pause means: stop all the current peers connection, only for tests. /// Note: /// 1. must pause the'seed' thread also, to avoid the new egress peer connection /// 2. must pause the 'p2p-server' thread also, to avoid the new ingress peer connection. pub fn pause(&self) { self.peers.stop(); } } /// A no-op network adapter used for testing. pub struct DummyAdapter {} impl ChainAdapter for DummyAdapter { fn total_difficulty(&self) -> Result<Difficulty, chain::Error> { Ok(Difficulty::min_dma()) } fn total_height(&self) -> Result<u64, chain::Error> { Ok(0) } fn get_transaction(&self, _h: Hash) -> Option<core::Transaction> { None } fn tx_kernel_received(&self, _h: Hash, _peer_info: &PeerInfo) -> Result<bool, chain::Error> { Ok(true) } fn transaction_received( &self, _: core::Transaction, _stem: bool, ) -> Result<bool, chain::Error> { Ok(true) } fn compact_block_received( &self, _cb: core::CompactBlock, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn header_received( &self, _bh: core::BlockHeader, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn block_received( &self, _: core::Block, _: &PeerInfo, _: chain::Options, ) -> Result<bool, chain::Error> { Ok(true) } fn headers_received( &self, _: &[core::BlockHeader], _: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn locate_headers(&self, _: &[Hash]) -> Result<Vec<core::BlockHeader>, chain::Error> { Ok(vec![]) } fn get_block(&self, _: Hash, _: &PeerInfo) -> Option<core::Block> { None } fn txhashset_read(&self, _h: Hash) -> Option<TxHashSetRead> { unimplemented!() } fn txhashset_archive_header(&self) -> Result<core::BlockHeader, chain::Error> { unimplemented!() } fn txhashset_receive_ready(&self) -> bool { false } fn txhashset_write( &self, _h: Hash, _txhashset_data: File, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(false) } fn txhashset_download_update( &self, _start_time: DateTime<Utc>, _downloaded_size: u64, _total_size: u64, ) -> bool { false } fn get_tmp_dir(&self) -> PathBuf { unimplemented!() } fn get_tmpfile_pathname(&self, _tmpfile_name: String) -> PathBuf { unimplemented!() } fn get_kernel_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<TxKernel>, chain::Error> { unimplemented!() } fn get_bitmap_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<BitmapChunk>, Hash), chain::Error> { unimplemented!() } fn get_output_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<OutputIdentifier>, Hash), chain::Error> { unimplemented!() } fn get_rangeproof_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<RangeProof>, chain::Error> { unimplemented!() } } impl NetAdapter for DummyAdapter { fn find_peer_addrs(&self, _: Capabilities) -> Vec<PeerAddr> { vec![] } fn peer_addrs_received(&self, _: Vec<PeerAddr>) {} fn peer_difficulty(&self, _: PeerAddr, _: Difficulty, _: u64) {} fn is_banned(&self, _: PeerAddr) -> bool { false } }
) -> Result<Server, Error> { Ok(Server { config: config.clone(), capabilities, handshake: Arc::new(Handshake::new(genesis, config.clone())),
random_line_split
serv.rs
// Copyright 2021 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs::File; use std::io; use std::net::{IpAddr, Shutdown, SocketAddr, SocketAddrV4, TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::Arc; use std::thread; use std::time::Duration; use crate::chain; use crate::chain::txhashset::BitmapChunk; use crate::core::core; use crate::core::core::hash::Hash; use crate::core::core::{OutputIdentifier, Segment, SegmentIdentifier, TxKernel}; use crate::core::global; use crate::core::pow::Difficulty; use crate::handshake::Handshake; use crate::peer::Peer; use crate::peers::Peers; use crate::store::PeerStore; use crate::types::{ Capabilities, ChainAdapter, Error, NetAdapter, P2PConfig, PeerAddr, PeerInfo, ReasonForBan, TxHashSetRead, }; use crate::util::secp::pedersen::RangeProof; use crate::util::StopState; use chrono::prelude::{DateTime, Utc}; /// P2P server implementation, handling bootstrapping to find and connect to /// peers, receiving connections from other peers and keep track of all of them. pub struct Server { pub config: P2PConfig, capabilities: Capabilities, handshake: Arc<Handshake>, pub peers: Arc<Peers>, stop_state: Arc<StopState>, } // TODO TLS impl Server { /// Creates a new idle p2p server with no peers pub fn new( db_root: &str, capabilities: Capabilities, config: P2PConfig, adapter: Arc<dyn ChainAdapter>, genesis: Hash, stop_state: Arc<StopState>, ) -> Result<Server, Error> { Ok(Server { config: config.clone(), capabilities, handshake: Arc::new(Handshake::new(genesis, config.clone())), peers: Arc::new(Peers::new(PeerStore::new(db_root)?, adapter, config)), stop_state, }) } /// Starts a new TCP server and listen to incoming connections. This is a /// blocking call until the TCP server stops. pub fn listen(&self) -> Result<(), Error> { // start TCP listener and handle incoming connections let addr = SocketAddr::new(self.config.host, self.config.port); let listener = TcpListener::bind(addr)?; listener.set_nonblocking(true)?; let sleep_time = Duration::from_millis(5); loop { // Pause peer ingress connection request. Only for tests. if self.stop_state.is_paused() { thread::sleep(Duration::from_secs(1)); continue; } match listener.accept() { Ok((stream, peer_addr)) => { // We want out TCP stream to be in blocking mode. // The TCP listener is in nonblocking mode so we *must* explicitly // move the accepted TCP stream into blocking mode (or all kinds of // bad things can and will happen). // A nonblocking TCP listener will accept nonblocking TCP streams which // we do not want. stream.set_nonblocking(false)?; let mut peer_addr = PeerAddr(peer_addr); // attempt to see if it an ipv4-mapped ipv6 // if yes convert to ipv4 if peer_addr.0.is_ipv6() { if let IpAddr::V6(ipv6) = peer_addr.0.ip() { if let Some(ipv4) = ipv6.to_ipv4() { peer_addr = PeerAddr(SocketAddr::V4(SocketAddrV4::new( ipv4, peer_addr.0.port(), ))) } } } if self.check_undesirable(&stream) { // Shutdown the incoming TCP connection if it is not desired if let Err(e) = stream.shutdown(Shutdown::Both) { debug!("Error shutting down conn: {:?}", e); } continue; } match self.handle_new_peer(stream) { Err(Error::ConnectionClose) => debug!("shutting down, ignoring a new peer"), Err(e) => { debug!("Error accepting peer {}: {:?}", peer_addr.to_string(), e); let _ = self.peers.add_banned(peer_addr, ReasonForBan::BadHandshake); } Ok(_) => {} } } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { // nothing to do, will retry in next iteration } Err(e) => { debug!("Couldn't establish new client connection: {:?}", e); } } if self.stop_state.is_stopped() { break; } thread::sleep(sleep_time); } Ok(()) } /// Asks the server to connect to a new peer. Directly returns the peer if /// we're already connected to the provided address. pub fn connect(&self, addr: PeerAddr) -> Result<Arc<Peer>, Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } if Peer::is_denied(&self.config, addr) { debug!("connect_peer: peer {} denied, not connecting.", addr); return Err(Error::ConnectionClose); } if global::is_production_mode()
if let Some(p) = self.peers.get_connected_peer(addr) { // if we're already connected to the addr, just return the peer trace!("connect_peer: already connected {}", addr); return Ok(p); } trace!( "connect_peer: on {}:{}. connecting to {}", self.config.host, self.config.port, addr ); match TcpStream::connect_timeout(&addr.0, Duration::from_secs(10)) { Ok(stream) => { let addr = SocketAddr::new(self.config.host, self.config.port); let total_diff = self.peers.total_difficulty()?; let peer = Peer::connect( stream, self.capabilities, total_diff, PeerAddr(addr), &self.handshake, self.peers.clone(), )?; let peer = Arc::new(peer); self.peers.add_connected(peer.clone())?; Ok(peer) } Err(e) => { trace!( "connect_peer: on {}:{}. Could not connect to {}: {:?}", self.config.host, self.config.port, addr, e ); Err(Error::Connection(e)) } } } fn handle_new_peer(&self, stream: TcpStream) -> Result<(), Error> { if self.stop_state.is_stopped() { return Err(Error::ConnectionClose); } let total_diff = self.peers.total_difficulty()?; // accept the peer and add it to the server map let peer = Peer::accept( stream, self.capabilities, total_diff, &self.handshake, self.peers.clone(), )?; self.peers.add_connected(Arc::new(peer))?; Ok(()) } /// Checks whether there's any reason we don't want to accept an incoming peer /// connection. There can be a few of them: /// 1. Accepting the peer connection would exceed the configured maximum allowed /// inbound peer count. Note that seed nodes may wish to increase the default /// value for PEER_LISTENER_BUFFER_COUNT to help with network bootstrapping. /// A default buffer of 8 peers is allowed to help with network growth. /// 2. The peer has been previously banned and the ban period hasn't /// expired yet. /// 3. We're already connected to a peer at the same IP. While there are /// many reasons multiple peers can legitimately share identical IP /// addresses (NAT), network distribution is improved if they choose /// different sets of peers themselves. In addition, it prevent potential /// duplicate connections, malicious or not. fn check_undesirable(&self, stream: &TcpStream) -> bool { if self.peers.iter().inbound().connected().count() as u32 >= self.config.peer_max_inbound_count() + self.config.peer_listener_buffer_count() { debug!("Accepting new connection will exceed peer limit, refusing connection."); return true; } if let Ok(peer_addr) = stream.peer_addr() { let peer_addr = PeerAddr(peer_addr); if self.peers.is_banned(peer_addr) { debug!("Peer {} banned, refusing connection.", peer_addr); return true; } // The call to is_known() can fail due to contention on the peers map. // If it fails we want to default to refusing the connection. match self.peers.is_known(peer_addr) { Ok(true) => { debug!("Peer {} already known, refusing connection.", peer_addr); return true; } Err(_) => { error!( "Peer {} is_known check failed, refusing connection.", peer_addr ); return true; } _ => (), } } false } pub fn stop(&self) { self.stop_state.stop(); self.peers.stop(); } /// Pause means: stop all the current peers connection, only for tests. /// Note: /// 1. must pause the'seed' thread also, to avoid the new egress peer connection /// 2. must pause the 'p2p-server' thread also, to avoid the new ingress peer connection. pub fn pause(&self) { self.peers.stop(); } } /// A no-op network adapter used for testing. pub struct DummyAdapter {} impl ChainAdapter for DummyAdapter { fn total_difficulty(&self) -> Result<Difficulty, chain::Error> { Ok(Difficulty::min_dma()) } fn total_height(&self) -> Result<u64, chain::Error> { Ok(0) } fn get_transaction(&self, _h: Hash) -> Option<core::Transaction> { None } fn tx_kernel_received(&self, _h: Hash, _peer_info: &PeerInfo) -> Result<bool, chain::Error> { Ok(true) } fn transaction_received( &self, _: core::Transaction, _stem: bool, ) -> Result<bool, chain::Error> { Ok(true) } fn compact_block_received( &self, _cb: core::CompactBlock, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn header_received( &self, _bh: core::BlockHeader, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn block_received( &self, _: core::Block, _: &PeerInfo, _: chain::Options, ) -> Result<bool, chain::Error> { Ok(true) } fn headers_received( &self, _: &[core::BlockHeader], _: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(true) } fn locate_headers(&self, _: &[Hash]) -> Result<Vec<core::BlockHeader>, chain::Error> { Ok(vec![]) } fn get_block(&self, _: Hash, _: &PeerInfo) -> Option<core::Block> { None } fn txhashset_read(&self, _h: Hash) -> Option<TxHashSetRead> { unimplemented!() } fn txhashset_archive_header(&self) -> Result<core::BlockHeader, chain::Error> { unimplemented!() } fn txhashset_receive_ready(&self) -> bool { false } fn txhashset_write( &self, _h: Hash, _txhashset_data: File, _peer_info: &PeerInfo, ) -> Result<bool, chain::Error> { Ok(false) } fn txhashset_download_update( &self, _start_time: DateTime<Utc>, _downloaded_size: u64, _total_size: u64, ) -> bool { false } fn get_tmp_dir(&self) -> PathBuf { unimplemented!() } fn get_tmpfile_pathname(&self, _tmpfile_name: String) -> PathBuf { unimplemented!() } fn get_kernel_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<TxKernel>, chain::Error> { unimplemented!() } fn get_bitmap_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<BitmapChunk>, Hash), chain::Error> { unimplemented!() } fn get_output_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<(Segment<OutputIdentifier>, Hash), chain::Error> { unimplemented!() } fn get_rangeproof_segment( &self, _hash: Hash, _id: SegmentIdentifier, ) -> Result<Segment<RangeProof>, chain::Error> { unimplemented!() } } impl NetAdapter for DummyAdapter { fn find_peer_addrs(&self, _: Capabilities) -> Vec<PeerAddr> { vec![] } fn peer_addrs_received(&self, _: Vec<PeerAddr>) {} fn peer_difficulty(&self, _: PeerAddr, _: Difficulty, _: u64) {} fn is_banned(&self, _: PeerAddr) -> bool { false } }
{ let hs = self.handshake.clone(); let addrs = hs.addrs.read(); if addrs.contains(&addr) { debug!("connect: ignore connecting to PeerWithSelf, addr: {}", addr); return Err(Error::PeerWithSelf); } }
conditional_block
lib.rs
extern crate regex; macro_rules! regex( ($s:expr) => (regex::Regex::new($s).unwrap()); ); pub fn is_valid(kennitala : &str) -> bool { let constants = [3, 2, 7, 6, 5, 4, 3, 2]; let re = regex!(r"^\d{6}-?\d{4}$"); if re.is_match(kennitala)
false }
{ let sanitized = kennitala.replace("-",""); let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap(); let c = constants .iter() .zip(sanitized.bytes()) .fold(0, |sum : u32, (x, y) : (&u32, u8)| sum + x * (y as char).to_digit(10).unwrap() ); println!("check digit: {0}", check_digit); if 11 - (c % 11) == check_digit { return true } }
conditional_block
lib.rs
extern crate regex; macro_rules! regex( ($s:expr) => (regex::Regex::new($s).unwrap()); ); pub fn is_valid(kennitala : &str) -> bool { let constants = [3, 2, 7, 6, 5, 4, 3, 2]; let re = regex!(r"^\d{6}-?\d{4}$"); if re.is_match(kennitala) { let sanitized = kennitala.replace("-",""); let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap(); let c = constants .iter() .zip(sanitized.bytes()) .fold(0, |sum : u32, (x, y) : (&u32, u8)| sum + x * (y as char).to_digit(10).unwrap() ); println!("check digit: {0}", check_digit); if 11 - (c % 11) == check_digit { return true
}
} } false
random_line_split
lib.rs
extern crate regex; macro_rules! regex( ($s:expr) => (regex::Regex::new($s).unwrap()); ); pub fn is_valid(kennitala : &str) -> bool
return true } } false }
{ let constants = [3, 2, 7, 6, 5, 4, 3, 2]; let re = regex!(r"^\d{6}-?\d{4}$"); if re.is_match(kennitala) { let sanitized = kennitala.replace("-",""); let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap(); let c = constants .iter() .zip(sanitized.bytes()) .fold(0, |sum : u32, (x, y) : (&u32, u8)| sum + x * (y as char).to_digit(10).unwrap() ); println!("check digit: {0}", check_digit); if 11 - (c % 11) == check_digit {
identifier_body
lib.rs
extern crate regex; macro_rules! regex( ($s:expr) => (regex::Regex::new($s).unwrap()); ); pub fn
(kennitala : &str) -> bool { let constants = [3, 2, 7, 6, 5, 4, 3, 2]; let re = regex!(r"^\d{6}-?\d{4}$"); if re.is_match(kennitala) { let sanitized = kennitala.replace("-",""); let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap(); let c = constants .iter() .zip(sanitized.bytes()) .fold(0, |sum : u32, (x, y) : (&u32, u8)| sum + x * (y as char).to_digit(10).unwrap() ); println!("check digit: {0}", check_digit); if 11 - (c % 11) == check_digit { return true } } false }
is_valid
identifier_name
cpp.rs
//! Enables the generation of header and source files for using intercom //! libraries from C++ projects. extern crate std; use std::borrow::Cow; use std::io::Write; use super::GeneratorError; use super::{pascal_case, LibraryContext, ModelOptions, TypeSystemOptions}; use intercom::typelib::{ Arg, CoClass, Direction, Interface, InterfaceVariant, Method, TypeInfo, TypeLib, }; use handlebars::Handlebars; use serde_derive::Serialize; #[derive(PartialEq, Serialize, Debug)] pub struct CppLibrary { pub lib_name: String, pub interfaces: Vec<CppInterface>, pub coclass_count: usize, pub coclasses: Vec<CppClass>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppInterface { pub name: String, pub iid_struct: String, pub base: Option<String>, pub methods: Vec<CppMethod>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppMethod { pub name: String, pub ret_type: String, pub args: Vec<CppArg>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppArg { pub name: String, pub arg_type: String, } #[derive(PartialEq, Serialize, Debug)] pub struct CppClass { pub name: String, pub clsid_struct: String, pub interface_count: usize, pub interfaces: Vec<String>, } impl CppLibrary { fn
(lib: TypeLib, opts: &ModelOptions) -> Result<Self, GeneratorError> { let ctx = LibraryContext::try_from(&lib)?; let mut interfaces = vec![]; let mut coclasses = vec![]; for t in &lib.types { match t { TypeInfo::Class(cls) => { coclasses.push(CppClass::try_from(cls.as_ref(), opts, &ctx)?) } TypeInfo::Interface(itf) => { interfaces.push(CppInterface::gather(itf.as_ref(), opts, &ctx)?) } } } let interfaces = interfaces .into_iter() .flatten() .collect::<Vec<CppInterface>>(); Ok(Self { lib_name: lib.name.to_string(), interfaces, coclass_count: coclasses.len(), coclasses, }) } } impl CppInterface { fn gather( itf: &Interface, opts: &ModelOptions, ctx: &LibraryContext, ) -> Result<Vec<Self>, GeneratorError> { Ok(opts .type_systems .iter() .map( |ts_opts| match itf.variants.iter().find(|v| v.as_ref().ts == ts_opts.ts) { Some(v) => Some(CppInterface::try_from(&itf, v.as_ref(), ts_opts, ctx)), None => None, }, ) .filter_map(|i| i) .collect::<Result<Vec<_>, _>>()?) } fn try_from( itf: &Interface, itf_variant: &InterfaceVariant, ts_opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { Ok(Self { name: Self::final_name(&itf, ts_opts), iid_struct: guid_as_struct(&itf_variant.iid), base: Some("IUnknown".to_string()), methods: itf_variant .methods .iter() .map(|m| CppMethod::try_from(m.as_ref(), ts_opts, ctx)) .collect::<Result<Vec<_>, _>>()?, }) } pub fn final_name(itf: &Interface, opts: &TypeSystemOptions) -> String { let base_name = if itf.options.class_impl_interface { Cow::from(format!("I{}", itf.name)) } else { itf.name.clone() }; match opts.use_full_name { true => format!("{}_{:?}", base_name, opts.ts), false => base_name.to_string(), } } } impl CppMethod { fn try_from( method: &Method, opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { Ok(Self { name: pascal_case(&method.name), ret_type: CppArg::cpp_type(&method.return_type, opts, ctx), args: method .parameters .iter() .map(|arg| CppArg::try_from(arg, opts, ctx)) .collect::<Result<Vec<_>, _>>()?, }) } } impl CppArg { fn try_from( arg: &Arg, opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { let mut attrs = vec![]; match arg.direction { Direction::In => attrs.push("in"), Direction::Out => attrs.push("out"), Direction::Retval => { attrs.push("out"); attrs.push("retval"); } Direction::Return => { return Err("Direction::Return is invalid direction for arguments" .to_string() .into()); } } Ok(Self { name: arg.name.to_string(), arg_type: Self::cpp_type(arg, opts, ctx), }) } fn cpp_type(arg: &Arg, opts: &TypeSystemOptions, ctx: &LibraryContext) -> String { let base_name = ctx .itfs_by_name .get(arg.ty.as_ref()) .map(|itf| CppInterface::final_name(itf, opts)) .unwrap_or_else(|| arg.ty.to_string()); let indirection = match arg.direction { Direction::In | Direction::Return => arg.indirection_level, Direction::Out | Direction::Retval => arg.indirection_level + 1, }; let base_name = match base_name.as_ref() { "std::ffi::c_void" => "void".to_string(), "HRESULT" => "intercom::HRESULT".to_string(), other => other.to_string(), }; format!("{}{}", base_name, "*".repeat(indirection as usize)) } } impl CppClass { fn try_from( cls: &CoClass, opts: &ModelOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { let interfaces = cls .interfaces .iter() .flat_map(|itf_ref| { opts.type_systems .iter() .map(|opt| { let itf = ctx.itfs_by_ref[itf_ref.name.as_ref()]; CppInterface::final_name(itf, opt) }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); Ok(CppClass { name: cls.name.to_string(), clsid_struct: guid_as_struct(&cls.clsid), interface_count: interfaces.len(), interfaces, }) } } /// Generates the manifest content. /// /// - `out` - The writer to use for output. pub fn write( lib: intercom::typelib::TypeLib, opts: ModelOptions, out_header: Option<&mut dyn Write>, out_source: Option<&mut dyn Write>, ) -> Result<(), GeneratorError> { let mut reg = Handlebars::new(); reg.register_template_string("cpp_header", include_str!("cpp_header.hbs")) .expect("Error in the built-in C++ template."); reg.register_template_string("cpp_source", include_str!("cpp_source.hbs")) .expect("Error in the built-in C++ template."); let cpp_model = CppLibrary::try_from(lib, &opts)?; if let Some(out_header) = out_header { let rendered = reg .render("cpp_header", &cpp_model) .expect("Rendering a valid ComCrate to C++ failed"); write!(out_header, "{}", rendered)?; } if let Some(out_source) = out_source { let rendered = reg .render("cpp_source", &cpp_model) .expect("Rendering a valid ComCrate to C++ failed"); write!(out_source, "{}", rendered)?; } Ok(()) } /// Converts a guid to binarys representation. pub fn guid_as_struct(g: &intercom::GUID) -> String { format!( "{{0x{:08x},0x{:04x},0x{:04x},{{0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x}}}}}", g.data1, g.data2, g.data3, g.data4[0], g.data4[1], g.data4[2], g.data4[3], g.data4[4], g.data4[5], g.data4[6], g.data4[7] ) }
try_from
identifier_name
cpp.rs
//! Enables the generation of header and source files for using intercom //! libraries from C++ projects. extern crate std; use std::borrow::Cow; use std::io::Write; use super::GeneratorError; use super::{pascal_case, LibraryContext, ModelOptions, TypeSystemOptions}; use intercom::typelib::{ Arg, CoClass, Direction, Interface, InterfaceVariant, Method, TypeInfo, TypeLib, }; use handlebars::Handlebars; use serde_derive::Serialize; #[derive(PartialEq, Serialize, Debug)] pub struct CppLibrary { pub lib_name: String, pub interfaces: Vec<CppInterface>, pub coclass_count: usize, pub coclasses: Vec<CppClass>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppInterface { pub name: String, pub iid_struct: String, pub base: Option<String>, pub methods: Vec<CppMethod>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppMethod { pub name: String, pub ret_type: String, pub args: Vec<CppArg>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppArg { pub name: String, pub arg_type: String, } #[derive(PartialEq, Serialize, Debug)] pub struct CppClass { pub name: String, pub clsid_struct: String, pub interface_count: usize, pub interfaces: Vec<String>, } impl CppLibrary { fn try_from(lib: TypeLib, opts: &ModelOptions) -> Result<Self, GeneratorError> { let ctx = LibraryContext::try_from(&lib)?; let mut interfaces = vec![]; let mut coclasses = vec![]; for t in &lib.types { match t { TypeInfo::Class(cls) => { coclasses.push(CppClass::try_from(cls.as_ref(), opts, &ctx)?) } TypeInfo::Interface(itf) => { interfaces.push(CppInterface::gather(itf.as_ref(), opts, &ctx)?) } } } let interfaces = interfaces .into_iter() .flatten() .collect::<Vec<CppInterface>>(); Ok(Self { lib_name: lib.name.to_string(), interfaces, coclass_count: coclasses.len(), coclasses, }) } } impl CppInterface { fn gather( itf: &Interface, opts: &ModelOptions, ctx: &LibraryContext, ) -> Result<Vec<Self>, GeneratorError> { Ok(opts .type_systems .iter() .map( |ts_opts| match itf.variants.iter().find(|v| v.as_ref().ts == ts_opts.ts) { Some(v) => Some(CppInterface::try_from(&itf, v.as_ref(), ts_opts, ctx)), None => None, }, ) .filter_map(|i| i) .collect::<Result<Vec<_>, _>>()?) } fn try_from( itf: &Interface, itf_variant: &InterfaceVariant, ts_opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { Ok(Self { name: Self::final_name(&itf, ts_opts), iid_struct: guid_as_struct(&itf_variant.iid), base: Some("IUnknown".to_string()), methods: itf_variant .methods .iter() .map(|m| CppMethod::try_from(m.as_ref(), ts_opts, ctx)) .collect::<Result<Vec<_>, _>>()?, }) } pub fn final_name(itf: &Interface, opts: &TypeSystemOptions) -> String { let base_name = if itf.options.class_impl_interface { Cow::from(format!("I{}", itf.name)) } else { itf.name.clone() }; match opts.use_full_name { true => format!("{}_{:?}", base_name, opts.ts), false => base_name.to_string(), } } } impl CppMethod { fn try_from( method: &Method, opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { Ok(Self { name: pascal_case(&method.name), ret_type: CppArg::cpp_type(&method.return_type, opts, ctx), args: method .parameters .iter() .map(|arg| CppArg::try_from(arg, opts, ctx)) .collect::<Result<Vec<_>, _>>()?, }) } } impl CppArg { fn try_from( arg: &Arg, opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { let mut attrs = vec![]; match arg.direction { Direction::In => attrs.push("in"), Direction::Out => attrs.push("out"), Direction::Retval => { attrs.push("out"); attrs.push("retval"); } Direction::Return => { return Err("Direction::Return is invalid direction for arguments" .to_string() .into()); } } Ok(Self { name: arg.name.to_string(), arg_type: Self::cpp_type(arg, opts, ctx), }) } fn cpp_type(arg: &Arg, opts: &TypeSystemOptions, ctx: &LibraryContext) -> String { let base_name = ctx .itfs_by_name .get(arg.ty.as_ref()) .map(|itf| CppInterface::final_name(itf, opts)) .unwrap_or_else(|| arg.ty.to_string()); let indirection = match arg.direction { Direction::In | Direction::Return => arg.indirection_level, Direction::Out | Direction::Retval => arg.indirection_level + 1, }; let base_name = match base_name.as_ref() { "std::ffi::c_void" => "void".to_string(), "HRESULT" => "intercom::HRESULT".to_string(), other => other.to_string(), }; format!("{}{}", base_name, "*".repeat(indirection as usize)) } } impl CppClass { fn try_from( cls: &CoClass, opts: &ModelOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError>
} } /// Generates the manifest content. /// /// - `out` - The writer to use for output. pub fn write( lib: intercom::typelib::TypeLib, opts: ModelOptions, out_header: Option<&mut dyn Write>, out_source: Option<&mut dyn Write>, ) -> Result<(), GeneratorError> { let mut reg = Handlebars::new(); reg.register_template_string("cpp_header", include_str!("cpp_header.hbs")) .expect("Error in the built-in C++ template."); reg.register_template_string("cpp_source", include_str!("cpp_source.hbs")) .expect("Error in the built-in C++ template."); let cpp_model = CppLibrary::try_from(lib, &opts)?; if let Some(out_header) = out_header { let rendered = reg .render("cpp_header", &cpp_model) .expect("Rendering a valid ComCrate to C++ failed"); write!(out_header, "{}", rendered)?; } if let Some(out_source) = out_source { let rendered = reg .render("cpp_source", &cpp_model) .expect("Rendering a valid ComCrate to C++ failed"); write!(out_source, "{}", rendered)?; } Ok(()) } /// Converts a guid to binarys representation. pub fn guid_as_struct(g: &intercom::GUID) -> String { format!( "{{0x{:08x},0x{:04x},0x{:04x},{{0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x}}}}}", g.data1, g.data2, g.data3, g.data4[0], g.data4[1], g.data4[2], g.data4[3], g.data4[4], g.data4[5], g.data4[6], g.data4[7] ) }
{ let interfaces = cls .interfaces .iter() .flat_map(|itf_ref| { opts.type_systems .iter() .map(|opt| { let itf = ctx.itfs_by_ref[itf_ref.name.as_ref()]; CppInterface::final_name(itf, opt) }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); Ok(CppClass { name: cls.name.to_string(), clsid_struct: guid_as_struct(&cls.clsid), interface_count: interfaces.len(), interfaces, })
identifier_body
cpp.rs
//! Enables the generation of header and source files for using intercom //! libraries from C++ projects. extern crate std; use std::borrow::Cow; use std::io::Write; use super::GeneratorError; use super::{pascal_case, LibraryContext, ModelOptions, TypeSystemOptions}; use intercom::typelib::{ Arg, CoClass, Direction, Interface, InterfaceVariant, Method, TypeInfo, TypeLib, }; use handlebars::Handlebars; use serde_derive::Serialize; #[derive(PartialEq, Serialize, Debug)] pub struct CppLibrary { pub lib_name: String, pub interfaces: Vec<CppInterface>, pub coclass_count: usize, pub coclasses: Vec<CppClass>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppInterface { pub name: String, pub iid_struct: String, pub base: Option<String>, pub methods: Vec<CppMethod>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppMethod { pub name: String, pub ret_type: String, pub args: Vec<CppArg>, } #[derive(PartialEq, Serialize, Debug)] pub struct CppArg { pub name: String, pub arg_type: String, } #[derive(PartialEq, Serialize, Debug)] pub struct CppClass { pub name: String, pub clsid_struct: String, pub interface_count: usize, pub interfaces: Vec<String>, } impl CppLibrary { fn try_from(lib: TypeLib, opts: &ModelOptions) -> Result<Self, GeneratorError> { let ctx = LibraryContext::try_from(&lib)?; let mut interfaces = vec![]; let mut coclasses = vec![]; for t in &lib.types { match t { TypeInfo::Class(cls) => { coclasses.push(CppClass::try_from(cls.as_ref(), opts, &ctx)?) } TypeInfo::Interface(itf) => { interfaces.push(CppInterface::gather(itf.as_ref(), opts, &ctx)?) } } } let interfaces = interfaces .into_iter() .flatten() .collect::<Vec<CppInterface>>(); Ok(Self { lib_name: lib.name.to_string(), interfaces, coclass_count: coclasses.len(), coclasses, }) } } impl CppInterface { fn gather( itf: &Interface, opts: &ModelOptions, ctx: &LibraryContext, ) -> Result<Vec<Self>, GeneratorError> { Ok(opts .type_systems .iter() .map( |ts_opts| match itf.variants.iter().find(|v| v.as_ref().ts == ts_opts.ts) { Some(v) => Some(CppInterface::try_from(&itf, v.as_ref(), ts_opts, ctx)), None => None, }, ) .filter_map(|i| i) .collect::<Result<Vec<_>, _>>()?) } fn try_from( itf: &Interface, itf_variant: &InterfaceVariant, ts_opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { Ok(Self { name: Self::final_name(&itf, ts_opts), iid_struct: guid_as_struct(&itf_variant.iid), base: Some("IUnknown".to_string()), methods: itf_variant .methods .iter() .map(|m| CppMethod::try_from(m.as_ref(), ts_opts, ctx)) .collect::<Result<Vec<_>, _>>()?, }) } pub fn final_name(itf: &Interface, opts: &TypeSystemOptions) -> String { let base_name = if itf.options.class_impl_interface { Cow::from(format!("I{}", itf.name)) } else { itf.name.clone() }; match opts.use_full_name { true => format!("{}_{:?}", base_name, opts.ts), false => base_name.to_string(), } } } impl CppMethod { fn try_from( method: &Method, opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { Ok(Self { name: pascal_case(&method.name), ret_type: CppArg::cpp_type(&method.return_type, opts, ctx), args: method .parameters .iter() .map(|arg| CppArg::try_from(arg, opts, ctx)) .collect::<Result<Vec<_>, _>>()?, }) } } impl CppArg { fn try_from( arg: &Arg, opts: &TypeSystemOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { let mut attrs = vec![]; match arg.direction { Direction::In => attrs.push("in"), Direction::Out => attrs.push("out"), Direction::Retval => { attrs.push("out"); attrs.push("retval"); } Direction::Return => { return Err("Direction::Return is invalid direction for arguments" .to_string() .into()); } } Ok(Self { name: arg.name.to_string(), arg_type: Self::cpp_type(arg, opts, ctx), }) } fn cpp_type(arg: &Arg, opts: &TypeSystemOptions, ctx: &LibraryContext) -> String { let base_name = ctx .itfs_by_name .get(arg.ty.as_ref()) .map(|itf| CppInterface::final_name(itf, opts)) .unwrap_or_else(|| arg.ty.to_string()); let indirection = match arg.direction { Direction::In | Direction::Return => arg.indirection_level, Direction::Out | Direction::Retval => arg.indirection_level + 1, }; let base_name = match base_name.as_ref() { "std::ffi::c_void" => "void".to_string(), "HRESULT" => "intercom::HRESULT".to_string(),
other => other.to_string(), }; format!("{}{}", base_name, "*".repeat(indirection as usize)) } } impl CppClass { fn try_from( cls: &CoClass, opts: &ModelOptions, ctx: &LibraryContext, ) -> Result<Self, GeneratorError> { let interfaces = cls .interfaces .iter() .flat_map(|itf_ref| { opts.type_systems .iter() .map(|opt| { let itf = ctx.itfs_by_ref[itf_ref.name.as_ref()]; CppInterface::final_name(itf, opt) }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); Ok(CppClass { name: cls.name.to_string(), clsid_struct: guid_as_struct(&cls.clsid), interface_count: interfaces.len(), interfaces, }) } } /// Generates the manifest content. /// /// - `out` - The writer to use for output. pub fn write( lib: intercom::typelib::TypeLib, opts: ModelOptions, out_header: Option<&mut dyn Write>, out_source: Option<&mut dyn Write>, ) -> Result<(), GeneratorError> { let mut reg = Handlebars::new(); reg.register_template_string("cpp_header", include_str!("cpp_header.hbs")) .expect("Error in the built-in C++ template."); reg.register_template_string("cpp_source", include_str!("cpp_source.hbs")) .expect("Error in the built-in C++ template."); let cpp_model = CppLibrary::try_from(lib, &opts)?; if let Some(out_header) = out_header { let rendered = reg .render("cpp_header", &cpp_model) .expect("Rendering a valid ComCrate to C++ failed"); write!(out_header, "{}", rendered)?; } if let Some(out_source) = out_source { let rendered = reg .render("cpp_source", &cpp_model) .expect("Rendering a valid ComCrate to C++ failed"); write!(out_source, "{}", rendered)?; } Ok(()) } /// Converts a guid to binarys representation. pub fn guid_as_struct(g: &intercom::GUID) -> String { format!( "{{0x{:08x},0x{:04x},0x{:04x},{{0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x},0x{:02x}}}}}", g.data1, g.data2, g.data3, g.data4[0], g.data4[1], g.data4[2], g.data4[3], g.data4[4], g.data4[5], g.data4[6], g.data4[7] ) }
random_line_split
bigint_extensions.rs
use ramp::int::Int; use core::convert::From; const DEFAULT_BUCKET_SIZE: usize = 5; pub trait ModPow<T, K> { fn mod_pow(&self, exp: &T, m: &K) -> Self; fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self; } impl ModPow<Int, Int> for Int { fn mod_pow(&self, exp: &Int, m: &Int) -> Int { self.mod_pow_k(exp, m, DEFAULT_BUCKET_SIZE) } fn mod_pow_k(&self, exp: &Int, m: &Int, k: usize) -> Int { let base = 2 << (k - 1); let mut table = Vec::with_capacity(base); table.push(Int::one()); for i in 1..base { let last = table.get_mut(i-1).unwrap().clone(); table.push((last * self) % m); } let mut r = Int::one(); for i in digits_of_n(exp, base).iter().rev() { for _ in 0..k { r = &r * &r % m } if *i!= 0 { r = &r * table.get(*i).unwrap() % m; } } r } } fn digits_of_n(e: &Int, b: usize) -> Vec<usize>
pub trait ModInverse<T> : Sized { fn mod_inverse(&self, n: &T) -> Option<Self>; } impl ModInverse<Int> for Int { fn mod_inverse(&self, n: &Int) -> Option<Int> { let mut u1 = Int::one(); let mut u3 = (*self).clone(); let mut v1 = Int::zero(); let mut v3 = (*n).clone(); let mut iter = true; while v3!= Int::zero() { let q = &u3 / &v3; let t3 = u3 % &v3; let t1 = u1 + &q * &v1; u1 = v1.clone(); v1 = t1.clone(); u3 = v3.clone(); v3 = t3.clone(); iter =!iter; } if u3!= Int::one() { return None; } let inv = if iter == false { n - u1 } else { u1 }; Some(inv) } } #[cfg(test)] mod tests { use super::*; use ramp::{ Int, RandomInt }; use rand; use test::Bencher; #[test] fn test_bigint_mod_pow() { fn check(b: &Int, e: &Int, m: &Int, r: &Int) { assert_eq!(b.mod_pow(&e, &m), *r); } fn check_i64(b: i64, e: i64, m: i64, r: i64) { let big_b = Int::from(b); let big_e = Int::from(e); let big_m = Int::from(m); let big_r = Int::from(r); check(&big_b, &big_e, &big_m, &big_r); } check_i64(-2, 5, 33, -32); check_i64(-2, 5, 32, 0); check_i64(-1, 3, 10, -1); check_i64(-1, 4, 10, 1); check_i64(0, 2352, 21, 0); check_i64(1, 26, 21, 1); check_i64(2, 5, 33, 32); check_i64(2, 5, 32, 0); check_i64(::std::i64::MAX, ::std::i64::MAX, 2, 1); } #[test] fn test_bigint_mod_inverse() { fn check(a: i64, b: i64, c: i64) { let big_a = Int::from(a); let big_b = Int::from(b); let big_c = Int::from(c); assert_eq!(big_a.mod_inverse(&big_b).unwrap(), big_c); } fn check_none(a: i64, b: i64) { let big_a = Int::from(a); let big_b = Int::from(b); assert_eq!(big_a.mod_inverse(&big_b), None); } check(7, 26, 15); check(37, 216, 181); check(17, 3120, 2753); check(7, -72, 31); check_none(0, 21); check_none(0, 198); check_none(7, 21); } #[bench] fn bench_mod_pow(b: &mut Bencher) { let mut rng = rand::thread_rng(); let base = rng.gen_uint(265); let m = rng.gen_uint(265); b.iter(|| { let exp = rng.gen_uint(265); base.mod_pow(&exp, &m); }); } #[bench] fn bench_mod_inverse(b: &mut Bencher) { let mut rng = rand::thread_rng(); let m = rng.gen_uint(128); b.iter(|| { let a = rng.gen_uint(128); a.mod_inverse(&m); }); } }
{ let mut digits = Vec::new(); let mut n = (*e).clone(); let base = Int::from(b); while n > Int::zero() { digits.push(usize::from(&(&n % &base))); n = &n / &base; } digits }
identifier_body
bigint_extensions.rs
use ramp::int::Int; use core::convert::From; const DEFAULT_BUCKET_SIZE: usize = 5; pub trait ModPow<T, K> { fn mod_pow(&self, exp: &T, m: &K) -> Self; fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self; } impl ModPow<Int, Int> for Int { fn mod_pow(&self, exp: &Int, m: &Int) -> Int { self.mod_pow_k(exp, m, DEFAULT_BUCKET_SIZE) } fn mod_pow_k(&self, exp: &Int, m: &Int, k: usize) -> Int { let base = 2 << (k - 1); let mut table = Vec::with_capacity(base); table.push(Int::one()); for i in 1..base { let last = table.get_mut(i-1).unwrap().clone(); table.push((last * self) % m); } let mut r = Int::one(); for i in digits_of_n(exp, base).iter().rev() { for _ in 0..k { r = &r * &r % m } if *i!= 0 { r = &r * table.get(*i).unwrap() % m; } } r } } fn digits_of_n(e: &Int, b: usize) -> Vec<usize> { let mut digits = Vec::new(); let mut n = (*e).clone(); let base = Int::from(b); while n > Int::zero() { digits.push(usize::from(&(&n % &base))); n = &n / &base; } digits } pub trait ModInverse<T> : Sized { fn mod_inverse(&self, n: &T) -> Option<Self>; } impl ModInverse<Int> for Int { fn mod_inverse(&self, n: &Int) -> Option<Int> { let mut u1 = Int::one(); let mut u3 = (*self).clone(); let mut v1 = Int::zero(); let mut v3 = (*n).clone(); let mut iter = true; while v3!= Int::zero() { let q = &u3 / &v3; let t3 = u3 % &v3; let t1 = u1 + &q * &v1; u1 = v1.clone(); v1 = t1.clone(); u3 = v3.clone(); v3 = t3.clone(); iter =!iter; } if u3!= Int::one() { return None; } let inv = if iter == false { n - u1 } else { u1 }; Some(inv) } } #[cfg(test)] mod tests { use super::*; use ramp::{ Int, RandomInt }; use rand; use test::Bencher; #[test] fn test_bigint_mod_pow() { fn check(b: &Int, e: &Int, m: &Int, r: &Int) { assert_eq!(b.mod_pow(&e, &m), *r); } fn check_i64(b: i64, e: i64, m: i64, r: i64) { let big_b = Int::from(b); let big_e = Int::from(e); let big_m = Int::from(m); let big_r = Int::from(r); check(&big_b, &big_e, &big_m, &big_r); } check_i64(-2, 5, 33, -32); check_i64(-2, 5, 32, 0); check_i64(-1, 3, 10, -1); check_i64(-1, 4, 10, 1); check_i64(0, 2352, 21, 0); check_i64(1, 26, 21, 1); check_i64(2, 5, 33, 32); check_i64(2, 5, 32, 0); check_i64(::std::i64::MAX, ::std::i64::MAX, 2, 1); } #[test] fn test_bigint_mod_inverse() { fn check(a: i64, b: i64, c: i64) { let big_a = Int::from(a); let big_b = Int::from(b); let big_c = Int::from(c); assert_eq!(big_a.mod_inverse(&big_b).unwrap(), big_c); } fn
(a: i64, b: i64) { let big_a = Int::from(a); let big_b = Int::from(b); assert_eq!(big_a.mod_inverse(&big_b), None); } check(7, 26, 15); check(37, 216, 181); check(17, 3120, 2753); check(7, -72, 31); check_none(0, 21); check_none(0, 198); check_none(7, 21); } #[bench] fn bench_mod_pow(b: &mut Bencher) { let mut rng = rand::thread_rng(); let base = rng.gen_uint(265); let m = rng.gen_uint(265); b.iter(|| { let exp = rng.gen_uint(265); base.mod_pow(&exp, &m); }); } #[bench] fn bench_mod_inverse(b: &mut Bencher) { let mut rng = rand::thread_rng(); let m = rng.gen_uint(128); b.iter(|| { let a = rng.gen_uint(128); a.mod_inverse(&m); }); } }
check_none
identifier_name
bigint_extensions.rs
use ramp::int::Int; use core::convert::From; const DEFAULT_BUCKET_SIZE: usize = 5; pub trait ModPow<T, K> { fn mod_pow(&self, exp: &T, m: &K) -> Self; fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self; } impl ModPow<Int, Int> for Int { fn mod_pow(&self, exp: &Int, m: &Int) -> Int { self.mod_pow_k(exp, m, DEFAULT_BUCKET_SIZE) } fn mod_pow_k(&self, exp: &Int, m: &Int, k: usize) -> Int { let base = 2 << (k - 1); let mut table = Vec::with_capacity(base); table.push(Int::one()); for i in 1..base { let last = table.get_mut(i-1).unwrap().clone(); table.push((last * self) % m); } let mut r = Int::one(); for i in digits_of_n(exp, base).iter().rev() { for _ in 0..k { r = &r * &r % m } if *i!= 0 { r = &r * table.get(*i).unwrap() % m; } } r } } fn digits_of_n(e: &Int, b: usize) -> Vec<usize> { let mut digits = Vec::new(); let mut n = (*e).clone(); let base = Int::from(b); while n > Int::zero() { digits.push(usize::from(&(&n % &base))); n = &n / &base; } digits } pub trait ModInverse<T> : Sized { fn mod_inverse(&self, n: &T) -> Option<Self>; } impl ModInverse<Int> for Int { fn mod_inverse(&self, n: &Int) -> Option<Int> { let mut u1 = Int::one(); let mut u3 = (*self).clone(); let mut v1 = Int::zero(); let mut v3 = (*n).clone(); let mut iter = true; while v3!= Int::zero() { let q = &u3 / &v3; let t3 = u3 % &v3; let t1 = u1 + &q * &v1; u1 = v1.clone(); v1 = t1.clone(); u3 = v3.clone(); v3 = t3.clone(); iter =!iter; } if u3!= Int::one() { return None; } let inv = if iter == false { n - u1 } else { u1 }; Some(inv) } } #[cfg(test)] mod tests { use super::*; use ramp::{ Int, RandomInt };
#[test] fn test_bigint_mod_pow() { fn check(b: &Int, e: &Int, m: &Int, r: &Int) { assert_eq!(b.mod_pow(&e, &m), *r); } fn check_i64(b: i64, e: i64, m: i64, r: i64) { let big_b = Int::from(b); let big_e = Int::from(e); let big_m = Int::from(m); let big_r = Int::from(r); check(&big_b, &big_e, &big_m, &big_r); } check_i64(-2, 5, 33, -32); check_i64(-2, 5, 32, 0); check_i64(-1, 3, 10, -1); check_i64(-1, 4, 10, 1); check_i64(0, 2352, 21, 0); check_i64(1, 26, 21, 1); check_i64(2, 5, 33, 32); check_i64(2, 5, 32, 0); check_i64(::std::i64::MAX, ::std::i64::MAX, 2, 1); } #[test] fn test_bigint_mod_inverse() { fn check(a: i64, b: i64, c: i64) { let big_a = Int::from(a); let big_b = Int::from(b); let big_c = Int::from(c); assert_eq!(big_a.mod_inverse(&big_b).unwrap(), big_c); } fn check_none(a: i64, b: i64) { let big_a = Int::from(a); let big_b = Int::from(b); assert_eq!(big_a.mod_inverse(&big_b), None); } check(7, 26, 15); check(37, 216, 181); check(17, 3120, 2753); check(7, -72, 31); check_none(0, 21); check_none(0, 198); check_none(7, 21); } #[bench] fn bench_mod_pow(b: &mut Bencher) { let mut rng = rand::thread_rng(); let base = rng.gen_uint(265); let m = rng.gen_uint(265); b.iter(|| { let exp = rng.gen_uint(265); base.mod_pow(&exp, &m); }); } #[bench] fn bench_mod_inverse(b: &mut Bencher) { let mut rng = rand::thread_rng(); let m = rng.gen_uint(128); b.iter(|| { let a = rng.gen_uint(128); a.mod_inverse(&m); }); } }
use rand; use test::Bencher;
random_line_split
bigint_extensions.rs
use ramp::int::Int; use core::convert::From; const DEFAULT_BUCKET_SIZE: usize = 5; pub trait ModPow<T, K> { fn mod_pow(&self, exp: &T, m: &K) -> Self; fn mod_pow_k(&self, exp: &T, m: &K, k: usize) -> Self; } impl ModPow<Int, Int> for Int { fn mod_pow(&self, exp: &Int, m: &Int) -> Int { self.mod_pow_k(exp, m, DEFAULT_BUCKET_SIZE) } fn mod_pow_k(&self, exp: &Int, m: &Int, k: usize) -> Int { let base = 2 << (k - 1); let mut table = Vec::with_capacity(base); table.push(Int::one()); for i in 1..base { let last = table.get_mut(i-1).unwrap().clone(); table.push((last * self) % m); } let mut r = Int::one(); for i in digits_of_n(exp, base).iter().rev() { for _ in 0..k { r = &r * &r % m } if *i!= 0 { r = &r * table.get(*i).unwrap() % m; } } r } } fn digits_of_n(e: &Int, b: usize) -> Vec<usize> { let mut digits = Vec::new(); let mut n = (*e).clone(); let base = Int::from(b); while n > Int::zero() { digits.push(usize::from(&(&n % &base))); n = &n / &base; } digits } pub trait ModInverse<T> : Sized { fn mod_inverse(&self, n: &T) -> Option<Self>; } impl ModInverse<Int> for Int { fn mod_inverse(&self, n: &Int) -> Option<Int> { let mut u1 = Int::one(); let mut u3 = (*self).clone(); let mut v1 = Int::zero(); let mut v3 = (*n).clone(); let mut iter = true; while v3!= Int::zero() { let q = &u3 / &v3; let t3 = u3 % &v3; let t1 = u1 + &q * &v1; u1 = v1.clone(); v1 = t1.clone(); u3 = v3.clone(); v3 = t3.clone(); iter =!iter; } if u3!= Int::one() { return None; } let inv = if iter == false
else { u1 }; Some(inv) } } #[cfg(test)] mod tests { use super::*; use ramp::{ Int, RandomInt }; use rand; use test::Bencher; #[test] fn test_bigint_mod_pow() { fn check(b: &Int, e: &Int, m: &Int, r: &Int) { assert_eq!(b.mod_pow(&e, &m), *r); } fn check_i64(b: i64, e: i64, m: i64, r: i64) { let big_b = Int::from(b); let big_e = Int::from(e); let big_m = Int::from(m); let big_r = Int::from(r); check(&big_b, &big_e, &big_m, &big_r); } check_i64(-2, 5, 33, -32); check_i64(-2, 5, 32, 0); check_i64(-1, 3, 10, -1); check_i64(-1, 4, 10, 1); check_i64(0, 2352, 21, 0); check_i64(1, 26, 21, 1); check_i64(2, 5, 33, 32); check_i64(2, 5, 32, 0); check_i64(::std::i64::MAX, ::std::i64::MAX, 2, 1); } #[test] fn test_bigint_mod_inverse() { fn check(a: i64, b: i64, c: i64) { let big_a = Int::from(a); let big_b = Int::from(b); let big_c = Int::from(c); assert_eq!(big_a.mod_inverse(&big_b).unwrap(), big_c); } fn check_none(a: i64, b: i64) { let big_a = Int::from(a); let big_b = Int::from(b); assert_eq!(big_a.mod_inverse(&big_b), None); } check(7, 26, 15); check(37, 216, 181); check(17, 3120, 2753); check(7, -72, 31); check_none(0, 21); check_none(0, 198); check_none(7, 21); } #[bench] fn bench_mod_pow(b: &mut Bencher) { let mut rng = rand::thread_rng(); let base = rng.gen_uint(265); let m = rng.gen_uint(265); b.iter(|| { let exp = rng.gen_uint(265); base.mod_pow(&exp, &m); }); } #[bench] fn bench_mod_inverse(b: &mut Bencher) { let mut rng = rand::thread_rng(); let m = rng.gen_uint(128); b.iter(|| { let a = rng.gen_uint(128); a.mod_inverse(&m); }); } }
{ n - u1 }
conditional_block
file_info.rs
extern crate libc; use std::mem; use crate::libproc::helpers; use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor}; #[cfg(target_os = "macos")] use self::libc::{c_int, c_void}; // this extern block links to the libproc library // Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c #[cfg(target_os = "macos")] #[link(name = "proc", kind = "dylib")] extern { // This method is supported in the minimum version of Mac OS X which is 10.5 fn proc_pidfdinfo(pid: c_int, fd: c_int, flavor: c_int, buffer: *mut c_void, buffersize: c_int) -> c_int; } /// Flavor of Pid FileDescriptor info for different types of File Descriptors pub enum PIDFDInfoFlavor { /// VNode Info VNodeInfo = 1, /// VNode Path Info VNodePathInfo = 2, /// Socket info SocketInfo = 3, /// PSEM Info PSEMInfo = 4, /// PSHM Info PSHMInfo = 5, /// Pipe Info PipeInfo = 6, /// KQueue Info KQueueInfo = 7, /// Apple Talk Info ATalkInfo = 8, } /// Struct for Listing File Descriptors pub struct ListFDs; impl ListPIDInfo for ListFDs { type Item = ProcFDInfo; fn flavor() -> PidInfoFlavor { PidInfoFlavor::ListFDs } } /// Struct to hold info about a Processes FileDescriptor Info #[repr(C)] pub struct ProcFDInfo { /// File Descriptor pub proc_fd: i32, /// File Descriptor type pub proc_fdtype: u32, } /// Enum for different File Descriptor types #[derive(Copy, Clone, Debug)] pub enum ProcFDType { /// AppleTalk ATalk = 0, /// Vnode VNode = 1, /// Socket Socket = 2, /// POSIX shared memory PSHM = 3, /// POSIX semaphore PSEM = 4, /// Kqueue KQueue = 5, /// Pipe Pipe = 6, /// FSEvents FSEvents = 7, /// Unknown Unknown, } impl From<u32> for ProcFDType { fn from(value: u32) -> ProcFDType { match value { 0 => ProcFDType::ATalk, 1 => ProcFDType::VNode, 2 => ProcFDType::Socket, 3 => ProcFDType::PSHM, 4 => ProcFDType::PSEM, 5 => ProcFDType::KQueue, 6 => ProcFDType::Pipe, 7 => ProcFDType::FSEvents, _ => ProcFDType::Unknown, } } } /// The `PIDFDInfo` trait is needed for polymorphism on pidfdinfo types, also abstracting flavor in order to provide /// type-guaranteed flavor correctness pub trait PIDFDInfo: Default { /// Return the Pid File Descriptor Info flavor of the implementing struct fn flavor() -> PIDFDInfoFlavor; } /// Returns the information about file descriptors of the process that match pid passed in. /// /// # Examples /// /// ``` /// use std::io::Write; /// use std::net::TcpListener; /// use libproc::libproc::proc_pid::{listpidinfo, pidinfo, ListThreads}; /// use libproc::libproc::bsd_info::{BSDInfo}; /// use libproc::libproc::net_info::{SocketFDInfo, SocketInfoKind}; /// use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType}; /// use std::process; /// /// let pid = process::id() as i32; /// /// // Open TCP port:8000 to test. /// let _listener = TcpListener::bind("127.0.0.1:8000"); /// /// if let Ok(info) = pidinfo::<BSDInfo>(pid, 0) { /// if let Ok(fds) = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize) { /// for fd in &fds { /// match fd.proc_fdtype.into() { /// ProcFDType::Socket => { /// if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) { /// match socket.psi.soi_kind.into() { /// SocketInfoKind::Tcp => { /// // access to the member of `soi_proto` is unsafe becasuse of union type. /// let info = unsafe { socket.psi.soi_proto.pri_tcp }; /// /// // change endian and cut off because insi_lport is network endian and 16bit witdh. /// let mut port = 0; /// port |= info.tcpsi_ini.insi_lport >> 8 & 0x00ff; /// port |= info.tcpsi_ini.insi_lport << 8 & 0xff00; /// /// // access to the member of `insi_laddr` is unsafe becasuse of union type. /// let s_addr = unsafe { info.tcpsi_ini.insi_laddr.ina_46.i46a_addr4.s_addr }; /// /// // change endian because insi_laddr is network endian. /// let mut addr = 0; /// addr |= s_addr >> 24 & 0x000000ff; /// addr |= s_addr >> 8 & 0x0000ff00; /// addr |= s_addr << 8 & 0x00ff0000; /// addr |= s_addr << 24 & 0xff000000; /// /// println!("{}.{}.{}.{}:{}", addr >> 24 & 0xff, addr >> 16 & 0xff, addr >> 8 & 0xff, addr & 0xff, port); /// } /// _ => (), /// } /// } /// } /// _ => (), /// } /// } /// } /// } /// ``` /// #[cfg(target_os = "macos")] pub fn
<T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> { let flavor = T::flavor() as i32; let buffer_size = mem::size_of::<T>() as i32; let mut pidinfo = T::default(); let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void; let ret: i32; unsafe { ret = proc_pidfdinfo(pid, fd, flavor, buffer_ptr, buffer_size); }; if ret <= 0 { Err(helpers::get_errno_with_message(ret)) } else { Ok(pidinfo) } } #[cfg(not(target_os = "macos"))] pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String> { unimplemented!() } #[cfg(all(test, target_os = "macos"))] mod test { use crate::libproc::bsd_info::BSDInfo; use crate::libproc::file_info::{ListFDs, ProcFDType}; use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind}; use crate::libproc::proc_pid::{listpidinfo, pidinfo}; use super::pidfdinfo; #[test] fn pidfdinfo_test() { use std::process; use std::net::TcpListener; let pid = process::id() as i32; let _listener = TcpListener::bind("127.0.0.1:65535"); let info = pidinfo::<BSDInfo>(pid, 0).expect("pidinfo() failed"); let fds = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize).expect("listpidinfo() failed"); for fd in fds { if let ProcFDType::Socket = fd.proc_fdtype.into() { let socket = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd).expect("pidfdinfo() failed"); if let SocketInfoKind::Tcp = socket.psi.soi_kind.into() { unsafe { let info = socket.psi.soi_proto.pri_tcp; assert_eq!(socket.psi.soi_protocol, libc::IPPROTO_TCP); assert_eq!(info.tcpsi_ini.insi_lport as u32, 65535); } } } } } }
pidfdinfo
identifier_name
file_info.rs
extern crate libc; use std::mem; use crate::libproc::helpers; use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor}; #[cfg(target_os = "macos")] use self::libc::{c_int, c_void}; // this extern block links to the libproc library // Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c #[cfg(target_os = "macos")] #[link(name = "proc", kind = "dylib")] extern { // This method is supported in the minimum version of Mac OS X which is 10.5 fn proc_pidfdinfo(pid: c_int, fd: c_int, flavor: c_int, buffer: *mut c_void, buffersize: c_int) -> c_int; } /// Flavor of Pid FileDescriptor info for different types of File Descriptors pub enum PIDFDInfoFlavor { /// VNode Info VNodeInfo = 1, /// VNode Path Info VNodePathInfo = 2, /// Socket info SocketInfo = 3, /// PSEM Info PSEMInfo = 4, /// PSHM Info PSHMInfo = 5, /// Pipe Info PipeInfo = 6, /// KQueue Info KQueueInfo = 7, /// Apple Talk Info ATalkInfo = 8, } /// Struct for Listing File Descriptors pub struct ListFDs; impl ListPIDInfo for ListFDs { type Item = ProcFDInfo; fn flavor() -> PidInfoFlavor { PidInfoFlavor::ListFDs } } /// Struct to hold info about a Processes FileDescriptor Info #[repr(C)] pub struct ProcFDInfo { /// File Descriptor pub proc_fd: i32, /// File Descriptor type pub proc_fdtype: u32, } /// Enum for different File Descriptor types #[derive(Copy, Clone, Debug)] pub enum ProcFDType { /// AppleTalk ATalk = 0, /// Vnode VNode = 1, /// Socket Socket = 2, /// POSIX shared memory PSHM = 3, /// POSIX semaphore PSEM = 4, /// Kqueue KQueue = 5, /// Pipe Pipe = 6, /// FSEvents FSEvents = 7, /// Unknown Unknown, } impl From<u32> for ProcFDType { fn from(value: u32) -> ProcFDType { match value { 0 => ProcFDType::ATalk, 1 => ProcFDType::VNode, 2 => ProcFDType::Socket, 3 => ProcFDType::PSHM, 4 => ProcFDType::PSEM, 5 => ProcFDType::KQueue, 6 => ProcFDType::Pipe, 7 => ProcFDType::FSEvents, _ => ProcFDType::Unknown, } } } /// The `PIDFDInfo` trait is needed for polymorphism on pidfdinfo types, also abstracting flavor in order to provide /// type-guaranteed flavor correctness pub trait PIDFDInfo: Default { /// Return the Pid File Descriptor Info flavor of the implementing struct fn flavor() -> PIDFDInfoFlavor; } /// Returns the information about file descriptors of the process that match pid passed in. /// /// # Examples /// /// ``` /// use std::io::Write; /// use std::net::TcpListener; /// use libproc::libproc::proc_pid::{listpidinfo, pidinfo, ListThreads}; /// use libproc::libproc::bsd_info::{BSDInfo}; /// use libproc::libproc::net_info::{SocketFDInfo, SocketInfoKind}; /// use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType}; /// use std::process; /// /// let pid = process::id() as i32; /// /// // Open TCP port:8000 to test. /// let _listener = TcpListener::bind("127.0.0.1:8000"); /// /// if let Ok(info) = pidinfo::<BSDInfo>(pid, 0) { /// if let Ok(fds) = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize) { /// for fd in &fds { /// match fd.proc_fdtype.into() { /// ProcFDType::Socket => { /// if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) { /// match socket.psi.soi_kind.into() { /// SocketInfoKind::Tcp => { /// // access to the member of `soi_proto` is unsafe becasuse of union type. /// let info = unsafe { socket.psi.soi_proto.pri_tcp }; /// /// // change endian and cut off because insi_lport is network endian and 16bit witdh. /// let mut port = 0; /// port |= info.tcpsi_ini.insi_lport >> 8 & 0x00ff; /// port |= info.tcpsi_ini.insi_lport << 8 & 0xff00; /// /// // access to the member of `insi_laddr` is unsafe becasuse of union type. /// let s_addr = unsafe { info.tcpsi_ini.insi_laddr.ina_46.i46a_addr4.s_addr }; /// /// // change endian because insi_laddr is network endian. /// let mut addr = 0; /// addr |= s_addr >> 24 & 0x000000ff; /// addr |= s_addr >> 8 & 0x0000ff00; /// addr |= s_addr << 8 & 0x00ff0000; /// addr |= s_addr << 24 & 0xff000000; /// /// println!("{}.{}.{}.{}:{}", addr >> 24 & 0xff, addr >> 16 & 0xff, addr >> 8 & 0xff, addr & 0xff, port); /// } /// _ => (), /// } /// } /// } /// _ => (), /// } /// } /// } /// } /// ``` /// #[cfg(target_os = "macos")] pub fn pidfdinfo<T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> { let flavor = T::flavor() as i32; let buffer_size = mem::size_of::<T>() as i32; let mut pidinfo = T::default(); let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void; let ret: i32; unsafe { ret = proc_pidfdinfo(pid, fd, flavor, buffer_ptr, buffer_size); }; if ret <= 0
else { Ok(pidinfo) } } #[cfg(not(target_os = "macos"))] pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String> { unimplemented!() } #[cfg(all(test, target_os = "macos"))] mod test { use crate::libproc::bsd_info::BSDInfo; use crate::libproc::file_info::{ListFDs, ProcFDType}; use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind}; use crate::libproc::proc_pid::{listpidinfo, pidinfo}; use super::pidfdinfo; #[test] fn pidfdinfo_test() { use std::process; use std::net::TcpListener; let pid = process::id() as i32; let _listener = TcpListener::bind("127.0.0.1:65535"); let info = pidinfo::<BSDInfo>(pid, 0).expect("pidinfo() failed"); let fds = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize).expect("listpidinfo() failed"); for fd in fds { if let ProcFDType::Socket = fd.proc_fdtype.into() { let socket = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd).expect("pidfdinfo() failed"); if let SocketInfoKind::Tcp = socket.psi.soi_kind.into() { unsafe { let info = socket.psi.soi_proto.pri_tcp; assert_eq!(socket.psi.soi_protocol, libc::IPPROTO_TCP); assert_eq!(info.tcpsi_ini.insi_lport as u32, 65535); } } } } } }
{ Err(helpers::get_errno_with_message(ret)) }
conditional_block
file_info.rs
extern crate libc; use std::mem; use crate::libproc::helpers; use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor}; #[cfg(target_os = "macos")] use self::libc::{c_int, c_void}; // this extern block links to the libproc library // Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c #[cfg(target_os = "macos")] #[link(name = "proc", kind = "dylib")] extern { // This method is supported in the minimum version of Mac OS X which is 10.5 fn proc_pidfdinfo(pid: c_int, fd: c_int, flavor: c_int, buffer: *mut c_void, buffersize: c_int) -> c_int; } /// Flavor of Pid FileDescriptor info for different types of File Descriptors pub enum PIDFDInfoFlavor { /// VNode Info VNodeInfo = 1, /// VNode Path Info VNodePathInfo = 2, /// Socket info SocketInfo = 3, /// PSEM Info PSEMInfo = 4, /// PSHM Info PSHMInfo = 5, /// Pipe Info PipeInfo = 6, /// KQueue Info KQueueInfo = 7, /// Apple Talk Info ATalkInfo = 8, } /// Struct for Listing File Descriptors pub struct ListFDs; impl ListPIDInfo for ListFDs { type Item = ProcFDInfo; fn flavor() -> PidInfoFlavor { PidInfoFlavor::ListFDs } } /// Struct to hold info about a Processes FileDescriptor Info #[repr(C)] pub struct ProcFDInfo { /// File Descriptor pub proc_fd: i32, /// File Descriptor type pub proc_fdtype: u32, } /// Enum for different File Descriptor types #[derive(Copy, Clone, Debug)] pub enum ProcFDType { /// AppleTalk ATalk = 0, /// Vnode VNode = 1, /// Socket Socket = 2, /// POSIX shared memory PSHM = 3, /// POSIX semaphore PSEM = 4, /// Kqueue KQueue = 5, /// Pipe Pipe = 6, /// FSEvents FSEvents = 7, /// Unknown Unknown, } impl From<u32> for ProcFDType { fn from(value: u32) -> ProcFDType { match value { 0 => ProcFDType::ATalk, 1 => ProcFDType::VNode, 2 => ProcFDType::Socket, 3 => ProcFDType::PSHM, 4 => ProcFDType::PSEM, 5 => ProcFDType::KQueue, 6 => ProcFDType::Pipe, 7 => ProcFDType::FSEvents, _ => ProcFDType::Unknown, } } } /// The `PIDFDInfo` trait is needed for polymorphism on pidfdinfo types, also abstracting flavor in order to provide /// type-guaranteed flavor correctness pub trait PIDFDInfo: Default { /// Return the Pid File Descriptor Info flavor of the implementing struct fn flavor() -> PIDFDInfoFlavor; } /// Returns the information about file descriptors of the process that match pid passed in. /// /// # Examples /// /// ``` /// use std::io::Write; /// use std::net::TcpListener; /// use libproc::libproc::proc_pid::{listpidinfo, pidinfo, ListThreads}; /// use libproc::libproc::bsd_info::{BSDInfo}; /// use libproc::libproc::net_info::{SocketFDInfo, SocketInfoKind}; /// use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType}; /// use std::process; /// /// let pid = process::id() as i32; /// /// // Open TCP port:8000 to test. /// let _listener = TcpListener::bind("127.0.0.1:8000"); /// /// if let Ok(info) = pidinfo::<BSDInfo>(pid, 0) { /// if let Ok(fds) = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize) { /// for fd in &fds { /// match fd.proc_fdtype.into() { /// ProcFDType::Socket => { /// if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) { /// match socket.psi.soi_kind.into() { /// SocketInfoKind::Tcp => { /// // access to the member of `soi_proto` is unsafe becasuse of union type. /// let info = unsafe { socket.psi.soi_proto.pri_tcp }; /// /// // change endian and cut off because insi_lport is network endian and 16bit witdh. /// let mut port = 0; /// port |= info.tcpsi_ini.insi_lport >> 8 & 0x00ff; /// port |= info.tcpsi_ini.insi_lport << 8 & 0xff00; /// /// // access to the member of `insi_laddr` is unsafe becasuse of union type. /// let s_addr = unsafe { info.tcpsi_ini.insi_laddr.ina_46.i46a_addr4.s_addr }; /// /// // change endian because insi_laddr is network endian. /// let mut addr = 0; /// addr |= s_addr >> 24 & 0x000000ff; /// addr |= s_addr >> 8 & 0x0000ff00; /// addr |= s_addr << 8 & 0x00ff0000; /// addr |= s_addr << 24 & 0xff000000; /// /// println!("{}.{}.{}.{}:{}", addr >> 24 & 0xff, addr >> 16 & 0xff, addr >> 8 & 0xff, addr & 0xff, port); /// } /// _ => (), /// } /// } /// } /// _ => (), /// } /// } /// } /// } /// ``` /// #[cfg(target_os = "macos")] pub fn pidfdinfo<T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> { let flavor = T::flavor() as i32; let buffer_size = mem::size_of::<T>() as i32; let mut pidinfo = T::default(); let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void; let ret: i32; unsafe { ret = proc_pidfdinfo(pid, fd, flavor, buffer_ptr, buffer_size); }; if ret <= 0 { Err(helpers::get_errno_with_message(ret)) } else { Ok(pidinfo) } } #[cfg(not(target_os = "macos"))] pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String>
#[cfg(all(test, target_os = "macos"))] mod test { use crate::libproc::bsd_info::BSDInfo; use crate::libproc::file_info::{ListFDs, ProcFDType}; use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind}; use crate::libproc::proc_pid::{listpidinfo, pidinfo}; use super::pidfdinfo; #[test] fn pidfdinfo_test() { use std::process; use std::net::TcpListener; let pid = process::id() as i32; let _listener = TcpListener::bind("127.0.0.1:65535"); let info = pidinfo::<BSDInfo>(pid, 0).expect("pidinfo() failed"); let fds = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize).expect("listpidinfo() failed"); for fd in fds { if let ProcFDType::Socket = fd.proc_fdtype.into() { let socket = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd).expect("pidfdinfo() failed"); if let SocketInfoKind::Tcp = socket.psi.soi_kind.into() { unsafe { let info = socket.psi.soi_proto.pri_tcp; assert_eq!(socket.psi.soi_protocol, libc::IPPROTO_TCP); assert_eq!(info.tcpsi_ini.insi_lport as u32, 65535); } } } } } }
{ unimplemented!() }
identifier_body
file_info.rs
use std::mem; use crate::libproc::helpers; use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor}; #[cfg(target_os = "macos")] use self::libc::{c_int, c_void}; // this extern block links to the libproc library // Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c #[cfg(target_os = "macos")] #[link(name = "proc", kind = "dylib")] extern { // This method is supported in the minimum version of Mac OS X which is 10.5 fn proc_pidfdinfo(pid: c_int, fd: c_int, flavor: c_int, buffer: *mut c_void, buffersize: c_int) -> c_int; } /// Flavor of Pid FileDescriptor info for different types of File Descriptors pub enum PIDFDInfoFlavor { /// VNode Info VNodeInfo = 1, /// VNode Path Info VNodePathInfo = 2, /// Socket info SocketInfo = 3, /// PSEM Info PSEMInfo = 4, /// PSHM Info PSHMInfo = 5, /// Pipe Info PipeInfo = 6, /// KQueue Info KQueueInfo = 7, /// Apple Talk Info ATalkInfo = 8, } /// Struct for Listing File Descriptors pub struct ListFDs; impl ListPIDInfo for ListFDs { type Item = ProcFDInfo; fn flavor() -> PidInfoFlavor { PidInfoFlavor::ListFDs } } /// Struct to hold info about a Processes FileDescriptor Info #[repr(C)] pub struct ProcFDInfo { /// File Descriptor pub proc_fd: i32, /// File Descriptor type pub proc_fdtype: u32, } /// Enum for different File Descriptor types #[derive(Copy, Clone, Debug)] pub enum ProcFDType { /// AppleTalk ATalk = 0, /// Vnode VNode = 1, /// Socket Socket = 2, /// POSIX shared memory PSHM = 3, /// POSIX semaphore PSEM = 4, /// Kqueue KQueue = 5, /// Pipe Pipe = 6, /// FSEvents FSEvents = 7, /// Unknown Unknown, } impl From<u32> for ProcFDType { fn from(value: u32) -> ProcFDType { match value { 0 => ProcFDType::ATalk, 1 => ProcFDType::VNode, 2 => ProcFDType::Socket, 3 => ProcFDType::PSHM, 4 => ProcFDType::PSEM, 5 => ProcFDType::KQueue, 6 => ProcFDType::Pipe, 7 => ProcFDType::FSEvents, _ => ProcFDType::Unknown, } } } /// The `PIDFDInfo` trait is needed for polymorphism on pidfdinfo types, also abstracting flavor in order to provide /// type-guaranteed flavor correctness pub trait PIDFDInfo: Default { /// Return the Pid File Descriptor Info flavor of the implementing struct fn flavor() -> PIDFDInfoFlavor; } /// Returns the information about file descriptors of the process that match pid passed in. /// /// # Examples /// /// ``` /// use std::io::Write; /// use std::net::TcpListener; /// use libproc::libproc::proc_pid::{listpidinfo, pidinfo, ListThreads}; /// use libproc::libproc::bsd_info::{BSDInfo}; /// use libproc::libproc::net_info::{SocketFDInfo, SocketInfoKind}; /// use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType}; /// use std::process; /// /// let pid = process::id() as i32; /// /// // Open TCP port:8000 to test. /// let _listener = TcpListener::bind("127.0.0.1:8000"); /// /// if let Ok(info) = pidinfo::<BSDInfo>(pid, 0) { /// if let Ok(fds) = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize) { /// for fd in &fds { /// match fd.proc_fdtype.into() { /// ProcFDType::Socket => { /// if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) { /// match socket.psi.soi_kind.into() { /// SocketInfoKind::Tcp => { /// // access to the member of `soi_proto` is unsafe becasuse of union type. /// let info = unsafe { socket.psi.soi_proto.pri_tcp }; /// /// // change endian and cut off because insi_lport is network endian and 16bit witdh. /// let mut port = 0; /// port |= info.tcpsi_ini.insi_lport >> 8 & 0x00ff; /// port |= info.tcpsi_ini.insi_lport << 8 & 0xff00; /// /// // access to the member of `insi_laddr` is unsafe becasuse of union type. /// let s_addr = unsafe { info.tcpsi_ini.insi_laddr.ina_46.i46a_addr4.s_addr }; /// /// // change endian because insi_laddr is network endian. /// let mut addr = 0; /// addr |= s_addr >> 24 & 0x000000ff; /// addr |= s_addr >> 8 & 0x0000ff00; /// addr |= s_addr << 8 & 0x00ff0000; /// addr |= s_addr << 24 & 0xff000000; /// /// println!("{}.{}.{}.{}:{}", addr >> 24 & 0xff, addr >> 16 & 0xff, addr >> 8 & 0xff, addr & 0xff, port); /// } /// _ => (), /// } /// } /// } /// _ => (), /// } /// } /// } /// } /// ``` /// #[cfg(target_os = "macos")] pub fn pidfdinfo<T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> { let flavor = T::flavor() as i32; let buffer_size = mem::size_of::<T>() as i32; let mut pidinfo = T::default(); let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void; let ret: i32; unsafe { ret = proc_pidfdinfo(pid, fd, flavor, buffer_ptr, buffer_size); }; if ret <= 0 { Err(helpers::get_errno_with_message(ret)) } else { Ok(pidinfo) } } #[cfg(not(target_os = "macos"))] pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String> { unimplemented!() } #[cfg(all(test, target_os = "macos"))] mod test { use crate::libproc::bsd_info::BSDInfo; use crate::libproc::file_info::{ListFDs, ProcFDType}; use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind}; use crate::libproc::proc_pid::{listpidinfo, pidinfo}; use super::pidfdinfo; #[test] fn pidfdinfo_test() { use std::process; use std::net::TcpListener; let pid = process::id() as i32; let _listener = TcpListener::bind("127.0.0.1:65535"); let info = pidinfo::<BSDInfo>(pid, 0).expect("pidinfo() failed"); let fds = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize).expect("listpidinfo() failed"); for fd in fds { if let ProcFDType::Socket = fd.proc_fdtype.into() { let socket = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd).expect("pidfdinfo() failed"); if let SocketInfoKind::Tcp = socket.psi.soi_kind.into() { unsafe { let info = socket.psi.soi_proto.pri_tcp; assert_eq!(socket.psi.soi_protocol, libc::IPPROTO_TCP); assert_eq!(info.tcpsi_ini.insi_lport as u32, 65535); } } } } } }
extern crate libc;
random_line_split
errors.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use crate::util::{b2s}; use std::error; use std::fmt; use jedec::*; /// Errors that can occur when parsing a bitstream #[derive(Clone, Debug, PartialEq, Eq)] pub enum XC2BitError { /// The.jed file could not be parsed JedParseError(JedParserError),
/// The device name is invalid BadDeviceName(String), /// The number of fuses was incorrect for the device WrongFuseCount, /// An unknown value was used in the `Oe` field UnsupportedOeConfiguration([bool; 4]), /// An unknown value was used in the ZIA selection bits UnsupportedZIAConfiguration(Vec<bool>), } impl From<JedParserError> for XC2BitError { fn from(err: JedParserError) -> Self { XC2BitError::JedParseError(err) } } impl From<()> for XC2BitError { fn from(_: ()) -> Self { // FIXME unreachable!(); } } impl error::Error for XC2BitError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { &XC2BitError::JedParseError(ref err) => Some(err), &XC2BitError::BadDeviceName(_) => None, &XC2BitError::WrongFuseCount => None, &XC2BitError::UnsupportedOeConfiguration(_) => None, &XC2BitError::UnsupportedZIAConfiguration(_) => None, } } } impl fmt::Display for XC2BitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &XC2BitError::JedParseError(err) => { write!(f, ".jed parsing failed: {}", err) }, &XC2BitError::BadDeviceName(ref devname) => { write!(f, "device name \"{}\" is invalid/unsupported", devname) }, &XC2BitError::WrongFuseCount => { write!(f, "wrong number of fuses") }, &XC2BitError::UnsupportedOeConfiguration(bits) => { write!(f, "unknown Oe field value {}{}{}{}", b2s(bits[0]), b2s(bits[1]), b2s(bits[2]), b2s(bits[3])) }, &XC2BitError::UnsupportedZIAConfiguration(ref bits) => { write!(f, "unknown ZIA selection bit pattern ")?; for &bit in bits { write!(f, "{}", b2s(bit))?; } Ok(()) }, } } }
random_line_split
errors.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use crate::util::{b2s}; use std::error; use std::fmt; use jedec::*; /// Errors that can occur when parsing a bitstream #[derive(Clone, Debug, PartialEq, Eq)] pub enum XC2BitError { /// The.jed file could not be parsed JedParseError(JedParserError), /// The device name is invalid BadDeviceName(String), /// The number of fuses was incorrect for the device WrongFuseCount, /// An unknown value was used in the `Oe` field UnsupportedOeConfiguration([bool; 4]), /// An unknown value was used in the ZIA selection bits UnsupportedZIAConfiguration(Vec<bool>), } impl From<JedParserError> for XC2BitError { fn from(err: JedParserError) -> Self { XC2BitError::JedParseError(err) } } impl From<()> for XC2BitError { fn
(_: ()) -> Self { // FIXME unreachable!(); } } impl error::Error for XC2BitError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { &XC2BitError::JedParseError(ref err) => Some(err), &XC2BitError::BadDeviceName(_) => None, &XC2BitError::WrongFuseCount => None, &XC2BitError::UnsupportedOeConfiguration(_) => None, &XC2BitError::UnsupportedZIAConfiguration(_) => None, } } } impl fmt::Display for XC2BitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &XC2BitError::JedParseError(err) => { write!(f, ".jed parsing failed: {}", err) }, &XC2BitError::BadDeviceName(ref devname) => { write!(f, "device name \"{}\" is invalid/unsupported", devname) }, &XC2BitError::WrongFuseCount => { write!(f, "wrong number of fuses") }, &XC2BitError::UnsupportedOeConfiguration(bits) => { write!(f, "unknown Oe field value {}{}{}{}", b2s(bits[0]), b2s(bits[1]), b2s(bits[2]), b2s(bits[3])) }, &XC2BitError::UnsupportedZIAConfiguration(ref bits) => { write!(f, "unknown ZIA selection bit pattern ")?; for &bit in bits { write!(f, "{}", b2s(bit))?; } Ok(()) }, } } }
from
identifier_name
errors.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use crate::util::{b2s}; use std::error; use std::fmt; use jedec::*; /// Errors that can occur when parsing a bitstream #[derive(Clone, Debug, PartialEq, Eq)] pub enum XC2BitError { /// The.jed file could not be parsed JedParseError(JedParserError), /// The device name is invalid BadDeviceName(String), /// The number of fuses was incorrect for the device WrongFuseCount, /// An unknown value was used in the `Oe` field UnsupportedOeConfiguration([bool; 4]), /// An unknown value was used in the ZIA selection bits UnsupportedZIAConfiguration(Vec<bool>), } impl From<JedParserError> for XC2BitError { fn from(err: JedParserError) -> Self { XC2BitError::JedParseError(err) } } impl From<()> for XC2BitError { fn from(_: ()) -> Self { // FIXME unreachable!(); } } impl error::Error for XC2BitError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { &XC2BitError::JedParseError(ref err) => Some(err), &XC2BitError::BadDeviceName(_) => None, &XC2BitError::WrongFuseCount => None, &XC2BitError::UnsupportedOeConfiguration(_) => None, &XC2BitError::UnsupportedZIAConfiguration(_) => None, } } } impl fmt::Display for XC2BitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &XC2BitError::JedParseError(err) => { write!(f, ".jed parsing failed: {}", err) }, &XC2BitError::BadDeviceName(ref devname) => { write!(f, "device name \"{}\" is invalid/unsupported", devname) }, &XC2BitError::WrongFuseCount => { write!(f, "wrong number of fuses") }, &XC2BitError::UnsupportedOeConfiguration(bits) => { write!(f, "unknown Oe field value {}{}{}{}", b2s(bits[0]), b2s(bits[1]), b2s(bits[2]), b2s(bits[3])) }, &XC2BitError::UnsupportedZIAConfiguration(ref bits) =>
, } } }
{ write!(f, "unknown ZIA selection bit pattern ")?; for &bit in bits { write!(f, "{}", b2s(bit))?; } Ok(()) }
conditional_block
errors.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use crate::util::{b2s}; use std::error; use std::fmt; use jedec::*; /// Errors that can occur when parsing a bitstream #[derive(Clone, Debug, PartialEq, Eq)] pub enum XC2BitError { /// The.jed file could not be parsed JedParseError(JedParserError), /// The device name is invalid BadDeviceName(String), /// The number of fuses was incorrect for the device WrongFuseCount, /// An unknown value was used in the `Oe` field UnsupportedOeConfiguration([bool; 4]), /// An unknown value was used in the ZIA selection bits UnsupportedZIAConfiguration(Vec<bool>), } impl From<JedParserError> for XC2BitError { fn from(err: JedParserError) -> Self { XC2BitError::JedParseError(err) } } impl From<()> for XC2BitError { fn from(_: ()) -> Self { // FIXME unreachable!(); } } impl error::Error for XC2BitError { fn source(&self) -> Option<&(dyn error::Error +'static)>
} impl fmt::Display for XC2BitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &XC2BitError::JedParseError(err) => { write!(f, ".jed parsing failed: {}", err) }, &XC2BitError::BadDeviceName(ref devname) => { write!(f, "device name \"{}\" is invalid/unsupported", devname) }, &XC2BitError::WrongFuseCount => { write!(f, "wrong number of fuses") }, &XC2BitError::UnsupportedOeConfiguration(bits) => { write!(f, "unknown Oe field value {}{}{}{}", b2s(bits[0]), b2s(bits[1]), b2s(bits[2]), b2s(bits[3])) }, &XC2BitError::UnsupportedZIAConfiguration(ref bits) => { write!(f, "unknown ZIA selection bit pattern ")?; for &bit in bits { write!(f, "{}", b2s(bit))?; } Ok(()) }, } } }
{ match self { &XC2BitError::JedParseError(ref err) => Some(err), &XC2BitError::BadDeviceName(_) => None, &XC2BitError::WrongFuseCount => None, &XC2BitError::UnsupportedOeConfiguration(_) => None, &XC2BitError::UnsupportedZIAConfiguration(_) => None, } }
identifier_body
stack_switcher.rs
// This file was generated by gir (17af302) from gir-files (11e0e6d) // DO NOT EDIT use Box; use Buildable; use Container; use Orientable; #[cfg(feature = "3.10")] use Stack; use Widget; use ffi; use glib::object::Downcast; use glib::translate::*; glib_wrapper! { pub struct StackSwitcher(Object<ffi::GtkStackSwitcher>): Widget, Container, Box, Buildable, Orientable; match fn { get_type => || ffi::gtk_stack_switcher_get_type(), } } impl StackSwitcher { #[cfg(feature = "3.10")] pub fn new() -> StackSwitcher { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_stack_switcher_new()).downcast_unchecked() } } #[cfg(feature = "3.10")] pub fn get_stack(&self) -> Option<Stack> { unsafe { from_glib_none(ffi::gtk_stack_switcher_get_stack(self.to_glib_none().0)) } } #[cfg(feature = "3.10")] pub fn set_stack(&self, stack: Option<&Stack>)
}
{ unsafe { ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.to_glib_none().0); } }
identifier_body
stack_switcher.rs
// This file was generated by gir (17af302) from gir-files (11e0e6d) // DO NOT EDIT use Box; use Buildable; use Container; use Orientable; #[cfg(feature = "3.10")] use Stack; use Widget; use ffi; use glib::object::Downcast; use glib::translate::*; glib_wrapper! { pub struct StackSwitcher(Object<ffi::GtkStackSwitcher>): Widget, Container, Box, Buildable, Orientable; match fn { get_type => || ffi::gtk_stack_switcher_get_type(), } } impl StackSwitcher { #[cfg(feature = "3.10")] pub fn new() -> StackSwitcher { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_stack_switcher_new()).downcast_unchecked() } } #[cfg(feature = "3.10")] pub fn
(&self) -> Option<Stack> { unsafe { from_glib_none(ffi::gtk_stack_switcher_get_stack(self.to_glib_none().0)) } } #[cfg(feature = "3.10")] pub fn set_stack(&self, stack: Option<&Stack>) { unsafe { ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.to_glib_none().0); } } }
get_stack
identifier_name
stack_switcher.rs
// This file was generated by gir (17af302) from gir-files (11e0e6d) // DO NOT EDIT use Box; use Buildable; use Container; use Orientable; #[cfg(feature = "3.10")] use Stack; use Widget; use ffi; use glib::object::Downcast; use glib::translate::*; glib_wrapper! { pub struct StackSwitcher(Object<ffi::GtkStackSwitcher>): Widget, Container, Box, Buildable, Orientable; match fn {
} } impl StackSwitcher { #[cfg(feature = "3.10")] pub fn new() -> StackSwitcher { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_stack_switcher_new()).downcast_unchecked() } } #[cfg(feature = "3.10")] pub fn get_stack(&self) -> Option<Stack> { unsafe { from_glib_none(ffi::gtk_stack_switcher_get_stack(self.to_glib_none().0)) } } #[cfg(feature = "3.10")] pub fn set_stack(&self, stack: Option<&Stack>) { unsafe { ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.to_glib_none().0); } } }
get_type => || ffi::gtk_stack_switcher_get_type(),
random_line_split
paths.rs
use std::env; use std::ffi::{OsStr, OsString}; use std::fs::{self, File, OpenOptions}; use std::io; use std::io::prelude::*; use std::iter; use std::path::{Component, Path, PathBuf}; use filetime::FileTime; use crate::util::errors::{CargoResult, CargoResultExt}; pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> { env::join_paths(paths.iter()) .chain_err(|| { let paths = paths.iter().map(Path::new).collect::<Vec<_>>(); format!("failed to join path array: {:?}", paths) }) .chain_err(|| { format!( "failed to join search paths together\n\ Does ${} have an unterminated quote character?", env ) }) } pub fn dylib_path_envvar() -> &'static str { if cfg!(windows) { "PATH" } else if cfg!(target_os = "macos") { // When loading and linking a dynamic library or bundle, dlopen // searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and // DYLD_FALLBACK_LIBRARY_PATH. // In the Mach-O format, a dynamic library has an "install path." // Clients linking against the library record this path, and the // dynamic linker, dyld, uses it to locate the library. // dyld searches DYLD_LIBRARY_PATH *before* the install path. // dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot // find the library in the install path. // Setting DYLD_LIBRARY_PATH can easily have unintended // consequences. // // Also, DYLD_LIBRARY_PATH appears to have significant performance // penalty starting in 10.13. Cargo's testsuite ran more than twice as // slow with it on CI. "DYLD_FALLBACK_LIBRARY_PATH" } else { "LD_LIBRARY_PATH" } } pub fn dylib_path() -> Vec<PathBuf> { match env::var_os(dylib_path_envvar()) { Some(var) => env::split_paths(&var).collect(), None => Vec::new(), } } pub fn normalize_path(path: &Path) -> PathBuf { let mut components = path.components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { components.next(); PathBuf::from(c.as_os_str()) } else { PathBuf::new() }; for component in components { match component { Component::Prefix(..) => unreachable!(), Component::RootDir => { ret.push(component.as_os_str()); } Component::CurDir => {} Component::ParentDir => { ret.pop(); } Component::Normal(c) => { ret.push(c); } } } ret } pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> { if exec.components().count() == 1 { let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?; let candidates = env::split_paths(&paths).flat_map(|path| { let candidate = path.join(&exec); let with_exe = if env::consts::EXE_EXTENSION == "" { None } else { Some(candidate.with_extension(env::consts::EXE_EXTENSION)) }; iter::once(candidate).chain(with_exe) }); for candidate in candidates { if candidate.is_file() { // PATH may have a component like "." in it, so we still need to // canonicalize. return Ok(candidate.canonicalize()?); } } anyhow::bail!("no executable for `{}` found in PATH", exec.display()) } else { Ok(exec.canonicalize()?) } } pub fn read(path: &Path) -> CargoResult<String> { match String::from_utf8(read_bytes(path)?) { Ok(s) => Ok(s), Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()), } } pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> { let res = (|| -> CargoResult<_> { let mut ret = Vec::new(); let mut f = File::open(path)?; if let Ok(m) = f.metadata() { ret.reserve(m.len() as usize + 1); } f.read_to_end(&mut ret)?; Ok(ret) })() .chain_err(|| format!("failed to read `{}`", path.display()))?; Ok(res) } pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> { (|| -> CargoResult<()> { let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.display()))?; Ok(()) } pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> { (|| -> CargoResult<()> { let contents = contents.as_ref(); let mut f = OpenOptions::new() .read(true) .write(true) .create(true) .open(&path)?; let mut orig = Vec::new(); f.read_to_end(&mut orig)?; if orig!= contents { f.set_len(0)?; f.seek(io::SeekFrom::Start(0))?; f.write_all(contents)?; } Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?; Ok(()) } pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> { (|| -> CargoResult<()> { let mut f = OpenOptions::new() .write(true) .append(true) .create(true) .open(path)?; f.write_all(contents)?; Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.display()))?; Ok(()) } pub fn mtime(path: &Path) -> CargoResult<FileTime> { let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?; Ok(FileTime::from_last_modification_time(&meta)) } /// Record the current time on the filesystem (using the filesystem's clock) /// using a file at the given directory. Returns the current time. pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> { // note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient, // then this can be removed. let timestamp = path.join("invoked.timestamp"); write( &timestamp, b"This file has an mtime of when this was started.", )?; let ft = mtime(&timestamp)?; log::debug!("invocation time for {:?} is {}", path, ft); Ok(ft) } #[cfg(unix)] pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> { use std::os::unix::prelude::*; Ok(path.as_os_str().as_bytes()) } #[cfg(windows)] pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> { match path.as_os_str().to_str() { Some(s) => Ok(s.as_bytes()), None => Err(anyhow::format_err!( "invalid non-unicode path: {}", path.display() )), } } #[cfg(unix)] pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> { use std::os::unix::prelude::*; Ok(PathBuf::from(OsStr::from_bytes(bytes))) } #[cfg(windows)] pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> { use std::str; match str::from_utf8(bytes) { Ok(s) => Ok(PathBuf::from(s)), Err(..) => Err(anyhow::format_err!("invalid non-unicode path")), } } pub fn ancestors(path: &Path) -> PathAncestors<'_> { PathAncestors::new(path) } pub struct PathAncestors<'a> { current: Option<&'a Path>, stop_at: Option<PathBuf>, } impl<'a> PathAncestors<'a> { fn
(path: &Path) -> PathAncestors<'_> { PathAncestors { current: Some(path), //HACK: avoid reading `~/.cargo/config` when testing Cargo itself. stop_at: env::var("__CARGO_TEST_ROOT").ok().map(PathBuf::from), } } } impl<'a> Iterator for PathAncestors<'a> { type Item = &'a Path; fn next(&mut self) -> Option<&'a Path> { if let Some(path) = self.current { self.current = path.parent(); if let Some(ref stop_at) = self.stop_at { if path == stop_at { self.current = None; } } Some(path) } else { None } } } pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> { _create_dir_all(p.as_ref()) } fn _create_dir_all(p: &Path) -> CargoResult<()> { fs::create_dir_all(p).chain_err(|| format!("failed to create directory `{}`", p.display()))?; Ok(()) } pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_dir_all(p.as_ref()) } fn _remove_dir_all(p: &Path) -> CargoResult<()> { if p.symlink_metadata()?.file_type().is_symlink() { return remove_file(p); } let entries = p .read_dir() .chain_err(|| format!("failed to read directory `{}`", p.display()))?; for entry in entries { let entry = entry?; let path = entry.path(); if entry.file_type()?.is_dir() { remove_dir_all(&path)?; } else { remove_file(&path)?; } } remove_dir(&p) } pub fn remove_dir<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_dir(p.as_ref()) } fn _remove_dir(p: &Path) -> CargoResult<()> { fs::remove_dir(p).chain_err(|| format!("failed to remove directory `{}`", p.display()))?; Ok(()) } pub fn remove_file<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_file(p.as_ref()) } fn _remove_file(p: &Path) -> CargoResult<()> { let mut err = match fs::remove_file(p) { Ok(()) => return Ok(()), Err(e) => e, }; if err.kind() == io::ErrorKind::PermissionDenied && set_not_readonly(p).unwrap_or(false) { match fs::remove_file(p) { Ok(()) => return Ok(()), Err(e) => err = e, } } Err(err).chain_err(|| format!("failed to remove file `{}`", p.display()))?; Ok(()) } fn set_not_readonly(p: &Path) -> io::Result<bool> { let mut perms = p.metadata()?.permissions(); if!perms.readonly() { return Ok(false); } perms.set_readonly(false); fs::set_permissions(p, perms)?; Ok(true) } /// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it. /// /// If the destination already exists, it is removed before linking. pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> CargoResult<()> { let src = src.as_ref(); let dst = dst.as_ref(); _link_or_copy(src, dst) } fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> { log::debug!("linking {} to {}", src.display(), dst.display()); if same_file::is_same_file(src, dst).unwrap_or(false) { return Ok(()); } // NB: we can't use dst.exists(), as if dst is a broken symlink, // dst.exists() will return false. This is problematic, as we still need to // unlink dst in this case. symlink_metadata(dst).is_ok() will tell us // whether dst exists *without* following symlinks, which is what we want. if fs::symlink_metadata(dst).is_ok() { remove_file(&dst)?; } let link_result = if src.is_dir() { #[cfg(target_os = "redox")] use std::os::redox::fs::symlink; #[cfg(unix)] use std::os::unix::fs::symlink; #[cfg(windows)] // FIXME: This should probably panic or have a copy fallback. Symlinks // are not supported in all windows environments. Currently symlinking // is only used for.dSYM directories on macos, but this shouldn't be // accidentally relied upon. use std::os::windows::fs::symlink_dir as symlink; let dst_dir = dst.parent().unwrap(); let src = if src.starts_with(dst_dir) { src.strip_prefix(dst_dir).unwrap() } else { src }; symlink(src, dst) } else if env::var_os("__CARGO_COPY_DONT_LINK_DO_NOT_USE_THIS").is_some() { // This is a work-around for a bug in macOS 10.15. When running on // APFS, there seems to be a strange race condition with // Gatekeeper where it will forcefully kill a process launched via // `cargo run` with SIGKILL. Copying seems to avoid the problem. // This shouldn't affect anyone except Cargo's test suite because // it is very rare, and only seems to happen under heavy load and // rapidly creating lots of executables and running them. // See https://github.com/rust-lang/cargo/issues/7821 for the // gory details. fs::copy(src, dst).map(|_| ()) } else { fs::hard_link(src, dst) }; link_result .or_else(|err| { log::debug!("link failed {}. falling back to fs::copy", err); fs::copy(src, dst).map(|_| ()) }) .chain_err(|| { format!( "failed to link or copy `{}` to `{}`", src.display(), dst.display() ) })?; Ok(()) }
new
identifier_name
paths.rs
use std::env; use std::ffi::{OsStr, OsString}; use std::fs::{self, File, OpenOptions}; use std::io; use std::io::prelude::*; use std::iter; use std::path::{Component, Path, PathBuf}; use filetime::FileTime; use crate::util::errors::{CargoResult, CargoResultExt}; pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> { env::join_paths(paths.iter()) .chain_err(|| { let paths = paths.iter().map(Path::new).collect::<Vec<_>>(); format!("failed to join path array: {:?}", paths) }) .chain_err(|| { format!( "failed to join search paths together\n\ Does ${} have an unterminated quote character?", env ) }) } pub fn dylib_path_envvar() -> &'static str { if cfg!(windows) { "PATH" } else if cfg!(target_os = "macos") { // When loading and linking a dynamic library or bundle, dlopen // searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and // DYLD_FALLBACK_LIBRARY_PATH. // In the Mach-O format, a dynamic library has an "install path." // Clients linking against the library record this path, and the // dynamic linker, dyld, uses it to locate the library. // dyld searches DYLD_LIBRARY_PATH *before* the install path. // dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot // find the library in the install path. // Setting DYLD_LIBRARY_PATH can easily have unintended // consequences. // // Also, DYLD_LIBRARY_PATH appears to have significant performance // penalty starting in 10.13. Cargo's testsuite ran more than twice as // slow with it on CI. "DYLD_FALLBACK_LIBRARY_PATH" } else { "LD_LIBRARY_PATH" } } pub fn dylib_path() -> Vec<PathBuf> { match env::var_os(dylib_path_envvar()) { Some(var) => env::split_paths(&var).collect(), None => Vec::new(), } } pub fn normalize_path(path: &Path) -> PathBuf { let mut components = path.components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { components.next(); PathBuf::from(c.as_os_str()) } else { PathBuf::new() }; for component in components { match component { Component::Prefix(..) => unreachable!(), Component::RootDir => { ret.push(component.as_os_str()); } Component::CurDir => {} Component::ParentDir => { ret.pop(); } Component::Normal(c) => { ret.push(c); } } } ret } pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> { if exec.components().count() == 1 { let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?; let candidates = env::split_paths(&paths).flat_map(|path| { let candidate = path.join(&exec); let with_exe = if env::consts::EXE_EXTENSION == "" { None } else { Some(candidate.with_extension(env::consts::EXE_EXTENSION)) }; iter::once(candidate).chain(with_exe) }); for candidate in candidates { if candidate.is_file() { // PATH may have a component like "." in it, so we still need to // canonicalize. return Ok(candidate.canonicalize()?); } } anyhow::bail!("no executable for `{}` found in PATH", exec.display()) } else { Ok(exec.canonicalize()?) } } pub fn read(path: &Path) -> CargoResult<String> { match String::from_utf8(read_bytes(path)?) { Ok(s) => Ok(s), Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()), } } pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> { let res = (|| -> CargoResult<_> { let mut ret = Vec::new(); let mut f = File::open(path)?; if let Ok(m) = f.metadata() { ret.reserve(m.len() as usize + 1); } f.read_to_end(&mut ret)?; Ok(ret) })() .chain_err(|| format!("failed to read `{}`", path.display()))?; Ok(res) } pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> { (|| -> CargoResult<()> { let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.display()))?; Ok(()) } pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> { (|| -> CargoResult<()> { let contents = contents.as_ref(); let mut f = OpenOptions::new() .read(true) .write(true) .create(true) .open(&path)?; let mut orig = Vec::new(); f.read_to_end(&mut orig)?; if orig!= contents { f.set_len(0)?; f.seek(io::SeekFrom::Start(0))?; f.write_all(contents)?; } Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?; Ok(()) } pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> { (|| -> CargoResult<()> { let mut f = OpenOptions::new() .write(true) .append(true) .create(true) .open(path)?; f.write_all(contents)?; Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.display()))?; Ok(()) } pub fn mtime(path: &Path) -> CargoResult<FileTime> { let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?; Ok(FileTime::from_last_modification_time(&meta)) } /// Record the current time on the filesystem (using the filesystem's clock) /// using a file at the given directory. Returns the current time. pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime>
#[cfg(unix)] pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> { use std::os::unix::prelude::*; Ok(path.as_os_str().as_bytes()) } #[cfg(windows)] pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> { match path.as_os_str().to_str() { Some(s) => Ok(s.as_bytes()), None => Err(anyhow::format_err!( "invalid non-unicode path: {}", path.display() )), } } #[cfg(unix)] pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> { use std::os::unix::prelude::*; Ok(PathBuf::from(OsStr::from_bytes(bytes))) } #[cfg(windows)] pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> { use std::str; match str::from_utf8(bytes) { Ok(s) => Ok(PathBuf::from(s)), Err(..) => Err(anyhow::format_err!("invalid non-unicode path")), } } pub fn ancestors(path: &Path) -> PathAncestors<'_> { PathAncestors::new(path) } pub struct PathAncestors<'a> { current: Option<&'a Path>, stop_at: Option<PathBuf>, } impl<'a> PathAncestors<'a> { fn new(path: &Path) -> PathAncestors<'_> { PathAncestors { current: Some(path), //HACK: avoid reading `~/.cargo/config` when testing Cargo itself. stop_at: env::var("__CARGO_TEST_ROOT").ok().map(PathBuf::from), } } } impl<'a> Iterator for PathAncestors<'a> { type Item = &'a Path; fn next(&mut self) -> Option<&'a Path> { if let Some(path) = self.current { self.current = path.parent(); if let Some(ref stop_at) = self.stop_at { if path == stop_at { self.current = None; } } Some(path) } else { None } } } pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> { _create_dir_all(p.as_ref()) } fn _create_dir_all(p: &Path) -> CargoResult<()> { fs::create_dir_all(p).chain_err(|| format!("failed to create directory `{}`", p.display()))?; Ok(()) } pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_dir_all(p.as_ref()) } fn _remove_dir_all(p: &Path) -> CargoResult<()> { if p.symlink_metadata()?.file_type().is_symlink() { return remove_file(p); } let entries = p .read_dir() .chain_err(|| format!("failed to read directory `{}`", p.display()))?; for entry in entries { let entry = entry?; let path = entry.path(); if entry.file_type()?.is_dir() { remove_dir_all(&path)?; } else { remove_file(&path)?; } } remove_dir(&p) } pub fn remove_dir<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_dir(p.as_ref()) } fn _remove_dir(p: &Path) -> CargoResult<()> { fs::remove_dir(p).chain_err(|| format!("failed to remove directory `{}`", p.display()))?; Ok(()) } pub fn remove_file<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_file(p.as_ref()) } fn _remove_file(p: &Path) -> CargoResult<()> { let mut err = match fs::remove_file(p) { Ok(()) => return Ok(()), Err(e) => e, }; if err.kind() == io::ErrorKind::PermissionDenied && set_not_readonly(p).unwrap_or(false) { match fs::remove_file(p) { Ok(()) => return Ok(()), Err(e) => err = e, } } Err(err).chain_err(|| format!("failed to remove file `{}`", p.display()))?; Ok(()) } fn set_not_readonly(p: &Path) -> io::Result<bool> { let mut perms = p.metadata()?.permissions(); if!perms.readonly() { return Ok(false); } perms.set_readonly(false); fs::set_permissions(p, perms)?; Ok(true) } /// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it. /// /// If the destination already exists, it is removed before linking. pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> CargoResult<()> { let src = src.as_ref(); let dst = dst.as_ref(); _link_or_copy(src, dst) } fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> { log::debug!("linking {} to {}", src.display(), dst.display()); if same_file::is_same_file(src, dst).unwrap_or(false) { return Ok(()); } // NB: we can't use dst.exists(), as if dst is a broken symlink, // dst.exists() will return false. This is problematic, as we still need to // unlink dst in this case. symlink_metadata(dst).is_ok() will tell us // whether dst exists *without* following symlinks, which is what we want. if fs::symlink_metadata(dst).is_ok() { remove_file(&dst)?; } let link_result = if src.is_dir() { #[cfg(target_os = "redox")] use std::os::redox::fs::symlink; #[cfg(unix)] use std::os::unix::fs::symlink; #[cfg(windows)] // FIXME: This should probably panic or have a copy fallback. Symlinks // are not supported in all windows environments. Currently symlinking // is only used for.dSYM directories on macos, but this shouldn't be // accidentally relied upon. use std::os::windows::fs::symlink_dir as symlink; let dst_dir = dst.parent().unwrap(); let src = if src.starts_with(dst_dir) { src.strip_prefix(dst_dir).unwrap() } else { src }; symlink(src, dst) } else if env::var_os("__CARGO_COPY_DONT_LINK_DO_NOT_USE_THIS").is_some() { // This is a work-around for a bug in macOS 10.15. When running on // APFS, there seems to be a strange race condition with // Gatekeeper where it will forcefully kill a process launched via // `cargo run` with SIGKILL. Copying seems to avoid the problem. // This shouldn't affect anyone except Cargo's test suite because // it is very rare, and only seems to happen under heavy load and // rapidly creating lots of executables and running them. // See https://github.com/rust-lang/cargo/issues/7821 for the // gory details. fs::copy(src, dst).map(|_| ()) } else { fs::hard_link(src, dst) }; link_result .or_else(|err| { log::debug!("link failed {}. falling back to fs::copy", err); fs::copy(src, dst).map(|_| ()) }) .chain_err(|| { format!( "failed to link or copy `{}` to `{}`", src.display(), dst.display() ) })?; Ok(()) }
{ // note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient, // then this can be removed. let timestamp = path.join("invoked.timestamp"); write( &timestamp, b"This file has an mtime of when this was started.", )?; let ft = mtime(&timestamp)?; log::debug!("invocation time for {:?} is {}", path, ft); Ok(ft) }
identifier_body
paths.rs
use std::env; use std::ffi::{OsStr, OsString}; use std::fs::{self, File, OpenOptions}; use std::io; use std::io::prelude::*; use std::iter; use std::path::{Component, Path, PathBuf}; use filetime::FileTime; use crate::util::errors::{CargoResult, CargoResultExt}; pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> { env::join_paths(paths.iter()) .chain_err(|| { let paths = paths.iter().map(Path::new).collect::<Vec<_>>(); format!("failed to join path array: {:?}", paths) }) .chain_err(|| { format!( "failed to join search paths together\n\ Does ${} have an unterminated quote character?", env ) }) } pub fn dylib_path_envvar() -> &'static str { if cfg!(windows) { "PATH" } else if cfg!(target_os = "macos") { // When loading and linking a dynamic library or bundle, dlopen // searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and // DYLD_FALLBACK_LIBRARY_PATH. // In the Mach-O format, a dynamic library has an "install path." // Clients linking against the library record this path, and the // dynamic linker, dyld, uses it to locate the library. // dyld searches DYLD_LIBRARY_PATH *before* the install path. // dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot // find the library in the install path. // Setting DYLD_LIBRARY_PATH can easily have unintended // consequences. // // Also, DYLD_LIBRARY_PATH appears to have significant performance // penalty starting in 10.13. Cargo's testsuite ran more than twice as // slow with it on CI. "DYLD_FALLBACK_LIBRARY_PATH" } else { "LD_LIBRARY_PATH" } } pub fn dylib_path() -> Vec<PathBuf> { match env::var_os(dylib_path_envvar()) { Some(var) => env::split_paths(&var).collect(), None => Vec::new(), } } pub fn normalize_path(path: &Path) -> PathBuf { let mut components = path.components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { components.next(); PathBuf::from(c.as_os_str()) } else { PathBuf::new() }; for component in components { match component { Component::Prefix(..) => unreachable!(), Component::RootDir => { ret.push(component.as_os_str()); } Component::CurDir => {} Component::ParentDir => { ret.pop(); } Component::Normal(c) => { ret.push(c); } } } ret } pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> { if exec.components().count() == 1 { let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?; let candidates = env::split_paths(&paths).flat_map(|path| { let candidate = path.join(&exec); let with_exe = if env::consts::EXE_EXTENSION == "" { None } else { Some(candidate.with_extension(env::consts::EXE_EXTENSION)) }; iter::once(candidate).chain(with_exe) }); for candidate in candidates { if candidate.is_file() { // PATH may have a component like "." in it, so we still need to // canonicalize. return Ok(candidate.canonicalize()?); } } anyhow::bail!("no executable for `{}` found in PATH", exec.display()) } else { Ok(exec.canonicalize()?) } } pub fn read(path: &Path) -> CargoResult<String> { match String::from_utf8(read_bytes(path)?) { Ok(s) => Ok(s), Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()), } } pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> { let res = (|| -> CargoResult<_> { let mut ret = Vec::new(); let mut f = File::open(path)?; if let Ok(m) = f.metadata() { ret.reserve(m.len() as usize + 1); } f.read_to_end(&mut ret)?; Ok(ret) })() .chain_err(|| format!("failed to read `{}`", path.display()))?; Ok(res) } pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> { (|| -> CargoResult<()> { let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.display()))?; Ok(()) } pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> { (|| -> CargoResult<()> { let contents = contents.as_ref(); let mut f = OpenOptions::new() .read(true) .write(true) .create(true) .open(&path)?; let mut orig = Vec::new(); f.read_to_end(&mut orig)?; if orig!= contents { f.set_len(0)?;
.chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?; Ok(()) } pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> { (|| -> CargoResult<()> { let mut f = OpenOptions::new() .write(true) .append(true) .create(true) .open(path)?; f.write_all(contents)?; Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.display()))?; Ok(()) } pub fn mtime(path: &Path) -> CargoResult<FileTime> { let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?; Ok(FileTime::from_last_modification_time(&meta)) } /// Record the current time on the filesystem (using the filesystem's clock) /// using a file at the given directory. Returns the current time. pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> { // note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient, // then this can be removed. let timestamp = path.join("invoked.timestamp"); write( &timestamp, b"This file has an mtime of when this was started.", )?; let ft = mtime(&timestamp)?; log::debug!("invocation time for {:?} is {}", path, ft); Ok(ft) } #[cfg(unix)] pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> { use std::os::unix::prelude::*; Ok(path.as_os_str().as_bytes()) } #[cfg(windows)] pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> { match path.as_os_str().to_str() { Some(s) => Ok(s.as_bytes()), None => Err(anyhow::format_err!( "invalid non-unicode path: {}", path.display() )), } } #[cfg(unix)] pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> { use std::os::unix::prelude::*; Ok(PathBuf::from(OsStr::from_bytes(bytes))) } #[cfg(windows)] pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> { use std::str; match str::from_utf8(bytes) { Ok(s) => Ok(PathBuf::from(s)), Err(..) => Err(anyhow::format_err!("invalid non-unicode path")), } } pub fn ancestors(path: &Path) -> PathAncestors<'_> { PathAncestors::new(path) } pub struct PathAncestors<'a> { current: Option<&'a Path>, stop_at: Option<PathBuf>, } impl<'a> PathAncestors<'a> { fn new(path: &Path) -> PathAncestors<'_> { PathAncestors { current: Some(path), //HACK: avoid reading `~/.cargo/config` when testing Cargo itself. stop_at: env::var("__CARGO_TEST_ROOT").ok().map(PathBuf::from), } } } impl<'a> Iterator for PathAncestors<'a> { type Item = &'a Path; fn next(&mut self) -> Option<&'a Path> { if let Some(path) = self.current { self.current = path.parent(); if let Some(ref stop_at) = self.stop_at { if path == stop_at { self.current = None; } } Some(path) } else { None } } } pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> { _create_dir_all(p.as_ref()) } fn _create_dir_all(p: &Path) -> CargoResult<()> { fs::create_dir_all(p).chain_err(|| format!("failed to create directory `{}`", p.display()))?; Ok(()) } pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_dir_all(p.as_ref()) } fn _remove_dir_all(p: &Path) -> CargoResult<()> { if p.symlink_metadata()?.file_type().is_symlink() { return remove_file(p); } let entries = p .read_dir() .chain_err(|| format!("failed to read directory `{}`", p.display()))?; for entry in entries { let entry = entry?; let path = entry.path(); if entry.file_type()?.is_dir() { remove_dir_all(&path)?; } else { remove_file(&path)?; } } remove_dir(&p) } pub fn remove_dir<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_dir(p.as_ref()) } fn _remove_dir(p: &Path) -> CargoResult<()> { fs::remove_dir(p).chain_err(|| format!("failed to remove directory `{}`", p.display()))?; Ok(()) } pub fn remove_file<P: AsRef<Path>>(p: P) -> CargoResult<()> { _remove_file(p.as_ref()) } fn _remove_file(p: &Path) -> CargoResult<()> { let mut err = match fs::remove_file(p) { Ok(()) => return Ok(()), Err(e) => e, }; if err.kind() == io::ErrorKind::PermissionDenied && set_not_readonly(p).unwrap_or(false) { match fs::remove_file(p) { Ok(()) => return Ok(()), Err(e) => err = e, } } Err(err).chain_err(|| format!("failed to remove file `{}`", p.display()))?; Ok(()) } fn set_not_readonly(p: &Path) -> io::Result<bool> { let mut perms = p.metadata()?.permissions(); if!perms.readonly() { return Ok(false); } perms.set_readonly(false); fs::set_permissions(p, perms)?; Ok(true) } /// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it. /// /// If the destination already exists, it is removed before linking. pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> CargoResult<()> { let src = src.as_ref(); let dst = dst.as_ref(); _link_or_copy(src, dst) } fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> { log::debug!("linking {} to {}", src.display(), dst.display()); if same_file::is_same_file(src, dst).unwrap_or(false) { return Ok(()); } // NB: we can't use dst.exists(), as if dst is a broken symlink, // dst.exists() will return false. This is problematic, as we still need to // unlink dst in this case. symlink_metadata(dst).is_ok() will tell us // whether dst exists *without* following symlinks, which is what we want. if fs::symlink_metadata(dst).is_ok() { remove_file(&dst)?; } let link_result = if src.is_dir() { #[cfg(target_os = "redox")] use std::os::redox::fs::symlink; #[cfg(unix)] use std::os::unix::fs::symlink; #[cfg(windows)] // FIXME: This should probably panic or have a copy fallback. Symlinks // are not supported in all windows environments. Currently symlinking // is only used for.dSYM directories on macos, but this shouldn't be // accidentally relied upon. use std::os::windows::fs::symlink_dir as symlink; let dst_dir = dst.parent().unwrap(); let src = if src.starts_with(dst_dir) { src.strip_prefix(dst_dir).unwrap() } else { src }; symlink(src, dst) } else if env::var_os("__CARGO_COPY_DONT_LINK_DO_NOT_USE_THIS").is_some() { // This is a work-around for a bug in macOS 10.15. When running on // APFS, there seems to be a strange race condition with // Gatekeeper where it will forcefully kill a process launched via // `cargo run` with SIGKILL. Copying seems to avoid the problem. // This shouldn't affect anyone except Cargo's test suite because // it is very rare, and only seems to happen under heavy load and // rapidly creating lots of executables and running them. // See https://github.com/rust-lang/cargo/issues/7821 for the // gory details. fs::copy(src, dst).map(|_| ()) } else { fs::hard_link(src, dst) }; link_result .or_else(|err| { log::debug!("link failed {}. falling back to fs::copy", err); fs::copy(src, dst).map(|_| ()) }) .chain_err(|| { format!( "failed to link or copy `{}` to `{}`", src.display(), dst.display() ) })?; Ok(()) }
f.seek(io::SeekFrom::Start(0))?; f.write_all(contents)?; } Ok(()) })()
random_line_split
trait-implementations.rs
// compile-flags:-Zprint-mono-items=eager #![deny(dead_code)] #![feature(start)] pub trait SomeTrait { fn foo(&self); fn bar<T>(&self, x: T); } impl SomeTrait for i64 { //~ MONO_ITEM fn <i64 as SomeTrait>::foo fn foo(&self) {} fn bar<T>(&self, _: T) {} }
fn bar<T>(&self, _: T) {} } pub trait SomeGenericTrait<T> { fn foo(&self, x: T); fn bar<T2>(&self, x: T, y: T2); } // Concrete impl of generic trait impl SomeGenericTrait<u32> for f64 { //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo fn foo(&self, _: u32) {} fn bar<T2>(&self, _: u32, _: T2) {} } // Generic impl of generic trait impl<T> SomeGenericTrait<T> for f32 { fn foo(&self, _: T) {} fn bar<T2>(&self, _: T, _: T2) {} } //~ MONO_ITEM fn start #[start] fn start(_: isize, _: *const *const u8) -> isize { //~ MONO_ITEM fn <i32 as SomeTrait>::bar::<char> 0i32.bar('x'); //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<&str> 0f64.bar(0u32, "&str"); //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<()> 0f64.bar(0u32, ()); //~ MONO_ITEM fn <f32 as SomeGenericTrait<char>>::foo 0f32.foo('x'); //~ MONO_ITEM fn <f32 as SomeGenericTrait<i64>>::foo 0f32.foo(-1i64); //~ MONO_ITEM fn <f32 as SomeGenericTrait<u32>>::bar::<()> 0f32.bar(0u32, ()); //~ MONO_ITEM fn <f32 as SomeGenericTrait<&str>>::bar::<&str> 0f32.bar("&str", "&str"); 0 }
impl SomeTrait for i32 { //~ MONO_ITEM fn <i32 as SomeTrait>::foo fn foo(&self) {}
random_line_split
trait-implementations.rs
// compile-flags:-Zprint-mono-items=eager #![deny(dead_code)] #![feature(start)] pub trait SomeTrait { fn foo(&self); fn bar<T>(&self, x: T); } impl SomeTrait for i64 { //~ MONO_ITEM fn <i64 as SomeTrait>::foo fn foo(&self) {} fn bar<T>(&self, _: T) {} } impl SomeTrait for i32 { //~ MONO_ITEM fn <i32 as SomeTrait>::foo fn foo(&self) {} fn
<T>(&self, _: T) {} } pub trait SomeGenericTrait<T> { fn foo(&self, x: T); fn bar<T2>(&self, x: T, y: T2); } // Concrete impl of generic trait impl SomeGenericTrait<u32> for f64 { //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo fn foo(&self, _: u32) {} fn bar<T2>(&self, _: u32, _: T2) {} } // Generic impl of generic trait impl<T> SomeGenericTrait<T> for f32 { fn foo(&self, _: T) {} fn bar<T2>(&self, _: T, _: T2) {} } //~ MONO_ITEM fn start #[start] fn start(_: isize, _: *const *const u8) -> isize { //~ MONO_ITEM fn <i32 as SomeTrait>::bar::<char> 0i32.bar('x'); //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<&str> 0f64.bar(0u32, "&str"); //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<()> 0f64.bar(0u32, ()); //~ MONO_ITEM fn <f32 as SomeGenericTrait<char>>::foo 0f32.foo('x'); //~ MONO_ITEM fn <f32 as SomeGenericTrait<i64>>::foo 0f32.foo(-1i64); //~ MONO_ITEM fn <f32 as SomeGenericTrait<u32>>::bar::<()> 0f32.bar(0u32, ()); //~ MONO_ITEM fn <f32 as SomeGenericTrait<&str>>::bar::<&str> 0f32.bar("&str", "&str"); 0 }
bar
identifier_name
trait-implementations.rs
// compile-flags:-Zprint-mono-items=eager #![deny(dead_code)] #![feature(start)] pub trait SomeTrait { fn foo(&self); fn bar<T>(&self, x: T); } impl SomeTrait for i64 { //~ MONO_ITEM fn <i64 as SomeTrait>::foo fn foo(&self)
fn bar<T>(&self, _: T) {} } impl SomeTrait for i32 { //~ MONO_ITEM fn <i32 as SomeTrait>::foo fn foo(&self) {} fn bar<T>(&self, _: T) {} } pub trait SomeGenericTrait<T> { fn foo(&self, x: T); fn bar<T2>(&self, x: T, y: T2); } // Concrete impl of generic trait impl SomeGenericTrait<u32> for f64 { //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo fn foo(&self, _: u32) {} fn bar<T2>(&self, _: u32, _: T2) {} } // Generic impl of generic trait impl<T> SomeGenericTrait<T> for f32 { fn foo(&self, _: T) {} fn bar<T2>(&self, _: T, _: T2) {} } //~ MONO_ITEM fn start #[start] fn start(_: isize, _: *const *const u8) -> isize { //~ MONO_ITEM fn <i32 as SomeTrait>::bar::<char> 0i32.bar('x'); //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<&str> 0f64.bar(0u32, "&str"); //~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<()> 0f64.bar(0u32, ()); //~ MONO_ITEM fn <f32 as SomeGenericTrait<char>>::foo 0f32.foo('x'); //~ MONO_ITEM fn <f32 as SomeGenericTrait<i64>>::foo 0f32.foo(-1i64); //~ MONO_ITEM fn <f32 as SomeGenericTrait<u32>>::bar::<()> 0f32.bar(0u32, ()); //~ MONO_ITEM fn <f32 as SomeGenericTrait<&str>>::bar::<&str> 0f32.bar("&str", "&str"); 0 }
{}
identifier_body
drop_flag_effects.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::mir::{self, Mir, Location}; use rustc::ty::{self, TyCtxt}; use util::elaborate_drops::DropFlagState; use super::{MoveDataParamEnv}; use super::indexes::MovePathIndex; use super::move_paths::{MoveData, LookupResult, InitKind}; pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>, path: MovePathIndex, mut cond: F) -> Option<MovePathIndex> where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool { let mut next_child = move_data.move_paths[path].first_child; while let Some(child_index) = next_child { match move_data.move_paths[child_index].place { mir::Place::Projection(ref proj) => { if cond(proj) { return Some(child_index) } } _ => {} } next_child = move_data.move_paths[child_index].next_sibling; } None } /// When enumerating the child fragments of a path, don't recurse into /// paths (1.) past arrays, slices, and pointers, nor (2.) into a type /// that implements `Drop`. /// /// Places behind references or arrays are not tracked by elaboration /// and are always assumed to be initialized when accessible. As /// references and indexes can be reseated, trying to track them can /// only lead to trouble. /// /// Places behind ADT's with a Drop impl are not tracked by /// elaboration since they can never have a drop-flag state that /// differs from that of the parent with the Drop impl. /// /// In both cases, the contents can only be accessed if and only if /// their parents are initialized. This implies for example that there /// is no need to maintain separate drop flags to track such state. /// /// FIXME: we have to do something for moving slice patterns. fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, place: &mir::Place<'tcx>) -> bool { let ty = place.ty(mir, tcx).to_ty(tcx); match ty.sty { ty::Array(..) => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", place, ty); false } ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", place, ty); true } ty::Adt(def, _) if (def.has_dtor(tcx) &&!def.is_box()) || def.is_union() => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", place, ty); true } _ => { false } } } pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, lookup_result: LookupResult, each_child: F) where F: FnMut(MovePathIndex) { match lookup_result { LookupResult::Parent(..) => { // access to untracked value - do not touch children } LookupResult::Exact(e) => { on_all_children_bits(tcx, mir, move_data, e, each_child) } } } pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { fn
<'a, 'gcx, 'tcx>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, path: MovePathIndex) -> bool { place_contents_drop_state_cannot_differ( tcx, mir, &move_data.move_paths[path].place) } fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, each_child: &mut F) where F: FnMut(MovePathIndex) { each_child(move_path_index); if is_terminal_path(tcx, mir, move_data, move_path_index) { return } let mut next_child_index = move_data.move_paths[move_path_index].first_child; while let Some(child_index) = next_child_index { on_all_children_bits(tcx, mir, move_data, child_index, each_child); next_child_index = move_data.move_paths[child_index].next_sibling; } } on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child); } pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, path: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| { let place = &ctxt.move_data.move_paths[path].place; let ty = place.ty(mir, tcx).to_ty(tcx); debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty); let gcx = tcx.global_tcx(); let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap(); if erased_ty.needs_drop(gcx, ctxt.param_env) { each_child(child); } else { debug!("on_all_drop_children_bits - skipping") } }) } pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; for arg in mir.args_iter() { let place = mir::Place::Local(arg); let lookup_result = move_data.rev_lookup.find(&place); on_lookup_result_bits(tcx, mir, move_data, lookup_result, |mpi| callback(mpi, DropFlagState::Present)); } } pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; debug!("drop_flag_effects_for_location({:?})", loc); // first, move out of the RHS for mi in &move_data.loc_map[loc] { let path = mi.move_path_index(move_data); debug!("moving out of path {:?}", move_data.move_paths[path]); on_all_children_bits(tcx, mir, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) } debug!("drop_flag_effects: assignment for location({:?})", loc); for_location_inits( tcx, mir, move_data, loc, |mpi| callback(mpi, DropFlagState::Present) ); } pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex) { for ii in &move_data.init_loc_map[loc] { let init = move_data.inits[*ii]; match init.kind { InitKind::Deep => { let path = init.path; on_all_children_bits(tcx, mir, move_data, path, &mut callback) }, InitKind::Shallow => { let mpi = init.path; callback(mpi); } InitKind::NonPanicPathOnly => (), } } }
is_terminal_path
identifier_name
drop_flag_effects.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::mir::{self, Mir, Location}; use rustc::ty::{self, TyCtxt}; use util::elaborate_drops::DropFlagState; use super::{MoveDataParamEnv}; use super::indexes::MovePathIndex; use super::move_paths::{MoveData, LookupResult, InitKind}; pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>, path: MovePathIndex, mut cond: F) -> Option<MovePathIndex> where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool { let mut next_child = move_data.move_paths[path].first_child; while let Some(child_index) = next_child { match move_data.move_paths[child_index].place { mir::Place::Projection(ref proj) => { if cond(proj) { return Some(child_index) } } _ => {} } next_child = move_data.move_paths[child_index].next_sibling; } None } /// When enumerating the child fragments of a path, don't recurse into /// paths (1.) past arrays, slices, and pointers, nor (2.) into a type /// that implements `Drop`. /// /// Places behind references or arrays are not tracked by elaboration /// and are always assumed to be initialized when accessible. As /// references and indexes can be reseated, trying to track them can /// only lead to trouble. /// /// Places behind ADT's with a Drop impl are not tracked by /// elaboration since they can never have a drop-flag state that /// differs from that of the parent with the Drop impl. /// /// In both cases, the contents can only be accessed if and only if /// their parents are initialized. This implies for example that there /// is no need to maintain separate drop flags to track such state. /// /// FIXME: we have to do something for moving slice patterns. fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, place: &mir::Place<'tcx>) -> bool { let ty = place.ty(mir, tcx).to_ty(tcx); match ty.sty { ty::Array(..) =>
ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", place, ty); true } ty::Adt(def, _) if (def.has_dtor(tcx) &&!def.is_box()) || def.is_union() => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", place, ty); true } _ => { false } } } pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, lookup_result: LookupResult, each_child: F) where F: FnMut(MovePathIndex) { match lookup_result { LookupResult::Parent(..) => { // access to untracked value - do not touch children } LookupResult::Exact(e) => { on_all_children_bits(tcx, mir, move_data, e, each_child) } } } pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { fn is_terminal_path<'a, 'gcx, 'tcx>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, path: MovePathIndex) -> bool { place_contents_drop_state_cannot_differ( tcx, mir, &move_data.move_paths[path].place) } fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, each_child: &mut F) where F: FnMut(MovePathIndex) { each_child(move_path_index); if is_terminal_path(tcx, mir, move_data, move_path_index) { return } let mut next_child_index = move_data.move_paths[move_path_index].first_child; while let Some(child_index) = next_child_index { on_all_children_bits(tcx, mir, move_data, child_index, each_child); next_child_index = move_data.move_paths[child_index].next_sibling; } } on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child); } pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, path: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| { let place = &ctxt.move_data.move_paths[path].place; let ty = place.ty(mir, tcx).to_ty(tcx); debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty); let gcx = tcx.global_tcx(); let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap(); if erased_ty.needs_drop(gcx, ctxt.param_env) { each_child(child); } else { debug!("on_all_drop_children_bits - skipping") } }) } pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; for arg in mir.args_iter() { let place = mir::Place::Local(arg); let lookup_result = move_data.rev_lookup.find(&place); on_lookup_result_bits(tcx, mir, move_data, lookup_result, |mpi| callback(mpi, DropFlagState::Present)); } } pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; debug!("drop_flag_effects_for_location({:?})", loc); // first, move out of the RHS for mi in &move_data.loc_map[loc] { let path = mi.move_path_index(move_data); debug!("moving out of path {:?}", move_data.move_paths[path]); on_all_children_bits(tcx, mir, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) } debug!("drop_flag_effects: assignment for location({:?})", loc); for_location_inits( tcx, mir, move_data, loc, |mpi| callback(mpi, DropFlagState::Present) ); } pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex) { for ii in &move_data.init_loc_map[loc] { let init = move_data.inits[*ii]; match init.kind { InitKind::Deep => { let path = init.path; on_all_children_bits(tcx, mir, move_data, path, &mut callback) }, InitKind::Shallow => { let mpi = init.path; callback(mpi); } InitKind::NonPanicPathOnly => (), } } }
{ debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", place, ty); false }
conditional_block
drop_flag_effects.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::mir::{self, Mir, Location}; use rustc::ty::{self, TyCtxt}; use util::elaborate_drops::DropFlagState; use super::{MoveDataParamEnv}; use super::indexes::MovePathIndex; use super::move_paths::{MoveData, LookupResult, InitKind}; pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>, path: MovePathIndex, mut cond: F) -> Option<MovePathIndex> where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool { let mut next_child = move_data.move_paths[path].first_child; while let Some(child_index) = next_child { match move_data.move_paths[child_index].place { mir::Place::Projection(ref proj) => { if cond(proj) { return Some(child_index) } } _ => {} } next_child = move_data.move_paths[child_index].next_sibling; } None } /// When enumerating the child fragments of a path, don't recurse into /// paths (1.) past arrays, slices, and pointers, nor (2.) into a type /// that implements `Drop`. /// /// Places behind references or arrays are not tracked by elaboration /// and are always assumed to be initialized when accessible. As /// references and indexes can be reseated, trying to track them can /// only lead to trouble. /// /// Places behind ADT's with a Drop impl are not tracked by /// elaboration since they can never have a drop-flag state that /// differs from that of the parent with the Drop impl. /// /// In both cases, the contents can only be accessed if and only if /// their parents are initialized. This implies for example that there /// is no need to maintain separate drop flags to track such state. /// /// FIXME: we have to do something for moving slice patterns. fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, place: &mir::Place<'tcx>) -> bool
} } } pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, lookup_result: LookupResult, each_child: F) where F: FnMut(MovePathIndex) { match lookup_result { LookupResult::Parent(..) => { // access to untracked value - do not touch children } LookupResult::Exact(e) => { on_all_children_bits(tcx, mir, move_data, e, each_child) } } } pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { fn is_terminal_path<'a, 'gcx, 'tcx>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, path: MovePathIndex) -> bool { place_contents_drop_state_cannot_differ( tcx, mir, &move_data.move_paths[path].place) } fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, each_child: &mut F) where F: FnMut(MovePathIndex) { each_child(move_path_index); if is_terminal_path(tcx, mir, move_data, move_path_index) { return } let mut next_child_index = move_data.move_paths[move_path_index].first_child; while let Some(child_index) = next_child_index { on_all_children_bits(tcx, mir, move_data, child_index, each_child); next_child_index = move_data.move_paths[child_index].next_sibling; } } on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child); } pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, path: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| { let place = &ctxt.move_data.move_paths[path].place; let ty = place.ty(mir, tcx).to_ty(tcx); debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty); let gcx = tcx.global_tcx(); let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap(); if erased_ty.needs_drop(gcx, ctxt.param_env) { each_child(child); } else { debug!("on_all_drop_children_bits - skipping") } }) } pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; for arg in mir.args_iter() { let place = mir::Place::Local(arg); let lookup_result = move_data.rev_lookup.find(&place); on_lookup_result_bits(tcx, mir, move_data, lookup_result, |mpi| callback(mpi, DropFlagState::Present)); } } pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; debug!("drop_flag_effects_for_location({:?})", loc); // first, move out of the RHS for mi in &move_data.loc_map[loc] { let path = mi.move_path_index(move_data); debug!("moving out of path {:?}", move_data.move_paths[path]); on_all_children_bits(tcx, mir, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) } debug!("drop_flag_effects: assignment for location({:?})", loc); for_location_inits( tcx, mir, move_data, loc, |mpi| callback(mpi, DropFlagState::Present) ); } pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex) { for ii in &move_data.init_loc_map[loc] { let init = move_data.inits[*ii]; match init.kind { InitKind::Deep => { let path = init.path; on_all_children_bits(tcx, mir, move_data, path, &mut callback) }, InitKind::Shallow => { let mpi = init.path; callback(mpi); } InitKind::NonPanicPathOnly => (), } } }
{ let ty = place.ty(mir, tcx).to_ty(tcx); match ty.sty { ty::Array(..) => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", place, ty); false } ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", place, ty); true } ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", place, ty); true } _ => { false
identifier_body
drop_flag_effects.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::mir::{self, Mir, Location}; use rustc::ty::{self, TyCtxt}; use util::elaborate_drops::DropFlagState; use super::{MoveDataParamEnv}; use super::indexes::MovePathIndex;
use super::move_paths::{MoveData, LookupResult, InitKind}; pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>, path: MovePathIndex, mut cond: F) -> Option<MovePathIndex> where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool { let mut next_child = move_data.move_paths[path].first_child; while let Some(child_index) = next_child { match move_data.move_paths[child_index].place { mir::Place::Projection(ref proj) => { if cond(proj) { return Some(child_index) } } _ => {} } next_child = move_data.move_paths[child_index].next_sibling; } None } /// When enumerating the child fragments of a path, don't recurse into /// paths (1.) past arrays, slices, and pointers, nor (2.) into a type /// that implements `Drop`. /// /// Places behind references or arrays are not tracked by elaboration /// and are always assumed to be initialized when accessible. As /// references and indexes can be reseated, trying to track them can /// only lead to trouble. /// /// Places behind ADT's with a Drop impl are not tracked by /// elaboration since they can never have a drop-flag state that /// differs from that of the parent with the Drop impl. /// /// In both cases, the contents can only be accessed if and only if /// their parents are initialized. This implies for example that there /// is no need to maintain separate drop flags to track such state. /// /// FIXME: we have to do something for moving slice patterns. fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, place: &mir::Place<'tcx>) -> bool { let ty = place.ty(mir, tcx).to_ty(tcx); match ty.sty { ty::Array(..) => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", place, ty); false } ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", place, ty); true } ty::Adt(def, _) if (def.has_dtor(tcx) &&!def.is_box()) || def.is_union() => { debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", place, ty); true } _ => { false } } } pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, lookup_result: LookupResult, each_child: F) where F: FnMut(MovePathIndex) { match lookup_result { LookupResult::Parent(..) => { // access to untracked value - do not touch children } LookupResult::Exact(e) => { on_all_children_bits(tcx, mir, move_data, e, each_child) } } } pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { fn is_terminal_path<'a, 'gcx, 'tcx>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, path: MovePathIndex) -> bool { place_contents_drop_state_cannot_differ( tcx, mir, &move_data.move_paths[path].place) } fn on_all_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, move_path_index: MovePathIndex, each_child: &mut F) where F: FnMut(MovePathIndex) { each_child(move_path_index); if is_terminal_path(tcx, mir, move_data, move_path_index) { return } let mut next_child_index = move_data.move_paths[move_path_index].first_child; while let Some(child_index) = next_child_index { on_all_children_bits(tcx, mir, move_data, child_index, each_child); next_child_index = move_data.move_paths[child_index].next_sibling; } } on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child); } pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, path: MovePathIndex, mut each_child: F) where F: FnMut(MovePathIndex) { on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| { let place = &ctxt.move_data.move_paths[path].place; let ty = place.ty(mir, tcx).to_ty(tcx); debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty); let gcx = tcx.global_tcx(); let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap(); if erased_ty.needs_drop(gcx, ctxt.param_env) { each_child(child); } else { debug!("on_all_drop_children_bits - skipping") } }) } pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; for arg in mir.args_iter() { let place = mir::Place::Local(arg); let lookup_result = move_data.rev_lookup.find(&place); on_lookup_result_bits(tcx, mir, move_data, lookup_result, |mpi| callback(mpi, DropFlagState::Present)); } } pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, ctxt: &MoveDataParamEnv<'gcx, 'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex, DropFlagState) { let move_data = &ctxt.move_data; debug!("drop_flag_effects_for_location({:?})", loc); // first, move out of the RHS for mi in &move_data.loc_map[loc] { let path = mi.move_path_index(move_data); debug!("moving out of path {:?}", move_data.move_paths[path]); on_all_children_bits(tcx, mir, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) } debug!("drop_flag_effects: assignment for location({:?})", loc); for_location_inits( tcx, mir, move_data, loc, |mpi| callback(mpi, DropFlagState::Present) ); } pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>( tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &Mir<'tcx>, move_data: &MoveData<'tcx>, loc: Location, mut callback: F) where F: FnMut(MovePathIndex) { for ii in &move_data.init_loc_map[loc] { let init = move_data.inits[*ii]; match init.kind { InitKind::Deep => { let path = init.path; on_all_children_bits(tcx, mir, move_data, path, &mut callback) }, InitKind::Shallow => { let mpi = init.path; callback(mpi); } InitKind::NonPanicPathOnly => (), } } }
random_line_split
context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
//! Data needed by the layout thread. use fnv::FnvHasher; use gfx::display_list::{WebRenderImageInfo, OpaqueNode}; use gfx::font_cache_thread::FontCacheThread; use gfx::font_context::FontContext; use heapsize::HeapSizeOf; use msg::constellation_msg::PipelineId; use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState}; use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder}; use opaque_node::OpaqueNodeMethods; use parking_lot::RwLock; use script_layout_interface::{PendingImage, PendingImageState}; use script_traits::Painter; use script_traits::UntrustedNodeAddress; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::hash::BuildHasherDefault; use std::sync::{Arc, Mutex}; use std::thread; use style::context::RegisteredSpeculativePainter; use style::context::SharedStyleContext; thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None)); pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R where F: FnOnce(&mut FontContext) -> R { FONT_CONTEXT_KEY.with(|k| { let mut font_context = k.borrow_mut(); if font_context.is_none() { let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone(); *font_context = Some(FontContext::new(font_cache_thread)); } f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap())) }) } pub fn heap_size_of_persistent_local_context() -> usize { FONT_CONTEXT_KEY.with(|r| { if let Some(ref context) = *r.borrow() { context.heap_size_of_children() } else { 0 } }) } /// Layout information shared among all workers. This must be thread-safe. pub struct LayoutContext<'a> { /// The pipeline id of this LayoutContext. pub id: PipelineId, /// Bits shared by the layout and style system. pub style_context: SharedStyleContext<'a>, /// Reference to the script thread image cache. pub image_cache: Arc<ImageCache>, /// Interface to the font cache thread. pub font_cache_thread: Mutex<FontCacheThread>, /// A cache of WebRender image info. pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder), WebRenderImageInfo, BuildHasherDefault<FnvHasher>>>>, /// Paint worklets pub registered_painters: &'a RegisteredPainters, /// A list of in-progress image loads to be shared with the script thread. /// A None value means that this layout was not initiated by the script thread. pub pending_images: Option<Mutex<Vec<PendingImage>>>, /// A list of nodes that have just initiated a CSS transition. /// A None value means that this layout was not initiated by the script thread. pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>, } impl<'a> Drop for LayoutContext<'a> { fn drop(&mut self) { if!thread::panicking() { if let Some(ref pending_images) = self.pending_images { assert!(pending_images.lock().unwrap().is_empty()); } } } } impl<'a> LayoutContext<'a> { #[inline(always)] pub fn shared_context(&self) -> &SharedStyleContext { &self.style_context } pub fn get_or_request_image_or_meta(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<ImageOrMetadataAvailable> { //XXXjdm For cases where we do not request an image, we still need to // ensure the node gets another script-initiated reflow or it // won't be requested at all. let can_request = if self.pending_images.is_some() { CanRequestImages::Yes } else { CanRequestImages::No }; // See if the image is already available let result = self.image_cache.find_image_or_metadata(url.clone(), use_placeholder, can_request); match result { Ok(image_or_metadata) => Some(image_or_metadata), // Image failed to load, so just return nothing Err(ImageState::LoadError) => None, // Not yet requested - request image or metadata from the cache Err(ImageState::NotRequested(id)) => { let image = PendingImage { state: PendingImageState::Unrequested(url), node: node.to_untrusted_node_address(), id: id, }; self.pending_images.as_ref().unwrap().lock().unwrap().push(image); None } // Image has been requested, is still pending. Return no image for this paint loop. // When the image loads it will trigger a reflow and/or repaint. Err(ImageState::Pending(id)) => { //XXXjdm if self.pending_images is not available, we should make sure that // this node gets marked dirty again so it gets a script-initiated // reflow that deals with this properly. if let Some(ref pending_images) = self.pending_images { let image = PendingImage { state: PendingImageState::PendingResponse, node: node.to_untrusted_node_address(), id: id, }; pending_images.lock().unwrap().push(image); } None } } } pub fn get_webrender_image_for_url(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<WebRenderImageInfo> { if let Some(existing_webrender_image) = self.webrender_image_cache .read() .get(&(url.clone(), use_placeholder)) { return Some((*existing_webrender_image).clone()) } match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) { Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => { let image_info = WebRenderImageInfo::from_image(&*image); if image_info.key.is_none() { Some(image_info) } else { let mut webrender_image_cache = self.webrender_image_cache.write(); webrender_image_cache.insert((url, use_placeholder), image_info); Some(image_info) } } None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None, } } } /// A registered painter pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {} /// A set of registered painters pub trait RegisteredPainters: Sync { /// Look up a painter fn get(&self, name: &Atom) -> Option<&RegisteredPainter>; }
* 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/. */
random_line_split
context.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/. */ //! Data needed by the layout thread. use fnv::FnvHasher; use gfx::display_list::{WebRenderImageInfo, OpaqueNode}; use gfx::font_cache_thread::FontCacheThread; use gfx::font_context::FontContext; use heapsize::HeapSizeOf; use msg::constellation_msg::PipelineId; use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState}; use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder}; use opaque_node::OpaqueNodeMethods; use parking_lot::RwLock; use script_layout_interface::{PendingImage, PendingImageState}; use script_traits::Painter; use script_traits::UntrustedNodeAddress; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::hash::BuildHasherDefault; use std::sync::{Arc, Mutex}; use std::thread; use style::context::RegisteredSpeculativePainter; use style::context::SharedStyleContext; thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None)); pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R where F: FnOnce(&mut FontContext) -> R { FONT_CONTEXT_KEY.with(|k| { let mut font_context = k.borrow_mut(); if font_context.is_none() { let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone(); *font_context = Some(FontContext::new(font_cache_thread)); } f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap())) }) } pub fn heap_size_of_persistent_local_context() -> usize { FONT_CONTEXT_KEY.with(|r| { if let Some(ref context) = *r.borrow() { context.heap_size_of_children() } else { 0 } }) } /// Layout information shared among all workers. This must be thread-safe. pub struct LayoutContext<'a> { /// The pipeline id of this LayoutContext. pub id: PipelineId, /// Bits shared by the layout and style system. pub style_context: SharedStyleContext<'a>, /// Reference to the script thread image cache. pub image_cache: Arc<ImageCache>, /// Interface to the font cache thread. pub font_cache_thread: Mutex<FontCacheThread>, /// A cache of WebRender image info. pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder), WebRenderImageInfo, BuildHasherDefault<FnvHasher>>>>, /// Paint worklets pub registered_painters: &'a RegisteredPainters, /// A list of in-progress image loads to be shared with the script thread. /// A None value means that this layout was not initiated by the script thread. pub pending_images: Option<Mutex<Vec<PendingImage>>>, /// A list of nodes that have just initiated a CSS transition. /// A None value means that this layout was not initiated by the script thread. pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>, } impl<'a> Drop for LayoutContext<'a> { fn drop(&mut self) { if!thread::panicking() { if let Some(ref pending_images) = self.pending_images
} } } impl<'a> LayoutContext<'a> { #[inline(always)] pub fn shared_context(&self) -> &SharedStyleContext { &self.style_context } pub fn get_or_request_image_or_meta(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<ImageOrMetadataAvailable> { //XXXjdm For cases where we do not request an image, we still need to // ensure the node gets another script-initiated reflow or it // won't be requested at all. let can_request = if self.pending_images.is_some() { CanRequestImages::Yes } else { CanRequestImages::No }; // See if the image is already available let result = self.image_cache.find_image_or_metadata(url.clone(), use_placeholder, can_request); match result { Ok(image_or_metadata) => Some(image_or_metadata), // Image failed to load, so just return nothing Err(ImageState::LoadError) => None, // Not yet requested - request image or metadata from the cache Err(ImageState::NotRequested(id)) => { let image = PendingImage { state: PendingImageState::Unrequested(url), node: node.to_untrusted_node_address(), id: id, }; self.pending_images.as_ref().unwrap().lock().unwrap().push(image); None } // Image has been requested, is still pending. Return no image for this paint loop. // When the image loads it will trigger a reflow and/or repaint. Err(ImageState::Pending(id)) => { //XXXjdm if self.pending_images is not available, we should make sure that // this node gets marked dirty again so it gets a script-initiated // reflow that deals with this properly. if let Some(ref pending_images) = self.pending_images { let image = PendingImage { state: PendingImageState::PendingResponse, node: node.to_untrusted_node_address(), id: id, }; pending_images.lock().unwrap().push(image); } None } } } pub fn get_webrender_image_for_url(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<WebRenderImageInfo> { if let Some(existing_webrender_image) = self.webrender_image_cache .read() .get(&(url.clone(), use_placeholder)) { return Some((*existing_webrender_image).clone()) } match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) { Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => { let image_info = WebRenderImageInfo::from_image(&*image); if image_info.key.is_none() { Some(image_info) } else { let mut webrender_image_cache = self.webrender_image_cache.write(); webrender_image_cache.insert((url, use_placeholder), image_info); Some(image_info) } } None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None, } } } /// A registered painter pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {} /// A set of registered painters pub trait RegisteredPainters: Sync { /// Look up a painter fn get(&self, name: &Atom) -> Option<&RegisteredPainter>; }
{ assert!(pending_images.lock().unwrap().is_empty()); }
conditional_block
context.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/. */ //! Data needed by the layout thread. use fnv::FnvHasher; use gfx::display_list::{WebRenderImageInfo, OpaqueNode}; use gfx::font_cache_thread::FontCacheThread; use gfx::font_context::FontContext; use heapsize::HeapSizeOf; use msg::constellation_msg::PipelineId; use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState}; use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder}; use opaque_node::OpaqueNodeMethods; use parking_lot::RwLock; use script_layout_interface::{PendingImage, PendingImageState}; use script_traits::Painter; use script_traits::UntrustedNodeAddress; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::hash::BuildHasherDefault; use std::sync::{Arc, Mutex}; use std::thread; use style::context::RegisteredSpeculativePainter; use style::context::SharedStyleContext; thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None)); pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R where F: FnOnce(&mut FontContext) -> R { FONT_CONTEXT_KEY.with(|k| { let mut font_context = k.borrow_mut(); if font_context.is_none() { let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone(); *font_context = Some(FontContext::new(font_cache_thread)); } f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap())) }) } pub fn heap_size_of_persistent_local_context() -> usize { FONT_CONTEXT_KEY.with(|r| { if let Some(ref context) = *r.borrow() { context.heap_size_of_children() } else { 0 } }) } /// Layout information shared among all workers. This must be thread-safe. pub struct LayoutContext<'a> { /// The pipeline id of this LayoutContext. pub id: PipelineId, /// Bits shared by the layout and style system. pub style_context: SharedStyleContext<'a>, /// Reference to the script thread image cache. pub image_cache: Arc<ImageCache>, /// Interface to the font cache thread. pub font_cache_thread: Mutex<FontCacheThread>, /// A cache of WebRender image info. pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder), WebRenderImageInfo, BuildHasherDefault<FnvHasher>>>>, /// Paint worklets pub registered_painters: &'a RegisteredPainters, /// A list of in-progress image loads to be shared with the script thread. /// A None value means that this layout was not initiated by the script thread. pub pending_images: Option<Mutex<Vec<PendingImage>>>, /// A list of nodes that have just initiated a CSS transition. /// A None value means that this layout was not initiated by the script thread. pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>, } impl<'a> Drop for LayoutContext<'a> { fn drop(&mut self) { if!thread::panicking() { if let Some(ref pending_images) = self.pending_images { assert!(pending_images.lock().unwrap().is_empty()); } } } } impl<'a> LayoutContext<'a> { #[inline(always)] pub fn shared_context(&self) -> &SharedStyleContext { &self.style_context } pub fn get_or_request_image_or_meta(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<ImageOrMetadataAvailable> { //XXXjdm For cases where we do not request an image, we still need to // ensure the node gets another script-initiated reflow or it // won't be requested at all. let can_request = if self.pending_images.is_some() { CanRequestImages::Yes } else { CanRequestImages::No }; // See if the image is already available let result = self.image_cache.find_image_or_metadata(url.clone(), use_placeholder, can_request); match result { Ok(image_or_metadata) => Some(image_or_metadata), // Image failed to load, so just return nothing Err(ImageState::LoadError) => None, // Not yet requested - request image or metadata from the cache Err(ImageState::NotRequested(id)) => { let image = PendingImage { state: PendingImageState::Unrequested(url), node: node.to_untrusted_node_address(), id: id, }; self.pending_images.as_ref().unwrap().lock().unwrap().push(image); None } // Image has been requested, is still pending. Return no image for this paint loop. // When the image loads it will trigger a reflow and/or repaint. Err(ImageState::Pending(id)) => { //XXXjdm if self.pending_images is not available, we should make sure that // this node gets marked dirty again so it gets a script-initiated // reflow that deals with this properly. if let Some(ref pending_images) = self.pending_images { let image = PendingImage { state: PendingImageState::PendingResponse, node: node.to_untrusted_node_address(), id: id, }; pending_images.lock().unwrap().push(image); } None } } } pub fn
(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<WebRenderImageInfo> { if let Some(existing_webrender_image) = self.webrender_image_cache .read() .get(&(url.clone(), use_placeholder)) { return Some((*existing_webrender_image).clone()) } match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) { Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => { let image_info = WebRenderImageInfo::from_image(&*image); if image_info.key.is_none() { Some(image_info) } else { let mut webrender_image_cache = self.webrender_image_cache.write(); webrender_image_cache.insert((url, use_placeholder), image_info); Some(image_info) } } None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None, } } } /// A registered painter pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {} /// A set of registered painters pub trait RegisteredPainters: Sync { /// Look up a painter fn get(&self, name: &Atom) -> Option<&RegisteredPainter>; }
get_webrender_image_for_url
identifier_name
context.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/. */ //! Data needed by the layout thread. use fnv::FnvHasher; use gfx::display_list::{WebRenderImageInfo, OpaqueNode}; use gfx::font_cache_thread::FontCacheThread; use gfx::font_context::FontContext; use heapsize::HeapSizeOf; use msg::constellation_msg::PipelineId; use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState}; use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder}; use opaque_node::OpaqueNodeMethods; use parking_lot::RwLock; use script_layout_interface::{PendingImage, PendingImageState}; use script_traits::Painter; use script_traits::UntrustedNodeAddress; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::hash::BuildHasherDefault; use std::sync::{Arc, Mutex}; use std::thread; use style::context::RegisteredSpeculativePainter; use style::context::SharedStyleContext; thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None)); pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R where F: FnOnce(&mut FontContext) -> R
pub fn heap_size_of_persistent_local_context() -> usize { FONT_CONTEXT_KEY.with(|r| { if let Some(ref context) = *r.borrow() { context.heap_size_of_children() } else { 0 } }) } /// Layout information shared among all workers. This must be thread-safe. pub struct LayoutContext<'a> { /// The pipeline id of this LayoutContext. pub id: PipelineId, /// Bits shared by the layout and style system. pub style_context: SharedStyleContext<'a>, /// Reference to the script thread image cache. pub image_cache: Arc<ImageCache>, /// Interface to the font cache thread. pub font_cache_thread: Mutex<FontCacheThread>, /// A cache of WebRender image info. pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder), WebRenderImageInfo, BuildHasherDefault<FnvHasher>>>>, /// Paint worklets pub registered_painters: &'a RegisteredPainters, /// A list of in-progress image loads to be shared with the script thread. /// A None value means that this layout was not initiated by the script thread. pub pending_images: Option<Mutex<Vec<PendingImage>>>, /// A list of nodes that have just initiated a CSS transition. /// A None value means that this layout was not initiated by the script thread. pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>, } impl<'a> Drop for LayoutContext<'a> { fn drop(&mut self) { if!thread::panicking() { if let Some(ref pending_images) = self.pending_images { assert!(pending_images.lock().unwrap().is_empty()); } } } } impl<'a> LayoutContext<'a> { #[inline(always)] pub fn shared_context(&self) -> &SharedStyleContext { &self.style_context } pub fn get_or_request_image_or_meta(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<ImageOrMetadataAvailable> { //XXXjdm For cases where we do not request an image, we still need to // ensure the node gets another script-initiated reflow or it // won't be requested at all. let can_request = if self.pending_images.is_some() { CanRequestImages::Yes } else { CanRequestImages::No }; // See if the image is already available let result = self.image_cache.find_image_or_metadata(url.clone(), use_placeholder, can_request); match result { Ok(image_or_metadata) => Some(image_or_metadata), // Image failed to load, so just return nothing Err(ImageState::LoadError) => None, // Not yet requested - request image or metadata from the cache Err(ImageState::NotRequested(id)) => { let image = PendingImage { state: PendingImageState::Unrequested(url), node: node.to_untrusted_node_address(), id: id, }; self.pending_images.as_ref().unwrap().lock().unwrap().push(image); None } // Image has been requested, is still pending. Return no image for this paint loop. // When the image loads it will trigger a reflow and/or repaint. Err(ImageState::Pending(id)) => { //XXXjdm if self.pending_images is not available, we should make sure that // this node gets marked dirty again so it gets a script-initiated // reflow that deals with this properly. if let Some(ref pending_images) = self.pending_images { let image = PendingImage { state: PendingImageState::PendingResponse, node: node.to_untrusted_node_address(), id: id, }; pending_images.lock().unwrap().push(image); } None } } } pub fn get_webrender_image_for_url(&self, node: OpaqueNode, url: ServoUrl, use_placeholder: UsePlaceholder) -> Option<WebRenderImageInfo> { if let Some(existing_webrender_image) = self.webrender_image_cache .read() .get(&(url.clone(), use_placeholder)) { return Some((*existing_webrender_image).clone()) } match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) { Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => { let image_info = WebRenderImageInfo::from_image(&*image); if image_info.key.is_none() { Some(image_info) } else { let mut webrender_image_cache = self.webrender_image_cache.write(); webrender_image_cache.insert((url, use_placeholder), image_info); Some(image_info) } } None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None, } } } /// A registered painter pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {} /// A set of registered painters pub trait RegisteredPainters: Sync { /// Look up a painter fn get(&self, name: &Atom) -> Option<&RegisteredPainter>; }
{ FONT_CONTEXT_KEY.with(|k| { let mut font_context = k.borrow_mut(); if font_context.is_none() { let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone(); *font_context = Some(FontContext::new(font_cache_thread)); } f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap())) }) }
identifier_body
lib.rs
//! # bittrex-api //! //! **bittrex-api** provides a wrapper for the [Bittrex API](https://bittrex.com/home/api). //! This crate makes it easy to consume the **Bittrex API** in Rust. //! //! ##Example //! //! ```no_run //! extern crate bittrex_api; //! //! use bittrex_api::BittrexClient; //! # fn main() {
//! # } //! ``` extern crate time; extern crate hmac; extern crate sha2; extern crate generic_array; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; pub mod error; pub mod values; mod client; pub use client::BittrexClient;
//! let bittrex_client = BittrexClient::new("KEY".to_string(), "SECRET".to_string()); // Initialize the Bittrex Client with your API Key and Secret //! let markets = bittrex_client.get_markets().unwrap(); //Get all available markets of Bittrex
random_line_split
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geometry::Au; use cssparser::{self, RGBA, Color}; use libc::c_char; use num_lib::ToPrimitive; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::ffi::CStr; use std::iter::Filter; use std::ops::Deref; use std::str::{from_utf8, FromStr, Split}; pub type DOMString = String; pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; /// Whitespace as defined by HTML5 § 2.4.1. // TODO(SimonSapin) Maybe a custom Pattern can be more efficient? const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d']; pub fn is_whitespace(s: &str) -> bool { s.chars().all(char_is_whitespace) } #[inline] pub fn char_is_whitespace(c: char) -> bool { WHITESPACE.contains(&c) } /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn n
&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } /// Shared implementation to parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-integers> or /// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers> fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, _ => false, } } let mut input = input.skip_while(|c| { HTML_SPACE_CHARACTERS.iter().any(|s| s == c) }).peekable(); let sign = match input.peek() { None => return None, Some(&'-') => { input.next(); -1 }, Some(&'+') => { input.next(); 1 }, Some(_) => 1, }; match input.peek() { Some(c) if is_ascii_digit(c) => (), _ => return None, } let value = input.take_while(is_ascii_digit).map(|d| { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { accumulator.checked_mul(10) }).and_then(|accumulator| { accumulator.checked_add(d) }) }); return value.and_then(|value| value.checked_mul(sign)); } /// Parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-integers>. pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) } /// Parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers> pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> { do_parse_integer(input).and_then(|result| { result.to_u32() }) } #[derive(Copy, Clone, Debug)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f32), Length(Au), } /// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned. pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { value = value.trim_left_matches(WHITESPACE); if value.is_empty() { return LengthOrPercentageOrAuto::Auto } if value.starts_with("+") { value = &value[1..] } value = value.trim_left_matches('0'); if value.is_empty() { return LengthOrPercentageOrAuto::Auto } let mut end_index = value.len(); let (mut found_full_stop, mut found_percent) = (false, false); for (i, ch) in value.chars().enumerate() { match ch { '0'...'9' => continue, '%' => { found_percent = true; end_index = i; break } '.' if!found_full_stop => { found_full_stop = true; continue } _ => { end_index = i; break } } } value = &value[..end_index]; if found_percent { let result: Result<f32, _> = FromStr::from_str(value); match result { Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0), Err(_) => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)), Err(_) => LengthOrPercentageOrAuto::Auto, } } /// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned. pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> { // Steps 1 and 2. if input.is_empty() { return Err(()) } // Step 3. input = input.trim_matches(WHITESPACE); // Step 4. if input.eq_ignore_ascii_case("transparent") { return Err(()) } // Step 5. match cssparser::parse_color_keyword(input) { Ok(Color::RGBA(rgba)) => return Ok(rgba), _ => {} } // Step 6. if input.len() == 4 { match (input.as_bytes()[0], hex(input.as_bytes()[1] as char), hex(input.as_bytes()[2] as char), hex(input.as_bytes()[3] as char)) { (b'#', Ok(r), Ok(g), Ok(b)) => { return Ok(RGBA { red: (r as f32) * 17.0 / 255.0, green: (g as f32) * 17.0 / 255.0, blue: (b as f32) * 17.0 / 255.0, alpha: 1.0, }) } _ => {} } } // Step 7. let mut new_input = String::new(); for ch in input.chars() { if ch as u32 > 0xffff { new_input.push_str("00") } else { new_input.push(ch) } } let mut input = &*new_input; // Step 8. for (char_count, (index, _)) in input.char_indices().enumerate() { if char_count == 128 { input = &input[..index]; break } } // Step 9. if input.as_bytes()[0] == b'#' { input = &input[1..] } // Step 10. let mut new_input = Vec::new(); for ch in input.chars() { if hex(ch).is_ok() { new_input.push(ch as u8) } else { new_input.push(b'0') } } let mut input = new_input; // Step 11. while input.is_empty() || (input.len() % 3)!= 0 { input.push(b'0') } // Step 12. let mut length = input.len() / 3; let (mut red, mut green, mut blue) = (&input[..length], &input[length..length * 2], &input[length * 2..]); // Step 13. if length > 8 { red = &red[length - 8..]; green = &green[length - 8..]; blue = &blue[length - 8..]; length = 8 } // Step 14. while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' { red = &red[1..]; green = &green[1..]; blue = &blue[1..]; length -= 1 } // Steps 15-20. return Ok(RGBA { red: hex_string(red).unwrap() as f32 / 255.0, green: hex_string(green).unwrap() as f32 / 255.0, blue: hex_string(blue).unwrap() as f32 / 255.0, alpha: 1.0, }); fn hex(ch: char) -> Result<u8, ()> { match ch { '0'...'9' => Ok((ch as u8) - b'0'), 'a'...'f' => Ok((ch as u8) - b'a' + 10), 'A'...'F' => Ok((ch as u8) - b'A' + 10), _ => Err(()), } } fn hex_string(string: &[u8]) -> Result<u8, ()> { match string.len() { 0 => Err(()), 1 => hex(string[0] as char), _ => { let upper = try!(hex(string[0] as char)); let lower = try!(hex(string[1] as char)); Ok((upper << 4) | lower) } } } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct LowercaseString { inner: String, } impl LowercaseString { pub fn new(s: &str) -> LowercaseString { LowercaseString { inner: s.to_lowercase(), } } } impl Deref for LowercaseString { type Target = str; #[inline] fn deref(&self) -> &str { &*self.inner } } /// Creates a String from the given null-terminated buffer. /// Panics if the buffer does not contain UTF-8. pub unsafe fn c_str_to_string(s: *const c_char) -> String { from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned() } pub fn str_join<T: AsRef<str>>(strs: &[T], join: &str) -> String { strs.iter().fold(String::new(), |mut acc, s| { if!acc.is_empty() { acc.push_str(join); } acc.push_str(s.as_ref()); acc }) } // Lifted from Rust's StrExt implementation, which is being removed. pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in s.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) } if end_byte.is_none() && count == end { end_byte = Some(s.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) } } }
ot_empty(
identifier_name
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geometry::Au; use cssparser::{self, RGBA, Color}; use libc::c_char; use num_lib::ToPrimitive; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::ffi::CStr; use std::iter::Filter; use std::ops::Deref; use std::str::{from_utf8, FromStr, Split}; pub type DOMString = String; pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; /// Whitespace as defined by HTML5 § 2.4.1. // TODO(SimonSapin) Maybe a custom Pattern can be more efficient? const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d']; pub fn is_whitespace(s: &str) -> bool { s.chars().all(char_is_whitespace) } #[inline] pub fn char_is_whitespace(c: char) -> bool { WHITESPACE.contains(&c) } /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } /// Shared implementation to parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-integers> or /// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers> fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, _ => false, } } let mut input = input.skip_while(|c| { HTML_SPACE_CHARACTERS.iter().any(|s| s == c) }).peekable(); let sign = match input.peek() { None => return None, Some(&'-') => { input.next(); -1 }, Some(&'+') => { input.next(); 1 }, Some(_) => 1, }; match input.peek() { Some(c) if is_ascii_digit(c) => (), _ => return None, } let value = input.take_while(is_ascii_digit).map(|d| { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { accumulator.checked_mul(10) }).and_then(|accumulator| { accumulator.checked_add(d) }) }); return value.and_then(|value| value.checked_mul(sign)); } /// Parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-integers>. pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) } /// Parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers> pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> { do_parse_integer(input).and_then(|result| { result.to_u32() }) } #[derive(Copy, Clone, Debug)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f32), Length(Au), } /// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned. pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { value = value.trim_left_matches(WHITESPACE); if value.is_empty() { return LengthOrPercentageOrAuto::Auto } if value.starts_with("+") { value = &value[1..] } value = value.trim_left_matches('0'); if value.is_empty() { return LengthOrPercentageOrAuto::Auto } let mut end_index = value.len(); let (mut found_full_stop, mut found_percent) = (false, false); for (i, ch) in value.chars().enumerate() { match ch { '0'...'9' => continue, '%' => { found_percent = true; end_index = i; break } '.' if!found_full_stop => { found_full_stop = true; continue } _ => { end_index = i; break } } } value = &value[..end_index]; if found_percent { let result: Result<f32, _> = FromStr::from_str(value); match result { Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0), Err(_) => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)), Err(_) => LengthOrPercentageOrAuto::Auto, } } /// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned. pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> { // Steps 1 and 2. if input.is_empty() { return Err(()) } // Step 3. input = input.trim_matches(WHITESPACE); // Step 4. if input.eq_ignore_ascii_case("transparent") { return Err(()) } // Step 5. match cssparser::parse_color_keyword(input) { Ok(Color::RGBA(rgba)) => return Ok(rgba), _ => {} } // Step 6. if input.len() == 4 { match (input.as_bytes()[0], hex(input.as_bytes()[1] as char), hex(input.as_bytes()[2] as char), hex(input.as_bytes()[3] as char)) { (b'#', Ok(r), Ok(g), Ok(b)) => { return Ok(RGBA { red: (r as f32) * 17.0 / 255.0, green: (g as f32) * 17.0 / 255.0, blue: (b as f32) * 17.0 / 255.0, alpha: 1.0, }) } _ => {} } } // Step 7. let mut new_input = String::new(); for ch in input.chars() { if ch as u32 > 0xffff { new_input.push_str("00") } else { new_input.push(ch) } } let mut input = &*new_input; // Step 8. for (char_count, (index, _)) in input.char_indices().enumerate() { if char_count == 128 { input = &input[..index]; break } } // Step 9. if input.as_bytes()[0] == b'#' { input = &input[1..] } // Step 10. let mut new_input = Vec::new(); for ch in input.chars() { if hex(ch).is_ok() { new_input.push(ch as u8) } else { new_input.push(b'0') } } let mut input = new_input; // Step 11. while input.is_empty() || (input.len() % 3)!= 0 { input.push(b'0') } // Step 12. let mut length = input.len() / 3; let (mut red, mut green, mut blue) = (&input[..length], &input[length..length * 2], &input[length * 2..]); // Step 13. if length > 8 { red = &red[length - 8..]; green = &green[length - 8..]; blue = &blue[length - 8..]; length = 8 } // Step 14. while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' { red = &red[1..]; green = &green[1..]; blue = &blue[1..]; length -= 1 } // Steps 15-20. return Ok(RGBA { red: hex_string(red).unwrap() as f32 / 255.0, green: hex_string(green).unwrap() as f32 / 255.0, blue: hex_string(blue).unwrap() as f32 / 255.0, alpha: 1.0, }); fn hex(ch: char) -> Result<u8, ()> {
fn hex_string(string: &[u8]) -> Result<u8, ()> { match string.len() { 0 => Err(()), 1 => hex(string[0] as char), _ => { let upper = try!(hex(string[0] as char)); let lower = try!(hex(string[1] as char)); Ok((upper << 4) | lower) } } } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct LowercaseString { inner: String, } impl LowercaseString { pub fn new(s: &str) -> LowercaseString { LowercaseString { inner: s.to_lowercase(), } } } impl Deref for LowercaseString { type Target = str; #[inline] fn deref(&self) -> &str { &*self.inner } } /// Creates a String from the given null-terminated buffer. /// Panics if the buffer does not contain UTF-8. pub unsafe fn c_str_to_string(s: *const c_char) -> String { from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned() } pub fn str_join<T: AsRef<str>>(strs: &[T], join: &str) -> String { strs.iter().fold(String::new(), |mut acc, s| { if!acc.is_empty() { acc.push_str(join); } acc.push_str(s.as_ref()); acc }) } // Lifted from Rust's StrExt implementation, which is being removed. pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in s.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) } if end_byte.is_none() && count == end { end_byte = Some(s.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) } } }
match ch { '0'...'9' => Ok((ch as u8) - b'0'), 'a'...'f' => Ok((ch as u8) - b'a' + 10), 'A'...'F' => Ok((ch as u8) - b'A' + 10), _ => Err(()), } }
identifier_body
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geometry::Au; use cssparser::{self, RGBA, Color}; use libc::c_char; use num_lib::ToPrimitive; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::ffi::CStr; use std::iter::Filter; use std::ops::Deref; use std::str::{from_utf8, FromStr, Split}; pub type DOMString = String; pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; /// Whitespace as defined by HTML5 § 2.4.1. // TODO(SimonSapin) Maybe a custom Pattern can be more efficient? const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d']; pub fn is_whitespace(s: &str) -> bool { s.chars().all(char_is_whitespace) } #[inline] pub fn char_is_whitespace(c: char) -> bool { WHITESPACE.contains(&c) } /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{000d}', ]; pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } /// Shared implementation to parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-integers> or /// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers> fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, _ => false, } } let mut input = input.skip_while(|c| { HTML_SPACE_CHARACTERS.iter().any(|s| s == c) }).peekable(); let sign = match input.peek() { None => return None, Some(&'-') => { input.next(); -1 }, Some(&'+') => { input.next(); 1 }, Some(_) => 1, }; match input.peek() { Some(c) if is_ascii_digit(c) => (), _ => return None, } let value = input.take_while(is_ascii_digit).map(|d| { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { accumulator.checked_mul(10) }).and_then(|accumulator| { accumulator.checked_add(d) }) }); return value.and_then(|value| value.checked_mul(sign)); } /// Parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-integers>. pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) } /// Parse an integer according to /// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers> pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> { do_parse_integer(input).and_then(|result| { result.to_u32() }) } #[derive(Copy, Clone, Debug)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f32), Length(Au), } /// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned. pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { value = value.trim_left_matches(WHITESPACE); if value.is_empty() { return LengthOrPercentageOrAuto::Auto } if value.starts_with("+") { value = &value[1..] } value = value.trim_left_matches('0'); if value.is_empty() { return LengthOrPercentageOrAuto::Auto } let mut end_index = value.len(); let (mut found_full_stop, mut found_percent) = (false, false); for (i, ch) in value.chars().enumerate() { match ch { '0'...'9' => continue, '%' => { found_percent = true; end_index = i; break } '.' if!found_full_stop => { found_full_stop = true; continue } _ => { end_index = i; break } } } value = &value[..end_index]; if found_percent { let result: Result<f32, _> = FromStr::from_str(value); match result { Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0), Err(_) => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)), Err(_) => LengthOrPercentageOrAuto::Auto, } } /// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned. pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> { // Steps 1 and 2. if input.is_empty() { return Err(()) } // Step 3. input = input.trim_matches(WHITESPACE); // Step 4. if input.eq_ignore_ascii_case("transparent") { return Err(()) } // Step 5. match cssparser::parse_color_keyword(input) { Ok(Color::RGBA(rgba)) => return Ok(rgba), _ => {} } // Step 6. if input.len() == 4 { match (input.as_bytes()[0], hex(input.as_bytes()[1] as char), hex(input.as_bytes()[2] as char), hex(input.as_bytes()[3] as char)) { (b'#', Ok(r), Ok(g), Ok(b)) => { return Ok(RGBA { red: (r as f32) * 17.0 / 255.0, green: (g as f32) * 17.0 / 255.0, blue: (b as f32) * 17.0 / 255.0, alpha: 1.0, }) } _ => {} } } // Step 7. let mut new_input = String::new(); for ch in input.chars() { if ch as u32 > 0xffff { new_input.push_str("00") } else { new_input.push(ch) } } let mut input = &*new_input; // Step 8. for (char_count, (index, _)) in input.char_indices().enumerate() { if char_count == 128 { input = &input[..index]; break } } // Step 9. if input.as_bytes()[0] == b'#' { input = &input[1..] } // Step 10. let mut new_input = Vec::new(); for ch in input.chars() { if hex(ch).is_ok() { new_input.push(ch as u8) } else { new_input.push(b'0') } } let mut input = new_input; // Step 11. while input.is_empty() || (input.len() % 3)!= 0 { input.push(b'0') } // Step 12. let mut length = input.len() / 3; let (mut red, mut green, mut blue) = (&input[..length], &input[length..length * 2], &input[length * 2..]); // Step 13. if length > 8 { red = &red[length - 8..]; green = &green[length - 8..]; blue = &blue[length - 8..]; length = 8 } // Step 14. while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' { red = &red[1..]; green = &green[1..]; blue = &blue[1..]; length -= 1 } // Steps 15-20. return Ok(RGBA { red: hex_string(red).unwrap() as f32 / 255.0, green: hex_string(green).unwrap() as f32 / 255.0, blue: hex_string(blue).unwrap() as f32 / 255.0, alpha: 1.0, }); fn hex(ch: char) -> Result<u8, ()> { match ch { '0'...'9' => Ok((ch as u8) - b'0'), 'a'...'f' => Ok((ch as u8) - b'a' + 10), 'A'...'F' => Ok((ch as u8) - b'A' + 10), _ => Err(()), } } fn hex_string(string: &[u8]) -> Result<u8, ()> { match string.len() { 0 => Err(()), 1 => hex(string[0] as char), _ => { let upper = try!(hex(string[0] as char)); let lower = try!(hex(string[1] as char)); Ok((upper << 4) | lower) } } } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct LowercaseString { inner: String, } impl LowercaseString { pub fn new(s: &str) -> LowercaseString { LowercaseString { inner: s.to_lowercase(), } } } impl Deref for LowercaseString { type Target = str; #[inline] fn deref(&self) -> &str { &*self.inner } } /// Creates a String from the given null-terminated buffer. /// Panics if the buffer does not contain UTF-8. pub unsafe fn c_str_to_string(s: *const c_char) -> String { from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned() } pub fn str_join<T: AsRef<str>>(strs: &[T], join: &str) -> String { strs.iter().fold(String::new(), |mut acc, s| { if!acc.is_empty() { acc.push_str(join); } acc.push_str(s.as_ref()); acc }) } // Lifted from Rust's StrExt implementation, which is being removed. pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in s.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) } if end_byte.is_none() && count == end { end_byte = Some(s.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) } } }
'\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}',
random_line_split
issue-5554.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. use std::default::Default; pub struct X<T> { a: T, } // reordering these bounds stops the ICE // // nmatsakis: This test used to have the bounds Default + PartialEq + // Default, but having duplicate bounds became illegal. impl<T: Default + PartialEq> Default for X<T> { fn default() -> X<T> { X { a: Default::default() } } } macro_rules! constants { () => { let _ : X<int> = Default::default(); } } pub fn main()
{ constants!(); }
identifier_body
issue-5554.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. use std::default::Default; pub struct
<T> { a: T, } // reordering these bounds stops the ICE // // nmatsakis: This test used to have the bounds Default + PartialEq + // Default, but having duplicate bounds became illegal. impl<T: Default + PartialEq> Default for X<T> { fn default() -> X<T> { X { a: Default::default() } } } macro_rules! constants { () => { let _ : X<int> = Default::default(); } } pub fn main() { constants!(); }
X
identifier_name
issue-5554.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
pub struct X<T> { a: T, } // reordering these bounds stops the ICE // // nmatsakis: This test used to have the bounds Default + PartialEq + // Default, but having duplicate bounds became illegal. impl<T: Default + PartialEq> Default for X<T> { fn default() -> X<T> { X { a: Default::default() } } } macro_rules! constants { () => { let _ : X<int> = Default::default(); } } pub fn main() { constants!(); }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::default::Default;
random_line_split
inefficient_to_string.rs
// run-rustfix #![deny(clippy::inefficient_to_string)] use std::borrow::Cow; fn
() { let rstr: &str = "hello"; let rrstr: &&str = &rstr; let rrrstr: &&&str = &rrstr; let _: String = rstr.to_string(); let _: String = rrstr.to_string(); let _: String = rrrstr.to_string(); let string: String = String::from("hello"); let rstring: &String = &string; let rrstring: &&String = &rstring; let rrrstring: &&&String = &rrstring; let _: String = string.to_string(); let _: String = rstring.to_string(); let _: String = rrstring.to_string(); let _: String = rrrstring.to_string(); let cow: Cow<'_, str> = Cow::Borrowed("hello"); let rcow: &Cow<'_, str> = &cow; let rrcow: &&Cow<'_, str> = &rcow; let rrrcow: &&&Cow<'_, str> = &rrcow; let _: String = cow.to_string(); let _: String = rcow.to_string(); let _: String = rrcow.to_string(); let _: String = rrrcow.to_string(); }
main
identifier_name
inefficient_to_string.rs
// run-rustfix #![deny(clippy::inefficient_to_string)] use std::borrow::Cow; fn main() { let rstr: &str = "hello"; let rrstr: &&str = &rstr; let rrrstr: &&&str = &rrstr;
let rstring: &String = &string; let rrstring: &&String = &rstring; let rrrstring: &&&String = &rrstring; let _: String = string.to_string(); let _: String = rstring.to_string(); let _: String = rrstring.to_string(); let _: String = rrrstring.to_string(); let cow: Cow<'_, str> = Cow::Borrowed("hello"); let rcow: &Cow<'_, str> = &cow; let rrcow: &&Cow<'_, str> = &rcow; let rrrcow: &&&Cow<'_, str> = &rrcow; let _: String = cow.to_string(); let _: String = rcow.to_string(); let _: String = rrcow.to_string(); let _: String = rrrcow.to_string(); }
let _: String = rstr.to_string(); let _: String = rrstr.to_string(); let _: String = rrrstr.to_string(); let string: String = String::from("hello");
random_line_split
inefficient_to_string.rs
// run-rustfix #![deny(clippy::inefficient_to_string)] use std::borrow::Cow; fn main()
let rrrcow: &&&Cow<'_, str> = &rrcow; let _: String = cow.to_string(); let _: String = rcow.to_string(); let _: String = rrcow.to_string(); let _: String = rrrcow.to_string(); }
{ let rstr: &str = "hello"; let rrstr: &&str = &rstr; let rrrstr: &&&str = &rrstr; let _: String = rstr.to_string(); let _: String = rrstr.to_string(); let _: String = rrrstr.to_string(); let string: String = String::from("hello"); let rstring: &String = &string; let rrstring: &&String = &rstring; let rrrstring: &&&String = &rrstring; let _: String = string.to_string(); let _: String = rstring.to_string(); let _: String = rrstring.to_string(); let _: String = rrrstring.to_string(); let cow: Cow<'_, str> = Cow::Borrowed("hello"); let rcow: &Cow<'_, str> = &cow; let rrcow: &&Cow<'_, str> = &rcow;
identifier_body
lib.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. This file may not be copied, modified, or distributed // except according to those terms. //! The arena, a fast but limited type of allocator. //! //! Arenas are a type of allocator that destroy the objects within, all at //! once, once the arena itself is destroyed. They do not support deallocation //! of individual objects while the arena itself is still alive. The benefit //! of an arena is very fast allocation; just a pointer bump. //! //! This crate has two arenas implemented: `TypedArena`, which is a simpler //! arena but can only hold objects of a single type, and `Arena`, which is a //! more complex, slower arena which can hold objects of any type. #![crate_name = "arena"] #![experimental] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(unsafe_destructor)] #![allow(missing_docs)] extern crate alloc; use std::cell::{Cell, RefCell}; use std::cmp; use std::intrinsics::{TyDesc, get_tydesc}; use std::intrinsics; use std::mem; use std::num::{Int, UnsignedInt}; use std::ptr; use std::rc::Rc; use std::rt::heap::{allocate, deallocate}; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[deriving(Clone, PartialEq)] struct Chunk { data: Rc<RefCell<Vec<u8>>>, fill: Cell<uint>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> uint { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, } impl Arena { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena { Arena::new_with_size(32u) } /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: uint) -> Arena { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), } } } fn chunk(size: uint, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0u), is_copy: Cell::new(is_copy), } } #[unsafe_destructor] impl Drop for Arena { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: uint, align: uint) -> uint { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data: *const uint = mem::transmute(buf.offset(idx as int)); let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as int) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint { p as uint | (is_done as uint) } #[inline] fn un_bitpack_tydesc_ptr(p: uint) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } impl Arena { fn chunk_size(&self) -> uint { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as int) } } #[inline] fn alloc_copy<T>(&self, op: || -> T) -> &mut T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as int), buf.offset(start as int)); } } #[inline] fn alloc_noncopy<T>(&self, op: || -> T) -> &mut T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ty_ptr = ty_ptr as *mut uint; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = mem::transmute(tydesc); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T>(&self, op: || -> T) -> &mut T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] fn test_arena_alloc_nested() { struct Inner { value: uint } struct Outer<'a> { inner: &'a Inner } let arena = Arena::new(); let result = arena.alloc(|| Outer { inner: arena.alloc(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] #[should_fail] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1u8, 2u8] }); } // Now, panic while allocating arena.alloc::<Rc<int>>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. /// /// Safety note: Modifying objects in the arena that have already had their /// `drop` destructors run can cause leaks, because the destructor will not /// run again for these objects. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, } struct TypedArenaChunk<T> { /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: uint, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: uint) -> uint { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::min_align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: uint) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: uint) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in range(0, len) { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as int) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size, mem::min_align_of::<TypedArenaChunk<T>>()); if next.is_not_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { mem::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>())) } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as int) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: uint) -> TypedArena<T> { unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), } } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end
let ptr: &mut T = unsafe { let ptr: &mut T = mem::transmute(self.ptr); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } #[unsafe_destructor] impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as uint; let end = self.ptr.get() as uint; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: int, y: int, z: int, } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { box Point { x: 1, y: 2, z: 3, } }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2, z: 3, } }) }) } #[allow(dead_code)] struct Noncopy { string: String, array: Vec<int>, } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }); } } #[bench] pub fn bench_noncopy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }) }) } #[bench] pub fn bench_noncopy_nonarena(b: &mut Bencher) { b.iter(|| { box Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), } }) } #[bench] pub fn bench_noncopy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| {
{ self.grow() }
conditional_block
lib.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. This file may not be copied, modified, or distributed // except according to those terms. //! The arena, a fast but limited type of allocator. //! //! Arenas are a type of allocator that destroy the objects within, all at //! once, once the arena itself is destroyed. They do not support deallocation //! of individual objects while the arena itself is still alive. The benefit //! of an arena is very fast allocation; just a pointer bump. //! //! This crate has two arenas implemented: `TypedArena`, which is a simpler //! arena but can only hold objects of a single type, and `Arena`, which is a //! more complex, slower arena which can hold objects of any type. #![crate_name = "arena"] #![experimental] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(unsafe_destructor)] #![allow(missing_docs)] extern crate alloc; use std::cell::{Cell, RefCell}; use std::cmp; use std::intrinsics::{TyDesc, get_tydesc}; use std::intrinsics; use std::mem; use std::num::{Int, UnsignedInt}; use std::ptr; use std::rc::Rc; use std::rt::heap::{allocate, deallocate}; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[deriving(Clone, PartialEq)] struct Chunk { data: Rc<RefCell<Vec<u8>>>, fill: Cell<uint>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> uint { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, } impl Arena { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena { Arena::new_with_size(32u) } /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: uint) -> Arena { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), } } } fn chunk(size: uint, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0u), is_copy: Cell::new(is_copy), } } #[unsafe_destructor] impl Drop for Arena { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: uint, align: uint) -> uint { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data: *const uint = mem::transmute(buf.offset(idx as int)); let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as int) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint { p as uint | (is_done as uint) } #[inline] fn un_bitpack_tydesc_ptr(p: uint) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } impl Arena { fn chunk_size(&self) -> uint { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as int) } } #[inline] fn alloc_copy<T>(&self, op: || -> T) -> &mut T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as int), buf.offset(start as int)); } } #[inline] fn alloc_noncopy<T>(&self, op: || -> T) -> &mut T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ty_ptr = ty_ptr as *mut uint; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = mem::transmute(tydesc); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T>(&self, op: || -> T) -> &mut T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] fn test_arena_alloc_nested() { struct Inner { value: uint } struct Outer<'a> { inner: &'a Inner } let arena = Arena::new(); let result = arena.alloc(|| Outer { inner: arena.alloc(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] #[should_fail] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1u8, 2u8] }); } // Now, panic while allocating arena.alloc::<Rc<int>>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. /// /// Safety note: Modifying objects in the arena that have already had their /// `drop` destructors run can cause leaks, because the destructor will not /// run again for these objects. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, } struct
<T> { /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: uint, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: uint) -> uint { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::min_align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: uint) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: uint) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in range(0, len) { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as int) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size, mem::min_align_of::<TypedArenaChunk<T>>()); if next.is_not_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { mem::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>())) } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as int) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: uint) -> TypedArena<T> { unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), } } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end { self.grow() } let ptr: &mut T = unsafe { let ptr: &mut T = mem::transmute(self.ptr); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } #[unsafe_destructor] impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as uint; let end = self.ptr.get() as uint; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: int, y: int, z: int, } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { box Point { x: 1, y: 2, z: 3, } }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2, z: 3, } }) }) } #[allow(dead_code)] struct Noncopy { string: String, array: Vec<int>, } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }); } } #[bench] pub fn bench_noncopy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }) }) } #[bench] pub fn bench_noncopy_nonarena(b: &mut Bencher) { b.iter(|| { box Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), } }) } #[bench] pub fn bench_noncopy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| {
TypedArenaChunk
identifier_name
lib.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. This file may not be copied, modified, or distributed // except according to those terms. //! The arena, a fast but limited type of allocator. //! //! Arenas are a type of allocator that destroy the objects within, all at //! once, once the arena itself is destroyed. They do not support deallocation //! of individual objects while the arena itself is still alive. The benefit //! of an arena is very fast allocation; just a pointer bump. //! //! This crate has two arenas implemented: `TypedArena`, which is a simpler //! arena but can only hold objects of a single type, and `Arena`, which is a //! more complex, slower arena which can hold objects of any type. #![crate_name = "arena"] #![experimental] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(unsafe_destructor)] #![allow(missing_docs)] extern crate alloc; use std::cell::{Cell, RefCell}; use std::cmp; use std::intrinsics::{TyDesc, get_tydesc}; use std::intrinsics; use std::mem; use std::num::{Int, UnsignedInt}; use std::ptr; use std::rc::Rc; use std::rt::heap::{allocate, deallocate}; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[deriving(Clone, PartialEq)] struct Chunk { data: Rc<RefCell<Vec<u8>>>, fill: Cell<uint>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> uint { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, }
} /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: uint) -> Arena { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), } } } fn chunk(size: uint, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0u), is_copy: Cell::new(is_copy), } } #[unsafe_destructor] impl Drop for Arena { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: uint, align: uint) -> uint { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data: *const uint = mem::transmute(buf.offset(idx as int)); let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as int) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint { p as uint | (is_done as uint) } #[inline] fn un_bitpack_tydesc_ptr(p: uint) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } impl Arena { fn chunk_size(&self) -> uint { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as int) } } #[inline] fn alloc_copy<T>(&self, op: || -> T) -> &mut T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as int), buf.offset(start as int)); } } #[inline] fn alloc_noncopy<T>(&self, op: || -> T) -> &mut T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ty_ptr = ty_ptr as *mut uint; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = mem::transmute(tydesc); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T>(&self, op: || -> T) -> &mut T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] fn test_arena_alloc_nested() { struct Inner { value: uint } struct Outer<'a> { inner: &'a Inner } let arena = Arena::new(); let result = arena.alloc(|| Outer { inner: arena.alloc(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] #[should_fail] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1u8, 2u8] }); } // Now, panic while allocating arena.alloc::<Rc<int>>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. /// /// Safety note: Modifying objects in the arena that have already had their /// `drop` destructors run can cause leaks, because the destructor will not /// run again for these objects. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, } struct TypedArenaChunk<T> { /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: uint, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: uint) -> uint { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::min_align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: uint) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: uint) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in range(0, len) { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as int) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size, mem::min_align_of::<TypedArenaChunk<T>>()); if next.is_not_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { mem::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>())) } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as int) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: uint) -> TypedArena<T> { unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), } } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end { self.grow() } let ptr: &mut T = unsafe { let ptr: &mut T = mem::transmute(self.ptr); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } #[unsafe_destructor] impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as uint; let end = self.ptr.get() as uint; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: int, y: int, z: int, } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { box Point { x: 1, y: 2, z: 3, } }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2, z: 3, } }) }) } #[allow(dead_code)] struct Noncopy { string: String, array: Vec<int>, } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }); } } #[bench] pub fn bench_noncopy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }) }) } #[bench] pub fn bench_noncopy_nonarena(b: &mut Bencher) { b.iter(|| { box Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), } }) } #[bench] pub fn bench_noncopy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| {
impl Arena { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena { Arena::new_with_size(32u)
random_line_split
lib.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. This file may not be copied, modified, or distributed // except according to those terms. //! The arena, a fast but limited type of allocator. //! //! Arenas are a type of allocator that destroy the objects within, all at //! once, once the arena itself is destroyed. They do not support deallocation //! of individual objects while the arena itself is still alive. The benefit //! of an arena is very fast allocation; just a pointer bump. //! //! This crate has two arenas implemented: `TypedArena`, which is a simpler //! arena but can only hold objects of a single type, and `Arena`, which is a //! more complex, slower arena which can hold objects of any type. #![crate_name = "arena"] #![experimental] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(unsafe_destructor)] #![allow(missing_docs)] extern crate alloc; use std::cell::{Cell, RefCell}; use std::cmp; use std::intrinsics::{TyDesc, get_tydesc}; use std::intrinsics; use std::mem; use std::num::{Int, UnsignedInt}; use std::ptr; use std::rc::Rc; use std::rt::heap::{allocate, deallocate}; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[deriving(Clone, PartialEq)] struct Chunk { data: Rc<RefCell<Vec<u8>>>, fill: Cell<uint>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> uint { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } /// A slower reflection-based arena that can allocate objects of any type. /// /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For /// each allocated object, the arena stores a pointer to the type descriptor /// followed by the object (potentially with alignment padding after each /// element). When the arena is destroyed, it iterates through all of its /// chunks, and uses the tydesc information to trace through the objects, /// calling the destructors on them. One subtle point that needs to be /// addressed is how to handle panics while running the user provided /// initializer function. It is important to not run the destructor on /// uninitialized objects, but how to detect them is somewhat subtle. Since /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// the most recent object. To solve this without requiring extra space, we /// use the low order bit of the tydesc pointer to encode whether the object /// it describes has been fully initialized. /// /// As an optimization, objects with destructors are stored in different chunks /// than objects without destructors. This reduces overhead when initializing /// plain-old-data (`Copy` types) and means we don't need to waste time running /// their destructors. pub struct Arena { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to access the // head. head: RefCell<Chunk>, copy_head: RefCell<Chunk>, chunks: RefCell<Vec<Chunk>>, } impl Arena { /// Allocates a new Arena with 32 bytes preallocated. pub fn new() -> Arena { Arena::new_with_size(32u) } /// Allocates a new Arena with `initial_size` bytes preallocated. pub fn new_with_size(initial_size: uint) -> Arena { Arena { head: RefCell::new(chunk(initial_size, false)), copy_head: RefCell::new(chunk(initial_size, true)), chunks: RefCell::new(Vec::new()), } } } fn chunk(size: uint, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0u), is_copy: Cell::new(is_copy), } } #[unsafe_destructor] impl Drop for Arena { fn drop(&mut self) { unsafe { destroy_chunk(&*self.head.borrow()); for chunk in self.chunks.borrow().iter() { if!chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: uint, align: uint) -> uint { (base.checked_add(align - 1)).unwrap() &!(align - 1) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data: *const uint = mem::transmute(buf.offset(idx as int)); let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as int) as *const i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a panic occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint { p as uint | (is_done as uint) } #[inline] fn un_bitpack_tydesc_ptr(p: uint) -> (*const TyDesc, bool) { ((p &!1) as *const TyDesc, p & 1 == 1) } impl Arena { fn chunk_size(&self) -> uint { self.copy_head.borrow().capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); *self.copy_head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return self.alloc_copy_grow(n_bytes, align); } let copy_head = self.copy_head.borrow(); copy_head.fill.set(end); unsafe { copy_head.as_ptr().offset(start as int) } } #[inline] fn alloc_copy<T>(&self, op: || -> T) -> &mut T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ptr = ptr as *mut T; ptr::write(&mut (*ptr), op()); return &mut *ptr; } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); *self.head.borrow_mut() = chunk((new_min_chunk_size + 1u).next_power_of_two(), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&self, n_bytes: uint, align: uint) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { let head = self.head.borrow(); let fill = head.fill.get(); let tydesc_start = fill; let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; (start, end, tydesc_start, head.capacity()) }; if end > head_capacity { return self.alloc_noncopy_grow(n_bytes, align); } let head = self.head.borrow(); head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); return (buf.offset(tydesc_start as int), buf.offset(start as int)); } } #[inline] fn alloc_noncopy<T>(&self, op: || -> T) -> &mut T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ty_ptr = ty_ptr as *mut uint; let ptr = ptr as *mut T; // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = mem::transmute(tydesc); // Actually initialize it ptr::write(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return &mut *ptr; } } /// Allocates a new item in the arena, using `op` to initialize the value, /// and returns a reference to it. #[inline] pub fn alloc<T>(&self, op: || -> T) -> &mut T { unsafe { if intrinsics::needs_drop::<T>() { self.alloc_noncopy(op) } else { self.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| Rc::new(i)); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] fn test_arena_alloc_nested() { struct Inner { value: uint } struct Outer<'a> { inner: &'a Inner } let arena = Arena::new(); let result = arena.alloc(|| Outer { inner: arena.alloc(|| Inner { value: 10 }) }); assert_eq!(result.inner.value, 10); } #[test] #[should_fail] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { Rc::new(i) }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1u8, 2u8] }); } // Now, panic while allocating arena.alloc::<Rc<int>>(|| { panic!(); }); } /// A faster arena that can hold objects of only one type. /// /// Safety note: Modifying objects in the arena that have already had their /// `drop` destructors run can cause leaks, because the destructor will not /// run again for these objects. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<*mut TypedArenaChunk<T>>, } struct TypedArenaChunk<T> { /// Pointer to the next arena segment. next: *mut TypedArenaChunk<T>, /// The number of elements that this chunk can hold. capacity: uint, // Objects follow here, suitably aligned. } fn calculate_size<T>(capacity: uint) -> uint { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::min_align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(capacity).unwrap(); size = size.checked_add(elems_size).unwrap(); size } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: uint) -> *mut TypedArenaChunk<T> { let size = calculate_size::<T>(capacity); let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>()) as *mut TypedArenaChunk<T>; if chunk.is_null() { alloc::oom() } (*chunk).next = next; (*chunk).capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: uint) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in range(0, len) { ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as int) } } // Destroy the next chunk. let next = self.next; let size = calculate_size::<T>(self.capacity); deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size, mem::min_align_of::<TypedArenaChunk<T>>()); if next.is_not_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *const u8 { let this: *const TypedArenaChunk<T> = self; unsafe { mem::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>())) } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap(); self.start().offset(size as int) } } } impl<T> TypedArena<T> { /// Creates a new `TypedArena` with preallocated space for eight objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new `TypedArena` with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: uint) -> TypedArena<T>
/// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end { self.grow() } let ptr: &mut T = unsafe { let ptr: &mut T = mem::transmute(self.ptr); ptr::write(ptr, object); self.ptr.set(self.ptr.get().offset(1)); ptr }; ptr } /// Grows the arena. #[inline(never)] fn grow(&self) { unsafe { let chunk = *self.first.borrow_mut(); let new_capacity = (*chunk).capacity.checked_mul(2).unwrap(); let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity); self.ptr.set((*chunk).start() as *const T); self.end.set((*chunk).end() as *const T); *self.first.borrow_mut() = chunk } } } #[unsafe_destructor] impl<T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let start = self.first.borrow().as_ref().unwrap().start() as uint; let end = self.ptr.get() as uint; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. (**self.first.borrow_mut()).destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::{Arena, TypedArena}; #[allow(dead_code)] struct Point { x: int, y: int, z: int, } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { box Point { x: 1, y: 2, z: 3, } }) } #[bench] pub fn bench_copy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| { arena.alloc(|| { Point { x: 1, y: 2, z: 3, } }) }) } #[allow(dead_code)] struct Noncopy { string: String, array: Vec<int>, } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in range(0u, 100000) { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }); } } #[bench] pub fn bench_noncopy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), }) }) } #[bench] pub fn bench_noncopy_nonarena(b: &mut Bencher) { b.iter(|| { box Noncopy { string: "hello world".to_string(), array: vec!( 1, 2, 3, 4, 5 ), } }) } #[bench] pub fn bench_noncopy_old_arena(b: &mut Bencher) { let arena = Arena::new(); b.iter(|| {
{ unsafe { let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity); TypedArena { ptr: Cell::new((*chunk).start() as *const T), end: Cell::new((*chunk).end() as *const T), first: RefCell::new(chunk), } } }
identifier_body
cpu_timing.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. use std::cell::{Cell, RefCell}; use std::rc::Rc; use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn}; use zinc64_emu::cpu::Cpu6510; struct MockMemory { ram: Ram, } impl MockMemory { pub fn new(ram: Ram) -> Self { MockMemory { ram } } } impl Addressable for MockMemory { fn read(&self, address: u16) -> u8 { self.ram.read(address) } fn write(&mut self, address: u16, value: u8) { self.ram.write(address, value); } } fn setup_cpu() -> Cpu6510 { let ba_line = Rc::new(RefCell::new(Pin::new_high())); let cpu_io_port = Rc::new(RefCell::new(IoPort::new(0x00, 0xff))); let cpu_irq = Rc::new(RefCell::new(IrqLine::new("irq"))); let cpu_nmi = Rc::new(RefCell::new(IrqLine::new("nmi"))); let mem = Rc::new(RefCell::new(MockMemory::new(Ram::new(0x10000)))); Cpu6510::new(mem, cpu_io_port, ba_line, cpu_irq, cpu_nmi) } // Based on 65xx Processor Data from http://www.romhacking.net/documents/318/ const OPCODE_TIMING: [u8; 256] = [ 7, // 00 BRK #$ab 6, // 01 ORA ($ab,X) 0, // 02 HLT* 0, // 03 ASO* ($ab,X) 0, // 04 SKB* $ab 3, // 05 ORA $ab 5, // 06 ASL $ab 0, // 07 ASO* $ab 3, // 08 PHP 2, // 09 ORA #$ab 2, // 0A ASL A 0, // 0B ANC* #$ab 0, // 0C SKW* $abcd 4, // 0D ORA $abcd 6, // 0E ASL $abcd 0, // 0F ASO* $abcd 2, // 10 BPL nearlabel 5, // 11 ORA ($ab),Y 0, // 12 HLT* 0, // 13 ASO* ($ab),Y 0, // 14 SKB* $ab,X 4, // 15 ORA $ab,X 6, // 16 ASL $ab,X 0, // 17 ASO* $ab,X 2, // 18 CLC 4, // 19 ORA $abcd,Y 0, // 1A NOP* 0, // 1B ASO* $abcd,Y 0, // 1C SKW* $abcd,X 4, // 1D ORA $abcd,X 7, // 1E ASL $abcd,X 0, // 1F ASO* $abcd,X 6, // 20 JSR $abcd 6, // 21 AND ($ab,X) 0, // 22 HLT* 0, // 23 RLA* ($ab,X) 3, // 24 BIT $ab 3, // 25 AND $ab 5, // 26 ROL $ab 0, // 27 RLA* $ab 4, // 28 PLP 2, // 29 AND #$ab 2, // 2A ROL A 0, // 2B ANC* #$ab 4, // 2C BIT $abcd 4, // 2D AND $abcd 6, // 2E ROL $abcd 0, // 2F RLA* $abcd 2, // 30 BMI nearlabel 5, // 31 AND ($ab),Y 0, // 32 HLT* 0, // 33 RLA* ($ab),Y 0, // 34 SKB* $ab,X 4, // 35 AND $ab,X 6, // 36 ROL $ab,X 0, // 37 RLA* $ab,X 2, // 38 SEC 4, // 39 AND $abcd,Y 0, // 3A NOP* 0, // 3B RLA* $abcd,Y 0, // 3C SKW* $abcd,X 4, // 3D AND $abcd,X 7, // 3E ROL $abcd,X 0, // 3F RLA* $abcd,X 6, // 40 RTI 6, // 41 EOR ($ab,X) 0, // 42 HLT* 8, // 43 LSE* ($ab,X) 0, // 44 SKB* $ab 3, // 45 EOR $ab 5, // 46 LSR $ab 5, // 47 LSE* $ab 3, // 48 PHA 2, // 49 EOR #$ab 2, // 4A LSR A 2, // 4B ALR* #$ab 3, // 4C JMP $abcd 4, // 4D EOR $abcd 6, // 4E LSR $abcd 6, // 4F LSE* $abcd 2, // 50 BVC nearlabel 5, // 51 EOR ($ab),Y 0, // 52 HLT* 8, // 53 LSE* ($ab),Y 0, // 54 SKB* $ab,X 4, // 55 EOR $ab,X 6, // 56 LSR $ab,X 6, // 57 LSE* $ab,X 2, // 58 CLI 4, // 59 EOR $abcd,Y 0, // 5A NOP* 7, // 5B LSE* $abcd,Y 0, // 5C SKW* $abcd,X 4, // 5D EOR $abcd,X 7, // 5E LSR $abcd,X 7, // 5F LSE* $abcd,X 6, // 60 RTS 6, // 61 ADC ($ab,X) 0, // 62 HLT* 0, // 63 RRA* ($ab,X) 0, // 64 SKB* $ab 3, // 65 ADC $ab 5, // 66 ROR $ab 0, // 67 RRA* $ab 4, // 68 PLA 2, // 69 ADC #$ab 2, // 6A ROR A 0, // 6B ARR* #$ab 5, // 6C JMP ($abcd) 4, // 6D ADC $abcd 6, // 6E ROR $abcd 0, // 6F RRA* $abcd 2, // 70 BVS nearlabel 5, // 71 ADC ($ab),Y 0, // 72 HLT* 0, // 73 RRA* ($ab),Y 0, // 74 SKB* $ab,X 4, // 75 ADC $ab,X 6, // 76 ROR $ab,X 0, // 77 RRA* $ab,X 2, // 78 SEI 4, // 79 ADC $abcd,Y 0, // 7A NOP* 0, // 7B RRA* $abcd,Y 0, // 7C SKW* $abcd,X 4, // 7D ADC $abcd,X 7, // 7E ROR $abcd,X 0, // 7F RRA* $abcd,X 0, // 80 SKB* #$ab 6, // 81 STA ($ab,X) 0, // 82 SKB* #$ab 0, // 83 SAX* ($ab,X) 3, // 84 STY $ab 3, // 85 STA $ab 3, // 86 STX $ab 0, // 87 SAX* $ab 2, // 88 DEY 0, // 89 SKB* #$ab 2, // 8A TXA 2, // 8B ANE* #$ab 4, // 8C STY $abcd 4, // 8D STA $abcd 4, // 8E STX $abcd 0, // 8F SAX* $abcd 2, // 90 BCC nearlabel 6, // 91 STA ($ab),Y 0, // 92 HLT* 0, // 93 SHA* ($ab),Y 4, // 94 STY $ab,X 4, // 95 STA $ab,X 4, // 96 STX $ab,Y 0, // 97 SAX* $ab,Y 2, // 98 TYA 5, // 99 STA $abcd,Y 2, // 9A TXS 0, // 9B SHS* $abcd,Y 0, // 9C SHY* $abcd,X 5, // 9D STA $abcd,X 0, // 9E SHX* $abcd,Y 0, // 9F SHA* $abcd,Y 2, // A0 LDY #$ab 6, // A1 LDA ($ab,X) 2, // A2 LDX #$ab 6, // A3 LAX* ($ab,X) 3, // A4 LDY $ab 3, // A5 LDA $ab 3, // A6 LDX $ab 3, // A7 LAX* $ab 2, // A8 TAY 2, // A9 LDA #$ab 2, // AA TAX 2, // AB ANX* #$ab 4, // AC LDY $abcd 4, // AD LDA $abcd 4, // AE LDX $abcd 4, // AF LAX* $abcd 2, // B0 BCS nearlabel 5, // B1 LDA ($ab),Y 0, // B2 HLT* 5, // B3 LAX* ($ab),Y 4, // B4 LDY $ab,X 4, // B5 LDA $ab,X 4, // B6 LDX $ab,Y 4, // B7 LAX* $ab,Y 2, // B8 CLV 4, // B9 LDA $abcd,Y 2, // BA TSX 0, // BB LAS* $abcd,Y 4, // BC LDY $abcd,X 4, // BD LDA $abcd,X 4, // BE LDX $abcd,Y 4, // BF LAX* $abcd,Y 2, // C0 CPY #$ab 6, // C1 CMP ($ab,X) 0, // C2 SKB* #$ab 0, // C3 DCM* ($ab,X) 3, // C4 CPY $ab 3, // C5 CMP $ab 5, // C6 DEC $ab 0, // C7 DCM* $ab 2, // C8 INY 2, // C9 CMP #$ab 2, // CA DEX 2, // CB SBX* #$ab 4, // CC CPY $abcd 4, // CD CMP $abcd 6, // CE DEC $abcd 0, // CF DCM* $abcd 2, // D0 BNE nearlabel 5, // D1 CMP ($ab),Y 0, // D2 HLT* 0, // D3 DCM* ($ab),Y 0, // D4 SKB* $ab,X 4, // D5 CMP $ab,X 6, // D6 DEC $ab,X 0, // D7 DCM* $ab,X 2, // D8 CLD 4, // D9 CMP $abcd,Y 0, // DA NOP* 0, // DB DCM* $abcd,Y 0, // DC SKW* $abcd,X 4, // DD CMP $abcd,X 7, // DE DEC $abcd,X 0, // DF DCM* $abcd,X 2, // E0 CPX #$ab 6, // E1 SBC ($ab,X) 0, // E2 SKB* #$ab 0, // E3 INS* ($ab,X) 3, // E4 CPX $ab 3, // E5 SBC $ab 5, // E6 INC $ab 0, // E7 INS* $ab 2, // E8 INX 2, // E9 SBC #$ab 2, // EA NOP 0, // EB SBC* #$ab 4, // EC CPX $abcd 4, // ED SBC $abcd 6, // EE INC $abcd 0, // EF INS* $abcd 2, // F0 BEQ nearlabel 5, // F1 SBC ($ab),Y 0, // F2 HLT* 0, // F3 INS* ($ab),Y 0, // F4 SKB* $ab,X 4, // F5 SBC $ab,X 6, // F6 INC $ab,X 0, // F7 INS* $ab,X 2, // F8 SED 4, // F9 SBC $abcd,Y 0, // FA NOP* 0, // FB INS* $abcd,Y 0, // FC SKW* $abcd,X 4, // FD SBC $abcd,X 7, // FE INC $abcd,X 0, // FF INS* $abcd,X ]; #[test] fn opcode_timing() { let mut cpu = setup_cpu(); for opcode in 0..256 { let cycles = OPCODE_TIMING[opcode]; if cycles > 0
} }
{ let clock = Rc::new(Cell::new(0u8)); let clock_clone = clock.clone(); let tick_fn: TickFn = Rc::new(move || { clock_clone.set(clock_clone.get().wrapping_add(1)); }); cpu.write(0x1000, opcode as u8); cpu.write(0x1001, 0x00); cpu.write(0x1002, 0x10); cpu.set_pc(0x1000); cpu.step(&tick_fn); assert_eq!( cycles, clock.get(), "opcode {:02x} timing failed", opcode as u8 ); }
conditional_block
cpu_timing.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. use std::cell::{Cell, RefCell}; use std::rc::Rc; use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn}; use zinc64_emu::cpu::Cpu6510; struct MockMemory { ram: Ram, } impl MockMemory { pub fn
(ram: Ram) -> Self { MockMemory { ram } } } impl Addressable for MockMemory { fn read(&self, address: u16) -> u8 { self.ram.read(address) } fn write(&mut self, address: u16, value: u8) { self.ram.write(address, value); } } fn setup_cpu() -> Cpu6510 { let ba_line = Rc::new(RefCell::new(Pin::new_high())); let cpu_io_port = Rc::new(RefCell::new(IoPort::new(0x00, 0xff))); let cpu_irq = Rc::new(RefCell::new(IrqLine::new("irq"))); let cpu_nmi = Rc::new(RefCell::new(IrqLine::new("nmi"))); let mem = Rc::new(RefCell::new(MockMemory::new(Ram::new(0x10000)))); Cpu6510::new(mem, cpu_io_port, ba_line, cpu_irq, cpu_nmi) } // Based on 65xx Processor Data from http://www.romhacking.net/documents/318/ const OPCODE_TIMING: [u8; 256] = [ 7, // 00 BRK #$ab 6, // 01 ORA ($ab,X) 0, // 02 HLT* 0, // 03 ASO* ($ab,X) 0, // 04 SKB* $ab 3, // 05 ORA $ab 5, // 06 ASL $ab 0, // 07 ASO* $ab 3, // 08 PHP 2, // 09 ORA #$ab 2, // 0A ASL A 0, // 0B ANC* #$ab 0, // 0C SKW* $abcd 4, // 0D ORA $abcd 6, // 0E ASL $abcd 0, // 0F ASO* $abcd 2, // 10 BPL nearlabel 5, // 11 ORA ($ab),Y 0, // 12 HLT* 0, // 13 ASO* ($ab),Y 0, // 14 SKB* $ab,X 4, // 15 ORA $ab,X 6, // 16 ASL $ab,X 0, // 17 ASO* $ab,X 2, // 18 CLC 4, // 19 ORA $abcd,Y 0, // 1A NOP* 0, // 1B ASO* $abcd,Y 0, // 1C SKW* $abcd,X 4, // 1D ORA $abcd,X 7, // 1E ASL $abcd,X 0, // 1F ASO* $abcd,X 6, // 20 JSR $abcd 6, // 21 AND ($ab,X) 0, // 22 HLT* 0, // 23 RLA* ($ab,X) 3, // 24 BIT $ab 3, // 25 AND $ab 5, // 26 ROL $ab 0, // 27 RLA* $ab 4, // 28 PLP 2, // 29 AND #$ab 2, // 2A ROL A 0, // 2B ANC* #$ab 4, // 2C BIT $abcd 4, // 2D AND $abcd 6, // 2E ROL $abcd 0, // 2F RLA* $abcd 2, // 30 BMI nearlabel 5, // 31 AND ($ab),Y 0, // 32 HLT* 0, // 33 RLA* ($ab),Y 0, // 34 SKB* $ab,X 4, // 35 AND $ab,X 6, // 36 ROL $ab,X 0, // 37 RLA* $ab,X 2, // 38 SEC 4, // 39 AND $abcd,Y 0, // 3A NOP* 0, // 3B RLA* $abcd,Y 0, // 3C SKW* $abcd,X 4, // 3D AND $abcd,X 7, // 3E ROL $abcd,X 0, // 3F RLA* $abcd,X 6, // 40 RTI 6, // 41 EOR ($ab,X) 0, // 42 HLT* 8, // 43 LSE* ($ab,X) 0, // 44 SKB* $ab 3, // 45 EOR $ab 5, // 46 LSR $ab 5, // 47 LSE* $ab 3, // 48 PHA 2, // 49 EOR #$ab 2, // 4A LSR A 2, // 4B ALR* #$ab 3, // 4C JMP $abcd 4, // 4D EOR $abcd 6, // 4E LSR $abcd 6, // 4F LSE* $abcd 2, // 50 BVC nearlabel 5, // 51 EOR ($ab),Y 0, // 52 HLT* 8, // 53 LSE* ($ab),Y 0, // 54 SKB* $ab,X 4, // 55 EOR $ab,X 6, // 56 LSR $ab,X 6, // 57 LSE* $ab,X 2, // 58 CLI 4, // 59 EOR $abcd,Y 0, // 5A NOP* 7, // 5B LSE* $abcd,Y 0, // 5C SKW* $abcd,X 4, // 5D EOR $abcd,X 7, // 5E LSR $abcd,X 7, // 5F LSE* $abcd,X 6, // 60 RTS 6, // 61 ADC ($ab,X) 0, // 62 HLT* 0, // 63 RRA* ($ab,X) 0, // 64 SKB* $ab 3, // 65 ADC $ab 5, // 66 ROR $ab 0, // 67 RRA* $ab 4, // 68 PLA 2, // 69 ADC #$ab 2, // 6A ROR A 0, // 6B ARR* #$ab 5, // 6C JMP ($abcd) 4, // 6D ADC $abcd 6, // 6E ROR $abcd 0, // 6F RRA* $abcd 2, // 70 BVS nearlabel 5, // 71 ADC ($ab),Y 0, // 72 HLT* 0, // 73 RRA* ($ab),Y 0, // 74 SKB* $ab,X 4, // 75 ADC $ab,X 6, // 76 ROR $ab,X 0, // 77 RRA* $ab,X 2, // 78 SEI 4, // 79 ADC $abcd,Y 0, // 7A NOP* 0, // 7B RRA* $abcd,Y 0, // 7C SKW* $abcd,X 4, // 7D ADC $abcd,X 7, // 7E ROR $abcd,X 0, // 7F RRA* $abcd,X 0, // 80 SKB* #$ab 6, // 81 STA ($ab,X) 0, // 82 SKB* #$ab 0, // 83 SAX* ($ab,X) 3, // 84 STY $ab 3, // 85 STA $ab 3, // 86 STX $ab 0, // 87 SAX* $ab 2, // 88 DEY 0, // 89 SKB* #$ab 2, // 8A TXA 2, // 8B ANE* #$ab 4, // 8C STY $abcd 4, // 8D STA $abcd 4, // 8E STX $abcd 0, // 8F SAX* $abcd 2, // 90 BCC nearlabel 6, // 91 STA ($ab),Y 0, // 92 HLT* 0, // 93 SHA* ($ab),Y 4, // 94 STY $ab,X 4, // 95 STA $ab,X 4, // 96 STX $ab,Y 0, // 97 SAX* $ab,Y 2, // 98 TYA 5, // 99 STA $abcd,Y 2, // 9A TXS 0, // 9B SHS* $abcd,Y 0, // 9C SHY* $abcd,X 5, // 9D STA $abcd,X 0, // 9E SHX* $abcd,Y 0, // 9F SHA* $abcd,Y 2, // A0 LDY #$ab 6, // A1 LDA ($ab,X) 2, // A2 LDX #$ab 6, // A3 LAX* ($ab,X) 3, // A4 LDY $ab 3, // A5 LDA $ab 3, // A6 LDX $ab 3, // A7 LAX* $ab 2, // A8 TAY 2, // A9 LDA #$ab 2, // AA TAX 2, // AB ANX* #$ab 4, // AC LDY $abcd 4, // AD LDA $abcd 4, // AE LDX $abcd 4, // AF LAX* $abcd 2, // B0 BCS nearlabel 5, // B1 LDA ($ab),Y 0, // B2 HLT* 5, // B3 LAX* ($ab),Y 4, // B4 LDY $ab,X 4, // B5 LDA $ab,X 4, // B6 LDX $ab,Y 4, // B7 LAX* $ab,Y 2, // B8 CLV 4, // B9 LDA $abcd,Y 2, // BA TSX 0, // BB LAS* $abcd,Y 4, // BC LDY $abcd,X 4, // BD LDA $abcd,X 4, // BE LDX $abcd,Y 4, // BF LAX* $abcd,Y 2, // C0 CPY #$ab 6, // C1 CMP ($ab,X) 0, // C2 SKB* #$ab 0, // C3 DCM* ($ab,X) 3, // C4 CPY $ab 3, // C5 CMP $ab 5, // C6 DEC $ab 0, // C7 DCM* $ab 2, // C8 INY 2, // C9 CMP #$ab 2, // CA DEX 2, // CB SBX* #$ab 4, // CC CPY $abcd 4, // CD CMP $abcd 6, // CE DEC $abcd 0, // CF DCM* $abcd 2, // D0 BNE nearlabel 5, // D1 CMP ($ab),Y 0, // D2 HLT* 0, // D3 DCM* ($ab),Y 0, // D4 SKB* $ab,X 4, // D5 CMP $ab,X 6, // D6 DEC $ab,X 0, // D7 DCM* $ab,X 2, // D8 CLD 4, // D9 CMP $abcd,Y 0, // DA NOP* 0, // DB DCM* $abcd,Y 0, // DC SKW* $abcd,X 4, // DD CMP $abcd,X 7, // DE DEC $abcd,X 0, // DF DCM* $abcd,X 2, // E0 CPX #$ab 6, // E1 SBC ($ab,X) 0, // E2 SKB* #$ab 0, // E3 INS* ($ab,X) 3, // E4 CPX $ab 3, // E5 SBC $ab 5, // E6 INC $ab 0, // E7 INS* $ab 2, // E8 INX 2, // E9 SBC #$ab 2, // EA NOP 0, // EB SBC* #$ab 4, // EC CPX $abcd 4, // ED SBC $abcd 6, // EE INC $abcd 0, // EF INS* $abcd 2, // F0 BEQ nearlabel 5, // F1 SBC ($ab),Y 0, // F2 HLT* 0, // F3 INS* ($ab),Y 0, // F4 SKB* $ab,X 4, // F5 SBC $ab,X 6, // F6 INC $ab,X 0, // F7 INS* $ab,X 2, // F8 SED 4, // F9 SBC $abcd,Y 0, // FA NOP* 0, // FB INS* $abcd,Y 0, // FC SKW* $abcd,X 4, // FD SBC $abcd,X 7, // FE INC $abcd,X 0, // FF INS* $abcd,X ]; #[test] fn opcode_timing() { let mut cpu = setup_cpu(); for opcode in 0..256 { let cycles = OPCODE_TIMING[opcode]; if cycles > 0 { let clock = Rc::new(Cell::new(0u8)); let clock_clone = clock.clone(); let tick_fn: TickFn = Rc::new(move || { clock_clone.set(clock_clone.get().wrapping_add(1)); }); cpu.write(0x1000, opcode as u8); cpu.write(0x1001, 0x00); cpu.write(0x1002, 0x10); cpu.set_pc(0x1000); cpu.step(&tick_fn); assert_eq!( cycles, clock.get(), "opcode {:02x} timing failed", opcode as u8 ); } } }
new
identifier_name
cpu_timing.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. use std::cell::{Cell, RefCell}; use std::rc::Rc; use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn}; use zinc64_emu::cpu::Cpu6510; struct MockMemory { ram: Ram, } impl MockMemory { pub fn new(ram: Ram) -> Self { MockMemory { ram } } } impl Addressable for MockMemory { fn read(&self, address: u16) -> u8 { self.ram.read(address) } fn write(&mut self, address: u16, value: u8) { self.ram.write(address, value); } } fn setup_cpu() -> Cpu6510 { let ba_line = Rc::new(RefCell::new(Pin::new_high())); let cpu_io_port = Rc::new(RefCell::new(IoPort::new(0x00, 0xff))); let cpu_irq = Rc::new(RefCell::new(IrqLine::new("irq"))); let cpu_nmi = Rc::new(RefCell::new(IrqLine::new("nmi"))); let mem = Rc::new(RefCell::new(MockMemory::new(Ram::new(0x10000)))); Cpu6510::new(mem, cpu_io_port, ba_line, cpu_irq, cpu_nmi) } // Based on 65xx Processor Data from http://www.romhacking.net/documents/318/ const OPCODE_TIMING: [u8; 256] = [ 7, // 00 BRK #$ab 6, // 01 ORA ($ab,X) 0, // 02 HLT* 0, // 03 ASO* ($ab,X) 0, // 04 SKB* $ab 3, // 05 ORA $ab 5, // 06 ASL $ab 0, // 07 ASO* $ab 3, // 08 PHP 2, // 09 ORA #$ab 2, // 0A ASL A 0, // 0B ANC* #$ab 0, // 0C SKW* $abcd 4, // 0D ORA $abcd 6, // 0E ASL $abcd 0, // 0F ASO* $abcd 2, // 10 BPL nearlabel 5, // 11 ORA ($ab),Y 0, // 12 HLT* 0, // 13 ASO* ($ab),Y 0, // 14 SKB* $ab,X 4, // 15 ORA $ab,X 6, // 16 ASL $ab,X 0, // 17 ASO* $ab,X 2, // 18 CLC 4, // 19 ORA $abcd,Y 0, // 1A NOP* 0, // 1B ASO* $abcd,Y 0, // 1C SKW* $abcd,X 4, // 1D ORA $abcd,X 7, // 1E ASL $abcd,X 0, // 1F ASO* $abcd,X 6, // 20 JSR $abcd 6, // 21 AND ($ab,X) 0, // 22 HLT* 0, // 23 RLA* ($ab,X) 3, // 24 BIT $ab 3, // 25 AND $ab 5, // 26 ROL $ab 0, // 27 RLA* $ab 4, // 28 PLP 2, // 29 AND #$ab 2, // 2A ROL A 0, // 2B ANC* #$ab 4, // 2C BIT $abcd 4, // 2D AND $abcd 6, // 2E ROL $abcd 0, // 2F RLA* $abcd 2, // 30 BMI nearlabel 5, // 31 AND ($ab),Y 0, // 32 HLT* 0, // 33 RLA* ($ab),Y 0, // 34 SKB* $ab,X 4, // 35 AND $ab,X 6, // 36 ROL $ab,X 0, // 37 RLA* $ab,X 2, // 38 SEC 4, // 39 AND $abcd,Y 0, // 3A NOP* 0, // 3B RLA* $abcd,Y 0, // 3C SKW* $abcd,X 4, // 3D AND $abcd,X 7, // 3E ROL $abcd,X 0, // 3F RLA* $abcd,X 6, // 40 RTI 6, // 41 EOR ($ab,X) 0, // 42 HLT* 8, // 43 LSE* ($ab,X) 0, // 44 SKB* $ab 3, // 45 EOR $ab 5, // 46 LSR $ab 5, // 47 LSE* $ab 3, // 48 PHA 2, // 49 EOR #$ab 2, // 4A LSR A 2, // 4B ALR* #$ab 3, // 4C JMP $abcd 4, // 4D EOR $abcd 6, // 4E LSR $abcd 6, // 4F LSE* $abcd 2, // 50 BVC nearlabel 5, // 51 EOR ($ab),Y 0, // 52 HLT* 8, // 53 LSE* ($ab),Y 0, // 54 SKB* $ab,X 4, // 55 EOR $ab,X 6, // 56 LSR $ab,X 6, // 57 LSE* $ab,X 2, // 58 CLI 4, // 59 EOR $abcd,Y 0, // 5A NOP* 7, // 5B LSE* $abcd,Y 0, // 5C SKW* $abcd,X 4, // 5D EOR $abcd,X 7, // 5E LSR $abcd,X 7, // 5F LSE* $abcd,X 6, // 60 RTS 6, // 61 ADC ($ab,X) 0, // 62 HLT* 0, // 63 RRA* ($ab,X) 0, // 64 SKB* $ab 3, // 65 ADC $ab 5, // 66 ROR $ab 0, // 67 RRA* $ab 4, // 68 PLA 2, // 69 ADC #$ab 2, // 6A ROR A 0, // 6B ARR* #$ab 5, // 6C JMP ($abcd) 4, // 6D ADC $abcd 6, // 6E ROR $abcd 0, // 6F RRA* $abcd 2, // 70 BVS nearlabel 5, // 71 ADC ($ab),Y 0, // 72 HLT* 0, // 73 RRA* ($ab),Y 0, // 74 SKB* $ab,X 4, // 75 ADC $ab,X 6, // 76 ROR $ab,X 0, // 77 RRA* $ab,X 2, // 78 SEI 4, // 79 ADC $abcd,Y 0, // 7A NOP* 0, // 7B RRA* $abcd,Y 0, // 7C SKW* $abcd,X 4, // 7D ADC $abcd,X 7, // 7E ROR $abcd,X 0, // 7F RRA* $abcd,X 0, // 80 SKB* #$ab 6, // 81 STA ($ab,X) 0, // 82 SKB* #$ab 0, // 83 SAX* ($ab,X) 3, // 84 STY $ab 3, // 85 STA $ab 3, // 86 STX $ab 0, // 87 SAX* $ab 2, // 88 DEY 0, // 89 SKB* #$ab 2, // 8A TXA 2, // 8B ANE* #$ab 4, // 8C STY $abcd 4, // 8D STA $abcd 4, // 8E STX $abcd 0, // 8F SAX* $abcd 2, // 90 BCC nearlabel 6, // 91 STA ($ab),Y 0, // 92 HLT* 0, // 93 SHA* ($ab),Y 4, // 94 STY $ab,X 4, // 95 STA $ab,X 4, // 96 STX $ab,Y 0, // 97 SAX* $ab,Y 2, // 98 TYA 5, // 99 STA $abcd,Y 2, // 9A TXS 0, // 9B SHS* $abcd,Y 0, // 9C SHY* $abcd,X 5, // 9D STA $abcd,X 0, // 9E SHX* $abcd,Y 0, // 9F SHA* $abcd,Y 2, // A0 LDY #$ab 6, // A1 LDA ($ab,X) 2, // A2 LDX #$ab 6, // A3 LAX* ($ab,X) 3, // A4 LDY $ab 3, // A5 LDA $ab 3, // A6 LDX $ab 3, // A7 LAX* $ab 2, // A8 TAY 2, // A9 LDA #$ab 2, // AA TAX 2, // AB ANX* #$ab 4, // AC LDY $abcd 4, // AD LDA $abcd 4, // AE LDX $abcd 4, // AF LAX* $abcd 2, // B0 BCS nearlabel 5, // B1 LDA ($ab),Y 0, // B2 HLT* 5, // B3 LAX* ($ab),Y 4, // B4 LDY $ab,X 4, // B5 LDA $ab,X 4, // B6 LDX $ab,Y 4, // B7 LAX* $ab,Y 2, // B8 CLV 4, // B9 LDA $abcd,Y 2, // BA TSX 0, // BB LAS* $abcd,Y
4, // BE LDX $abcd,Y 4, // BF LAX* $abcd,Y 2, // C0 CPY #$ab 6, // C1 CMP ($ab,X) 0, // C2 SKB* #$ab 0, // C3 DCM* ($ab,X) 3, // C4 CPY $ab 3, // C5 CMP $ab 5, // C6 DEC $ab 0, // C7 DCM* $ab 2, // C8 INY 2, // C9 CMP #$ab 2, // CA DEX 2, // CB SBX* #$ab 4, // CC CPY $abcd 4, // CD CMP $abcd 6, // CE DEC $abcd 0, // CF DCM* $abcd 2, // D0 BNE nearlabel 5, // D1 CMP ($ab),Y 0, // D2 HLT* 0, // D3 DCM* ($ab),Y 0, // D4 SKB* $ab,X 4, // D5 CMP $ab,X 6, // D6 DEC $ab,X 0, // D7 DCM* $ab,X 2, // D8 CLD 4, // D9 CMP $abcd,Y 0, // DA NOP* 0, // DB DCM* $abcd,Y 0, // DC SKW* $abcd,X 4, // DD CMP $abcd,X 7, // DE DEC $abcd,X 0, // DF DCM* $abcd,X 2, // E0 CPX #$ab 6, // E1 SBC ($ab,X) 0, // E2 SKB* #$ab 0, // E3 INS* ($ab,X) 3, // E4 CPX $ab 3, // E5 SBC $ab 5, // E6 INC $ab 0, // E7 INS* $ab 2, // E8 INX 2, // E9 SBC #$ab 2, // EA NOP 0, // EB SBC* #$ab 4, // EC CPX $abcd 4, // ED SBC $abcd 6, // EE INC $abcd 0, // EF INS* $abcd 2, // F0 BEQ nearlabel 5, // F1 SBC ($ab),Y 0, // F2 HLT* 0, // F3 INS* ($ab),Y 0, // F4 SKB* $ab,X 4, // F5 SBC $ab,X 6, // F6 INC $ab,X 0, // F7 INS* $ab,X 2, // F8 SED 4, // F9 SBC $abcd,Y 0, // FA NOP* 0, // FB INS* $abcd,Y 0, // FC SKW* $abcd,X 4, // FD SBC $abcd,X 7, // FE INC $abcd,X 0, // FF INS* $abcd,X ]; #[test] fn opcode_timing() { let mut cpu = setup_cpu(); for opcode in 0..256 { let cycles = OPCODE_TIMING[opcode]; if cycles > 0 { let clock = Rc::new(Cell::new(0u8)); let clock_clone = clock.clone(); let tick_fn: TickFn = Rc::new(move || { clock_clone.set(clock_clone.get().wrapping_add(1)); }); cpu.write(0x1000, opcode as u8); cpu.write(0x1001, 0x00); cpu.write(0x1002, 0x10); cpu.set_pc(0x1000); cpu.step(&tick_fn); assert_eq!( cycles, clock.get(), "opcode {:02x} timing failed", opcode as u8 ); } } }
4, // BC LDY $abcd,X 4, // BD LDA $abcd,X
random_line_split
cpu_timing.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. use std::cell::{Cell, RefCell}; use std::rc::Rc; use zinc64_core::{Addressable, Cpu, IoPort, IrqLine, Pin, Ram, TickFn}; use zinc64_emu::cpu::Cpu6510; struct MockMemory { ram: Ram, } impl MockMemory { pub fn new(ram: Ram) -> Self { MockMemory { ram } } } impl Addressable for MockMemory { fn read(&self, address: u16) -> u8
fn write(&mut self, address: u16, value: u8) { self.ram.write(address, value); } } fn setup_cpu() -> Cpu6510 { let ba_line = Rc::new(RefCell::new(Pin::new_high())); let cpu_io_port = Rc::new(RefCell::new(IoPort::new(0x00, 0xff))); let cpu_irq = Rc::new(RefCell::new(IrqLine::new("irq"))); let cpu_nmi = Rc::new(RefCell::new(IrqLine::new("nmi"))); let mem = Rc::new(RefCell::new(MockMemory::new(Ram::new(0x10000)))); Cpu6510::new(mem, cpu_io_port, ba_line, cpu_irq, cpu_nmi) } // Based on 65xx Processor Data from http://www.romhacking.net/documents/318/ const OPCODE_TIMING: [u8; 256] = [ 7, // 00 BRK #$ab 6, // 01 ORA ($ab,X) 0, // 02 HLT* 0, // 03 ASO* ($ab,X) 0, // 04 SKB* $ab 3, // 05 ORA $ab 5, // 06 ASL $ab 0, // 07 ASO* $ab 3, // 08 PHP 2, // 09 ORA #$ab 2, // 0A ASL A 0, // 0B ANC* #$ab 0, // 0C SKW* $abcd 4, // 0D ORA $abcd 6, // 0E ASL $abcd 0, // 0F ASO* $abcd 2, // 10 BPL nearlabel 5, // 11 ORA ($ab),Y 0, // 12 HLT* 0, // 13 ASO* ($ab),Y 0, // 14 SKB* $ab,X 4, // 15 ORA $ab,X 6, // 16 ASL $ab,X 0, // 17 ASO* $ab,X 2, // 18 CLC 4, // 19 ORA $abcd,Y 0, // 1A NOP* 0, // 1B ASO* $abcd,Y 0, // 1C SKW* $abcd,X 4, // 1D ORA $abcd,X 7, // 1E ASL $abcd,X 0, // 1F ASO* $abcd,X 6, // 20 JSR $abcd 6, // 21 AND ($ab,X) 0, // 22 HLT* 0, // 23 RLA* ($ab,X) 3, // 24 BIT $ab 3, // 25 AND $ab 5, // 26 ROL $ab 0, // 27 RLA* $ab 4, // 28 PLP 2, // 29 AND #$ab 2, // 2A ROL A 0, // 2B ANC* #$ab 4, // 2C BIT $abcd 4, // 2D AND $abcd 6, // 2E ROL $abcd 0, // 2F RLA* $abcd 2, // 30 BMI nearlabel 5, // 31 AND ($ab),Y 0, // 32 HLT* 0, // 33 RLA* ($ab),Y 0, // 34 SKB* $ab,X 4, // 35 AND $ab,X 6, // 36 ROL $ab,X 0, // 37 RLA* $ab,X 2, // 38 SEC 4, // 39 AND $abcd,Y 0, // 3A NOP* 0, // 3B RLA* $abcd,Y 0, // 3C SKW* $abcd,X 4, // 3D AND $abcd,X 7, // 3E ROL $abcd,X 0, // 3F RLA* $abcd,X 6, // 40 RTI 6, // 41 EOR ($ab,X) 0, // 42 HLT* 8, // 43 LSE* ($ab,X) 0, // 44 SKB* $ab 3, // 45 EOR $ab 5, // 46 LSR $ab 5, // 47 LSE* $ab 3, // 48 PHA 2, // 49 EOR #$ab 2, // 4A LSR A 2, // 4B ALR* #$ab 3, // 4C JMP $abcd 4, // 4D EOR $abcd 6, // 4E LSR $abcd 6, // 4F LSE* $abcd 2, // 50 BVC nearlabel 5, // 51 EOR ($ab),Y 0, // 52 HLT* 8, // 53 LSE* ($ab),Y 0, // 54 SKB* $ab,X 4, // 55 EOR $ab,X 6, // 56 LSR $ab,X 6, // 57 LSE* $ab,X 2, // 58 CLI 4, // 59 EOR $abcd,Y 0, // 5A NOP* 7, // 5B LSE* $abcd,Y 0, // 5C SKW* $abcd,X 4, // 5D EOR $abcd,X 7, // 5E LSR $abcd,X 7, // 5F LSE* $abcd,X 6, // 60 RTS 6, // 61 ADC ($ab,X) 0, // 62 HLT* 0, // 63 RRA* ($ab,X) 0, // 64 SKB* $ab 3, // 65 ADC $ab 5, // 66 ROR $ab 0, // 67 RRA* $ab 4, // 68 PLA 2, // 69 ADC #$ab 2, // 6A ROR A 0, // 6B ARR* #$ab 5, // 6C JMP ($abcd) 4, // 6D ADC $abcd 6, // 6E ROR $abcd 0, // 6F RRA* $abcd 2, // 70 BVS nearlabel 5, // 71 ADC ($ab),Y 0, // 72 HLT* 0, // 73 RRA* ($ab),Y 0, // 74 SKB* $ab,X 4, // 75 ADC $ab,X 6, // 76 ROR $ab,X 0, // 77 RRA* $ab,X 2, // 78 SEI 4, // 79 ADC $abcd,Y 0, // 7A NOP* 0, // 7B RRA* $abcd,Y 0, // 7C SKW* $abcd,X 4, // 7D ADC $abcd,X 7, // 7E ROR $abcd,X 0, // 7F RRA* $abcd,X 0, // 80 SKB* #$ab 6, // 81 STA ($ab,X) 0, // 82 SKB* #$ab 0, // 83 SAX* ($ab,X) 3, // 84 STY $ab 3, // 85 STA $ab 3, // 86 STX $ab 0, // 87 SAX* $ab 2, // 88 DEY 0, // 89 SKB* #$ab 2, // 8A TXA 2, // 8B ANE* #$ab 4, // 8C STY $abcd 4, // 8D STA $abcd 4, // 8E STX $abcd 0, // 8F SAX* $abcd 2, // 90 BCC nearlabel 6, // 91 STA ($ab),Y 0, // 92 HLT* 0, // 93 SHA* ($ab),Y 4, // 94 STY $ab,X 4, // 95 STA $ab,X 4, // 96 STX $ab,Y 0, // 97 SAX* $ab,Y 2, // 98 TYA 5, // 99 STA $abcd,Y 2, // 9A TXS 0, // 9B SHS* $abcd,Y 0, // 9C SHY* $abcd,X 5, // 9D STA $abcd,X 0, // 9E SHX* $abcd,Y 0, // 9F SHA* $abcd,Y 2, // A0 LDY #$ab 6, // A1 LDA ($ab,X) 2, // A2 LDX #$ab 6, // A3 LAX* ($ab,X) 3, // A4 LDY $ab 3, // A5 LDA $ab 3, // A6 LDX $ab 3, // A7 LAX* $ab 2, // A8 TAY 2, // A9 LDA #$ab 2, // AA TAX 2, // AB ANX* #$ab 4, // AC LDY $abcd 4, // AD LDA $abcd 4, // AE LDX $abcd 4, // AF LAX* $abcd 2, // B0 BCS nearlabel 5, // B1 LDA ($ab),Y 0, // B2 HLT* 5, // B3 LAX* ($ab),Y 4, // B4 LDY $ab,X 4, // B5 LDA $ab,X 4, // B6 LDX $ab,Y 4, // B7 LAX* $ab,Y 2, // B8 CLV 4, // B9 LDA $abcd,Y 2, // BA TSX 0, // BB LAS* $abcd,Y 4, // BC LDY $abcd,X 4, // BD LDA $abcd,X 4, // BE LDX $abcd,Y 4, // BF LAX* $abcd,Y 2, // C0 CPY #$ab 6, // C1 CMP ($ab,X) 0, // C2 SKB* #$ab 0, // C3 DCM* ($ab,X) 3, // C4 CPY $ab 3, // C5 CMP $ab 5, // C6 DEC $ab 0, // C7 DCM* $ab 2, // C8 INY 2, // C9 CMP #$ab 2, // CA DEX 2, // CB SBX* #$ab 4, // CC CPY $abcd 4, // CD CMP $abcd 6, // CE DEC $abcd 0, // CF DCM* $abcd 2, // D0 BNE nearlabel 5, // D1 CMP ($ab),Y 0, // D2 HLT* 0, // D3 DCM* ($ab),Y 0, // D4 SKB* $ab,X 4, // D5 CMP $ab,X 6, // D6 DEC $ab,X 0, // D7 DCM* $ab,X 2, // D8 CLD 4, // D9 CMP $abcd,Y 0, // DA NOP* 0, // DB DCM* $abcd,Y 0, // DC SKW* $abcd,X 4, // DD CMP $abcd,X 7, // DE DEC $abcd,X 0, // DF DCM* $abcd,X 2, // E0 CPX #$ab 6, // E1 SBC ($ab,X) 0, // E2 SKB* #$ab 0, // E3 INS* ($ab,X) 3, // E4 CPX $ab 3, // E5 SBC $ab 5, // E6 INC $ab 0, // E7 INS* $ab 2, // E8 INX 2, // E9 SBC #$ab 2, // EA NOP 0, // EB SBC* #$ab 4, // EC CPX $abcd 4, // ED SBC $abcd 6, // EE INC $abcd 0, // EF INS* $abcd 2, // F0 BEQ nearlabel 5, // F1 SBC ($ab),Y 0, // F2 HLT* 0, // F3 INS* ($ab),Y 0, // F4 SKB* $ab,X 4, // F5 SBC $ab,X 6, // F6 INC $ab,X 0, // F7 INS* $ab,X 2, // F8 SED 4, // F9 SBC $abcd,Y 0, // FA NOP* 0, // FB INS* $abcd,Y 0, // FC SKW* $abcd,X 4, // FD SBC $abcd,X 7, // FE INC $abcd,X 0, // FF INS* $abcd,X ]; #[test] fn opcode_timing() { let mut cpu = setup_cpu(); for opcode in 0..256 { let cycles = OPCODE_TIMING[opcode]; if cycles > 0 { let clock = Rc::new(Cell::new(0u8)); let clock_clone = clock.clone(); let tick_fn: TickFn = Rc::new(move || { clock_clone.set(clock_clone.get().wrapping_add(1)); }); cpu.write(0x1000, opcode as u8); cpu.write(0x1001, 0x00); cpu.write(0x1002, 0x10); cpu.set_pc(0x1000); cpu.step(&tick_fn); assert_eq!( cycles, clock.get(), "opcode {:02x} timing failed", opcode as u8 ); } } }
{ self.ram.read(address) }
identifier_body
decodable.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The compiler code necessary for #[deriving(Decodable)]. See encodable.rs for more. */ use ast::{MetaItem, Item, Expr, MutMutable, Ident}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_decodable(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { let trait_def = TraitDef { cx: cx, span: span, path: Path::new_(~["extra", "serialize", "Decodable"], None, ~[~Literal(Path::new_local("__D"))], true), additional_bounds: ~[], generics: LifetimeBounds { lifetimes: ~[], bounds: ~[("__D", ~[Path::new(~["extra", "serialize", "Decoder"])])], }, methods: ~[ MethodDef { name: "decode", generics: LifetimeBounds::empty(), explicit_self: None, args: ~[Ptr(~Literal(Path::new_local("__D")), Borrowed(None, MutMutable))], ret_ty: Self, inline: false, const_nonmatching: true, combine_substructure: decodable_substructure, }, ] }; trait_def.expand(mitem, in_items) } fn decodable_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { let decoder = substr.nonself_args[0]; let recurse = ~[cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode")]; // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(span, blkarg); let calldecode = cx.expr_call_global(span, recurse, ~[blkdecoder]); let lambdadecode = cx.lambda_expr_1(span, calldecode, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields) => fields.len(), Named(ref fields) => fields.len() }; let read_struct_field = cx.ident_of("read_struct_field"); let result = decode_static_fields(cx, span, substr.type_ident, summary, |span, name, field| { cx.expr_method_call(span, blkdecoder, read_struct_field, ~[cx.expr_str(span, name), cx.expr_uint(span, field), lambdadecode]) }); cx.expr_method_call(span, decoder, cx.ident_of("read_struct"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.expr_uint(span, nfields), cx.lambda_expr_1(span, result, blkarg)]) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = ~[]; let mut variants = ~[]; let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, f) in fields.iter().enumerate() { let (name, parts) = match *f { (i, ref p) => (i, p) }; variants.push(cx.expr_str(span, cx.str_of(name))); let decoded = decode_static_fields(cx, span, name, parts, |span, _, field| { cx.expr_method_call(span, blkdecoder, rvariant_arg, ~[cx.expr_uint(span, field), lambdadecode]) }); arms.push(cx.arm(span, ~[cx.pat_lit(span, cx.expr_uint(span, i))], decoded)); } arms.push(cx.arm_unreachable(span)); let result = cx.expr_match(span, cx.expr_ident(span, variant), arms); let lambda = cx.lambda_expr(span, ~[blkarg, variant], result); let variant_vec = cx.expr_vec(span, variants); let result = cx.expr_method_call(span, blkdecoder, cx.ident_of("read_enum_variant"), ~[variant_vec, lambda]); cx.expr_method_call(span, decoder, cx.ident_of("read_enum"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.lambda_expr_1(span, result, blkarg)]) } _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)") }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_ident` is the name of this enum variant/struct /// - `getarg` should retrieve the `uint`-th field with name `@str`. fn decode_static_fields(cx: &ExtCtxt, outer_span: Span, outer_pat_ident: Ident, fields: &StaticFields, getarg: |Span, @str, uint| -> @Expr) -> @Expr { match *fields { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(outer_span, outer_pat_ident) } else
} Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter().enumerate().map(|(i, &(name, span))| { cx.field_imm(span, name, getarg(span, cx.str_of(name), i)) }).collect(); cx.expr_struct_ident(outer_span, outer_pat_ident, fields) } } }
{ let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(span, format!("_field{}", i).to_managed(), i) }).collect(); cx.expr_call_ident(outer_span, outer_pat_ident, fields) }
conditional_block
decodable.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The compiler code necessary for #[deriving(Decodable)]. See encodable.rs for more. */ use ast::{MetaItem, Item, Expr, MutMutable, Ident}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_decodable(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { let trait_def = TraitDef { cx: cx, span: span, path: Path::new_(~["extra", "serialize", "Decodable"], None, ~[~Literal(Path::new_local("__D"))], true), additional_bounds: ~[], generics: LifetimeBounds { lifetimes: ~[], bounds: ~[("__D", ~[Path::new(~["extra", "serialize", "Decoder"])])], }, methods: ~[ MethodDef { name: "decode", generics: LifetimeBounds::empty(), explicit_self: None, args: ~[Ptr(~Literal(Path::new_local("__D")), Borrowed(None, MutMutable))], ret_ty: Self, inline: false, const_nonmatching: true, combine_substructure: decodable_substructure, }, ] }; trait_def.expand(mitem, in_items) } fn
(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { let decoder = substr.nonself_args[0]; let recurse = ~[cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode")]; // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(span, blkarg); let calldecode = cx.expr_call_global(span, recurse, ~[blkdecoder]); let lambdadecode = cx.lambda_expr_1(span, calldecode, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields) => fields.len(), Named(ref fields) => fields.len() }; let read_struct_field = cx.ident_of("read_struct_field"); let result = decode_static_fields(cx, span, substr.type_ident, summary, |span, name, field| { cx.expr_method_call(span, blkdecoder, read_struct_field, ~[cx.expr_str(span, name), cx.expr_uint(span, field), lambdadecode]) }); cx.expr_method_call(span, decoder, cx.ident_of("read_struct"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.expr_uint(span, nfields), cx.lambda_expr_1(span, result, blkarg)]) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = ~[]; let mut variants = ~[]; let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, f) in fields.iter().enumerate() { let (name, parts) = match *f { (i, ref p) => (i, p) }; variants.push(cx.expr_str(span, cx.str_of(name))); let decoded = decode_static_fields(cx, span, name, parts, |span, _, field| { cx.expr_method_call(span, blkdecoder, rvariant_arg, ~[cx.expr_uint(span, field), lambdadecode]) }); arms.push(cx.arm(span, ~[cx.pat_lit(span, cx.expr_uint(span, i))], decoded)); } arms.push(cx.arm_unreachable(span)); let result = cx.expr_match(span, cx.expr_ident(span, variant), arms); let lambda = cx.lambda_expr(span, ~[blkarg, variant], result); let variant_vec = cx.expr_vec(span, variants); let result = cx.expr_method_call(span, blkdecoder, cx.ident_of("read_enum_variant"), ~[variant_vec, lambda]); cx.expr_method_call(span, decoder, cx.ident_of("read_enum"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.lambda_expr_1(span, result, blkarg)]) } _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)") }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_ident` is the name of this enum variant/struct /// - `getarg` should retrieve the `uint`-th field with name `@str`. fn decode_static_fields(cx: &ExtCtxt, outer_span: Span, outer_pat_ident: Ident, fields: &StaticFields, getarg: |Span, @str, uint| -> @Expr) -> @Expr { match *fields { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(outer_span, outer_pat_ident) } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(span, format!("_field{}", i).to_managed(), i) }).collect(); cx.expr_call_ident(outer_span, outer_pat_ident, fields) } } Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter().enumerate().map(|(i, &(name, span))| { cx.field_imm(span, name, getarg(span, cx.str_of(name), i)) }).collect(); cx.expr_struct_ident(outer_span, outer_pat_ident, fields) } } }
decodable_substructure
identifier_name
decodable.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The compiler code necessary for #[deriving(Decodable)]. See encodable.rs for more. */ use ast::{MetaItem, Item, Expr, MutMutable, Ident}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_decodable(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item]
const_nonmatching: true, combine_substructure: decodable_substructure, }, ] }; trait_def.expand(mitem, in_items) } fn decodable_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { let decoder = substr.nonself_args[0]; let recurse = ~[cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode")]; // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(span, blkarg); let calldecode = cx.expr_call_global(span, recurse, ~[blkdecoder]); let lambdadecode = cx.lambda_expr_1(span, calldecode, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields) => fields.len(), Named(ref fields) => fields.len() }; let read_struct_field = cx.ident_of("read_struct_field"); let result = decode_static_fields(cx, span, substr.type_ident, summary, |span, name, field| { cx.expr_method_call(span, blkdecoder, read_struct_field, ~[cx.expr_str(span, name), cx.expr_uint(span, field), lambdadecode]) }); cx.expr_method_call(span, decoder, cx.ident_of("read_struct"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.expr_uint(span, nfields), cx.lambda_expr_1(span, result, blkarg)]) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = ~[]; let mut variants = ~[]; let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, f) in fields.iter().enumerate() { let (name, parts) = match *f { (i, ref p) => (i, p) }; variants.push(cx.expr_str(span, cx.str_of(name))); let decoded = decode_static_fields(cx, span, name, parts, |span, _, field| { cx.expr_method_call(span, blkdecoder, rvariant_arg, ~[cx.expr_uint(span, field), lambdadecode]) }); arms.push(cx.arm(span, ~[cx.pat_lit(span, cx.expr_uint(span, i))], decoded)); } arms.push(cx.arm_unreachable(span)); let result = cx.expr_match(span, cx.expr_ident(span, variant), arms); let lambda = cx.lambda_expr(span, ~[blkarg, variant], result); let variant_vec = cx.expr_vec(span, variants); let result = cx.expr_method_call(span, blkdecoder, cx.ident_of("read_enum_variant"), ~[variant_vec, lambda]); cx.expr_method_call(span, decoder, cx.ident_of("read_enum"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.lambda_expr_1(span, result, blkarg)]) } _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)") }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_ident` is the name of this enum variant/struct /// - `getarg` should retrieve the `uint`-th field with name `@str`. fn decode_static_fields(cx: &ExtCtxt, outer_span: Span, outer_pat_ident: Ident, fields: &StaticFields, getarg: |Span, @str, uint| -> @Expr) -> @Expr { match *fields { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(outer_span, outer_pat_ident) } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(span, format!("_field{}", i).to_managed(), i) }).collect(); cx.expr_call_ident(outer_span, outer_pat_ident, fields) } } Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter().enumerate().map(|(i, &(name, span))| { cx.field_imm(span, name, getarg(span, cx.str_of(name), i)) }).collect(); cx.expr_struct_ident(outer_span, outer_pat_ident, fields) } } }
{ let trait_def = TraitDef { cx: cx, span: span, path: Path::new_(~["extra", "serialize", "Decodable"], None, ~[~Literal(Path::new_local("__D"))], true), additional_bounds: ~[], generics: LifetimeBounds { lifetimes: ~[], bounds: ~[("__D", ~[Path::new(~["extra", "serialize", "Decoder"])])], }, methods: ~[ MethodDef { name: "decode", generics: LifetimeBounds::empty(), explicit_self: None, args: ~[Ptr(~Literal(Path::new_local("__D")), Borrowed(None, MutMutable))], ret_ty: Self, inline: false,
identifier_body
decodable.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The compiler code necessary for #[deriving(Decodable)]. See encodable.rs for more. */ use ast::{MetaItem, Item, Expr, MutMutable, Ident}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_decodable(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { let trait_def = TraitDef { cx: cx, span: span, path: Path::new_(~["extra", "serialize", "Decodable"], None, ~[~Literal(Path::new_local("__D"))], true), additional_bounds: ~[], generics: LifetimeBounds { lifetimes: ~[], bounds: ~[("__D", ~[Path::new(~["extra", "serialize", "Decoder"])])], }, methods: ~[ MethodDef { name: "decode", generics: LifetimeBounds::empty(), explicit_self: None, args: ~[Ptr(~Literal(Path::new_local("__D")), Borrowed(None, MutMutable))], ret_ty: Self, inline: false, const_nonmatching: true, combine_substructure: decodable_substructure, }, ] }; trait_def.expand(mitem, in_items) } fn decodable_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { let decoder = substr.nonself_args[0]; let recurse = ~[cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode")]; // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(span, blkarg); let calldecode = cx.expr_call_global(span, recurse, ~[blkdecoder]); let lambdadecode = cx.lambda_expr_1(span, calldecode, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields) => fields.len(), Named(ref fields) => fields.len() }; let read_struct_field = cx.ident_of("read_struct_field"); let result = decode_static_fields(cx, span, substr.type_ident, summary, |span, name, field| {
cx.expr_method_call(span, decoder, cx.ident_of("read_struct"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.expr_uint(span, nfields), cx.lambda_expr_1(span, result, blkarg)]) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = ~[]; let mut variants = ~[]; let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, f) in fields.iter().enumerate() { let (name, parts) = match *f { (i, ref p) => (i, p) }; variants.push(cx.expr_str(span, cx.str_of(name))); let decoded = decode_static_fields(cx, span, name, parts, |span, _, field| { cx.expr_method_call(span, blkdecoder, rvariant_arg, ~[cx.expr_uint(span, field), lambdadecode]) }); arms.push(cx.arm(span, ~[cx.pat_lit(span, cx.expr_uint(span, i))], decoded)); } arms.push(cx.arm_unreachable(span)); let result = cx.expr_match(span, cx.expr_ident(span, variant), arms); let lambda = cx.lambda_expr(span, ~[blkarg, variant], result); let variant_vec = cx.expr_vec(span, variants); let result = cx.expr_method_call(span, blkdecoder, cx.ident_of("read_enum_variant"), ~[variant_vec, lambda]); cx.expr_method_call(span, decoder, cx.ident_of("read_enum"), ~[cx.expr_str(span, cx.str_of(substr.type_ident)), cx.lambda_expr_1(span, result, blkarg)]) } _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)") }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_ident` is the name of this enum variant/struct /// - `getarg` should retrieve the `uint`-th field with name `@str`. fn decode_static_fields(cx: &ExtCtxt, outer_span: Span, outer_pat_ident: Ident, fields: &StaticFields, getarg: |Span, @str, uint| -> @Expr) -> @Expr { match *fields { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(outer_span, outer_pat_ident) } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(span, format!("_field{}", i).to_managed(), i) }).collect(); cx.expr_call_ident(outer_span, outer_pat_ident, fields) } } Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter().enumerate().map(|(i, &(name, span))| { cx.field_imm(span, name, getarg(span, cx.str_of(name), i)) }).collect(); cx.expr_struct_ident(outer_span, outer_pat_ident, fields) } } }
cx.expr_method_call(span, blkdecoder, read_struct_field, ~[cx.expr_str(span, name), cx.expr_uint(span, field), lambdadecode]) });
random_line_split
evaluator.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with zero_sum. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2016-2017 Chris Foster // use std::fmt::Display; use std::ops::{Add, Div, Mul, Neg, Sub}; use state::State; /// An evaluation type. /// /// This is usually a tuple around a signed numeric type. /// /// # Example /// /// There is a [helper macro](../macro.prepare_evaluation_tuple.html) to facilitate the implementation of tuple structs: /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0 > 99000 } /// } /// # fn main() { } /// ``` pub trait Evaluation: Sized + Clone + Copy + Display + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Neg<Output = Self> + Div<Output = Self> + PartialEq + PartialOrd { /// An empty, or zero evaluation. fn null() -> Self; /// Shift the evaluation by the smallest representable amount `steps` times in the positive or negative direction. fn shift(self, steps: i32) -> Self; /// The base value of a win. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn win() -> Self; /// The base value of a loss. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn lose() -> Self { -Self::win() } /// The maximum value representable. This must be safely negatable. fn max() -> Self; /// The minimum value representable. fn min() -> Self { -Self::max() } /// Returns `true` if this evaluation contains a win. This is usually a check to /// see if the value is above a certain threshold. fn is_win(&self) -> bool; /// Returns `true` if this evaluation contains a loss. fn is_lose(&self) -> bool { (-*self).is_win() } /// Returns `true` if this evaluation is either a win or a loss. fn is_end(&self) -> bool { self.is_win() || self.is_lose() } } /// Evaluates a State. pub trait Evaluator { type State: State; type Evaluation: Evaluation; /// Returns the evaluation of `state`. fn evaluate(&self, state: &Self::State) -> Self::Evaluation; /// Returns the evaluation of `state` after executing `plies`. /// /// # Panics /// Will panic if the execution of any ply in `plies` causes an error. fn evaluate_plies(&self, state: &Self::State, plies: &[<Self::State as State>::Ply]) -> Self::Evaluation
} /// Implement arithmetic operators (`Add`, `Sub`, `Mul`, `Neg`, `Div`) and `Display` for a tuple /// struct in terms of the enclosed type. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0.abs() > 99000 } /// } /// # fn main() { } /// ``` #[macro_export] macro_rules! prepare_evaluation_tuple { ($type_: ident) => { impl ::std::ops::Add for $type_ { type Output = $type_; fn add(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a + b) } } impl ::std::ops::Sub for $type_ { type Output = $type_; fn sub(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a - b) } } impl ::std::ops::Mul for $type_ { type Output = $type_; fn mul(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a * b) } } impl ::std::ops::Div for $type_ { type Output = $type_; fn div(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a / b) } } impl ::std::ops::Neg for $type_ { type Output = $type_; fn neg(self) -> $type_ { let $type_(a) = self; $type_(-a) } } impl ::std::fmt::Display for $type_ { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let $type_(a) = *self; write!(f, "{}", a) } } } }
{ let mut state = state.clone(); if let Err(error) = state.execute_plies(plies) { panic!("Error calculating evaluation: {}", error); } if plies.len() % 2 == 0 { self.evaluate(&state) } else { -self.evaluate(&state) } }
identifier_body
evaluator.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with zero_sum. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2016-2017 Chris Foster // use std::fmt::Display; use std::ops::{Add, Div, Mul, Neg, Sub}; use state::State; /// An evaluation type. ///
/// This is usually a tuple around a signed numeric type. /// /// # Example /// /// There is a [helper macro](../macro.prepare_evaluation_tuple.html) to facilitate the implementation of tuple structs: /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0 > 99000 } /// } /// # fn main() { } /// ``` pub trait Evaluation: Sized + Clone + Copy + Display + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Neg<Output = Self> + Div<Output = Self> + PartialEq + PartialOrd { /// An empty, or zero evaluation. fn null() -> Self; /// Shift the evaluation by the smallest representable amount `steps` times in the positive or negative direction. fn shift(self, steps: i32) -> Self; /// The base value of a win. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn win() -> Self; /// The base value of a loss. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn lose() -> Self { -Self::win() } /// The maximum value representable. This must be safely negatable. fn max() -> Self; /// The minimum value representable. fn min() -> Self { -Self::max() } /// Returns `true` if this evaluation contains a win. This is usually a check to /// see if the value is above a certain threshold. fn is_win(&self) -> bool; /// Returns `true` if this evaluation contains a loss. fn is_lose(&self) -> bool { (-*self).is_win() } /// Returns `true` if this evaluation is either a win or a loss. fn is_end(&self) -> bool { self.is_win() || self.is_lose() } } /// Evaluates a State. pub trait Evaluator { type State: State; type Evaluation: Evaluation; /// Returns the evaluation of `state`. fn evaluate(&self, state: &Self::State) -> Self::Evaluation; /// Returns the evaluation of `state` after executing `plies`. /// /// # Panics /// Will panic if the execution of any ply in `plies` causes an error. fn evaluate_plies(&self, state: &Self::State, plies: &[<Self::State as State>::Ply]) -> Self::Evaluation { let mut state = state.clone(); if let Err(error) = state.execute_plies(plies) { panic!("Error calculating evaluation: {}", error); } if plies.len() % 2 == 0 { self.evaluate(&state) } else { -self.evaluate(&state) } } } /// Implement arithmetic operators (`Add`, `Sub`, `Mul`, `Neg`, `Div`) and `Display` for a tuple /// struct in terms of the enclosed type. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0.abs() > 99000 } /// } /// # fn main() { } /// ``` #[macro_export] macro_rules! prepare_evaluation_tuple { ($type_: ident) => { impl ::std::ops::Add for $type_ { type Output = $type_; fn add(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a + b) } } impl ::std::ops::Sub for $type_ { type Output = $type_; fn sub(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a - b) } } impl ::std::ops::Mul for $type_ { type Output = $type_; fn mul(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a * b) } } impl ::std::ops::Div for $type_ { type Output = $type_; fn div(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a / b) } } impl ::std::ops::Neg for $type_ { type Output = $type_; fn neg(self) -> $type_ { let $type_(a) = self; $type_(-a) } } impl ::std::fmt::Display for $type_ { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let $type_(a) = *self; write!(f, "{}", a) } } } }
random_line_split
evaluator.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with zero_sum. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2016-2017 Chris Foster // use std::fmt::Display; use std::ops::{Add, Div, Mul, Neg, Sub}; use state::State; /// An evaluation type. /// /// This is usually a tuple around a signed numeric type. /// /// # Example /// /// There is a [helper macro](../macro.prepare_evaluation_tuple.html) to facilitate the implementation of tuple structs: /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0 > 99000 } /// } /// # fn main() { } /// ``` pub trait Evaluation: Sized + Clone + Copy + Display + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Neg<Output = Self> + Div<Output = Self> + PartialEq + PartialOrd { /// An empty, or zero evaluation. fn null() -> Self; /// Shift the evaluation by the smallest representable amount `steps` times in the positive or negative direction. fn shift(self, steps: i32) -> Self; /// The base value of a win. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn win() -> Self; /// The base value of a loss. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn
() -> Self { -Self::win() } /// The maximum value representable. This must be safely negatable. fn max() -> Self; /// The minimum value representable. fn min() -> Self { -Self::max() } /// Returns `true` if this evaluation contains a win. This is usually a check to /// see if the value is above a certain threshold. fn is_win(&self) -> bool; /// Returns `true` if this evaluation contains a loss. fn is_lose(&self) -> bool { (-*self).is_win() } /// Returns `true` if this evaluation is either a win or a loss. fn is_end(&self) -> bool { self.is_win() || self.is_lose() } } /// Evaluates a State. pub trait Evaluator { type State: State; type Evaluation: Evaluation; /// Returns the evaluation of `state`. fn evaluate(&self, state: &Self::State) -> Self::Evaluation; /// Returns the evaluation of `state` after executing `plies`. /// /// # Panics /// Will panic if the execution of any ply in `plies` causes an error. fn evaluate_plies(&self, state: &Self::State, plies: &[<Self::State as State>::Ply]) -> Self::Evaluation { let mut state = state.clone(); if let Err(error) = state.execute_plies(plies) { panic!("Error calculating evaluation: {}", error); } if plies.len() % 2 == 0 { self.evaluate(&state) } else { -self.evaluate(&state) } } } /// Implement arithmetic operators (`Add`, `Sub`, `Mul`, `Neg`, `Div`) and `Display` for a tuple /// struct in terms of the enclosed type. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0.abs() > 99000 } /// } /// # fn main() { } /// ``` #[macro_export] macro_rules! prepare_evaluation_tuple { ($type_: ident) => { impl ::std::ops::Add for $type_ { type Output = $type_; fn add(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a + b) } } impl ::std::ops::Sub for $type_ { type Output = $type_; fn sub(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a - b) } } impl ::std::ops::Mul for $type_ { type Output = $type_; fn mul(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a * b) } } impl ::std::ops::Div for $type_ { type Output = $type_; fn div(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a / b) } } impl ::std::ops::Neg for $type_ { type Output = $type_; fn neg(self) -> $type_ { let $type_(a) = self; $type_(-a) } } impl ::std::fmt::Display for $type_ { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let $type_(a) = *self; write!(f, "{}", a) } } } }
lose
identifier_name
evaluator.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with zero_sum. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2016-2017 Chris Foster // use std::fmt::Display; use std::ops::{Add, Div, Mul, Neg, Sub}; use state::State; /// An evaluation type. /// /// This is usually a tuple around a signed numeric type. /// /// # Example /// /// There is a [helper macro](../macro.prepare_evaluation_tuple.html) to facilitate the implementation of tuple structs: /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0 > 99000 } /// } /// # fn main() { } /// ``` pub trait Evaluation: Sized + Clone + Copy + Display + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Neg<Output = Self> + Div<Output = Self> + PartialEq + PartialOrd { /// An empty, or zero evaluation. fn null() -> Self; /// Shift the evaluation by the smallest representable amount `steps` times in the positive or negative direction. fn shift(self, steps: i32) -> Self; /// The base value of a win. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn win() -> Self; /// The base value of a loss. The evaluator may add or subtract to it in /// in order to promote it or discourage it in favor of others in the search. fn lose() -> Self { -Self::win() } /// The maximum value representable. This must be safely negatable. fn max() -> Self; /// The minimum value representable. fn min() -> Self { -Self::max() } /// Returns `true` if this evaluation contains a win. This is usually a check to /// see if the value is above a certain threshold. fn is_win(&self) -> bool; /// Returns `true` if this evaluation contains a loss. fn is_lose(&self) -> bool { (-*self).is_win() } /// Returns `true` if this evaluation is either a win or a loss. fn is_end(&self) -> bool { self.is_win() || self.is_lose() } } /// Evaluates a State. pub trait Evaluator { type State: State; type Evaluation: Evaluation; /// Returns the evaluation of `state`. fn evaluate(&self, state: &Self::State) -> Self::Evaluation; /// Returns the evaluation of `state` after executing `plies`. /// /// # Panics /// Will panic if the execution of any ply in `plies` causes an error. fn evaluate_plies(&self, state: &Self::State, plies: &[<Self::State as State>::Ply]) -> Self::Evaluation { let mut state = state.clone(); if let Err(error) = state.execute_plies(plies) { panic!("Error calculating evaluation: {}", error); } if plies.len() % 2 == 0 { self.evaluate(&state) } else
} } /// Implement arithmetic operators (`Add`, `Sub`, `Mul`, `Neg`, `Div`) and `Display` for a tuple /// struct in terms of the enclosed type. /// /// # Example /// /// ```rust /// #[macro_use] /// extern crate zero_sum; /// # use zero_sum::analysis::Evaluation; /// # use std::fmt; /// use std::i32; /// use std::ops::{Add, Div, Mul, Neg, Sub}; /// /// #[derive(Clone, Copy, PartialEq, PartialOrd)] /// struct Eval(i32); /// /// prepare_evaluation_tuple!(Eval); // impl Add, Div, Mul, Neg, Sub, and Display /// /// impl Evaluation for Eval { /// fn null() -> Eval { Eval(0) } /// fn shift(self, steps: i32) -> Eval { Eval(self.0 + steps) } /// fn win() -> Eval { Eval(100000) } /// fn max() -> Eval { Eval(i32::MAX) } /// fn is_win(&self) -> bool { self.0.abs() > 99000 } /// } /// # fn main() { } /// ``` #[macro_export] macro_rules! prepare_evaluation_tuple { ($type_: ident) => { impl ::std::ops::Add for $type_ { type Output = $type_; fn add(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a + b) } } impl ::std::ops::Sub for $type_ { type Output = $type_; fn sub(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a - b) } } impl ::std::ops::Mul for $type_ { type Output = $type_; fn mul(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a * b) } } impl ::std::ops::Div for $type_ { type Output = $type_; fn div(self, $type_(b): $type_) -> $type_ { let $type_(a) = self; $type_(a / b) } } impl ::std::ops::Neg for $type_ { type Output = $type_; fn neg(self) -> $type_ { let $type_(a) = self; $type_(-a) } } impl ::std::fmt::Display for $type_ { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let $type_(a) = *self; write!(f, "{}", a) } } } }
{ -self.evaluate(&state) }
conditional_block
main.rs
extern crate clap; extern crate yaml_rust; extern crate lxd; use std::env; use std::fs::File; use std::io::Read; use clap::{App, Arg, ArgMatches, SubCommand}; use yaml_rust::YamlLoader; use lxd::{Container,LxdServer}; fn create_dividing_line(widths: &Vec<usize>) -> String { let mut dividing_line = String::new(); dividing_line.push_str("+"); for width in widths { dividing_line.push_str(&format!("{:-^1$}", "", width + 2)); dividing_line.push_str("+"); } dividing_line.push_str("\n"); dividing_line } fn create_header_line(headers: &Vec<&str>, widths: &Vec<usize>) -> String { let mut header_line = String::new(); header_line.push_str("|"); for (n, header) in headers.iter().enumerate() { header_line.push_str(&format!("{:^1$}", &header, widths[n] + 2)); header_line.push_str("|"); } header_line.push_str("\n"); header_line } fn create_content_line(item: &Vec<String>, widths: &Vec<usize>) -> String { let mut content_line = String::new(); content_line.push_str("|"); for (n, column_content) in item.iter().enumerate() { content_line.push_str(" "); content_line.push_str(&format!("{:1$}", &column_content, widths[n] + 1)); content_line.push_str("|"); } content_line.push_str("\n"); content_line } fn format_output(headers: &Vec<&str>, items: &Vec<Vec<String>>) -> String { let mut widths = Vec::new(); for header in headers { widths.push(header.len()); } for item in items { for (n, column) in item.iter().enumerate() { if column.len() > widths[n] { widths[n] = column.len(); } } } let dividing_line = create_dividing_line(&widths); let mut output_string = String::new(); output_string.push_str(&dividing_line); output_string.push_str(&create_header_line(headers, &widths)); output_string.push_str(&dividing_line); for item in items { output_string.push_str(&create_content_line(item, &widths)); } output_string.push_str(&dividing_line); output_string } fn prepare_container_line(c: &Container) -> Vec<String>
fn list(matches: &ArgMatches) { let home_dir = env::var("HOME").unwrap(); let mut config_file = File::open(home_dir.clone() + "/.config/lxc/config.yml").unwrap(); let mut file_contents = String::new(); config_file.read_to_string(&mut file_contents).unwrap(); let lxd_config = YamlLoader::load_from_str(&file_contents).unwrap(); let default_remote = lxd_config[0]["default-remote"].as_str().unwrap(); let remote = matches.value_of("resource").unwrap_or(default_remote); let lxd_server = match lxd_config[0]["remotes"][remote]["addr"].as_str() { Some(remote_addr) => remote_addr, None => panic!("No remote named {} configured", remote) }; let server = LxdServer::new( lxd_server, &(home_dir.clone() + "/.config/lxc/client.crt"), &(home_dir.clone() + "/.config/lxc/client.key") ); let headers = vec!["NAME", "STATE", "IPV4", "IPV6", "EPHEMERAL", "SNAPSHOTS"]; let container_items = server.list_containers().iter().map(prepare_container_line).collect(); print!("{}", format_output(&headers, &container_items)); } fn main() { let matches = App::new("lxd") .subcommand(SubCommand::with_name("list") .arg(Arg::with_name("resource") .help("the resource to use") .required(true) .index(1))) .get_matches(); match matches.subcommand_name() { Some("list") => list(matches.subcommand_matches("list").unwrap()), _ => println!("{}", matches.usage()), } }
{ let mut ipv4_address = String::new(); let mut ipv6_address = String::new(); for ip in &c.status.ips { if ip.protocol == "IPV4" && ip.address != "127.0.0.1" { ipv4_address = ip.address.clone(); } if ip.protocol == "IPV6" && ip.address != "::1" { ipv6_address = ip.address.clone(); } } let ephemeral = if c.ephemeral { "YES" } else { "NO" }; vec![c.name.clone(), c.status.status.clone().to_uppercase(), ipv4_address.to_string(), ipv6_address.to_string(), ephemeral.to_string(), c.snapshot_urls.len().to_string()] }
identifier_body
main.rs
extern crate clap; extern crate yaml_rust; extern crate lxd; use std::env; use std::fs::File; use std::io::Read; use clap::{App, Arg, ArgMatches, SubCommand}; use yaml_rust::YamlLoader; use lxd::{Container,LxdServer}; fn create_dividing_line(widths: &Vec<usize>) -> String { let mut dividing_line = String::new(); dividing_line.push_str("+"); for width in widths { dividing_line.push_str(&format!("{:-^1$}", "", width + 2)); dividing_line.push_str("+"); } dividing_line.push_str("\n"); dividing_line } fn create_header_line(headers: &Vec<&str>, widths: &Vec<usize>) -> String { let mut header_line = String::new(); header_line.push_str("|"); for (n, header) in headers.iter().enumerate() { header_line.push_str(&format!("{:^1$}", &header, widths[n] + 2)); header_line.push_str("|"); } header_line.push_str("\n"); header_line } fn
(item: &Vec<String>, widths: &Vec<usize>) -> String { let mut content_line = String::new(); content_line.push_str("|"); for (n, column_content) in item.iter().enumerate() { content_line.push_str(" "); content_line.push_str(&format!("{:1$}", &column_content, widths[n] + 1)); content_line.push_str("|"); } content_line.push_str("\n"); content_line } fn format_output(headers: &Vec<&str>, items: &Vec<Vec<String>>) -> String { let mut widths = Vec::new(); for header in headers { widths.push(header.len()); } for item in items { for (n, column) in item.iter().enumerate() { if column.len() > widths[n] { widths[n] = column.len(); } } } let dividing_line = create_dividing_line(&widths); let mut output_string = String::new(); output_string.push_str(&dividing_line); output_string.push_str(&create_header_line(headers, &widths)); output_string.push_str(&dividing_line); for item in items { output_string.push_str(&create_content_line(item, &widths)); } output_string.push_str(&dividing_line); output_string } fn prepare_container_line(c: &Container) -> Vec<String> { let mut ipv4_address = String::new(); let mut ipv6_address = String::new(); for ip in &c.status.ips { if ip.protocol == "IPV4" && ip.address!= "127.0.0.1" { ipv4_address = ip.address.clone(); } if ip.protocol == "IPV6" && ip.address!= "::1" { ipv6_address = ip.address.clone(); } } let ephemeral = if c.ephemeral { "YES" } else { "NO" }; vec![c.name.clone(), c.status.status.clone().to_uppercase(), ipv4_address.to_string(), ipv6_address.to_string(), ephemeral.to_string(), c.snapshot_urls.len().to_string()] } fn list(matches: &ArgMatches) { let home_dir = env::var("HOME").unwrap(); let mut config_file = File::open(home_dir.clone() + "/.config/lxc/config.yml").unwrap(); let mut file_contents = String::new(); config_file.read_to_string(&mut file_contents).unwrap(); let lxd_config = YamlLoader::load_from_str(&file_contents).unwrap(); let default_remote = lxd_config[0]["default-remote"].as_str().unwrap(); let remote = matches.value_of("resource").unwrap_or(default_remote); let lxd_server = match lxd_config[0]["remotes"][remote]["addr"].as_str() { Some(remote_addr) => remote_addr, None => panic!("No remote named {} configured", remote) }; let server = LxdServer::new( lxd_server, &(home_dir.clone() + "/.config/lxc/client.crt"), &(home_dir.clone() + "/.config/lxc/client.key") ); let headers = vec!["NAME", "STATE", "IPV4", "IPV6", "EPHEMERAL", "SNAPSHOTS"]; let container_items = server.list_containers().iter().map(prepare_container_line).collect(); print!("{}", format_output(&headers, &container_items)); } fn main() { let matches = App::new("lxd") .subcommand(SubCommand::with_name("list") .arg(Arg::with_name("resource") .help("the resource to use") .required(true) .index(1))) .get_matches(); match matches.subcommand_name() { Some("list") => list(matches.subcommand_matches("list").unwrap()), _ => println!("{}", matches.usage()), } }
create_content_line
identifier_name
main.rs
extern crate clap; extern crate yaml_rust; extern crate lxd; use std::env; use std::fs::File; use std::io::Read; use clap::{App, Arg, ArgMatches, SubCommand}; use yaml_rust::YamlLoader; use lxd::{Container,LxdServer}; fn create_dividing_line(widths: &Vec<usize>) -> String { let mut dividing_line = String::new(); dividing_line.push_str("+"); for width in widths { dividing_line.push_str(&format!("{:-^1$}", "", width + 2)); dividing_line.push_str("+"); } dividing_line.push_str("\n"); dividing_line } fn create_header_line(headers: &Vec<&str>, widths: &Vec<usize>) -> String { let mut header_line = String::new(); header_line.push_str("|"); for (n, header) in headers.iter().enumerate() { header_line.push_str(&format!("{:^1$}", &header, widths[n] + 2)); header_line.push_str("|"); } header_line.push_str("\n"); header_line } fn create_content_line(item: &Vec<String>, widths: &Vec<usize>) -> String { let mut content_line = String::new(); content_line.push_str("|"); for (n, column_content) in item.iter().enumerate() { content_line.push_str(" "); content_line.push_str(&format!("{:1$}", &column_content, widths[n] + 1)); content_line.push_str("|"); } content_line.push_str("\n"); content_line } fn format_output(headers: &Vec<&str>, items: &Vec<Vec<String>>) -> String { let mut widths = Vec::new(); for header in headers { widths.push(header.len()); } for item in items { for (n, column) in item.iter().enumerate() { if column.len() > widths[n] { widths[n] = column.len(); } } } let dividing_line = create_dividing_line(&widths); let mut output_string = String::new(); output_string.push_str(&dividing_line); output_string.push_str(&create_header_line(headers, &widths)); output_string.push_str(&dividing_line); for item in items { output_string.push_str(&create_content_line(item, &widths)); } output_string.push_str(&dividing_line); output_string } fn prepare_container_line(c: &Container) -> Vec<String> { let mut ipv4_address = String::new(); let mut ipv6_address = String::new(); for ip in &c.status.ips { if ip.protocol == "IPV4" && ip.address!= "127.0.0.1" { ipv4_address = ip.address.clone(); } if ip.protocol == "IPV6" && ip.address!= "::1" { ipv6_address = ip.address.clone(); } } let ephemeral = if c.ephemeral { "YES" } else { "NO" }; vec![c.name.clone(), c.status.status.clone().to_uppercase(), ipv4_address.to_string(), ipv6_address.to_string(), ephemeral.to_string(), c.snapshot_urls.len().to_string()] } fn list(matches: &ArgMatches) { let home_dir = env::var("HOME").unwrap(); let mut config_file = File::open(home_dir.clone() + "/.config/lxc/config.yml").unwrap(); let mut file_contents = String::new(); config_file.read_to_string(&mut file_contents).unwrap(); let lxd_config = YamlLoader::load_from_str(&file_contents).unwrap(); let default_remote = lxd_config[0]["default-remote"].as_str().unwrap(); let remote = matches.value_of("resource").unwrap_or(default_remote); let lxd_server = match lxd_config[0]["remotes"][remote]["addr"].as_str() { Some(remote_addr) => remote_addr, None => panic!("No remote named {} configured", remote) }; let server = LxdServer::new( lxd_server, &(home_dir.clone() + "/.config/lxc/client.crt"), &(home_dir.clone() + "/.config/lxc/client.key") ); let headers = vec!["NAME", "STATE", "IPV4", "IPV6", "EPHEMERAL", "SNAPSHOTS"]; let container_items = server.list_containers().iter().map(prepare_container_line).collect(); print!("{}", format_output(&headers, &container_items)); } fn main() { let matches = App::new("lxd") .subcommand(SubCommand::with_name("list") .arg(Arg::with_name("resource") .help("the resource to use") .required(true)
match matches.subcommand_name() { Some("list") => list(matches.subcommand_matches("list").unwrap()), _ => println!("{}", matches.usage()), } }
.index(1))) .get_matches();
random_line_split
main.rs
extern crate clap; extern crate yaml_rust; extern crate lxd; use std::env; use std::fs::File; use std::io::Read; use clap::{App, Arg, ArgMatches, SubCommand}; use yaml_rust::YamlLoader; use lxd::{Container,LxdServer}; fn create_dividing_line(widths: &Vec<usize>) -> String { let mut dividing_line = String::new(); dividing_line.push_str("+"); for width in widths { dividing_line.push_str(&format!("{:-^1$}", "", width + 2)); dividing_line.push_str("+"); } dividing_line.push_str("\n"); dividing_line } fn create_header_line(headers: &Vec<&str>, widths: &Vec<usize>) -> String { let mut header_line = String::new(); header_line.push_str("|"); for (n, header) in headers.iter().enumerate() { header_line.push_str(&format!("{:^1$}", &header, widths[n] + 2)); header_line.push_str("|"); } header_line.push_str("\n"); header_line } fn create_content_line(item: &Vec<String>, widths: &Vec<usize>) -> String { let mut content_line = String::new(); content_line.push_str("|"); for (n, column_content) in item.iter().enumerate() { content_line.push_str(" "); content_line.push_str(&format!("{:1$}", &column_content, widths[n] + 1)); content_line.push_str("|"); } content_line.push_str("\n"); content_line } fn format_output(headers: &Vec<&str>, items: &Vec<Vec<String>>) -> String { let mut widths = Vec::new(); for header in headers { widths.push(header.len()); } for item in items { for (n, column) in item.iter().enumerate() { if column.len() > widths[n] { widths[n] = column.len(); } } } let dividing_line = create_dividing_line(&widths); let mut output_string = String::new(); output_string.push_str(&dividing_line); output_string.push_str(&create_header_line(headers, &widths)); output_string.push_str(&dividing_line); for item in items { output_string.push_str(&create_content_line(item, &widths)); } output_string.push_str(&dividing_line); output_string } fn prepare_container_line(c: &Container) -> Vec<String> { let mut ipv4_address = String::new(); let mut ipv6_address = String::new(); for ip in &c.status.ips { if ip.protocol == "IPV4" && ip.address!= "127.0.0.1"
if ip.protocol == "IPV6" && ip.address!= "::1" { ipv6_address = ip.address.clone(); } } let ephemeral = if c.ephemeral { "YES" } else { "NO" }; vec![c.name.clone(), c.status.status.clone().to_uppercase(), ipv4_address.to_string(), ipv6_address.to_string(), ephemeral.to_string(), c.snapshot_urls.len().to_string()] } fn list(matches: &ArgMatches) { let home_dir = env::var("HOME").unwrap(); let mut config_file = File::open(home_dir.clone() + "/.config/lxc/config.yml").unwrap(); let mut file_contents = String::new(); config_file.read_to_string(&mut file_contents).unwrap(); let lxd_config = YamlLoader::load_from_str(&file_contents).unwrap(); let default_remote = lxd_config[0]["default-remote"].as_str().unwrap(); let remote = matches.value_of("resource").unwrap_or(default_remote); let lxd_server = match lxd_config[0]["remotes"][remote]["addr"].as_str() { Some(remote_addr) => remote_addr, None => panic!("No remote named {} configured", remote) }; let server = LxdServer::new( lxd_server, &(home_dir.clone() + "/.config/lxc/client.crt"), &(home_dir.clone() + "/.config/lxc/client.key") ); let headers = vec!["NAME", "STATE", "IPV4", "IPV6", "EPHEMERAL", "SNAPSHOTS"]; let container_items = server.list_containers().iter().map(prepare_container_line).collect(); print!("{}", format_output(&headers, &container_items)); } fn main() { let matches = App::new("lxd") .subcommand(SubCommand::with_name("list") .arg(Arg::with_name("resource") .help("the resource to use") .required(true) .index(1))) .get_matches(); match matches.subcommand_name() { Some("list") => list(matches.subcommand_matches("list").unwrap()), _ => println!("{}", matches.usage()), } }
{ ipv4_address = ip.address.clone(); }
conditional_block
string.rs
/* * Copyright (c) 2016 Boucher, Antoni <[email protected]> * * 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. */ /// Convert a snake case string to a camel case. pub fn snake_to_camel(string: &str) -> String { let mut chars = string.chars(); let string = match chars.next() { None => String::new(), Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(), }; let mut camel = String::new(); let mut underscore = false; for character in string.chars() { if character == '_' { underscore = true; } else { if underscore { camel.push_str(&character.to_uppercase().collect::<String>()); } else { camel.push(character); } underscore = false; } } camel } /// Transform a camel case command name to its dashed version. /// WinOpen is transformed to win-open. pub fn to_dash_name(name: &str) -> String { let mut result = String::new(); for (index, character) in name.chars().enumerate() { let string: String = character.to_lowercase().collect(); if character.is_uppercase() && index > 0 {
} result.push_str(&string); } result }
result.push('-');
random_line_split
string.rs
/* * Copyright (c) 2016 Boucher, Antoni <[email protected]> * * 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. */ /// Convert a snake case string to a camel case. pub fn snake_to_camel(string: &str) -> String
underscore = false; } } camel } /// Transform a camel case command name to its dashed version. /// WinOpen is transformed to win-open. pub fn to_dash_name(name: &str) -> String { let mut result = String::new(); for (index, character) in name.chars().enumerate() { let string: String = character.to_lowercase().collect(); if character.is_uppercase() && index > 0 { result.push('-'); } result.push_str(&string); } result }
{ let mut chars = string.chars(); let string = match chars.next() { None => String::new(), Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(), }; let mut camel = String::new(); let mut underscore = false; for character in string.chars() { if character == '_' { underscore = true; } else { if underscore { camel.push_str(&character.to_uppercase().collect::<String>()); } else { camel.push(character); }
identifier_body
string.rs
/* * Copyright (c) 2016 Boucher, Antoni <[email protected]> * * 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. */ /// Convert a snake case string to a camel case. pub fn snake_to_camel(string: &str) -> String { let mut chars = string.chars(); let string = match chars.next() { None => String::new(), Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(), }; let mut camel = String::new(); let mut underscore = false; for character in string.chars() { if character == '_' { underscore = true; } else { if underscore { camel.push_str(&character.to_uppercase().collect::<String>()); } else { camel.push(character); } underscore = false; } } camel } /// Transform a camel case command name to its dashed version. /// WinOpen is transformed to win-open. pub fn
(name: &str) -> String { let mut result = String::new(); for (index, character) in name.chars().enumerate() { let string: String = character.to_lowercase().collect(); if character.is_uppercase() && index > 0 { result.push('-'); } result.push_str(&string); } result }
to_dash_name
identifier_name
histogram.rs
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ #include "ip.rsh" rs_allocation gSrc; rs_allocation gDest; rs_allocation gSums; rs_allocation gSum; int gWidth; int gHeight; int gStep; int gSteps; void RS_KERNEL pass1(int in, uint x, uint y) { for (int i=0; i < (256); i++) { rsSetElementAt_int(gSums, 0, i, y); } for (int i = 0; i < gStep; i++) { int py = y*gStep + i; if (py >= gHeight) return; for (int px=0; px < gWidth; px++) { uchar4 c = rsGetElementAt_uchar4(gSrc, px, py); int lum = (77 * c.r + 150 * c.g + 29 * c.b) >> 8; int old = rsGetElementAt_int(gSums, lum, y); rsSetElementAt_int(gSums, old+1, lum, y); } } } int RS_KERNEL pass2(uint x) { int sum = 0; for (int i=0; i < gSteps; i++) { sum += rsGetElementAt_int(gSums, x, i); } return sum; } void rescale() { int maxv = 0; for (int i=0; i < 256; i++) { maxv = max(maxv, rsGetElementAt_int(gSum, i)); } float overMax = (1.f / maxv) * gHeight; for (int i=0; i < 256; i++) { int t = rsGetElementAt_int(gSum, i); t = gHeight - (overMax * rsGetElementAt_int(gSum, i)); t = max(0, t); rsSetElementAt_int(gSum, t, i); } } static const uchar4 gClear = {0, 0, 0, 0xff}; uchar4 RS_KERNEL clear() { return gClear; } uchar4 RS_KERNEL draw(uint x, uint y) { int l = rsGetElementAt_int(gSum, x >> 2); if (y > l) {
return gClear; }
return 0xff; }
random_line_split
project-fn-ret-contravariant.rs
#![feature(unboxed_closures)] #![feature(rustc_attrs)] // Test for projection cache. We should be able to project distinct // lifetimes from `foo` as we reinstantiate it multiple times, but not // if we do it just once. In this variant, the region `'a` is used in // an contravariant position, which affects the results. // revisions: ok oneuse transmute krisskross #![allow(dead_code, unused_variables)] fn foo<'a>() -> &'a u32 { loop { } } fn
<T>(t: T, x: T::Output) -> T::Output where T: FnOnce<()> { t() } #[cfg(ok)] // two instantiations: OK fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let a = bar(foo, x); let b = bar(foo, y); (a, b) } #[cfg(oneuse)] // one instantiation: OK (surprisingly) fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let f /* : fn() -> &'static u32 */ = foo; // <-- inferred type annotated let a = bar(f, x); // this is considered ok because fn args are contravariant... let b = bar(f, y); //...and hence we infer T to distinct values in each call. (a, b) } #[cfg(transmute)] // one instantiations: BAD fn baz<'a,'b>(x: &'a u32) -> &'static u32 { bar(foo, x) //[transmute]~ ERROR E0759 } #[cfg(krisskross)] // two instantiations, mixing and matching: BAD fn transmute<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let a = bar(foo, y); let b = bar(foo, x); (a, b) //[krisskross]~ ERROR lifetime mismatch [E0623] //[krisskross]~^ ERROR lifetime mismatch [E0623] } #[rustc_error] fn main() { } //[ok,oneuse]~ ERROR fatal error triggered by #[rustc_error]
bar
identifier_name
project-fn-ret-contravariant.rs
#![feature(unboxed_closures)] #![feature(rustc_attrs)] // Test for projection cache. We should be able to project distinct // lifetimes from `foo` as we reinstantiate it multiple times, but not // if we do it just once. In this variant, the region `'a` is used in // an contravariant position, which affects the results. // revisions: ok oneuse transmute krisskross #![allow(dead_code, unused_variables)] fn foo<'a>() -> &'a u32 { loop { } } fn bar<T>(t: T, x: T::Output) -> T::Output where T: FnOnce<()> { t() } #[cfg(ok)] // two instantiations: OK fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let a = bar(foo, x); let b = bar(foo, y); (a, b) } #[cfg(oneuse)] // one instantiation: OK (surprisingly) fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let f /* : fn() -> &'static u32 */ = foo; // <-- inferred type annotated let a = bar(f, x); // this is considered ok because fn args are contravariant... let b = bar(f, y); //...and hence we infer T to distinct values in each call.
#[cfg(transmute)] // one instantiations: BAD fn baz<'a,'b>(x: &'a u32) -> &'static u32 { bar(foo, x) //[transmute]~ ERROR E0759 } #[cfg(krisskross)] // two instantiations, mixing and matching: BAD fn transmute<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let a = bar(foo, y); let b = bar(foo, x); (a, b) //[krisskross]~ ERROR lifetime mismatch [E0623] //[krisskross]~^ ERROR lifetime mismatch [E0623] } #[rustc_error] fn main() { } //[ok,oneuse]~ ERROR fatal error triggered by #[rustc_error]
(a, b) }
random_line_split
project-fn-ret-contravariant.rs
#![feature(unboxed_closures)] #![feature(rustc_attrs)] // Test for projection cache. We should be able to project distinct // lifetimes from `foo` as we reinstantiate it multiple times, but not // if we do it just once. In this variant, the region `'a` is used in // an contravariant position, which affects the results. // revisions: ok oneuse transmute krisskross #![allow(dead_code, unused_variables)] fn foo<'a>() -> &'a u32 { loop { } } fn bar<T>(t: T, x: T::Output) -> T::Output where T: FnOnce<()> { t() } #[cfg(ok)] // two instantiations: OK fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32)
#[cfg(oneuse)] // one instantiation: OK (surprisingly) fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let f /* : fn() -> &'static u32 */ = foo; // <-- inferred type annotated let a = bar(f, x); // this is considered ok because fn args are contravariant... let b = bar(f, y); //...and hence we infer T to distinct values in each call. (a, b) } #[cfg(transmute)] // one instantiations: BAD fn baz<'a,'b>(x: &'a u32) -> &'static u32 { bar(foo, x) //[transmute]~ ERROR E0759 } #[cfg(krisskross)] // two instantiations, mixing and matching: BAD fn transmute<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let a = bar(foo, y); let b = bar(foo, x); (a, b) //[krisskross]~ ERROR lifetime mismatch [E0623] //[krisskross]~^ ERROR lifetime mismatch [E0623] } #[rustc_error] fn main() { } //[ok,oneuse]~ ERROR fatal error triggered by #[rustc_error]
{ let a = bar(foo, x); let b = bar(foo, y); (a, b) }
identifier_body
glue.rs
<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, size: ValueRef, align: ValueRef, debug_loc: DebugLoc) -> Block<'blk, 'tcx> { let _icx = push_ctxt("trans_exchange_free"); let ccx = cx.ccx(); callee::trans_lang_call(cx, langcall(cx, None, "", ExchangeFreeFnLangItem), &[PointerCast(cx, v, Type::i8p(ccx)), size, align], Some(expr::Ignore), debug_loc).bcx } pub fn trans_exchange_free<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, size: u64, align: u32, debug_loc: DebugLoc) -> Block<'blk, 'tcx> { trans_exchange_free_dyn(cx, v, C_uint(cx.ccx(), size), C_uint(cx.ccx(), align), debug_loc) } pub fn trans_exchange_free_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, content_ty: Ty<'tcx>, debug_loc: DebugLoc) -> Block<'blk, 'tcx> { assert!(type_is_sized(bcx.ccx().tcx(), content_ty)); let sizing_type = sizing_type_of(bcx.ccx(), content_ty); let content_size = llsize_of_alloc(bcx.ccx(), sizing_type); // `Box<ZeroSizeType>` does not allocate. if content_size!= 0 { let content_align = align_of(bcx.ccx(), content_ty); trans_exchange_free(bcx, ptr, content_size, content_align, debug_loc) } else { bcx } } pub fn get_drop_glue_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> { let tcx = ccx.tcx(); // Even if there is no dtor for t, there might be one deeper down and we // might need to pass in the vtable ptr. if!type_is_sized(tcx, t) { return t } // FIXME (#22815): note that type_needs_drop conservatively // approximates in some cases and may say a type expression // requires drop glue when it actually does not. // // (In this case it is not clear whether any harm is done, i.e. // erroneously returning `t` in some cases where we could have // returned `tcx.types.i8` does not appear unsound. The impact on // code quality is unknown at this time.) if!type_needs_drop(tcx, t) { return tcx.types.i8; } match t.sty { ty::TyBox(typ) if!type_needs_drop(tcx, typ) && type_is_sized(tcx, typ) => { let llty = sizing_type_of(ccx, typ); // `Box<ZeroSizeType>` does not allocate. if llsize_of_alloc(ccx, llty) == 0 { tcx.types.i8 } else { t } } _ => t } } pub fn drop_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>, debug_loc: DebugLoc) -> Block<'blk, 'tcx> { drop_ty_core(bcx, v, t, debug_loc, false, None) } pub fn drop_ty_core<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>, debug_loc: DebugLoc, skip_dtor: bool, drop_hint: Option<cleanup::DropHintValue>) -> Block<'blk, 'tcx> { // NB: v is an *alias* of type t here, not a direct value. debug!("drop_ty_core(t={:?}, skip_dtor={} drop_hint={:?})", t, skip_dtor, drop_hint); let _icx = push_ctxt("drop_ty"); let mut bcx = bcx; if bcx.fcx.type_needs_drop(t) { let ccx = bcx.ccx(); let g = if skip_dtor { DropGlueKind::TyContents(t) } else { DropGlueKind::Ty(t) }; let glue = get_drop_glue_core(ccx, g); let glue_type = get_drop_glue_type(ccx, t); let ptr = if glue_type!= t { PointerCast(bcx, v, type_of(ccx, glue_type).ptr_to()) } else { v }; match drop_hint { Some(drop_hint) => { let hint_val = load_ty(bcx, drop_hint.value(), bcx.tcx().types.u8); let moved_val = C_integral(Type::i8(bcx.ccx()), adt::DTOR_MOVED_HINT as u64, false); let may_need_drop = ICmp(bcx, llvm::IntNE, hint_val, moved_val, DebugLoc::None); bcx = with_cond(bcx, may_need_drop, |cx| { Call(cx, glue, &[ptr], None, debug_loc); cx }) } None => { // No drop-hint ==> call standard drop glue Call(bcx, glue, &[ptr], None, debug_loc); } } } bcx } pub fn drop_ty_immediate<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>, debug_loc: DebugLoc, skip_dtor: bool) -> Block<'blk, 'tcx> { let _icx = push_ctxt("drop_ty_immediate"); let vp = alloca(bcx, type_of(bcx.ccx(), t), ""); store_ty(bcx, v, vp, t); drop_ty_core(bcx, vp, t, debug_loc, skip_dtor, None) } pub fn get_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> ValueRef { get_drop_glue_core(ccx, DropGlueKind::Ty(t)) } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum DropGlueKind<'tcx> { /// The normal path; runs the dtor, and then recurs on the contents Ty(Ty<'tcx>), /// Skips the dtor, if any, for ty; drops the contents directly. /// Note that the dtor is only skipped at the most *shallow* /// level, namely, an `impl Drop for Ty` itself. So, for example, /// if Ty is Newtype(S) then only the Drop impl for for Newtype /// itself will be skipped, while the Drop impl for S, if any, /// will be invoked. TyContents(Ty<'tcx>), } impl<'tcx> DropGlueKind<'tcx> { fn ty(&self) -> Ty<'tcx> { match *self { DropGlueKind::Ty(t) | DropGlueKind::TyContents(t) => t } } fn map_ty<F>(&self, mut f: F) -> DropGlueKind<'tcx> where F: FnMut(Ty<'tcx>) -> Ty<'tcx> { match *self { DropGlueKind::Ty(t) => DropGlueKind::Ty(f(t)), DropGlueKind::TyContents(t) => DropGlueKind::TyContents(f(t)), } } } fn get_drop_glue_core<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, g: DropGlueKind<'tcx>) -> ValueRef { debug!("make drop glue for {:?}", g); let g = g.map_ty(|t| get_drop_glue_type(ccx, t)); debug!("drop glue type {:?}", g); match ccx.drop_glues().borrow().get(&g) { Some(&glue) => return glue, _ => { } } let t = g.ty(); let llty = if type_is_sized(ccx.tcx(), t) { type_of(ccx, t).ptr_to() } else { type_of(ccx, ccx.tcx().mk_box(t)).ptr_to() }; let llfnty = Type::glue_fn(ccx, llty); // To avoid infinite recursion, don't `make_drop_glue` until after we've // added the entry to the `drop_glues` cache. if let Some(old_sym) = ccx.available_drop_glues().borrow().get(&g) { let llfn = declare::declare_cfn(ccx, &old_sym, llfnty, ccx.tcx().mk_nil()); ccx.drop_glues().borrow_mut().insert(g, llfn); return llfn; }; let fn_nm = mangle_internal_name_by_type_and_seq(ccx, t, "drop"); let llfn = declare::define_cfn(ccx, &fn_nm, llfnty, ccx.tcx().mk_nil()).unwrap_or_else(||{ ccx.sess().bug(&format!("symbol `{}` already defined", fn_nm)); }); ccx.available_drop_glues().borrow_mut().insert(g, fn_nm); let _s = StatRecorder::new(ccx, format!("drop {:?}", t)); let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty()); let (arena, fcx): (TypedArena<_>, FunctionContext); arena = TypedArena::new(); fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, false, ty::FnConverging(ccx.tcx().mk_nil()), empty_substs, None, &arena); let bcx = init_function(&fcx, false, ty::FnConverging(ccx.tcx().mk_nil())); update_linkage(ccx, llfn, None, OriginalTranslation); ccx.stats().n_glues_created.set(ccx.stats().n_glues_created.get() + 1); // All glue functions take values passed *by alias*; this is a // requirement since in many contexts glue is invoked indirectly and // the caller has no idea if it's dealing with something that can be // passed by value. // // llfn is expected be declared to take a parameter of the appropriate // type, so we don't need to explicitly cast the function parameter. let llrawptr0 = get_param(llfn, fcx.arg_offset() as c_uint); let bcx = make_drop_glue(bcx, llrawptr0, g); finish_fn(&fcx, bcx, ty::FnConverging(ccx.tcx().mk_nil()), DebugLoc::None); llfn } fn trans_struct_drop_flag<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, struct_data: ValueRef, dtor_did: ast::DefId, class_did: ast::DefId, substs: &subst::Substs<'tcx>) -> Block<'blk, 'tcx> { assert!(type_is_sized(bcx.tcx(), t), "Precondition: caller must ensure t is sized"); let repr = adt::represent_type(bcx.ccx(), t); let drop_flag = unpack_datum!(bcx, adt::trans_drop_flag_ptr(bcx, &*repr, struct_data)); let loaded = load_ty(bcx, drop_flag.val, bcx.tcx().dtor_type()); let drop_flag_llty = type_of(bcx.fcx.ccx, bcx.tcx().dtor_type()); let init_val = C_integral(drop_flag_llty, adt::DTOR_NEEDED as u64, false); let bcx = if!bcx.ccx().check_drop_flag_for_sanity() { bcx } else { let drop_flag_llty = type_of(bcx.fcx.ccx, bcx.tcx().dtor_type()); let done_val = C_integral(drop_flag_llty, adt::DTOR_DONE as u64, false); let not_init = ICmp(bcx, llvm::IntNE, loaded, init_val, DebugLoc::None); let not_done = ICmp(bcx, llvm::IntNE, loaded, done_val, DebugLoc::None); let drop_flag_neither_initialized_nor_cleared = And(bcx, not_init, not_done, DebugLoc::None); with_cond(bcx, drop_flag_neither_initialized_nor_cleared, |cx| { let llfn = cx.ccx().get_intrinsic(&("llvm.debugtrap")); Call(cx, llfn, &[], None, DebugLoc::None); cx }) }; let drop_flag_dtor_needed = ICmp(bcx, llvm::IntEQ, loaded, init_val, DebugLoc::None); with_cond(bcx, drop_flag_dtor_needed, |cx| { trans_struct_drop(cx, t, struct_data, dtor_did, class_did, substs) }) } pub fn get_res_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId, parent_id: ast::DefId, substs: &Substs<'tcx>) -> ValueRef { let _icx = push_ctxt("trans_res_dtor"); let did = inline::maybe_instantiate_inline(ccx, did); if!substs.types.is_empty() { assert_eq!(did.krate, ast::LOCAL_CRATE); // Since we're in trans we don't care for any region parameters let substs = ccx.tcx().mk_substs(Substs::erased(substs.types.clone())); let (val, _, _) = monomorphize::monomorphic_fn(ccx, did, substs, None); val } else if did.krate == ast::LOCAL_CRATE { get_item_val(ccx, did.node) } else { let tcx = ccx.tcx(); let name = csearch::get_symbol(&ccx.sess().cstore, did); let class_ty = tcx.lookup_item_type(parent_id).ty.subst(tcx, substs); let llty = type_of_dtor(ccx, class_ty); foreign::get_extern_fn(ccx, &mut *ccx.externs().borrow_mut(), &name[..], llvm::CCallConv, llty, ccx.tcx().mk_nil()) } } fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, v0: ValueRef, dtor_did: ast::DefId, class_did: ast::DefId, substs: &subst::Substs<'tcx>) -> Block<'blk, 'tcx> { debug!("trans_struct_drop t: {}", t); // Find and call the actual destructor let dtor_addr = get_res_dtor(bcx.ccx(), dtor_did, class_did, substs); // Class dtors have no explicit args, so the params should // just consist of the environment (self). let params = unsafe { let ty = Type::from_ref(llvm::LLVMTypeOf(dtor_addr)); ty.element_type().func_params() }; assert_eq!(params.len(), if type_is_sized(bcx.tcx(), t) { 1 } else { 2 }); // Be sure to put the contents into a scope so we can use an invoke // instruction to call the user destructor but still call the field // destructors if the user destructor panics. // // FIXME (#14875) panic-in-drop semantics might be unsupported; we // might well consider changing below to more direct code. let contents_scope = bcx.fcx.push_custom_cleanup_scope(); // Issue #23611: schedule cleanup of contents, re-inspecting the // discriminant (if any) in case of variant swap in drop code. bcx.fcx.schedule_drop_adt_contents(cleanup::CustomScope(contents_scope), v0, t); let glue_type = get_drop_glue_type(bcx.ccx(), t); let dtor_ty = bcx.tcx().mk_ctor_fn(class_did, &[glue_type], bcx.tcx().mk_nil()); let (_, bcx) = if type_is_sized(bcx.tcx(), t) { invoke(bcx, dtor_addr, &[v0], dtor_ty, DebugLoc::None) } else { let args = [Load(bcx, expr::get_dataptr(bcx, v0)), Load(bcx, expr::get_len(bcx, v0))]; invoke(bcx, dtor_addr, &args, dtor_ty, DebugLoc::None) }; bcx.fcx.pop_and_trans_custom_cleanup_scope(bcx, contents_scope) } pub fn size_and_align_of_dst<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, info: ValueRef) -> (ValueRef, ValueRef) { debug!("calculate size of DST: {}; with lost info: {}", t, bcx.val_to_string(info)); if type_is_sized(bcx.tcx(), t) { let sizing_type = sizing_type_of(bcx.ccx(), t); let size = llsize_of_alloc(bcx.ccx(), sizing_type); let align = align_of(bcx.ccx(), t); debug!("size_and_align_of_dst t={} info={} size: {} align: {}", t, bcx.val_to_string(info), size, align); let size = C_uint(bcx.ccx(), size); let align = C_uint(bcx.ccx(), align); return (size, align); } match t.sty { ty::TyStruct(def, substs) => { let ccx = bcx.ccx(); // First get the size of all statically known fields. // Don't use type_of::sizing_type_of because that expects t to be sized. assert!(!t.is_simd()); let repr = adt::represent_type(ccx, t); let sizing_type = adt::sizing_type_context_of(ccx, &*repr, true); debug!("DST {} sizing_type: {}", t, sizing_type.to_string()); let sized_size = llsize_of_alloc(ccx, sizing_type.prefix()); let sized_align = llalign_of_min(ccx, sizing_type.prefix()); debug!("DST {} statically sized prefix size: {} align: {}", t, sized_size, sized_align); let sized_size = C_uint(ccx, sized_size); let sized_align = C_uint(ccx, sized_align); // Recurse to get the size of the dynamically sized field (must be // the last field). let last_field = def.struct_variant().fields.last().unwrap(); let field_ty =
trans_exchange_free_dyn
identifier_name