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
main.rs
use rand::{thread_rng, seq::SliceRandom}; use mcc4::*; fn
() { env_logger::init(); let game = ConnectFour::<BitState>::new(7, 6).unwrap(); let human_player = HumanPlayer::new(); let ai_player = TreeSearchPlayer::new(&game); let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)]; players.shuffle(&mut thread_rng()); println!("\x1B[2J\x1B[H"); println!("{}", game.state()); for (state, player, move_, winner) in game.iter(players) { print!("\x1B[2J\x1B[H"); println!("Player {} has moved {}", player, move_); println!("{}", state); match winner { Winner::Winner(winner) => println!("Player {} has won.", winner), Winner::Draw => println!("Draw."), Winner::NotFinishedYet => {} }; } }
main
identifier_name
main.rs
use rand::{thread_rng, seq::SliceRandom}; use mcc4::*; fn main()
}
{ env_logger::init(); let game = ConnectFour::<BitState>::new(7, 6).unwrap(); let human_player = HumanPlayer::new(); let ai_player = TreeSearchPlayer::new(&game); let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)]; players.shuffle(&mut thread_rng()); println!("\x1B[2J\x1B[H"); println!("{}", game.state()); for (state, player, move_, winner) in game.iter(players) { print!("\x1B[2J\x1B[H"); println!("Player {} has moved {}", player, move_); println!("{}", state); match winner { Winner::Winner(winner) => println!("Player {} has won.", winner), Winner::Draw => println!("Draw."), Winner::NotFinishedYet => {} }; }
identifier_body
opts.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/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use geometry::ScreenPx; use euclid::size::{Size2D, TypedSize2D}; use getopts; use num_cpus; use std::collections::HashSet; use std::cmp; use std::env; use std::io::{self, Write}; use std::fs::PathExt; use std::mem; use std::path::Path; use std::process; use std::ptr; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use url::{self, Url}; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] pub struct Opts { /// The initial URL to load. pub url: Option<Url>, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// True to use GPU painting via Skia-GL, false to use CPU painting via Skia (`-g`). Note that /// compositing is always done on the GPU. pub gpu_painting: bool, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<f32>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiler_period: Option<f64>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, /// Enable experimental web features (`-e`). pub enable_experimental: bool, /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, pub nossl: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other
/// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// True if we should paint tiles a random color whenever they're repainted. Useful for /// debugging invalidation. pub paint_flashing: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// If set with --disable-canvas-aa, disable antialiasing on the HTML canvas element. /// Like --disable-text-aa, this is useful for reftests where pixel perfect results are required. pub enable_canvas_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// If true, instrument the runtime for each task created and dump /// that information to a JSON file that can be viewed in the task /// profile viewer. pub profile_tasks: bool, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Option<String>, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list after optimization (post layout, at painting time). pub dump_display_list_optimized: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether to show an error when display list geometry escapes flow overflow regions. pub validate_display_list_geometry: bool, /// A specific path to find required resources (such as user-agent.css). pub resources_path: Option<String>, /// Whether MIME sniffing should be used pub sniff_mime_types: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, } fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options... ] [URL]\n\twhere options include", app); println!("{}", getopts::usage(&message, opts)); } pub fn print_debug_usage(app: &str) ->! { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-optimized", "Print optimized display list (at paint time)."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-tasks", "Instrument each task, writing the output to a file."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("paint-flashing", "Overlay repainted areas with a random color."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("validate-display-list-geometry", "Display an error when display list geometry escapes overflow region."); print_option("disable-share-style-cache", "Disable the style sharing cache."); println!(""); process::exit(0) } fn args_fail(msg: &str) ->! { let mut stderr = io::stderr(); stderr.write_all(msg.as_bytes()).unwrap(); stderr.write_all(b"\n").unwrap(); process::exit(1) } // Always use CPU painting on android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { url: Some(Url::parse("about:blank").unwrap()), paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, enable_experimental: false, layout_threads: 1, nonincremental_layout: false, nossl: false, userscripts: None, output_file: None, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, paint_flashing: false, enable_text_antialiasing: false, enable_canvas_antialiasing: false, trace_layout: false, devtools_port: None, webdriver_port: None, initial_window_size: Size2D::typed(800, 600), user_agent: None, dump_flow_tree: false, dump_display_list: false, dump_display_list_optimized: false, relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, } } pub fn from_cmdline_args(args: &[String]) { let app_name = args[0].to_string(); let args = args.tail(); let opts = vec!( getopts::optflag("c", "cpu", "CPU painting (default)"), getopts::optflag("g", "gpu", "GPU painting"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("s", "size", "Size of tiles", "512"), getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""), getopts::optflag("e", "experimental", "Enable experimental web features"), getopts::optopt("t", "threads", "Number of paint threads", "1"), getopts::optflagopt("p", "profile", "Profiler flag and output interval", "10"), getopts::optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"), getopts::optflag("x", "exit", "Exit after load flag"), getopts::optopt("y", "layout-threads", "Number of threads to use for layout", "1"), getopts::optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."), getopts::optflag("", "no-ssl", "Disables ssl certificate verification."), getopts::optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path",""), getopts::optflag("z", "headless", "Headless mode"), getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflagopt("", "devtools", "Start remote devtools server on port", "6000"), getopts::optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"), getopts::optopt("", "resolution", "Set window resolution.", "800x600"), getopts::optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"), getopts::optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""), getopts::optflag("h", "help", "Print this message"), getopts::optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"), getopts::optflag("", "sniff-mime-types", "Enable MIME sniffing"), ); let opt_match = match getopts::getopts(args, &opts) { Ok(m) => m, Err(f) => args_fail(&f.to_string()), }; if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(&app_name, &opts); process::exit(0); }; let debug_string = match opt_match.opt_str("Z") { Some(string) => string, None => String::new() }; let mut debug_options = HashSet::new(); for split in debug_string.split(',') { debug_options.insert(split.clone()); } if debug_options.contains(&"help") { print_debug_usage(&app_name) } let url = if opt_match.free.is_empty() { print_usage(&app_name, &opts); args_fail("servo asks that you provide a URL") } else { let ref url = opt_match.free[0]; let cwd = env::current_dir().unwrap(); match Url::parse(url) { Ok(url) => url, Err(url::ParseError::RelativeUrlWithoutBase) => { if Path::new(url).exists() { Url::from_file_path(&*cwd.join(url)).unwrap() } else { args_fail(&format!("File not found: {}", url)) } } Err(_) => panic!("URL parsing failed"), } }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| dppx_str.parse().unwrap() ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse().unwrap(), None => cmp::max(num_cpus::get() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { period.parse().unwrap() }); let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap() }); let gpu_painting =!FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: usize = match opt_match.opt_str("y") { Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(num_cpus::get() * 3 / 4, 1), }; let nonincremental_layout = opt_match.opt_present("i"); let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.contains(&"bubble-widths"); let trace_layout = debug_options.contains(&"trace-layout"); if trace_layout { paint_threads = 1; layout_threads = 1; bubble_inline_sizes_separately = true; } let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap() }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); Size2D::typed(res[0], res[1]) } None => { Size2D::typed(800, 600) } }; let opts = Opts { url: Some(url), paint_threads: paint_threads, gpu_painting: gpu_painting, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), output_file: opt_match.opt_str("o"), headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.contains(&"profile-tasks"), trace_layout: trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: opt_match.opt_str("u"), show_debug_borders: debug_options.contains(&"show-compositor-borders"), show_debug_fragment_borders: debug_options.contains(&"show-fragment-borders"), show_debug_parallel_paint: debug_options.contains(&"show-parallel-paint"), show_debug_parallel_layout: debug_options.contains(&"show-parallel-layout"), paint_flashing: debug_options.contains(&"paint-flashing"), enable_text_antialiasing:!debug_options.contains(&"disable-text-aa"), enable_canvas_antialiasing:!debug_options.contains(&"disable-canvas-aa"), dump_flow_tree: debug_options.contains(&"dump-flow-tree"), dump_display_list: debug_options.contains(&"dump-display-list"), dump_display_list_optimized: debug_options.contains(&"dump-display-list-optimized"), relayout_event: debug_options.contains(&"relayout-event"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), sniff_mime_types: opt_match.opt_present("sniff-mime-types"), disable_share_style_cache: debug_options.contains(&"disable-share-style-cache"), }; set(opts); } static EXPERIMENTAL_ENABLED: AtomicBool = ATOMIC_BOOL_INIT; /// Turn on experimental features globally. Normally this is done /// during initialization by `set` or `from_cmdline_args`, but /// tests that require experimental features will also set it. pub fn set_experimental_enabled(new_value: bool) { EXPERIMENTAL_ENABLED.store(new_value, Ordering::SeqCst); } pub fn experimental_enabled() -> bool { EXPERIMENTAL_ENABLED.load(Ordering::SeqCst) } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut OPTIONS: *mut Opts = 0 as *mut Opts; pub fn set(opts: Opts) { unsafe { assert!(OPTIONS.is_null()); set_experimental_enabled(opts.enable_experimental); let box_opts = box opts; OPTIONS = mem::transmute(box_opts); } } #[inline] pub fn get<'a>() -> &'a Opts { unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default // set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::null_mut() { set(default_opts()); } mem::transmute(OPTIONS) } }
/// browser engines. pub bubble_inline_sizes_separately: bool,
random_line_split
opts.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/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use geometry::ScreenPx; use euclid::size::{Size2D, TypedSize2D}; use getopts; use num_cpus; use std::collections::HashSet; use std::cmp; use std::env; use std::io::{self, Write}; use std::fs::PathExt; use std::mem; use std::path::Path; use std::process; use std::ptr; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use url::{self, Url}; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] pub struct Opts { /// The initial URL to load. pub url: Option<Url>, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// True to use GPU painting via Skia-GL, false to use CPU painting via Skia (`-g`). Note that /// compositing is always done on the GPU. pub gpu_painting: bool, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<f32>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiler_period: Option<f64>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, /// Enable experimental web features (`-e`). pub enable_experimental: bool, /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, pub nossl: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other /// browser engines. pub bubble_inline_sizes_separately: bool, /// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// True if we should paint tiles a random color whenever they're repainted. Useful for /// debugging invalidation. pub paint_flashing: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// If set with --disable-canvas-aa, disable antialiasing on the HTML canvas element. /// Like --disable-text-aa, this is useful for reftests where pixel perfect results are required. pub enable_canvas_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// If true, instrument the runtime for each task created and dump /// that information to a JSON file that can be viewed in the task /// profile viewer. pub profile_tasks: bool, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Option<String>, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list after optimization (post layout, at painting time). pub dump_display_list_optimized: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether to show an error when display list geometry escapes flow overflow regions. pub validate_display_list_geometry: bool, /// A specific path to find required resources (such as user-agent.css). pub resources_path: Option<String>, /// Whether MIME sniffing should be used pub sniff_mime_types: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, } fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options... ] [URL]\n\twhere options include", app); println!("{}", getopts::usage(&message, opts)); } pub fn print_debug_usage(app: &str) ->! { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-optimized", "Print optimized display list (at paint time)."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-tasks", "Instrument each task, writing the output to a file."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("paint-flashing", "Overlay repainted areas with a random color."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("validate-display-list-geometry", "Display an error when display list geometry escapes overflow region."); print_option("disable-share-style-cache", "Disable the style sharing cache."); println!(""); process::exit(0) } fn args_fail(msg: &str) ->! { let mut stderr = io::stderr(); stderr.write_all(msg.as_bytes()).unwrap(); stderr.write_all(b"\n").unwrap(); process::exit(1) } // Always use CPU painting on android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { url: Some(Url::parse("about:blank").unwrap()), paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, enable_experimental: false, layout_threads: 1, nonincremental_layout: false, nossl: false, userscripts: None, output_file: None, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, paint_flashing: false, enable_text_antialiasing: false, enable_canvas_antialiasing: false, trace_layout: false, devtools_port: None, webdriver_port: None, initial_window_size: Size2D::typed(800, 600), user_agent: None, dump_flow_tree: false, dump_display_list: false, dump_display_list_optimized: false, relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, } } pub fn from_cmdline_args(args: &[String]) { let app_name = args[0].to_string(); let args = args.tail(); let opts = vec!( getopts::optflag("c", "cpu", "CPU painting (default)"), getopts::optflag("g", "gpu", "GPU painting"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("s", "size", "Size of tiles", "512"), getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""), getopts::optflag("e", "experimental", "Enable experimental web features"), getopts::optopt("t", "threads", "Number of paint threads", "1"), getopts::optflagopt("p", "profile", "Profiler flag and output interval", "10"), getopts::optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"), getopts::optflag("x", "exit", "Exit after load flag"), getopts::optopt("y", "layout-threads", "Number of threads to use for layout", "1"), getopts::optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."), getopts::optflag("", "no-ssl", "Disables ssl certificate verification."), getopts::optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path",""), getopts::optflag("z", "headless", "Headless mode"), getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflagopt("", "devtools", "Start remote devtools server on port", "6000"), getopts::optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"), getopts::optopt("", "resolution", "Set window resolution.", "800x600"), getopts::optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"), getopts::optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""), getopts::optflag("h", "help", "Print this message"), getopts::optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"), getopts::optflag("", "sniff-mime-types", "Enable MIME sniffing"), ); let opt_match = match getopts::getopts(args, &opts) { Ok(m) => m, Err(f) => args_fail(&f.to_string()), }; if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(&app_name, &opts); process::exit(0); }; let debug_string = match opt_match.opt_str("Z") { Some(string) => string, None => String::new() }; let mut debug_options = HashSet::new(); for split in debug_string.split(',') { debug_options.insert(split.clone()); } if debug_options.contains(&"help") { print_debug_usage(&app_name) } let url = if opt_match.free.is_empty() { print_usage(&app_name, &opts); args_fail("servo asks that you provide a URL") } else { let ref url = opt_match.free[0]; let cwd = env::current_dir().unwrap(); match Url::parse(url) { Ok(url) => url, Err(url::ParseError::RelativeUrlWithoutBase) => { if Path::new(url).exists() { Url::from_file_path(&*cwd.join(url)).unwrap() } else { args_fail(&format!("File not found: {}", url)) } } Err(_) => panic!("URL parsing failed"), } }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| dppx_str.parse().unwrap() ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse().unwrap(), None => cmp::max(num_cpus::get() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { period.parse().unwrap() }); let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap() }); let gpu_painting =!FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: usize = match opt_match.opt_str("y") { Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(num_cpus::get() * 3 / 4, 1), }; let nonincremental_layout = opt_match.opt_present("i"); let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.contains(&"bubble-widths"); let trace_layout = debug_options.contains(&"trace-layout"); if trace_layout { paint_threads = 1; layout_threads = 1; bubble_inline_sizes_separately = true; } let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap() }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); Size2D::typed(res[0], res[1]) } None => { Size2D::typed(800, 600) } }; let opts = Opts { url: Some(url), paint_threads: paint_threads, gpu_painting: gpu_painting, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), output_file: opt_match.opt_str("o"), headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.contains(&"profile-tasks"), trace_layout: trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: opt_match.opt_str("u"), show_debug_borders: debug_options.contains(&"show-compositor-borders"), show_debug_fragment_borders: debug_options.contains(&"show-fragment-borders"), show_debug_parallel_paint: debug_options.contains(&"show-parallel-paint"), show_debug_parallel_layout: debug_options.contains(&"show-parallel-layout"), paint_flashing: debug_options.contains(&"paint-flashing"), enable_text_antialiasing:!debug_options.contains(&"disable-text-aa"), enable_canvas_antialiasing:!debug_options.contains(&"disable-canvas-aa"), dump_flow_tree: debug_options.contains(&"dump-flow-tree"), dump_display_list: debug_options.contains(&"dump-display-list"), dump_display_list_optimized: debug_options.contains(&"dump-display-list-optimized"), relayout_event: debug_options.contains(&"relayout-event"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), sniff_mime_types: opt_match.opt_present("sniff-mime-types"), disable_share_style_cache: debug_options.contains(&"disable-share-style-cache"), }; set(opts); } static EXPERIMENTAL_ENABLED: AtomicBool = ATOMIC_BOOL_INIT; /// Turn on experimental features globally. Normally this is done /// during initialization by `set` or `from_cmdline_args`, but /// tests that require experimental features will also set it. pub fn set_experimental_enabled(new_value: bool)
pub fn experimental_enabled() -> bool { EXPERIMENTAL_ENABLED.load(Ordering::SeqCst) } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut OPTIONS: *mut Opts = 0 as *mut Opts; pub fn set(opts: Opts) { unsafe { assert!(OPTIONS.is_null()); set_experimental_enabled(opts.enable_experimental); let box_opts = box opts; OPTIONS = mem::transmute(box_opts); } } #[inline] pub fn get<'a>() -> &'a Opts { unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default // set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::null_mut() { set(default_opts()); } mem::transmute(OPTIONS) } }
{ EXPERIMENTAL_ENABLED.store(new_value, Ordering::SeqCst); }
identifier_body
opts.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/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use geometry::ScreenPx; use euclid::size::{Size2D, TypedSize2D}; use getopts; use num_cpus; use std::collections::HashSet; use std::cmp; use std::env; use std::io::{self, Write}; use std::fs::PathExt; use std::mem; use std::path::Path; use std::process; use std::ptr; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use url::{self, Url}; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] pub struct Opts { /// The initial URL to load. pub url: Option<Url>, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// True to use GPU painting via Skia-GL, false to use CPU painting via Skia (`-g`). Note that /// compositing is always done on the GPU. pub gpu_painting: bool, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<f32>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiler_period: Option<f64>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, /// Enable experimental web features (`-e`). pub enable_experimental: bool, /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, pub nossl: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other /// browser engines. pub bubble_inline_sizes_separately: bool, /// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// True if we should paint tiles a random color whenever they're repainted. Useful for /// debugging invalidation. pub paint_flashing: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// If set with --disable-canvas-aa, disable antialiasing on the HTML canvas element. /// Like --disable-text-aa, this is useful for reftests where pixel perfect results are required. pub enable_canvas_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// If true, instrument the runtime for each task created and dump /// that information to a JSON file that can be viewed in the task /// profile viewer. pub profile_tasks: bool, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Option<String>, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list after optimization (post layout, at painting time). pub dump_display_list_optimized: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether to show an error when display list geometry escapes flow overflow regions. pub validate_display_list_geometry: bool, /// A specific path to find required resources (such as user-agent.css). pub resources_path: Option<String>, /// Whether MIME sniffing should be used pub sniff_mime_types: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, } fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options... ] [URL]\n\twhere options include", app); println!("{}", getopts::usage(&message, opts)); } pub fn print_debug_usage(app: &str) ->! { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-optimized", "Print optimized display list (at paint time)."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-tasks", "Instrument each task, writing the output to a file."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("paint-flashing", "Overlay repainted areas with a random color."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("validate-display-list-geometry", "Display an error when display list geometry escapes overflow region."); print_option("disable-share-style-cache", "Disable the style sharing cache."); println!(""); process::exit(0) } fn args_fail(msg: &str) ->! { let mut stderr = io::stderr(); stderr.write_all(msg.as_bytes()).unwrap(); stderr.write_all(b"\n").unwrap(); process::exit(1) } // Always use CPU painting on android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { url: Some(Url::parse("about:blank").unwrap()), paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, enable_experimental: false, layout_threads: 1, nonincremental_layout: false, nossl: false, userscripts: None, output_file: None, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, paint_flashing: false, enable_text_antialiasing: false, enable_canvas_antialiasing: false, trace_layout: false, devtools_port: None, webdriver_port: None, initial_window_size: Size2D::typed(800, 600), user_agent: None, dump_flow_tree: false, dump_display_list: false, dump_display_list_optimized: false, relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, } } pub fn from_cmdline_args(args: &[String]) { let app_name = args[0].to_string(); let args = args.tail(); let opts = vec!( getopts::optflag("c", "cpu", "CPU painting (default)"), getopts::optflag("g", "gpu", "GPU painting"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("s", "size", "Size of tiles", "512"), getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""), getopts::optflag("e", "experimental", "Enable experimental web features"), getopts::optopt("t", "threads", "Number of paint threads", "1"), getopts::optflagopt("p", "profile", "Profiler flag and output interval", "10"), getopts::optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"), getopts::optflag("x", "exit", "Exit after load flag"), getopts::optopt("y", "layout-threads", "Number of threads to use for layout", "1"), getopts::optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."), getopts::optflag("", "no-ssl", "Disables ssl certificate verification."), getopts::optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path",""), getopts::optflag("z", "headless", "Headless mode"), getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflagopt("", "devtools", "Start remote devtools server on port", "6000"), getopts::optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"), getopts::optopt("", "resolution", "Set window resolution.", "800x600"), getopts::optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"), getopts::optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""), getopts::optflag("h", "help", "Print this message"), getopts::optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"), getopts::optflag("", "sniff-mime-types", "Enable MIME sniffing"), ); let opt_match = match getopts::getopts(args, &opts) { Ok(m) => m, Err(f) => args_fail(&f.to_string()), }; if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(&app_name, &opts); process::exit(0); }; let debug_string = match opt_match.opt_str("Z") { Some(string) => string, None => String::new() }; let mut debug_options = HashSet::new(); for split in debug_string.split(',') { debug_options.insert(split.clone()); } if debug_options.contains(&"help") { print_debug_usage(&app_name) } let url = if opt_match.free.is_empty() { print_usage(&app_name, &opts); args_fail("servo asks that you provide a URL") } else { let ref url = opt_match.free[0]; let cwd = env::current_dir().unwrap(); match Url::parse(url) { Ok(url) => url, Err(url::ParseError::RelativeUrlWithoutBase) => { if Path::new(url).exists() { Url::from_file_path(&*cwd.join(url)).unwrap() } else { args_fail(&format!("File not found: {}", url)) } } Err(_) => panic!("URL parsing failed"), } }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| dppx_str.parse().unwrap() ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse().unwrap(), None => cmp::max(num_cpus::get() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { period.parse().unwrap() }); let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap() }); let gpu_painting =!FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: usize = match opt_match.opt_str("y") { Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(num_cpus::get() * 3 / 4, 1), }; let nonincremental_layout = opt_match.opt_present("i"); let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.contains(&"bubble-widths"); let trace_layout = debug_options.contains(&"trace-layout"); if trace_layout { paint_threads = 1; layout_threads = 1; bubble_inline_sizes_separately = true; } let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap() }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); Size2D::typed(res[0], res[1]) } None => { Size2D::typed(800, 600) } }; let opts = Opts { url: Some(url), paint_threads: paint_threads, gpu_painting: gpu_painting, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), output_file: opt_match.opt_str("o"), headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.contains(&"profile-tasks"), trace_layout: trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: opt_match.opt_str("u"), show_debug_borders: debug_options.contains(&"show-compositor-borders"), show_debug_fragment_borders: debug_options.contains(&"show-fragment-borders"), show_debug_parallel_paint: debug_options.contains(&"show-parallel-paint"), show_debug_parallel_layout: debug_options.contains(&"show-parallel-layout"), paint_flashing: debug_options.contains(&"paint-flashing"), enable_text_antialiasing:!debug_options.contains(&"disable-text-aa"), enable_canvas_antialiasing:!debug_options.contains(&"disable-canvas-aa"), dump_flow_tree: debug_options.contains(&"dump-flow-tree"), dump_display_list: debug_options.contains(&"dump-display-list"), dump_display_list_optimized: debug_options.contains(&"dump-display-list-optimized"), relayout_event: debug_options.contains(&"relayout-event"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), sniff_mime_types: opt_match.opt_present("sniff-mime-types"), disable_share_style_cache: debug_options.contains(&"disable-share-style-cache"), }; set(opts); } static EXPERIMENTAL_ENABLED: AtomicBool = ATOMIC_BOOL_INIT; /// Turn on experimental features globally. Normally this is done /// during initialization by `set` or `from_cmdline_args`, but /// tests that require experimental features will also set it. pub fn set_experimental_enabled(new_value: bool) { EXPERIMENTAL_ENABLED.store(new_value, Ordering::SeqCst); } pub fn experimental_enabled() -> bool { EXPERIMENTAL_ENABLED.load(Ordering::SeqCst) } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut OPTIONS: *mut Opts = 0 as *mut Opts; pub fn set(opts: Opts) { unsafe { assert!(OPTIONS.is_null()); set_experimental_enabled(opts.enable_experimental); let box_opts = box opts; OPTIONS = mem::transmute(box_opts); } } #[inline] pub fn
<'a>() -> &'a Opts { unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default // set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::null_mut() { set(default_opts()); } mem::transmute(OPTIONS) } }
get
identifier_name
server.rs
//! Shadowsocks Local Tunnel Server use std::{io, sync::Arc, time::Duration}; use futures::{future, FutureExt}; use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr}; use crate::local::{context::ServiceContext, loadbalancing::PingBalancer}; use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel}; /// Tunnel Server pub struct Tunnel { context: Arc<ServiceContext>, forward_addr: Address,
impl Tunnel { /// Create a new Tunnel server forwarding to `forward_addr` pub fn new(forward_addr: Address) -> Tunnel { let context = ServiceContext::new(); Tunnel::with_context(Arc::new(context), forward_addr) } /// Create a new Tunnel server with context pub fn with_context(context: Arc<ServiceContext>, forward_addr: Address) -> Tunnel { Tunnel { context, forward_addr, mode: Mode::TcpOnly, udp_expiry_duration: None, udp_capacity: None, } } /// Set UDP association's expiry duration pub fn set_udp_expiry_duration(&mut self, d: Duration) { self.udp_expiry_duration = Some(d); } /// Set total UDP association to be kept simultaneously in server pub fn set_udp_capacity(&mut self, c: usize) { self.udp_capacity = Some(c); } /// Set server mode pub fn set_mode(&mut self, mode: Mode) { self.mode = mode; } /// Start serving pub async fn run(self, tcp_addr: &ServerAddr, udp_addr: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut vfut = Vec::new(); if self.mode.enable_tcp() { vfut.push(self.run_tcp_tunnel(tcp_addr, balancer.clone()).boxed()); } if self.mode.enable_udp() { vfut.push(self.run_udp_tunnel(udp_addr, balancer).boxed()); } let (res,..) = future::select_all(vfut).await; res } async fn run_tcp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { run_tcp_tunnel(self.context.clone(), client_config, balancer, &self.forward_addr).await } async fn run_udp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut server = UdpTunnel::new(self.context.clone(), self.udp_expiry_duration, self.udp_capacity); server.run(client_config, balancer, &self.forward_addr).await } }
mode: Mode, udp_expiry_duration: Option<Duration>, udp_capacity: Option<usize>, }
random_line_split
server.rs
//! Shadowsocks Local Tunnel Server use std::{io, sync::Arc, time::Duration}; use futures::{future, FutureExt}; use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr}; use crate::local::{context::ServiceContext, loadbalancing::PingBalancer}; use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel}; /// Tunnel Server pub struct Tunnel { context: Arc<ServiceContext>, forward_addr: Address, mode: Mode, udp_expiry_duration: Option<Duration>, udp_capacity: Option<usize>, } impl Tunnel { /// Create a new Tunnel server forwarding to `forward_addr` pub fn
(forward_addr: Address) -> Tunnel { let context = ServiceContext::new(); Tunnel::with_context(Arc::new(context), forward_addr) } /// Create a new Tunnel server with context pub fn with_context(context: Arc<ServiceContext>, forward_addr: Address) -> Tunnel { Tunnel { context, forward_addr, mode: Mode::TcpOnly, udp_expiry_duration: None, udp_capacity: None, } } /// Set UDP association's expiry duration pub fn set_udp_expiry_duration(&mut self, d: Duration) { self.udp_expiry_duration = Some(d); } /// Set total UDP association to be kept simultaneously in server pub fn set_udp_capacity(&mut self, c: usize) { self.udp_capacity = Some(c); } /// Set server mode pub fn set_mode(&mut self, mode: Mode) { self.mode = mode; } /// Start serving pub async fn run(self, tcp_addr: &ServerAddr, udp_addr: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut vfut = Vec::new(); if self.mode.enable_tcp() { vfut.push(self.run_tcp_tunnel(tcp_addr, balancer.clone()).boxed()); } if self.mode.enable_udp() { vfut.push(self.run_udp_tunnel(udp_addr, balancer).boxed()); } let (res,..) = future::select_all(vfut).await; res } async fn run_tcp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { run_tcp_tunnel(self.context.clone(), client_config, balancer, &self.forward_addr).await } async fn run_udp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut server = UdpTunnel::new(self.context.clone(), self.udp_expiry_duration, self.udp_capacity); server.run(client_config, balancer, &self.forward_addr).await } }
new
identifier_name
server.rs
//! Shadowsocks Local Tunnel Server use std::{io, sync::Arc, time::Duration}; use futures::{future, FutureExt}; use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr}; use crate::local::{context::ServiceContext, loadbalancing::PingBalancer}; use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel}; /// Tunnel Server pub struct Tunnel { context: Arc<ServiceContext>, forward_addr: Address, mode: Mode, udp_expiry_duration: Option<Duration>, udp_capacity: Option<usize>, } impl Tunnel { /// Create a new Tunnel server forwarding to `forward_addr` pub fn new(forward_addr: Address) -> Tunnel { let context = ServiceContext::new(); Tunnel::with_context(Arc::new(context), forward_addr) } /// Create a new Tunnel server with context pub fn with_context(context: Arc<ServiceContext>, forward_addr: Address) -> Tunnel { Tunnel { context, forward_addr, mode: Mode::TcpOnly, udp_expiry_duration: None, udp_capacity: None, } } /// Set UDP association's expiry duration pub fn set_udp_expiry_duration(&mut self, d: Duration) { self.udp_expiry_duration = Some(d); } /// Set total UDP association to be kept simultaneously in server pub fn set_udp_capacity(&mut self, c: usize) { self.udp_capacity = Some(c); } /// Set server mode pub fn set_mode(&mut self, mode: Mode) { self.mode = mode; } /// Start serving pub async fn run(self, tcp_addr: &ServerAddr, udp_addr: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut vfut = Vec::new(); if self.mode.enable_tcp()
if self.mode.enable_udp() { vfut.push(self.run_udp_tunnel(udp_addr, balancer).boxed()); } let (res,..) = future::select_all(vfut).await; res } async fn run_tcp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { run_tcp_tunnel(self.context.clone(), client_config, balancer, &self.forward_addr).await } async fn run_udp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut server = UdpTunnel::new(self.context.clone(), self.udp_expiry_duration, self.udp_capacity); server.run(client_config, balancer, &self.forward_addr).await } }
{ vfut.push(self.run_tcp_tunnel(tcp_addr, balancer.clone()).boxed()); }
conditional_block
server.rs
//! Shadowsocks Local Tunnel Server use std::{io, sync::Arc, time::Duration}; use futures::{future, FutureExt}; use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr}; use crate::local::{context::ServiceContext, loadbalancing::PingBalancer}; use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel}; /// Tunnel Server pub struct Tunnel { context: Arc<ServiceContext>, forward_addr: Address, mode: Mode, udp_expiry_duration: Option<Duration>, udp_capacity: Option<usize>, } impl Tunnel { /// Create a new Tunnel server forwarding to `forward_addr` pub fn new(forward_addr: Address) -> Tunnel { let context = ServiceContext::new(); Tunnel::with_context(Arc::new(context), forward_addr) } /// Create a new Tunnel server with context pub fn with_context(context: Arc<ServiceContext>, forward_addr: Address) -> Tunnel { Tunnel { context, forward_addr, mode: Mode::TcpOnly, udp_expiry_duration: None, udp_capacity: None, } } /// Set UDP association's expiry duration pub fn set_udp_expiry_duration(&mut self, d: Duration) { self.udp_expiry_duration = Some(d); } /// Set total UDP association to be kept simultaneously in server pub fn set_udp_capacity(&mut self, c: usize)
/// Set server mode pub fn set_mode(&mut self, mode: Mode) { self.mode = mode; } /// Start serving pub async fn run(self, tcp_addr: &ServerAddr, udp_addr: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut vfut = Vec::new(); if self.mode.enable_tcp() { vfut.push(self.run_tcp_tunnel(tcp_addr, balancer.clone()).boxed()); } if self.mode.enable_udp() { vfut.push(self.run_udp_tunnel(udp_addr, balancer).boxed()); } let (res,..) = future::select_all(vfut).await; res } async fn run_tcp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { run_tcp_tunnel(self.context.clone(), client_config, balancer, &self.forward_addr).await } async fn run_udp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> { let mut server = UdpTunnel::new(self.context.clone(), self.udp_expiry_duration, self.udp_capacity); server.run(client_config, balancer, &self.forward_addr).await } }
{ self.udp_capacity = Some(c); }
identifier_body
design_pattern-chain_of_command.rs
#![crate_type = "bin"] //! Example of design pattern inspired from PHP code of //! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html //! //! Tested with rust-1.41.1-nightly //! //! @author Eliovir <http://github.com/~eliovir> //! //! @license MIT license <http://www.opensource.org/licenses/mit-license.php> //! //! @since 2014-04-20 trait Command { fn on_command(&self, name: &str, args: &[&str]); } struct CommandChain<'a> { commands: Vec<Box<dyn Command + 'a>>, } impl<'a> CommandChain<'a> { fn new() -> CommandChain<'a> { CommandChain{commands: Vec::new()} } fn add_command(&mut self, command: Box<dyn Command + 'a>) { self.commands.push(command); } fn run_command(&self, name: &str, args: &[&str])
} struct UserCommand; impl UserCommand { fn new() -> UserCommand { UserCommand } } impl Command for UserCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser" { println!("UserCommand handling '{}' with args {:?}.", name, args); } } } struct MailCommand; impl MailCommand { fn new() -> MailCommand { MailCommand } } impl Command for MailCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser" { println!("MailCommand handling '{}' with args {:?}.", name, args); } else if name == "mail" { println!("MailCommand handling '{}' with args {:?}.", name, args); } } } fn main() { let mut cc = CommandChain::new(); cc.add_command(Box::new(UserCommand::new())); cc.add_command(Box::new(MailCommand::new())); cc.run_command("addUser", &["Toto", "users"]); cc.run_command("mail", &["Sender", "Subject"]); }
{ for command in self.commands.iter() { command.on_command(name, args); } }
identifier_body
design_pattern-chain_of_command.rs
#![crate_type = "bin"] //! Example of design pattern inspired from PHP code of //! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html //! //! Tested with rust-1.41.1-nightly //! //! @author Eliovir <http://github.com/~eliovir> //! //! @license MIT license <http://www.opensource.org/licenses/mit-license.php> //! //! @since 2014-04-20 trait Command { fn on_command(&self, name: &str, args: &[&str]); } struct CommandChain<'a> { commands: Vec<Box<dyn Command + 'a>>, } impl<'a> CommandChain<'a> { fn
() -> CommandChain<'a> { CommandChain{commands: Vec::new()} } fn add_command(&mut self, command: Box<dyn Command + 'a>) { self.commands.push(command); } fn run_command(&self, name: &str, args: &[&str]) { for command in self.commands.iter() { command.on_command(name, args); } } } struct UserCommand; impl UserCommand { fn new() -> UserCommand { UserCommand } } impl Command for UserCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser" { println!("UserCommand handling '{}' with args {:?}.", name, args); } } } struct MailCommand; impl MailCommand { fn new() -> MailCommand { MailCommand } } impl Command for MailCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser" { println!("MailCommand handling '{}' with args {:?}.", name, args); } else if name == "mail" { println!("MailCommand handling '{}' with args {:?}.", name, args); } } } fn main() { let mut cc = CommandChain::new(); cc.add_command(Box::new(UserCommand::new())); cc.add_command(Box::new(MailCommand::new())); cc.run_command("addUser", &["Toto", "users"]); cc.run_command("mail", &["Sender", "Subject"]); }
new
identifier_name
design_pattern-chain_of_command.rs
#![crate_type = "bin"] //! Example of design pattern inspired from PHP code of //! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html //! //! Tested with rust-1.41.1-nightly //! //! @author Eliovir <http://github.com/~eliovir> //! //! @license MIT license <http://www.opensource.org/licenses/mit-license.php> //! //! @since 2014-04-20 trait Command { fn on_command(&self, name: &str, args: &[&str]); } struct CommandChain<'a> { commands: Vec<Box<dyn Command + 'a>>, } impl<'a> CommandChain<'a> { fn new() -> CommandChain<'a> { CommandChain{commands: Vec::new()} } fn add_command(&mut self, command: Box<dyn Command + 'a>) { self.commands.push(command); } fn run_command(&self, name: &str, args: &[&str]) { for command in self.commands.iter() { command.on_command(name, args); } } } struct UserCommand; impl UserCommand { fn new() -> UserCommand { UserCommand } } impl Command for UserCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser" { println!("UserCommand handling '{}' with args {:?}.", name, args); } } } struct MailCommand; impl MailCommand { fn new() -> MailCommand { MailCommand } } impl Command for MailCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser"
else if name == "mail" { println!("MailCommand handling '{}' with args {:?}.", name, args); } } } fn main() { let mut cc = CommandChain::new(); cc.add_command(Box::new(UserCommand::new())); cc.add_command(Box::new(MailCommand::new())); cc.run_command("addUser", &["Toto", "users"]); cc.run_command("mail", &["Sender", "Subject"]); }
{ println!("MailCommand handling '{}' with args {:?}.", name, args); }
conditional_block
design_pattern-chain_of_command.rs
#![crate_type = "bin"] //! Example of design pattern inspired from PHP code of //! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html //! //! Tested with rust-1.41.1-nightly //! //! @author Eliovir <http://github.com/~eliovir> //! //! @license MIT license <http://www.opensource.org/licenses/mit-license.php> //! //! @since 2014-04-20 trait Command { fn on_command(&self, name: &str, args: &[&str]); } struct CommandChain<'a> { commands: Vec<Box<dyn Command + 'a>>, } impl<'a> CommandChain<'a> { fn new() -> CommandChain<'a> { CommandChain{commands: Vec::new()} } fn add_command(&mut self, command: Box<dyn Command + 'a>) { self.commands.push(command); } fn run_command(&self, name: &str, args: &[&str]) { for command in self.commands.iter() { command.on_command(name, args); } } } struct UserCommand; impl UserCommand { fn new() -> UserCommand { UserCommand } } impl Command for UserCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser" { println!("UserCommand handling '{}' with args {:?}.", name, args); }
} } struct MailCommand; impl MailCommand { fn new() -> MailCommand { MailCommand } } impl Command for MailCommand { fn on_command(&self, name: &str, args: &[&str]) { if name == "addUser" { println!("MailCommand handling '{}' with args {:?}.", name, args); } else if name == "mail" { println!("MailCommand handling '{}' with args {:?}.", name, args); } } } fn main() { let mut cc = CommandChain::new(); cc.add_command(Box::new(UserCommand::new())); cc.add_command(Box::new(MailCommand::new())); cc.run_command("addUser", &["Toto", "users"]); cc.run_command("mail", &["Sender", "Subject"]); }
random_line_split
mode.rs
//! TODO Documentation
use crate::output::Output; #[derive(Debug, Eq, PartialEq)] pub struct Mode<'output> { output_mode: *mut wlr_output_mode, phantom: PhantomData<&'output Output> } impl<'output> Mode<'output> { /// NOTE This is a lifetime defined by the user of this function, but it /// must not outlive the `Output` that hosts this output mode. pub(crate) unsafe fn new<'unbound>(output_mode: *mut wlr_output_mode) -> Mode<'unbound> { Mode { output_mode, phantom: PhantomData } } pub(crate) unsafe fn as_ptr(&self) -> *mut wlr_output_mode { self.output_mode } /// Gets the flags set on this Mode. pub fn flags(&self) -> u32 { unsafe { (*self.output_mode).flags } } /// Gets the dimensions of this Mode. /// /// Returned value is (width, height) pub fn dimensions(&self) -> (i32, i32) { unsafe { ((*self.output_mode).width, (*self.output_mode).height) } } /// Get the refresh value of the output. pub fn refresh(&self) -> i32 { unsafe { (*self.output_mode).refresh } } }
use std::marker::PhantomData; use wlroots_sys::wlr_output_mode;
random_line_split
mode.rs
//! TODO Documentation use std::marker::PhantomData; use wlroots_sys::wlr_output_mode; use crate::output::Output; #[derive(Debug, Eq, PartialEq)] pub struct Mode<'output> { output_mode: *mut wlr_output_mode, phantom: PhantomData<&'output Output> } impl<'output> Mode<'output> { /// NOTE This is a lifetime defined by the user of this function, but it /// must not outlive the `Output` that hosts this output mode. pub(crate) unsafe fn new<'unbound>(output_mode: *mut wlr_output_mode) -> Mode<'unbound> { Mode { output_mode, phantom: PhantomData } } pub(crate) unsafe fn as_ptr(&self) -> *mut wlr_output_mode { self.output_mode } /// Gets the flags set on this Mode. pub fn flags(&self) -> u32 { unsafe { (*self.output_mode).flags } } /// Gets the dimensions of this Mode. /// /// Returned value is (width, height) pub fn dimensions(&self) -> (i32, i32) { unsafe { ((*self.output_mode).width, (*self.output_mode).height) } } /// Get the refresh value of the output. pub fn
(&self) -> i32 { unsafe { (*self.output_mode).refresh } } }
refresh
identifier_name
x86_64_rumprun_netbsd.rs
// Copyright 2014-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. use spec::{LinkerFlavor, Target, TargetResult}; pub fn
() -> TargetResult { let mut base = super::netbsd_base::opts(); base.cpu = "x86-64".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); base.linker = Some("x86_64-rumprun-netbsd-gcc".to_string()); base.max_atomic_width = Some(64); base.dynamic_linking = false; base.has_rpath = false; base.position_independent_executables = false; base.disable_redzone = true; base.stack_probes = true; Ok(Target { llvm_target: "x86_64-rumprun-netbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(), arch: "x86_64".to_string(), target_os: "netbsd".to_string(), target_env: String::new(), target_vendor: "rumprun".to_string(), linker_flavor: LinkerFlavor::Gcc, options: base, }) }
target
identifier_name
x86_64_rumprun_netbsd.rs
// Copyright 2014-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. use spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); base.cpu = "x86-64".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); base.linker = Some("x86_64-rumprun-netbsd-gcc".to_string()); base.max_atomic_width = Some(64); base.dynamic_linking = false; base.has_rpath = false; base.position_independent_executables = false; base.disable_redzone = true; base.stack_probes = true; Ok(Target { llvm_target: "x86_64-rumprun-netbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(), arch: "x86_64".to_string(), target_os: "netbsd".to_string(), target_env: String::new(), target_vendor: "rumprun".to_string(), linker_flavor: LinkerFlavor::Gcc, options: base,
}) }
random_line_split
x86_64_rumprun_netbsd.rs
// Copyright 2014-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. use spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult
target_os: "netbsd".to_string(), target_env: String::new(), target_vendor: "rumprun".to_string(), linker_flavor: LinkerFlavor::Gcc, options: base, }) }
{ let mut base = super::netbsd_base::opts(); base.cpu = "x86-64".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); base.linker = Some("x86_64-rumprun-netbsd-gcc".to_string()); base.max_atomic_width = Some(64); base.dynamic_linking = false; base.has_rpath = false; base.position_independent_executables = false; base.disable_redzone = true; base.stack_probes = true; Ok(Target { llvm_target: "x86_64-rumprun-netbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(), arch: "x86_64".to_string(),
identifier_body
path.rs
use std::fmt::{self, Debug, Formatter}; use std::fs; use std::io::prelude::*; use std::path::{Path, PathBuf}; use filetime::FileTime; use git2; use glob::Pattern; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use ops; use util::{self, CargoResult, internal, internal_error, human, ChainError}; use util::Config; pub struct PathSource<'cfg> { id: SourceId, path: PathBuf, updated: bool, packages: Vec<Package>, config: &'cfg Config, } // TODO: Figure out if packages should be discovered in new or self should be // mut and packages are discovered in update impl<'cfg> PathSource<'cfg> { pub fn for_path(path: &Path, config: &'cfg Config) -> CargoResult<PathSource<'cfg>> { trace!("PathSource::for_path; path={}", path.display()); Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config)) } /// Invoked with an absolute path to a directory that contains a Cargo.toml. /// The source will read the manifest and find any other packages contained /// in the directory structure reachable by the root manifest. pub fn
(path: &Path, id: &SourceId, config: &'cfg Config) -> PathSource<'cfg> { trace!("new; id={}", id); PathSource { id: id.clone(), path: path.to_path_buf(), updated: false, packages: Vec::new(), config: config, } } pub fn root_package(&mut self) -> CargoResult<Package> { trace!("root_package; source={:?}", self); try!(self.update()); match self.packages.iter().find(|p| p.root() == &*self.path) { Some(pkg) => Ok(pkg.clone()), None => Err(internal("no package found in source")) } } pub fn read_packages(&self) -> CargoResult<Vec<Package>> { if self.updated { Ok(self.packages.clone()) } else if self.id.is_path() && self.id.precise().is_some() { // If our source id is a path and it's listed with a precise // version, then it means that we're not allowed to have nested // dependencies (they've been rewritten to crates.io dependencies) // In this case we specifically read just one package, not a list of // packages. let path = self.path.join("Cargo.toml"); let (pkg, _) = try!(ops::read_package(&path, &self.id, self.config)); Ok(vec![pkg]) } else { ops::read_packages(&self.path, &self.id, self.config) } } /// List all files relevant to building this package inside this source. /// /// This function will use the appropriate methods to determine the /// set of files underneath this source's directory which are relevant for /// building `pkg`. /// /// The basic assumption of this method is that all files in the directory /// are relevant for building this package, but it also contains logic to /// use other methods like.gitignore to filter the list of files. pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> { let root = pkg.root(); let parse = |p: &String| { Pattern::new(p).map_err(|e| { human(format!("could not parse pattern `{}`: {}", p, e)) }) }; let exclude = try!(pkg.manifest().exclude().iter() .map(|p| parse(p)).collect::<Result<Vec<_>, _>>()); let include = try!(pkg.manifest().include().iter() .map(|p| parse(p)).collect::<Result<Vec<_>, _>>()); let mut filter = |p: &Path| { let relative_path = util::without_prefix(p, &root).unwrap(); include.iter().any(|p| p.matches_path(&relative_path)) || { include.len() == 0 && !exclude.iter().any(|p| p.matches_path(&relative_path)) } }; // If this package is a git repository, then we really do want to query // the git repository as it takes into account items such as.gitignore. // We're not quite sure where the git repository is, however, so we do a // bit of a probe. // // We check all packages in this source that are ancestors of the // specified package (including the same package) to see if they're at // the root of the git repository. This isn't always true, but it'll get // us there most of the time! let repo = self.packages.iter() .map(|pkg| pkg.root()) .filter(|path| root.starts_with(path)) .filter_map(|path| git2::Repository::open(&path).ok()) .next(); match repo { Some(repo) => self.list_files_git(pkg, repo, &mut filter), None => self.list_files_walk(pkg, &mut filter), } } fn list_files_git(&self, pkg: &Package, repo: git2::Repository, filter: &mut FnMut(&Path) -> bool) -> CargoResult<Vec<PathBuf>> { warn!("list_files_git {}", pkg.package_id()); let index = try!(repo.index()); let root = try!(repo.workdir().chain_error(|| { internal_error("Can't list files on a bare repository.", "") })); let pkg_path = pkg.root(); let mut ret = Vec::new(); // We use information from the git repository to guide us in traversing // its tree. The primary purpose of this is to take advantage of the //.gitignore and auto-ignore files that don't matter. // // Here we're also careful to look at both tracked and untracked files as // the untracked files are often part of a build and may become relevant // as part of a future commit. let index_files = index.iter().map(|entry| { use libgit2_sys::git_filemode_t::GIT_FILEMODE_COMMIT; let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32; (join(&root, &entry.path), Some(is_dir)) }); let mut opts = git2::StatusOptions::new(); opts.include_untracked(true); if let Some(suffix) = util::without_prefix(pkg_path, &root) { opts.pathspec(suffix); } let statuses = try!(repo.statuses(Some(&mut opts))); let untracked = statuses.iter().map(|entry| { (join(&root, entry.path_bytes()), None) }); 'outer: for (file_path, is_dir) in index_files.chain(untracked) { let file_path = try!(file_path); // Filter out files outside this package. if!file_path.starts_with(pkg_path) { continue } // Filter out Cargo.lock and target always { let fname = file_path.file_name().and_then(|s| s.to_str()); if fname == Some("Cargo.lock") { continue } if fname == Some("target") { continue } } // Filter out sub-packages of this package for other_pkg in self.packages.iter().filter(|p| *p!= pkg) { let other_path = other_pkg.root(); if other_path.starts_with(pkg_path) && file_path.starts_with(other_path) { continue 'outer; } } let is_dir = is_dir.or_else(|| { fs::metadata(&file_path).ok().map(|m| m.is_dir()) }).unwrap_or(false); if is_dir { warn!(" found submodule {}", file_path.display()); let rel = util::without_prefix(&file_path, &root).unwrap(); let rel = try!(rel.to_str().chain_error(|| { human(format!("invalid utf-8 filename: {}", rel.display())) })); // Git submodules are currently only named through `/` path // separators, explicitly not `\` which windows uses. Who knew? let rel = rel.replace(r"\", "/"); match repo.find_submodule(&rel).and_then(|s| s.open()) { Ok(repo) => { let files = try!(self.list_files_git(pkg, repo, filter)); ret.extend(files.into_iter()); } Err(..) => { try!(PathSource::walk(&file_path, &mut ret, false, filter)); } } } else if (*filter)(&file_path) { // We found a file! warn!(" found {}", file_path.display()); ret.push(file_path); } } return Ok(ret); #[cfg(unix)] fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> { use std::os::unix::prelude::*; use std::ffi::OsStr; Ok(path.join(<OsStr as OsStrExt>::from_bytes(data))) } #[cfg(windows)] fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> { use std::str; match str::from_utf8(data) { Ok(s) => Ok(path.join(s)), Err(..) => Err(internal("cannot process path in git with a non \ unicode filename")), } } } fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> bool) -> CargoResult<Vec<PathBuf>> { let mut ret = Vec::new(); for pkg in self.packages.iter().filter(|p| *p == pkg) { let loc = pkg.root(); try!(PathSource::walk(loc, &mut ret, true, filter)); } return Ok(ret); } fn walk(path: &Path, ret: &mut Vec<PathBuf>, is_root: bool, filter: &mut FnMut(&Path) -> bool) -> CargoResult<()> { if!fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) { if (*filter)(path) { ret.push(path.to_path_buf()); } return Ok(()) } // Don't recurse into any sub-packages that we have if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() { return Ok(()) } for dir in try!(fs::read_dir(path)) { let dir = try!(dir).path(); let name = dir.file_name().and_then(|s| s.to_str()); // Skip dotfile directories if name.map(|s| s.starts_with(".")) == Some(true) { continue } else if is_root { // Skip cargo artifacts match name { Some("target") | Some("Cargo.lock") => continue, _ => {} } } try!(PathSource::walk(&dir, ret, false, filter)); } return Ok(()) } } impl<'cfg> Debug for PathSource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "the paths source") } } impl<'cfg> Registry for PathSource<'cfg> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { self.packages.query(dep) } } impl<'cfg> Source for PathSource<'cfg> { fn update(&mut self) -> CargoResult<()> { if!self.updated { let packages = try!(self.read_packages()); self.packages.extend(packages.into_iter()); self.updated = true; } Ok(()) } fn download(&mut self, _: &[PackageId]) -> CargoResult<()>{ // TODO: assert! that the PackageId is contained by the source Ok(()) } fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; ids={:?}", ids); Ok(self.packages.iter() .filter(|pkg| ids.iter().any(|id| pkg.package_id() == id)) .map(|pkg| pkg.clone()) .collect()) } fn fingerprint(&self, pkg: &Package) -> CargoResult<String> { if!self.updated { return Err(internal_error("BUG: source was not updated", "")); } let mut max = FileTime::zero(); let mut max_path = PathBuf::from(""); for file in try!(self.list_files(pkg)) { // An fs::stat error here is either because path is a // broken symlink, a permissions error, or a race // condition where this path was rm'ed - either way, // we can ignore the error and treat the path's mtime // as 0. let mtime = fs::metadata(&file).map(|meta| { FileTime::from_last_modification_time(&meta) }).unwrap_or(FileTime::zero()); warn!("{} {}", mtime, file.display()); if mtime > max { max = mtime; max_path = file; } } trace!("fingerprint {}: {}", self.path.display(), max); Ok(format!("{} ({})", max, max_path.display())) } }
new
identifier_name
path.rs
use std::fmt::{self, Debug, Formatter}; use std::fs; use std::io::prelude::*; use std::path::{Path, PathBuf}; use filetime::FileTime; use git2; use glob::Pattern; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use ops; use util::{self, CargoResult, internal, internal_error, human, ChainError}; use util::Config; pub struct PathSource<'cfg> { id: SourceId, path: PathBuf, updated: bool, packages: Vec<Package>, config: &'cfg Config, } // TODO: Figure out if packages should be discovered in new or self should be // mut and packages are discovered in update impl<'cfg> PathSource<'cfg> { pub fn for_path(path: &Path, config: &'cfg Config) -> CargoResult<PathSource<'cfg>> { trace!("PathSource::for_path; path={}", path.display()); Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config)) } /// Invoked with an absolute path to a directory that contains a Cargo.toml. /// The source will read the manifest and find any other packages contained /// in the directory structure reachable by the root manifest. pub fn new(path: &Path, id: &SourceId, config: &'cfg Config) -> PathSource<'cfg> { trace!("new; id={}", id); PathSource { id: id.clone(), path: path.to_path_buf(), updated: false, packages: Vec::new(), config: config, } } pub fn root_package(&mut self) -> CargoResult<Package> { trace!("root_package; source={:?}", self); try!(self.update()); match self.packages.iter().find(|p| p.root() == &*self.path) { Some(pkg) => Ok(pkg.clone()), None => Err(internal("no package found in source")) } } pub fn read_packages(&self) -> CargoResult<Vec<Package>> { if self.updated { Ok(self.packages.clone()) } else if self.id.is_path() && self.id.precise().is_some() { // If our source id is a path and it's listed with a precise // version, then it means that we're not allowed to have nested // dependencies (they've been rewritten to crates.io dependencies) // In this case we specifically read just one package, not a list of // packages. let path = self.path.join("Cargo.toml"); let (pkg, _) = try!(ops::read_package(&path, &self.id, self.config)); Ok(vec![pkg]) } else { ops::read_packages(&self.path, &self.id, self.config) } } /// List all files relevant to building this package inside this source. /// /// This function will use the appropriate methods to determine the /// set of files underneath this source's directory which are relevant for /// building `pkg`. /// /// The basic assumption of this method is that all files in the directory /// are relevant for building this package, but it also contains logic to /// use other methods like.gitignore to filter the list of files. pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> { let root = pkg.root(); let parse = |p: &String| { Pattern::new(p).map_err(|e| { human(format!("could not parse pattern `{}`: {}", p, e)) }) }; let exclude = try!(pkg.manifest().exclude().iter() .map(|p| parse(p)).collect::<Result<Vec<_>, _>>()); let include = try!(pkg.manifest().include().iter() .map(|p| parse(p)).collect::<Result<Vec<_>, _>>()); let mut filter = |p: &Path| { let relative_path = util::without_prefix(p, &root).unwrap(); include.iter().any(|p| p.matches_path(&relative_path)) || { include.len() == 0 && !exclude.iter().any(|p| p.matches_path(&relative_path)) } }; // If this package is a git repository, then we really do want to query // the git repository as it takes into account items such as.gitignore. // We're not quite sure where the git repository is, however, so we do a // bit of a probe. // // We check all packages in this source that are ancestors of the // specified package (including the same package) to see if they're at // the root of the git repository. This isn't always true, but it'll get // us there most of the time! let repo = self.packages.iter() .map(|pkg| pkg.root()) .filter(|path| root.starts_with(path)) .filter_map(|path| git2::Repository::open(&path).ok()) .next(); match repo { Some(repo) => self.list_files_git(pkg, repo, &mut filter), None => self.list_files_walk(pkg, &mut filter), } } fn list_files_git(&self, pkg: &Package, repo: git2::Repository, filter: &mut FnMut(&Path) -> bool) -> CargoResult<Vec<PathBuf>> { warn!("list_files_git {}", pkg.package_id()); let index = try!(repo.index()); let root = try!(repo.workdir().chain_error(|| { internal_error("Can't list files on a bare repository.", "") })); let pkg_path = pkg.root(); let mut ret = Vec::new(); // We use information from the git repository to guide us in traversing // its tree. The primary purpose of this is to take advantage of the //.gitignore and auto-ignore files that don't matter. // // Here we're also careful to look at both tracked and untracked files as // the untracked files are often part of a build and may become relevant // as part of a future commit. let index_files = index.iter().map(|entry| { use libgit2_sys::git_filemode_t::GIT_FILEMODE_COMMIT; let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32; (join(&root, &entry.path), Some(is_dir)) }); let mut opts = git2::StatusOptions::new(); opts.include_untracked(true); if let Some(suffix) = util::without_prefix(pkg_path, &root) { opts.pathspec(suffix); } let statuses = try!(repo.statuses(Some(&mut opts))); let untracked = statuses.iter().map(|entry| { (join(&root, entry.path_bytes()), None) }); 'outer: for (file_path, is_dir) in index_files.chain(untracked) { let file_path = try!(file_path); // Filter out files outside this package. if!file_path.starts_with(pkg_path) { continue } // Filter out Cargo.lock and target always { let fname = file_path.file_name().and_then(|s| s.to_str()); if fname == Some("Cargo.lock") { continue } if fname == Some("target") { continue } } // Filter out sub-packages of this package for other_pkg in self.packages.iter().filter(|p| *p!= pkg) { let other_path = other_pkg.root(); if other_path.starts_with(pkg_path) && file_path.starts_with(other_path) { continue 'outer; } } let is_dir = is_dir.or_else(|| { fs::metadata(&file_path).ok().map(|m| m.is_dir()) }).unwrap_or(false); if is_dir { warn!(" found submodule {}", file_path.display()); let rel = util::without_prefix(&file_path, &root).unwrap(); let rel = try!(rel.to_str().chain_error(|| { human(format!("invalid utf-8 filename: {}", rel.display())) })); // Git submodules are currently only named through `/` path // separators, explicitly not `\` which windows uses. Who knew? let rel = rel.replace(r"\", "/"); match repo.find_submodule(&rel).and_then(|s| s.open()) { Ok(repo) => { let files = try!(self.list_files_git(pkg, repo, filter)); ret.extend(files.into_iter()); } Err(..) => { try!(PathSource::walk(&file_path, &mut ret, false, filter)); } } } else if (*filter)(&file_path) { // We found a file! warn!(" found {}", file_path.display()); ret.push(file_path); } } return Ok(ret); #[cfg(unix)] fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> { use std::os::unix::prelude::*; use std::ffi::OsStr; Ok(path.join(<OsStr as OsStrExt>::from_bytes(data))) } #[cfg(windows)] fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> { use std::str; match str::from_utf8(data) { Ok(s) => Ok(path.join(s)), Err(..) => Err(internal("cannot process path in git with a non \ unicode filename")), } } } fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> bool) -> CargoResult<Vec<PathBuf>> { let mut ret = Vec::new(); for pkg in self.packages.iter().filter(|p| *p == pkg) { let loc = pkg.root(); try!(PathSource::walk(loc, &mut ret, true, filter)); } return Ok(ret); } fn walk(path: &Path, ret: &mut Vec<PathBuf>, is_root: bool, filter: &mut FnMut(&Path) -> bool) -> CargoResult<()> { if!fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) { if (*filter)(path) { ret.push(path.to_path_buf()); } return Ok(()) } // Don't recurse into any sub-packages that we have if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() { return Ok(()) } for dir in try!(fs::read_dir(path)) { let dir = try!(dir).path(); let name = dir.file_name().and_then(|s| s.to_str()); // Skip dotfile directories if name.map(|s| s.starts_with(".")) == Some(true) { continue } else if is_root { // Skip cargo artifacts match name { Some("target") | Some("Cargo.lock") => continue, _ => {} } } try!(PathSource::walk(&dir, ret, false, filter)); } return Ok(()) } } impl<'cfg> Debug for PathSource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "the paths source") } } impl<'cfg> Registry for PathSource<'cfg> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { self.packages.query(dep) } } impl<'cfg> Source for PathSource<'cfg> { fn update(&mut self) -> CargoResult<()> { if!self.updated { let packages = try!(self.read_packages()); self.packages.extend(packages.into_iter()); self.updated = true; } Ok(()) } fn download(&mut self, _: &[PackageId]) -> CargoResult<()>
fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; ids={:?}", ids); Ok(self.packages.iter() .filter(|pkg| ids.iter().any(|id| pkg.package_id() == id)) .map(|pkg| pkg.clone()) .collect()) } fn fingerprint(&self, pkg: &Package) -> CargoResult<String> { if!self.updated { return Err(internal_error("BUG: source was not updated", "")); } let mut max = FileTime::zero(); let mut max_path = PathBuf::from(""); for file in try!(self.list_files(pkg)) { // An fs::stat error here is either because path is a // broken symlink, a permissions error, or a race // condition where this path was rm'ed - either way, // we can ignore the error and treat the path's mtime // as 0. let mtime = fs::metadata(&file).map(|meta| { FileTime::from_last_modification_time(&meta) }).unwrap_or(FileTime::zero()); warn!("{} {}", mtime, file.display()); if mtime > max { max = mtime; max_path = file; } } trace!("fingerprint {}: {}", self.path.display(), max); Ok(format!("{} ({})", max, max_path.display())) } }
{ // TODO: assert! that the PackageId is contained by the source Ok(()) }
identifier_body
path.rs
use std::fmt::{self, Debug, Formatter}; use std::fs; use std::io::prelude::*; use std::path::{Path, PathBuf}; use filetime::FileTime; use git2; use glob::Pattern; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use ops; use util::{self, CargoResult, internal, internal_error, human, ChainError}; use util::Config; pub struct PathSource<'cfg> { id: SourceId, path: PathBuf, updated: bool, packages: Vec<Package>, config: &'cfg Config, } // TODO: Figure out if packages should be discovered in new or self should be // mut and packages are discovered in update impl<'cfg> PathSource<'cfg> { pub fn for_path(path: &Path, config: &'cfg Config) -> CargoResult<PathSource<'cfg>> { trace!("PathSource::for_path; path={}", path.display()); Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config)) } /// Invoked with an absolute path to a directory that contains a Cargo.toml. /// The source will read the manifest and find any other packages contained /// in the directory structure reachable by the root manifest. pub fn new(path: &Path, id: &SourceId, config: &'cfg Config) -> PathSource<'cfg> { trace!("new; id={}", id); PathSource { id: id.clone(), path: path.to_path_buf(), updated: false, packages: Vec::new(), config: config, } } pub fn root_package(&mut self) -> CargoResult<Package> { trace!("root_package; source={:?}", self); try!(self.update()); match self.packages.iter().find(|p| p.root() == &*self.path) { Some(pkg) => Ok(pkg.clone()), None => Err(internal("no package found in source")) } } pub fn read_packages(&self) -> CargoResult<Vec<Package>> { if self.updated { Ok(self.packages.clone()) } else if self.id.is_path() && self.id.precise().is_some() { // If our source id is a path and it's listed with a precise // version, then it means that we're not allowed to have nested // dependencies (they've been rewritten to crates.io dependencies) // In this case we specifically read just one package, not a list of // packages. let path = self.path.join("Cargo.toml"); let (pkg, _) = try!(ops::read_package(&path, &self.id, self.config)); Ok(vec![pkg]) } else { ops::read_packages(&self.path, &self.id, self.config) } } /// List all files relevant to building this package inside this source. /// /// This function will use the appropriate methods to determine the /// set of files underneath this source's directory which are relevant for /// building `pkg`. /// /// The basic assumption of this method is that all files in the directory /// are relevant for building this package, but it also contains logic to /// use other methods like.gitignore to filter the list of files. pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> { let root = pkg.root(); let parse = |p: &String| { Pattern::new(p).map_err(|e| { human(format!("could not parse pattern `{}`: {}", p, e)) }) }; let exclude = try!(pkg.manifest().exclude().iter() .map(|p| parse(p)).collect::<Result<Vec<_>, _>>()); let include = try!(pkg.manifest().include().iter() .map(|p| parse(p)).collect::<Result<Vec<_>, _>>()); let mut filter = |p: &Path| { let relative_path = util::without_prefix(p, &root).unwrap(); include.iter().any(|p| p.matches_path(&relative_path)) || { include.len() == 0 && !exclude.iter().any(|p| p.matches_path(&relative_path)) } }; // If this package is a git repository, then we really do want to query // the git repository as it takes into account items such as.gitignore. // We're not quite sure where the git repository is, however, so we do a // bit of a probe. // // We check all packages in this source that are ancestors of the // specified package (including the same package) to see if they're at // the root of the git repository. This isn't always true, but it'll get // us there most of the time! let repo = self.packages.iter() .map(|pkg| pkg.root()) .filter(|path| root.starts_with(path)) .filter_map(|path| git2::Repository::open(&path).ok()) .next(); match repo { Some(repo) => self.list_files_git(pkg, repo, &mut filter), None => self.list_files_walk(pkg, &mut filter), } } fn list_files_git(&self, pkg: &Package, repo: git2::Repository, filter: &mut FnMut(&Path) -> bool) -> CargoResult<Vec<PathBuf>> { warn!("list_files_git {}", pkg.package_id()); let index = try!(repo.index()); let root = try!(repo.workdir().chain_error(|| { internal_error("Can't list files on a bare repository.", "") })); let pkg_path = pkg.root(); let mut ret = Vec::new(); // We use information from the git repository to guide us in traversing // its tree. The primary purpose of this is to take advantage of the
//.gitignore and auto-ignore files that don't matter. // // Here we're also careful to look at both tracked and untracked files as // the untracked files are often part of a build and may become relevant // as part of a future commit. let index_files = index.iter().map(|entry| { use libgit2_sys::git_filemode_t::GIT_FILEMODE_COMMIT; let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32; (join(&root, &entry.path), Some(is_dir)) }); let mut opts = git2::StatusOptions::new(); opts.include_untracked(true); if let Some(suffix) = util::without_prefix(pkg_path, &root) { opts.pathspec(suffix); } let statuses = try!(repo.statuses(Some(&mut opts))); let untracked = statuses.iter().map(|entry| { (join(&root, entry.path_bytes()), None) }); 'outer: for (file_path, is_dir) in index_files.chain(untracked) { let file_path = try!(file_path); // Filter out files outside this package. if!file_path.starts_with(pkg_path) { continue } // Filter out Cargo.lock and target always { let fname = file_path.file_name().and_then(|s| s.to_str()); if fname == Some("Cargo.lock") { continue } if fname == Some("target") { continue } } // Filter out sub-packages of this package for other_pkg in self.packages.iter().filter(|p| *p!= pkg) { let other_path = other_pkg.root(); if other_path.starts_with(pkg_path) && file_path.starts_with(other_path) { continue 'outer; } } let is_dir = is_dir.or_else(|| { fs::metadata(&file_path).ok().map(|m| m.is_dir()) }).unwrap_or(false); if is_dir { warn!(" found submodule {}", file_path.display()); let rel = util::without_prefix(&file_path, &root).unwrap(); let rel = try!(rel.to_str().chain_error(|| { human(format!("invalid utf-8 filename: {}", rel.display())) })); // Git submodules are currently only named through `/` path // separators, explicitly not `\` which windows uses. Who knew? let rel = rel.replace(r"\", "/"); match repo.find_submodule(&rel).and_then(|s| s.open()) { Ok(repo) => { let files = try!(self.list_files_git(pkg, repo, filter)); ret.extend(files.into_iter()); } Err(..) => { try!(PathSource::walk(&file_path, &mut ret, false, filter)); } } } else if (*filter)(&file_path) { // We found a file! warn!(" found {}", file_path.display()); ret.push(file_path); } } return Ok(ret); #[cfg(unix)] fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> { use std::os::unix::prelude::*; use std::ffi::OsStr; Ok(path.join(<OsStr as OsStrExt>::from_bytes(data))) } #[cfg(windows)] fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> { use std::str; match str::from_utf8(data) { Ok(s) => Ok(path.join(s)), Err(..) => Err(internal("cannot process path in git with a non \ unicode filename")), } } } fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> bool) -> CargoResult<Vec<PathBuf>> { let mut ret = Vec::new(); for pkg in self.packages.iter().filter(|p| *p == pkg) { let loc = pkg.root(); try!(PathSource::walk(loc, &mut ret, true, filter)); } return Ok(ret); } fn walk(path: &Path, ret: &mut Vec<PathBuf>, is_root: bool, filter: &mut FnMut(&Path) -> bool) -> CargoResult<()> { if!fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) { if (*filter)(path) { ret.push(path.to_path_buf()); } return Ok(()) } // Don't recurse into any sub-packages that we have if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() { return Ok(()) } for dir in try!(fs::read_dir(path)) { let dir = try!(dir).path(); let name = dir.file_name().and_then(|s| s.to_str()); // Skip dotfile directories if name.map(|s| s.starts_with(".")) == Some(true) { continue } else if is_root { // Skip cargo artifacts match name { Some("target") | Some("Cargo.lock") => continue, _ => {} } } try!(PathSource::walk(&dir, ret, false, filter)); } return Ok(()) } } impl<'cfg> Debug for PathSource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "the paths source") } } impl<'cfg> Registry for PathSource<'cfg> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { self.packages.query(dep) } } impl<'cfg> Source for PathSource<'cfg> { fn update(&mut self) -> CargoResult<()> { if!self.updated { let packages = try!(self.read_packages()); self.packages.extend(packages.into_iter()); self.updated = true; } Ok(()) } fn download(&mut self, _: &[PackageId]) -> CargoResult<()>{ // TODO: assert! that the PackageId is contained by the source Ok(()) } fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; ids={:?}", ids); Ok(self.packages.iter() .filter(|pkg| ids.iter().any(|id| pkg.package_id() == id)) .map(|pkg| pkg.clone()) .collect()) } fn fingerprint(&self, pkg: &Package) -> CargoResult<String> { if!self.updated { return Err(internal_error("BUG: source was not updated", "")); } let mut max = FileTime::zero(); let mut max_path = PathBuf::from(""); for file in try!(self.list_files(pkg)) { // An fs::stat error here is either because path is a // broken symlink, a permissions error, or a race // condition where this path was rm'ed - either way, // we can ignore the error and treat the path's mtime // as 0. let mtime = fs::metadata(&file).map(|meta| { FileTime::from_last_modification_time(&meta) }).unwrap_or(FileTime::zero()); warn!("{} {}", mtime, file.display()); if mtime > max { max = mtime; max_path = file; } } trace!("fingerprint {}: {}", self.path.display(), max); Ok(format!("{} ({})", max, max_path.display())) } }
random_line_split
privacy2.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. #[feature(globs)]; #[no_std]; // makes debugging this test *a lot* easier (during resolve) // Test to make sure that globs don't leak in regular `use` statements. mod bar { pub use self::glob::*; mod glob { use foo; } } pub fn foo() {} fn test1() { use bar::foo; //~ ERROR: unresolved import //~^ ERROR: failed to resolve } fn test2() { use bar::glob::foo;
//~^ ERROR: there is no //~^^ ERROR: failed to resolve } #[start] fn main(_: int, _: **u8) -> int { 3 }
random_line_split
privacy2.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. #[feature(globs)]; #[no_std]; // makes debugging this test *a lot* easier (during resolve) // Test to make sure that globs don't leak in regular `use` statements. mod bar { pub use self::glob::*; mod glob { use foo; } } pub fn foo() {} fn test1() { use bar::foo; //~ ERROR: unresolved import //~^ ERROR: failed to resolve } fn test2() { use bar::glob::foo; //~^ ERROR: there is no //~^^ ERROR: failed to resolve } #[start] fn main(_: int, _: **u8) -> int
{ 3 }
identifier_body
privacy2.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. #[feature(globs)]; #[no_std]; // makes debugging this test *a lot* easier (during resolve) // Test to make sure that globs don't leak in regular `use` statements. mod bar { pub use self::glob::*; mod glob { use foo; } } pub fn foo() {} fn test1() { use bar::foo; //~ ERROR: unresolved import //~^ ERROR: failed to resolve } fn test2() { use bar::glob::foo; //~^ ERROR: there is no //~^^ ERROR: failed to resolve } #[start] fn
(_: int, _: **u8) -> int { 3 }
main
identifier_name
visibility.rs
// A module named `my` mod my { // Items in modules default to private visibility. fn private_function() { println!("called `my::private_function()`"); } // Use the `pub` modifier to override default visibility. pub fn function() { println!("called `my::function()`"); } // Items can access other items in the same module, // even when private. pub fn indirect_access() { print!("called `my::indirect_access()`, that\n> "); private_function(); } // Modules can also be nested pub mod nested { pub fn function() { println!("called `my::nested::function()`"); } #[allow(dead_code)] fn private_function() { println!("called `my::nested::private_function()`"); } } // Nested modules follow the same rules for visibility mod private_nested { #[allow(dead_code)] pub fn function() { println!("called `my::private_nested::function()`"); } } } fn function() { println!("called `function()`"); }
// Modules allow disambiguation between items that have the same name. function(); my::function(); // Public items, including those inside nested modules, can be // accessed from outside the parent module. my::indirect_access(); my::nested::function(); // Private items of a module cannot be directly accessed, even if // nested in a public module: // Error! `private_function` is private //my::private_function(); // TODO ^ Try uncommenting this line // Error! `private_function` is private //my::nested::private_function(); // TODO ^ Try uncommenting this line // Error! `private_nested` is a private module //my::private_nested::function(); // TODO ^ Try uncommenting this line }
fn main() {
random_line_split
visibility.rs
// A module named `my` mod my { // Items in modules default to private visibility. fn private_function() { println!("called `my::private_function()`"); } // Use the `pub` modifier to override default visibility. pub fn function() { println!("called `my::function()`"); } // Items can access other items in the same module, // even when private. pub fn indirect_access() { print!("called `my::indirect_access()`, that\n> "); private_function(); } // Modules can also be nested pub mod nested { pub fn function() { println!("called `my::nested::function()`"); } #[allow(dead_code)] fn private_function() { println!("called `my::nested::private_function()`"); } } // Nested modules follow the same rules for visibility mod private_nested { #[allow(dead_code)] pub fn function() { println!("called `my::private_nested::function()`"); } } } fn function() { println!("called `function()`"); } fn main()
// Error! `private_nested` is a private module //my::private_nested::function(); // TODO ^ Try uncommenting this line }
{ // Modules allow disambiguation between items that have the same name. function(); my::function(); // Public items, including those inside nested modules, can be // accessed from outside the parent module. my::indirect_access(); my::nested::function(); // Private items of a module cannot be directly accessed, even if // nested in a public module: // Error! `private_function` is private //my::private_function(); // TODO ^ Try uncommenting this line // Error! `private_function` is private //my::nested::private_function(); // TODO ^ Try uncommenting this line
identifier_body
visibility.rs
// A module named `my` mod my { // Items in modules default to private visibility. fn
() { println!("called `my::private_function()`"); } // Use the `pub` modifier to override default visibility. pub fn function() { println!("called `my::function()`"); } // Items can access other items in the same module, // even when private. pub fn indirect_access() { print!("called `my::indirect_access()`, that\n> "); private_function(); } // Modules can also be nested pub mod nested { pub fn function() { println!("called `my::nested::function()`"); } #[allow(dead_code)] fn private_function() { println!("called `my::nested::private_function()`"); } } // Nested modules follow the same rules for visibility mod private_nested { #[allow(dead_code)] pub fn function() { println!("called `my::private_nested::function()`"); } } } fn function() { println!("called `function()`"); } fn main() { // Modules allow disambiguation between items that have the same name. function(); my::function(); // Public items, including those inside nested modules, can be // accessed from outside the parent module. my::indirect_access(); my::nested::function(); // Private items of a module cannot be directly accessed, even if // nested in a public module: // Error! `private_function` is private //my::private_function(); // TODO ^ Try uncommenting this line // Error! `private_function` is private //my::nested::private_function(); // TODO ^ Try uncommenting this line // Error! `private_nested` is a private module //my::private_nested::function(); // TODO ^ Try uncommenting this line }
private_function
identifier_name
if-check.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. fn
(x: uint) -> bool { if x < 2u { return false; } else if x == 2u { return true; } else { return even(x - 2u); } } fn foo(x: uint) { if even(x) { println!("{}", x); } else { panic!(); } } pub fn main() { foo(2u); }
even
identifier_name
if-check.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. fn even(x: uint) -> bool { if x < 2u { return false; } else if x == 2u { return true; } else { return even(x - 2u); } } fn foo(x: uint) { if even(x) { println!("{}", x); } else {
panic!(); } } pub fn main() { foo(2u); }
random_line_split
if-check.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. fn even(x: uint) -> bool { if x < 2u { return false; } else if x == 2u { return true; } else { return even(x - 2u); } } fn foo(x: uint) { if even(x)
else { panic!(); } } pub fn main() { foo(2u); }
{ println!("{}", x); }
conditional_block
if-check.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. fn even(x: uint) -> bool
fn foo(x: uint) { if even(x) { println!("{}", x); } else { panic!(); } } pub fn main() { foo(2u); }
{ if x < 2u { return false; } else if x == 2u { return true; } else { return even(x - 2u); } }
identifier_body
type_names.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. // Type Names for Debug Info. use super::namespace::crate_root_namespace; use trans::common::CrateContext; use middle::subst::{self, Substs}; use middle::ty::{self, Ty}; use syntax::ast; // Compute the name of the type as it should be stored in debuginfo. Does not do // any caching, i.e. calling the function twice with the same type will also do // the work twice. The `qualified` parameter only affects the first level of the // type name, further levels (i.e. type parameters) are always fully qualified. pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, qualified: bool) -> String { let mut result = String::with_capacity(64); push_debuginfo_type_name(cx, t, qualified, &mut result); result } // Pushes the name of the type as it should be stored in debuginfo on the // `output` String. See also compute_debuginfo_type_name(). pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, qualified: bool, output: &mut String) { match t.sty { ty::TyBool => output.push_str("bool"), ty::TyChar => output.push_str("char"), ty::TyStr => output.push_str("str"), ty::TyInt(ast::TyIs) => output.push_str("isize"), ty::TyInt(ast::TyI8) => output.push_str("i8"), ty::TyInt(ast::TyI16) => output.push_str("i16"), ty::TyInt(ast::TyI32) => output.push_str("i32"), ty::TyInt(ast::TyI64) => output.push_str("i64"), ty::TyUint(ast::TyUs) => output.push_str("usize"), ty::TyUint(ast::TyU8) => output.push_str("u8"), ty::TyUint(ast::TyU16) => output.push_str("u16"), ty::TyUint(ast::TyU32) => output.push_str("u32"), ty::TyUint(ast::TyU64) => output.push_str("u64"), ty::TyFloat(ast::TyF32) => output.push_str("f32"), ty::TyFloat(ast::TyF64) => output.push_str("f64"), ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => { push_item_name(cx, def.did, qualified, output); push_type_params(cx, substs, output); }, ty::TyTuple(ref component_types) => { output.push('('); for &component_type in component_types { push_debuginfo_type_name(cx, component_type, true, output); output.push_str(", "); } if!component_types.is_empty() { output.pop(); output.pop(); } output.push(')'); }, ty::TyBox(inner_type) => { output.push_str("Box<"); push_debuginfo_type_name(cx, inner_type, true, output); output.push('>'); }, ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => { output.push('*'); match mutbl { ast::MutImmutable => output.push_str("const "), ast::MutMutable => output.push_str("mut "), } push_debuginfo_type_name(cx, inner_type, true, output); }, ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => { output.push('&'); if mutbl == ast::MutMutable { output.push_str("mut "); } push_debuginfo_type_name(cx, inner_type, true, output); }, ty::TyArray(inner_type, len) => { output.push('['); push_debuginfo_type_name(cx, inner_type, true, output); output.push_str(&format!("; {}", len)); output.push(']'); }, ty::TySlice(inner_type) => { output.push('['); push_debuginfo_type_name(cx, inner_type, true, output); output.push(']'); }, ty::TyTrait(ref trait_data) => { let principal = cx.tcx().erase_late_bound_regions(&trait_data.principal); push_item_name(cx, principal.def_id, false, output); push_type_params(cx, principal.substs, output); }, ty::TyBareFn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => { if unsafety == ast::Unsafety::Unsafe { output.push_str("unsafe "); } if abi!= ::syntax::abi::Rust { output.push_str("extern \""); output.push_str(abi.name()); output.push_str("\" "); } output.push_str("fn("); let sig = cx.tcx().erase_late_bound_regions(sig); if!sig.inputs.is_empty() { for &parameter_type in &sig.inputs { push_debuginfo_type_name(cx, parameter_type, true, output); output.push_str(", "); } output.pop(); output.pop(); } if sig.variadic { if!sig.inputs.is_empty() { output.push_str(",..."); } else { output.push_str("..."); } } output.push(')'); match sig.output { ty::FnConverging(result_type) if result_type.is_nil() => {} ty::FnConverging(result_type) => { output.push_str(" -> "); push_debuginfo_type_name(cx, result_type, true, output); } ty::FnDiverging => { output.push_str(" ->!"); } } }, ty::TyClosure(..) => { output.push_str("closure"); } ty::TyError | ty::TyInfer(_) | ty::TyProjection(..) | ty::TyParam(_) => { cx.sess().bug(&format!("debuginfo: Trying to create type name for \ unexpected type: {:?}", t)); } } fn push_item_name(cx: &CrateContext, def_id: ast::DefId, qualified: bool, output: &mut String) { cx.tcx().with_path(def_id, |path| { if qualified { if def_id.krate == ast::LOCAL_CRATE { output.push_str(crate_root_namespace(cx)); output.push_str("::"); } let mut path_element_count = 0; for path_element in path { output.push_str(&path_element.name().as_str()); output.push_str("::"); path_element_count += 1; } if path_element_count == 0 { cx.sess().bug("debuginfo: Encountered empty item path!"); } output.pop(); output.pop(); } else { let name = path.last().expect("debuginfo: Empty item path?").name(); output.push_str(&name.as_str()); } }); } // Pushes the type parameters in the given `Substs` to the output string. // This ignores region parameters, since they can't reliably be // reconstructed for items from non-local crates. For local crates, this // would be possible but with inlining and LTO we have to use the least // common denominator - otherwise we would run into conflicts. fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, substs: &subst::Substs<'tcx>, output: &mut String)
}
{ if substs.types.is_empty() { return; } output.push('<'); for &type_parameter in &substs.types { push_debuginfo_type_name(cx, type_parameter, true, output); output.push_str(", "); } output.pop(); output.pop(); output.push('>'); }
identifier_body
type_names.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. // Type Names for Debug Info. use super::namespace::crate_root_namespace; use trans::common::CrateContext; use middle::subst::{self, Substs}; use middle::ty::{self, Ty}; use syntax::ast; // Compute the name of the type as it should be stored in debuginfo. Does not do // any caching, i.e. calling the function twice with the same type will also do // the work twice. The `qualified` parameter only affects the first level of the // type name, further levels (i.e. type parameters) are always fully qualified. pub fn
<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, qualified: bool) -> String { let mut result = String::with_capacity(64); push_debuginfo_type_name(cx, t, qualified, &mut result); result } // Pushes the name of the type as it should be stored in debuginfo on the // `output` String. See also compute_debuginfo_type_name(). pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, qualified: bool, output: &mut String) { match t.sty { ty::TyBool => output.push_str("bool"), ty::TyChar => output.push_str("char"), ty::TyStr => output.push_str("str"), ty::TyInt(ast::TyIs) => output.push_str("isize"), ty::TyInt(ast::TyI8) => output.push_str("i8"), ty::TyInt(ast::TyI16) => output.push_str("i16"), ty::TyInt(ast::TyI32) => output.push_str("i32"), ty::TyInt(ast::TyI64) => output.push_str("i64"), ty::TyUint(ast::TyUs) => output.push_str("usize"), ty::TyUint(ast::TyU8) => output.push_str("u8"), ty::TyUint(ast::TyU16) => output.push_str("u16"), ty::TyUint(ast::TyU32) => output.push_str("u32"), ty::TyUint(ast::TyU64) => output.push_str("u64"), ty::TyFloat(ast::TyF32) => output.push_str("f32"), ty::TyFloat(ast::TyF64) => output.push_str("f64"), ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => { push_item_name(cx, def.did, qualified, output); push_type_params(cx, substs, output); }, ty::TyTuple(ref component_types) => { output.push('('); for &component_type in component_types { push_debuginfo_type_name(cx, component_type, true, output); output.push_str(", "); } if!component_types.is_empty() { output.pop(); output.pop(); } output.push(')'); }, ty::TyBox(inner_type) => { output.push_str("Box<"); push_debuginfo_type_name(cx, inner_type, true, output); output.push('>'); }, ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => { output.push('*'); match mutbl { ast::MutImmutable => output.push_str("const "), ast::MutMutable => output.push_str("mut "), } push_debuginfo_type_name(cx, inner_type, true, output); }, ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => { output.push('&'); if mutbl == ast::MutMutable { output.push_str("mut "); } push_debuginfo_type_name(cx, inner_type, true, output); }, ty::TyArray(inner_type, len) => { output.push('['); push_debuginfo_type_name(cx, inner_type, true, output); output.push_str(&format!("; {}", len)); output.push(']'); }, ty::TySlice(inner_type) => { output.push('['); push_debuginfo_type_name(cx, inner_type, true, output); output.push(']'); }, ty::TyTrait(ref trait_data) => { let principal = cx.tcx().erase_late_bound_regions(&trait_data.principal); push_item_name(cx, principal.def_id, false, output); push_type_params(cx, principal.substs, output); }, ty::TyBareFn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => { if unsafety == ast::Unsafety::Unsafe { output.push_str("unsafe "); } if abi!= ::syntax::abi::Rust { output.push_str("extern \""); output.push_str(abi.name()); output.push_str("\" "); } output.push_str("fn("); let sig = cx.tcx().erase_late_bound_regions(sig); if!sig.inputs.is_empty() { for &parameter_type in &sig.inputs { push_debuginfo_type_name(cx, parameter_type, true, output); output.push_str(", "); } output.pop(); output.pop(); } if sig.variadic { if!sig.inputs.is_empty() { output.push_str(",..."); } else { output.push_str("..."); } } output.push(')'); match sig.output { ty::FnConverging(result_type) if result_type.is_nil() => {} ty::FnConverging(result_type) => { output.push_str(" -> "); push_debuginfo_type_name(cx, result_type, true, output); } ty::FnDiverging => { output.push_str(" ->!"); } } }, ty::TyClosure(..) => { output.push_str("closure"); } ty::TyError | ty::TyInfer(_) | ty::TyProjection(..) | ty::TyParam(_) => { cx.sess().bug(&format!("debuginfo: Trying to create type name for \ unexpected type: {:?}", t)); } } fn push_item_name(cx: &CrateContext, def_id: ast::DefId, qualified: bool, output: &mut String) { cx.tcx().with_path(def_id, |path| { if qualified { if def_id.krate == ast::LOCAL_CRATE { output.push_str(crate_root_namespace(cx)); output.push_str("::"); } let mut path_element_count = 0; for path_element in path { output.push_str(&path_element.name().as_str()); output.push_str("::"); path_element_count += 1; } if path_element_count == 0 { cx.sess().bug("debuginfo: Encountered empty item path!"); } output.pop(); output.pop(); } else { let name = path.last().expect("debuginfo: Empty item path?").name(); output.push_str(&name.as_str()); } }); } // Pushes the type parameters in the given `Substs` to the output string. // This ignores region parameters, since they can't reliably be // reconstructed for items from non-local crates. For local crates, this // would be possible but with inlining and LTO we have to use the least // common denominator - otherwise we would run into conflicts. fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, substs: &subst::Substs<'tcx>, output: &mut String) { if substs.types.is_empty() { return; } output.push('<'); for &type_parameter in &substs.types { push_debuginfo_type_name(cx, type_parameter, true, output); output.push_str(", "); } output.pop(); output.pop(); output.push('>'); } }
compute_debuginfo_type_name
identifier_name
type_names.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. // Type Names for Debug Info. use super::namespace::crate_root_namespace; use trans::common::CrateContext; use middle::subst::{self, Substs}; use middle::ty::{self, Ty}; use syntax::ast; // Compute the name of the type as it should be stored in debuginfo. Does not do // any caching, i.e. calling the function twice with the same type will also do // the work twice. The `qualified` parameter only affects the first level of the // type name, further levels (i.e. type parameters) are always fully qualified. pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, qualified: bool) -> String { let mut result = String::with_capacity(64); push_debuginfo_type_name(cx, t, qualified, &mut result); result } // Pushes the name of the type as it should be stored in debuginfo on the // `output` String. See also compute_debuginfo_type_name(). pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, qualified: bool, output: &mut String) { match t.sty { ty::TyBool => output.push_str("bool"), ty::TyChar => output.push_str("char"), ty::TyStr => output.push_str("str"), ty::TyInt(ast::TyIs) => output.push_str("isize"), ty::TyInt(ast::TyI8) => output.push_str("i8"), ty::TyInt(ast::TyI16) => output.push_str("i16"), ty::TyInt(ast::TyI32) => output.push_str("i32"), ty::TyInt(ast::TyI64) => output.push_str("i64"), ty::TyUint(ast::TyUs) => output.push_str("usize"), ty::TyUint(ast::TyU8) => output.push_str("u8"), ty::TyUint(ast::TyU16) => output.push_str("u16"), ty::TyUint(ast::TyU32) => output.push_str("u32"), ty::TyUint(ast::TyU64) => output.push_str("u64"), ty::TyFloat(ast::TyF32) => output.push_str("f32"), ty::TyFloat(ast::TyF64) => output.push_str("f64"), ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => { push_item_name(cx, def.did, qualified, output); push_type_params(cx, substs, output); }, ty::TyTuple(ref component_types) => { output.push('('); for &component_type in component_types { push_debuginfo_type_name(cx, component_type, true, output); output.push_str(", "); } if!component_types.is_empty() { output.pop(); output.pop(); } output.push(')'); }, ty::TyBox(inner_type) => { output.push_str("Box<"); push_debuginfo_type_name(cx, inner_type, true, output); output.push('>'); }, ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => { output.push('*'); match mutbl { ast::MutImmutable => output.push_str("const "), ast::MutMutable => output.push_str("mut "), } push_debuginfo_type_name(cx, inner_type, true, output); }, ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => { output.push('&'); if mutbl == ast::MutMutable { output.push_str("mut "); } push_debuginfo_type_name(cx, inner_type, true, output); }, ty::TyArray(inner_type, len) => { output.push('['); push_debuginfo_type_name(cx, inner_type, true, output); output.push_str(&format!("; {}", len)); output.push(']'); }, ty::TySlice(inner_type) => { output.push('['); push_debuginfo_type_name(cx, inner_type, true, output); output.push(']'); }, ty::TyTrait(ref trait_data) => { let principal = cx.tcx().erase_late_bound_regions(&trait_data.principal); push_item_name(cx, principal.def_id, false, output); push_type_params(cx, principal.substs, output); }, ty::TyBareFn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => { if unsafety == ast::Unsafety::Unsafe { output.push_str("unsafe "); } if abi!= ::syntax::abi::Rust { output.push_str("extern \""); output.push_str(abi.name()); output.push_str("\" "); } output.push_str("fn("); let sig = cx.tcx().erase_late_bound_regions(sig); if!sig.inputs.is_empty() { for &parameter_type in &sig.inputs { push_debuginfo_type_name(cx, parameter_type, true, output); output.push_str(", "); } output.pop(); output.pop(); }
output.push_str(",..."); } else { output.push_str("..."); } } output.push(')'); match sig.output { ty::FnConverging(result_type) if result_type.is_nil() => {} ty::FnConverging(result_type) => { output.push_str(" -> "); push_debuginfo_type_name(cx, result_type, true, output); } ty::FnDiverging => { output.push_str(" ->!"); } } }, ty::TyClosure(..) => { output.push_str("closure"); } ty::TyError | ty::TyInfer(_) | ty::TyProjection(..) | ty::TyParam(_) => { cx.sess().bug(&format!("debuginfo: Trying to create type name for \ unexpected type: {:?}", t)); } } fn push_item_name(cx: &CrateContext, def_id: ast::DefId, qualified: bool, output: &mut String) { cx.tcx().with_path(def_id, |path| { if qualified { if def_id.krate == ast::LOCAL_CRATE { output.push_str(crate_root_namespace(cx)); output.push_str("::"); } let mut path_element_count = 0; for path_element in path { output.push_str(&path_element.name().as_str()); output.push_str("::"); path_element_count += 1; } if path_element_count == 0 { cx.sess().bug("debuginfo: Encountered empty item path!"); } output.pop(); output.pop(); } else { let name = path.last().expect("debuginfo: Empty item path?").name(); output.push_str(&name.as_str()); } }); } // Pushes the type parameters in the given `Substs` to the output string. // This ignores region parameters, since they can't reliably be // reconstructed for items from non-local crates. For local crates, this // would be possible but with inlining and LTO we have to use the least // common denominator - otherwise we would run into conflicts. fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, substs: &subst::Substs<'tcx>, output: &mut String) { if substs.types.is_empty() { return; } output.push('<'); for &type_parameter in &substs.types { push_debuginfo_type_name(cx, type_parameter, true, output); output.push_str(", "); } output.pop(); output.pop(); output.push('>'); } }
if sig.variadic { if !sig.inputs.is_empty() {
random_line_split
text.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/. */ //! Text layout. use layout::box_::{Box, ScannedTextBox, ScannedTextBoxInfo, UnscannedTextBox}; use layout::flow::Flow; use gfx::font_context::FontContext; use gfx::text::text_run::TextRun; use gfx::text::util::{CompressWhitespaceNewline, transform_text, CompressNone}; use servo_util::range::Range; use std::slice; use style::computed_values::white_space; use sync::Arc; /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es. pub struct TextRunScanner { clump: Range, } impl TextRunScanner { pub fn new() -> TextRunScanner { TextRunScanner { clump: Range::empty(), } } pub fn scan_for_runs(&mut self, font_context: &mut FontContext, flow: &mut Flow)
// handle remaining clumps if self.clump.length() > 0 { self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes); } debug!("TextRunScanner: swapping out boxes."); // Swap out the old and new box list of the flow. flow.as_inline().boxes = out_boxes; // A helper function. fn can_coalesce_text_nodes(boxes: &[Box], left_i: uint, right_i: uint) -> bool { assert!(left_i < boxes.len()); assert!(right_i > 0 && right_i < boxes.len()); assert!(left_i!= right_i); boxes[left_i].can_merge_with_box(&boxes[right_i]) } } /// A "clump" is a range of inline flow leaves that can be merged together into a single box. /// Adjacent text with the same style can be merged, and nothing else can. /// /// The flow keeps track of the boxes contained by all non-leaf DOM nodes. This is necessary /// for correct painting order. Since we compress several leaf boxes here, the mapping must be /// adjusted. /// /// FIXME(pcwalton): Stop cloning boxes. Instead we will need to consume the `in_box`es as we /// iterate over them. pub fn flush_clump_to_list(&mut self, font_context: &mut FontContext, flow: &mut Flow, last_whitespace: bool, out_boxes: &mut ~[Box]) -> bool { let inline = flow.as_inline(); let in_boxes = &mut inline.boxes; assert!(self.clump.length() > 0); debug!("TextRunScanner: flushing boxes in range={}", self.clump); let is_singleton = self.clump.length() == 1; let is_text_clump = match in_boxes[self.clump.begin()].specific { UnscannedTextBox(_) => true, _ => false, }; let mut new_whitespace = last_whitespace; match (is_singleton, is_text_clump) { (false, false) => { fail!(~"WAT: can't coalesce non-text nodes in flush_clump_to_list()!") } (true, false) => { // FIXME(pcwalton): Stop cloning boxes, as above. debug!("TextRunScanner: pushing single non-text box in range: {}", self.clump); let new_box = in_boxes[self.clump.begin()].clone(); out_boxes.push(new_box) }, (true, true) => { let old_box = &in_boxes[self.clump.begin()]; let text = match old_box.specific { UnscannedTextBox(ref text_box_info) => &text_box_info.text, _ => fail!("Expected an unscanned text box!"), }; let font_style = old_box.font_style(); let decoration = old_box.text_decoration(); // TODO(#115): Use the actual CSS `white-space` property of the relevant style. let compression = match old_box.white_space() { white_space::normal => CompressWhitespaceNewline, white_space::pre => CompressNone, }; let mut new_line_pos = ~[]; let (transformed_text, whitespace) = transform_text(*text, compression, last_whitespace, &mut new_line_pos); new_whitespace = whitespace; if transformed_text.len() > 0 { // TODO(#177): Text run creation must account for the renderability of text by // font group fonts. This is probably achieved by creating the font group above // and then letting `FontGroup` decide which `Font` to stick into the text run. let fontgroup = font_context.get_resolved_font_for_style(&font_style); let run = ~fontgroup.borrow().create_textrun(transformed_text.clone(), decoration); debug!("TextRunScanner: pushing single text box in range: {} ({})", self.clump, *text); let range = Range::new(0, run.char_len()); let new_metrics = run.metrics_for_range(&range); let new_text_box_info = ScannedTextBoxInfo::new(Arc::new(run), range); let mut new_box = old_box.transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); new_box.new_line_pos = new_line_pos; out_boxes.push(new_box) } else { if self.clump.begin() + 1 < in_boxes.len() { // if the this box has border,margin,padding of inline, // we should copy that stuff to next box. in_boxes[self.clump.begin() + 1] .merge_noncontent_inline_left(&in_boxes[self.clump.begin()]); } } }, (false, true) => { // TODO(#177): Text run creation must account for the renderability of text by // font group fonts. This is probably achieved by creating the font group above // and then letting `FontGroup` decide which `Font` to stick into the text run. let in_box = &in_boxes[self.clump.begin()]; let font_style = in_box.font_style(); let fontgroup = font_context.get_resolved_font_for_style(&font_style); let decoration = in_box.text_decoration(); // TODO(#115): Use the actual CSS `white-space` property of the relevant style. let compression = match in_box.white_space() { white_space::normal => CompressWhitespaceNewline, white_space::pre => CompressNone, }; struct NewLinePositions { new_line_pos: ~[uint], } let mut new_line_positions: ~[NewLinePositions] = ~[]; // First, transform/compress text of all the nodes. let mut last_whitespace_in_clump = new_whitespace; let transformed_strs: ~[~str] = slice::from_fn(self.clump.length(), |i| { // TODO(#113): We should be passing the compression context between calls to // `transform_text`, so that boxes starting and/or ending with whitespace can // be compressed correctly with respect to the text run. let idx = i + self.clump.begin(); let in_box = match in_boxes[idx].specific { UnscannedTextBox(ref text_box_info) => &text_box_info.text, _ => fail!("Expected an unscanned text box!"), }; let mut new_line_pos = ~[]; let (new_str, new_whitespace) = transform_text(*in_box, compression, last_whitespace_in_clump, &mut new_line_pos); new_line_positions.push(NewLinePositions { new_line_pos: new_line_pos }); last_whitespace_in_clump = new_whitespace; new_str }); new_whitespace = last_whitespace_in_clump; // Next, concatenate all of the transformed strings together, saving the new // character indices. let mut run_str: ~str = ~""; let mut new_ranges: ~[Range] = ~[]; let mut char_total = 0; for i in range(0, transformed_strs.len()) { let added_chars = transformed_strs[i].char_len(); new_ranges.push(Range::new(char_total, added_chars)); run_str.push_str(transformed_strs[i]); char_total += added_chars; } // Now create the run. // TextRuns contain a cycle which is usually resolved by the teardown // sequence. If no clump takes ownership, however, it will leak. let clump = self.clump; let run = if clump.length()!= 0 && run_str.len() > 0 { Some(Arc::new(~TextRun::new(&mut *fontgroup.borrow().fonts[0].borrow_mut(), run_str.clone(), decoration))) } else { None }; // Make new boxes with the run and adjusted text indices. debug!("TextRunScanner: pushing box(es) in range: {}", self.clump); for i in clump.eachi() { let logical_offset = i - self.clump.begin(); let range = new_ranges[logical_offset]; if range.length() == 0 { debug!("Elided an `UnscannedTextbox` because it was zero-length after \ compression; {:s}", in_boxes[i].debug_str()); // in this case, in_boxes[i] is elided // so, we should merge inline info with next index of in_boxes if i + 1 < in_boxes.len() { in_boxes[i + 1].merge_noncontent_inline_left(&in_boxes[i]); } continue } let new_text_box_info = ScannedTextBoxInfo::new(run.get_ref().clone(), range); let new_metrics = new_text_box_info.run.get().metrics_for_range(&range); let mut new_box = in_boxes[i].transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); new_box.new_line_pos = new_line_positions[logical_offset].new_line_pos.clone(); out_boxes.push(new_box) } } } // End of match. debug!("--- In boxes: ---"); for (i, box_) in in_boxes.iter().enumerate() { debug!("{:u} --> {:s}", i, box_.debug_str()); } debug!("------------------"); debug!("--- Out boxes: ---"); for (i, box_) in out_boxes.iter().enumerate() { debug!("{:u} --> {:s}", i, box_.debug_str()); } debug!("------------------"); debug!("--- Elem ranges: ---"); for (i, nr) in inline.elems.eachi() { debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id()); () } debug!("--------------------"); let end = self.clump.end(); // FIXME: borrow checker workaround self.clump.reset(end, 0); new_whitespace } // End of `flush_clump_to_list`. }
{ { let inline = flow.as_immutable_inline(); debug!("TextRunScanner: scanning {:u} boxes for text runs...", inline.boxes.len()); } let mut last_whitespace = true; let mut out_boxes = ~[]; for box_i in range(0, flow.as_immutable_inline().boxes.len()) { debug!("TextRunScanner: considering box: {:u}", box_i); if box_i > 0 && !can_coalesce_text_nodes(flow.as_immutable_inline().boxes, box_i - 1, box_i) { last_whitespace = self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes); } self.clump.extend_by(1); }
identifier_body
text.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/. */ //! Text layout. use layout::box_::{Box, ScannedTextBox, ScannedTextBoxInfo, UnscannedTextBox}; use layout::flow::Flow; use gfx::font_context::FontContext; use gfx::text::text_run::TextRun; use gfx::text::util::{CompressWhitespaceNewline, transform_text, CompressNone}; use servo_util::range::Range; use std::slice; use style::computed_values::white_space; use sync::Arc; /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es. pub struct TextRunScanner { clump: Range, } impl TextRunScanner { pub fn new() -> TextRunScanner { TextRunScanner { clump: Range::empty(), } } pub fn scan_for_runs(&mut self, font_context: &mut FontContext, flow: &mut Flow) { { let inline = flow.as_immutable_inline(); debug!("TextRunScanner: scanning {:u} boxes for text runs...", inline.boxes.len()); } let mut last_whitespace = true; let mut out_boxes = ~[]; for box_i in range(0, flow.as_immutable_inline().boxes.len()) { debug!("TextRunScanner: considering box: {:u}", box_i); if box_i > 0 &&!can_coalesce_text_nodes(flow.as_immutable_inline().boxes, box_i - 1, box_i) { last_whitespace = self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes); } self.clump.extend_by(1); } // handle remaining clumps if self.clump.length() > 0 { self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes); } debug!("TextRunScanner: swapping out boxes."); // Swap out the old and new box list of the flow. flow.as_inline().boxes = out_boxes; // A helper function. fn
(boxes: &[Box], left_i: uint, right_i: uint) -> bool { assert!(left_i < boxes.len()); assert!(right_i > 0 && right_i < boxes.len()); assert!(left_i!= right_i); boxes[left_i].can_merge_with_box(&boxes[right_i]) } } /// A "clump" is a range of inline flow leaves that can be merged together into a single box. /// Adjacent text with the same style can be merged, and nothing else can. /// /// The flow keeps track of the boxes contained by all non-leaf DOM nodes. This is necessary /// for correct painting order. Since we compress several leaf boxes here, the mapping must be /// adjusted. /// /// FIXME(pcwalton): Stop cloning boxes. Instead we will need to consume the `in_box`es as we /// iterate over them. pub fn flush_clump_to_list(&mut self, font_context: &mut FontContext, flow: &mut Flow, last_whitespace: bool, out_boxes: &mut ~[Box]) -> bool { let inline = flow.as_inline(); let in_boxes = &mut inline.boxes; assert!(self.clump.length() > 0); debug!("TextRunScanner: flushing boxes in range={}", self.clump); let is_singleton = self.clump.length() == 1; let is_text_clump = match in_boxes[self.clump.begin()].specific { UnscannedTextBox(_) => true, _ => false, }; let mut new_whitespace = last_whitespace; match (is_singleton, is_text_clump) { (false, false) => { fail!(~"WAT: can't coalesce non-text nodes in flush_clump_to_list()!") } (true, false) => { // FIXME(pcwalton): Stop cloning boxes, as above. debug!("TextRunScanner: pushing single non-text box in range: {}", self.clump); let new_box = in_boxes[self.clump.begin()].clone(); out_boxes.push(new_box) }, (true, true) => { let old_box = &in_boxes[self.clump.begin()]; let text = match old_box.specific { UnscannedTextBox(ref text_box_info) => &text_box_info.text, _ => fail!("Expected an unscanned text box!"), }; let font_style = old_box.font_style(); let decoration = old_box.text_decoration(); // TODO(#115): Use the actual CSS `white-space` property of the relevant style. let compression = match old_box.white_space() { white_space::normal => CompressWhitespaceNewline, white_space::pre => CompressNone, }; let mut new_line_pos = ~[]; let (transformed_text, whitespace) = transform_text(*text, compression, last_whitespace, &mut new_line_pos); new_whitespace = whitespace; if transformed_text.len() > 0 { // TODO(#177): Text run creation must account for the renderability of text by // font group fonts. This is probably achieved by creating the font group above // and then letting `FontGroup` decide which `Font` to stick into the text run. let fontgroup = font_context.get_resolved_font_for_style(&font_style); let run = ~fontgroup.borrow().create_textrun(transformed_text.clone(), decoration); debug!("TextRunScanner: pushing single text box in range: {} ({})", self.clump, *text); let range = Range::new(0, run.char_len()); let new_metrics = run.metrics_for_range(&range); let new_text_box_info = ScannedTextBoxInfo::new(Arc::new(run), range); let mut new_box = old_box.transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); new_box.new_line_pos = new_line_pos; out_boxes.push(new_box) } else { if self.clump.begin() + 1 < in_boxes.len() { // if the this box has border,margin,padding of inline, // we should copy that stuff to next box. in_boxes[self.clump.begin() + 1] .merge_noncontent_inline_left(&in_boxes[self.clump.begin()]); } } }, (false, true) => { // TODO(#177): Text run creation must account for the renderability of text by // font group fonts. This is probably achieved by creating the font group above // and then letting `FontGroup` decide which `Font` to stick into the text run. let in_box = &in_boxes[self.clump.begin()]; let font_style = in_box.font_style(); let fontgroup = font_context.get_resolved_font_for_style(&font_style); let decoration = in_box.text_decoration(); // TODO(#115): Use the actual CSS `white-space` property of the relevant style. let compression = match in_box.white_space() { white_space::normal => CompressWhitespaceNewline, white_space::pre => CompressNone, }; struct NewLinePositions { new_line_pos: ~[uint], } let mut new_line_positions: ~[NewLinePositions] = ~[]; // First, transform/compress text of all the nodes. let mut last_whitespace_in_clump = new_whitespace; let transformed_strs: ~[~str] = slice::from_fn(self.clump.length(), |i| { // TODO(#113): We should be passing the compression context between calls to // `transform_text`, so that boxes starting and/or ending with whitespace can // be compressed correctly with respect to the text run. let idx = i + self.clump.begin(); let in_box = match in_boxes[idx].specific { UnscannedTextBox(ref text_box_info) => &text_box_info.text, _ => fail!("Expected an unscanned text box!"), }; let mut new_line_pos = ~[]; let (new_str, new_whitespace) = transform_text(*in_box, compression, last_whitespace_in_clump, &mut new_line_pos); new_line_positions.push(NewLinePositions { new_line_pos: new_line_pos }); last_whitespace_in_clump = new_whitespace; new_str }); new_whitespace = last_whitespace_in_clump; // Next, concatenate all of the transformed strings together, saving the new // character indices. let mut run_str: ~str = ~""; let mut new_ranges: ~[Range] = ~[]; let mut char_total = 0; for i in range(0, transformed_strs.len()) { let added_chars = transformed_strs[i].char_len(); new_ranges.push(Range::new(char_total, added_chars)); run_str.push_str(transformed_strs[i]); char_total += added_chars; } // Now create the run. // TextRuns contain a cycle which is usually resolved by the teardown // sequence. If no clump takes ownership, however, it will leak. let clump = self.clump; let run = if clump.length()!= 0 && run_str.len() > 0 { Some(Arc::new(~TextRun::new(&mut *fontgroup.borrow().fonts[0].borrow_mut(), run_str.clone(), decoration))) } else { None }; // Make new boxes with the run and adjusted text indices. debug!("TextRunScanner: pushing box(es) in range: {}", self.clump); for i in clump.eachi() { let logical_offset = i - self.clump.begin(); let range = new_ranges[logical_offset]; if range.length() == 0 { debug!("Elided an `UnscannedTextbox` because it was zero-length after \ compression; {:s}", in_boxes[i].debug_str()); // in this case, in_boxes[i] is elided // so, we should merge inline info with next index of in_boxes if i + 1 < in_boxes.len() { in_boxes[i + 1].merge_noncontent_inline_left(&in_boxes[i]); } continue } let new_text_box_info = ScannedTextBoxInfo::new(run.get_ref().clone(), range); let new_metrics = new_text_box_info.run.get().metrics_for_range(&range); let mut new_box = in_boxes[i].transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); new_box.new_line_pos = new_line_positions[logical_offset].new_line_pos.clone(); out_boxes.push(new_box) } } } // End of match. debug!("--- In boxes: ---"); for (i, box_) in in_boxes.iter().enumerate() { debug!("{:u} --> {:s}", i, box_.debug_str()); } debug!("------------------"); debug!("--- Out boxes: ---"); for (i, box_) in out_boxes.iter().enumerate() { debug!("{:u} --> {:s}", i, box_.debug_str()); } debug!("------------------"); debug!("--- Elem ranges: ---"); for (i, nr) in inline.elems.eachi() { debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id()); () } debug!("--------------------"); let end = self.clump.end(); // FIXME: borrow checker workaround self.clump.reset(end, 0); new_whitespace } // End of `flush_clump_to_list`. }
can_coalesce_text_nodes
identifier_name
text.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/. */ //! Text layout. use layout::box_::{Box, ScannedTextBox, ScannedTextBoxInfo, UnscannedTextBox}; use layout::flow::Flow; use gfx::font_context::FontContext; use gfx::text::text_run::TextRun; use gfx::text::util::{CompressWhitespaceNewline, transform_text, CompressNone}; use servo_util::range::Range; use std::slice; use style::computed_values::white_space; use sync::Arc; /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es. pub struct TextRunScanner { clump: Range, } impl TextRunScanner { pub fn new() -> TextRunScanner { TextRunScanner { clump: Range::empty(), } } pub fn scan_for_runs(&mut self, font_context: &mut FontContext, flow: &mut Flow) { { let inline = flow.as_immutable_inline(); debug!("TextRunScanner: scanning {:u} boxes for text runs...", inline.boxes.len()); } let mut last_whitespace = true; let mut out_boxes = ~[]; for box_i in range(0, flow.as_immutable_inline().boxes.len()) { debug!("TextRunScanner: considering box: {:u}", box_i); if box_i > 0 &&!can_coalesce_text_nodes(flow.as_immutable_inline().boxes, box_i - 1, box_i) { last_whitespace = self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes); } self.clump.extend_by(1); } // handle remaining clumps if self.clump.length() > 0 { self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes); } debug!("TextRunScanner: swapping out boxes."); // Swap out the old and new box list of the flow. flow.as_inline().boxes = out_boxes; // A helper function. fn can_coalesce_text_nodes(boxes: &[Box], left_i: uint, right_i: uint) -> bool { assert!(left_i < boxes.len()); assert!(right_i > 0 && right_i < boxes.len()); assert!(left_i!= right_i); boxes[left_i].can_merge_with_box(&boxes[right_i]) } } /// A "clump" is a range of inline flow leaves that can be merged together into a single box. /// Adjacent text with the same style can be merged, and nothing else can. /// /// The flow keeps track of the boxes contained by all non-leaf DOM nodes. This is necessary /// for correct painting order. Since we compress several leaf boxes here, the mapping must be /// adjusted. /// /// FIXME(pcwalton): Stop cloning boxes. Instead we will need to consume the `in_box`es as we /// iterate over them. pub fn flush_clump_to_list(&mut self, font_context: &mut FontContext, flow: &mut Flow, last_whitespace: bool, out_boxes: &mut ~[Box]) -> bool { let inline = flow.as_inline(); let in_boxes = &mut inline.boxes; assert!(self.clump.length() > 0); debug!("TextRunScanner: flushing boxes in range={}", self.clump); let is_singleton = self.clump.length() == 1; let is_text_clump = match in_boxes[self.clump.begin()].specific { UnscannedTextBox(_) => true, _ => false, }; let mut new_whitespace = last_whitespace; match (is_singleton, is_text_clump) { (false, false) => { fail!(~"WAT: can't coalesce non-text nodes in flush_clump_to_list()!") } (true, false) => { // FIXME(pcwalton): Stop cloning boxes, as above. debug!("TextRunScanner: pushing single non-text box in range: {}", self.clump); let new_box = in_boxes[self.clump.begin()].clone(); out_boxes.push(new_box) }, (true, true) => { let old_box = &in_boxes[self.clump.begin()]; let text = match old_box.specific { UnscannedTextBox(ref text_box_info) => &text_box_info.text, _ => fail!("Expected an unscanned text box!"), }; let font_style = old_box.font_style(); let decoration = old_box.text_decoration(); // TODO(#115): Use the actual CSS `white-space` property of the relevant style. let compression = match old_box.white_space() { white_space::normal => CompressWhitespaceNewline, white_space::pre => CompressNone, }; let mut new_line_pos = ~[]; let (transformed_text, whitespace) = transform_text(*text, compression, last_whitespace, &mut new_line_pos); new_whitespace = whitespace; if transformed_text.len() > 0 { // TODO(#177): Text run creation must account for the renderability of text by // font group fonts. This is probably achieved by creating the font group above // and then letting `FontGroup` decide which `Font` to stick into the text run. let fontgroup = font_context.get_resolved_font_for_style(&font_style); let run = ~fontgroup.borrow().create_textrun(transformed_text.clone(), decoration); debug!("TextRunScanner: pushing single text box in range: {} ({})", self.clump, *text); let range = Range::new(0, run.char_len()); let new_metrics = run.metrics_for_range(&range); let new_text_box_info = ScannedTextBoxInfo::new(Arc::new(run), range); let mut new_box = old_box.transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); new_box.new_line_pos = new_line_pos; out_boxes.push(new_box) } else { if self.clump.begin() + 1 < in_boxes.len() { // if the this box has border,margin,padding of inline, // we should copy that stuff to next box. in_boxes[self.clump.begin() + 1] .merge_noncontent_inline_left(&in_boxes[self.clump.begin()]); } } }, (false, true) => { // TODO(#177): Text run creation must account for the renderability of text by // font group fonts. This is probably achieved by creating the font group above // and then letting `FontGroup` decide which `Font` to stick into the text run. let in_box = &in_boxes[self.clump.begin()]; let font_style = in_box.font_style(); let fontgroup = font_context.get_resolved_font_for_style(&font_style); let decoration = in_box.text_decoration(); // TODO(#115): Use the actual CSS `white-space` property of the relevant style. let compression = match in_box.white_space() { white_space::normal => CompressWhitespaceNewline, white_space::pre => CompressNone, };
struct NewLinePositions { new_line_pos: ~[uint], } let mut new_line_positions: ~[NewLinePositions] = ~[]; // First, transform/compress text of all the nodes. let mut last_whitespace_in_clump = new_whitespace; let transformed_strs: ~[~str] = slice::from_fn(self.clump.length(), |i| { // TODO(#113): We should be passing the compression context between calls to // `transform_text`, so that boxes starting and/or ending with whitespace can // be compressed correctly with respect to the text run. let idx = i + self.clump.begin(); let in_box = match in_boxes[idx].specific { UnscannedTextBox(ref text_box_info) => &text_box_info.text, _ => fail!("Expected an unscanned text box!"), }; let mut new_line_pos = ~[]; let (new_str, new_whitespace) = transform_text(*in_box, compression, last_whitespace_in_clump, &mut new_line_pos); new_line_positions.push(NewLinePositions { new_line_pos: new_line_pos }); last_whitespace_in_clump = new_whitespace; new_str }); new_whitespace = last_whitespace_in_clump; // Next, concatenate all of the transformed strings together, saving the new // character indices. let mut run_str: ~str = ~""; let mut new_ranges: ~[Range] = ~[]; let mut char_total = 0; for i in range(0, transformed_strs.len()) { let added_chars = transformed_strs[i].char_len(); new_ranges.push(Range::new(char_total, added_chars)); run_str.push_str(transformed_strs[i]); char_total += added_chars; } // Now create the run. // TextRuns contain a cycle which is usually resolved by the teardown // sequence. If no clump takes ownership, however, it will leak. let clump = self.clump; let run = if clump.length()!= 0 && run_str.len() > 0 { Some(Arc::new(~TextRun::new(&mut *fontgroup.borrow().fonts[0].borrow_mut(), run_str.clone(), decoration))) } else { None }; // Make new boxes with the run and adjusted text indices. debug!("TextRunScanner: pushing box(es) in range: {}", self.clump); for i in clump.eachi() { let logical_offset = i - self.clump.begin(); let range = new_ranges[logical_offset]; if range.length() == 0 { debug!("Elided an `UnscannedTextbox` because it was zero-length after \ compression; {:s}", in_boxes[i].debug_str()); // in this case, in_boxes[i] is elided // so, we should merge inline info with next index of in_boxes if i + 1 < in_boxes.len() { in_boxes[i + 1].merge_noncontent_inline_left(&in_boxes[i]); } continue } let new_text_box_info = ScannedTextBoxInfo::new(run.get_ref().clone(), range); let new_metrics = new_text_box_info.run.get().metrics_for_range(&range); let mut new_box = in_boxes[i].transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); new_box.new_line_pos = new_line_positions[logical_offset].new_line_pos.clone(); out_boxes.push(new_box) } } } // End of match. debug!("--- In boxes: ---"); for (i, box_) in in_boxes.iter().enumerate() { debug!("{:u} --> {:s}", i, box_.debug_str()); } debug!("------------------"); debug!("--- Out boxes: ---"); for (i, box_) in out_boxes.iter().enumerate() { debug!("{:u} --> {:s}", i, box_.debug_str()); } debug!("------------------"); debug!("--- Elem ranges: ---"); for (i, nr) in inline.elems.eachi() { debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id()); () } debug!("--------------------"); let end = self.clump.end(); // FIXME: borrow checker workaround self.clump.reset(end, 0); new_whitespace } // End of `flush_clump_to_list`. }
random_line_split
ping.rs
extern crate mqttc; extern crate netopt; #[macro_use] extern crate log; extern crate env_logger; use std::env; use std::process::exit; use std::time::Duration; use netopt::NetworkOptions; use mqttc::{Client, ClientOptions, ReconnectMethod}; fn main()
Some(message) => println!("{:?}", message), None => { println!("."); } } } }
{ env_logger::init(); let mut args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: cargo run --example ping -- 127.0.0.1:1883"); exit(0); } let ref address = args[1]; info!("Display logs"); println!("Establish connection to {}", address); // Connect to broker, send CONNECT then wait CONNACK let netopt = NetworkOptions::new(); let mut opts = ClientOptions::new(); opts.set_keep_alive(15); opts.set_reconnect(ReconnectMethod::ReconnectAfter(Duration::new(5,0))); let mut client = opts.connect(address.as_str(), netopt).unwrap(); loop { match client.await().unwrap() {
identifier_body
ping.rs
extern crate mqttc; extern crate netopt;
extern crate env_logger; use std::env; use std::process::exit; use std::time::Duration; use netopt::NetworkOptions; use mqttc::{Client, ClientOptions, ReconnectMethod}; fn main() { env_logger::init(); let mut args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: cargo run --example ping -- 127.0.0.1:1883"); exit(0); } let ref address = args[1]; info!("Display logs"); println!("Establish connection to {}", address); // Connect to broker, send CONNECT then wait CONNACK let netopt = NetworkOptions::new(); let mut opts = ClientOptions::new(); opts.set_keep_alive(15); opts.set_reconnect(ReconnectMethod::ReconnectAfter(Duration::new(5,0))); let mut client = opts.connect(address.as_str(), netopt).unwrap(); loop { match client.await().unwrap() { Some(message) => println!("{:?}", message), None => { println!("."); } } } }
#[macro_use] extern crate log;
random_line_split
ping.rs
extern crate mqttc; extern crate netopt; #[macro_use] extern crate log; extern crate env_logger; use std::env; use std::process::exit; use std::time::Duration; use netopt::NetworkOptions; use mqttc::{Client, ClientOptions, ReconnectMethod}; fn
() { env_logger::init(); let mut args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: cargo run --example ping -- 127.0.0.1:1883"); exit(0); } let ref address = args[1]; info!("Display logs"); println!("Establish connection to {}", address); // Connect to broker, send CONNECT then wait CONNACK let netopt = NetworkOptions::new(); let mut opts = ClientOptions::new(); opts.set_keep_alive(15); opts.set_reconnect(ReconnectMethod::ReconnectAfter(Duration::new(5,0))); let mut client = opts.connect(address.as_str(), netopt).unwrap(); loop { match client.await().unwrap() { Some(message) => println!("{:?}", message), None => { println!("."); } } } }
main
identifier_name
http_utils.rs
use url::Url; use hyper::Client; use hyper::header::{ContentType}; use hyper::status::StatusCode; use hyper::error::Error; use std::io::Read; pub struct HttpResponse { pub status: StatusCode, pub body: String } pub fn
(url: &Url) -> Result<HttpResponse, Error> { let mut client = Client::new(); let result_response = client.get(&url.to_string()).send(); //TODO: use try! macro here match result_response { Ok(mut res) => { let mut body = String::new(); let result = res.read_to_string(&mut body); match result { Ok(_) => { Ok(HttpResponse{status: res.status, body: body}) }, //TODO: review why we use Irror::Io here Err(err) => { Err(Error::Io(err)) } } }, Err(err) => Err(err) } } pub fn post_json(url: &Url, body: &str) -> Result<HttpResponse, Error> { let mut client = Client::new(); let result_response = client.post(&url.to_string()) .header(ContentType::json()) .body(body) .send(); match result_response { Ok(mut res) => { let mut body = String::new(); let result = res.read_to_string(&mut body); match result { Ok(_) => { Ok(HttpResponse{status: res.status, body: body}) }, Err(err) => { Err(Error::Io(err)) } } }, Err(err) => Err(err) } }
get
identifier_name
http_utils.rs
use url::Url; use hyper::Client; use hyper::header::{ContentType}; use hyper::status::StatusCode; use hyper::error::Error; use std::io::Read; pub struct HttpResponse { pub status: StatusCode, pub body: String } pub fn get(url: &Url) -> Result<HttpResponse, Error>
} pub fn post_json(url: &Url, body: &str) -> Result<HttpResponse, Error> { let mut client = Client::new(); let result_response = client.post(&url.to_string()) .header(ContentType::json()) .body(body) .send(); match result_response { Ok(mut res) => { let mut body = String::new(); let result = res.read_to_string(&mut body); match result { Ok(_) => { Ok(HttpResponse{status: res.status, body: body}) }, Err(err) => { Err(Error::Io(err)) } } }, Err(err) => Err(err) } }
{ let mut client = Client::new(); let result_response = client.get(&url.to_string()).send(); //TODO: use try! macro here match result_response { Ok(mut res) => { let mut body = String::new(); let result = res.read_to_string(&mut body); match result { Ok(_) => { Ok(HttpResponse{status: res.status, body: body}) }, //TODO: review why we use Irror::Io here Err(err) => { Err(Error::Io(err)) } } }, Err(err) => Err(err) }
identifier_body
http_utils.rs
use url::Url; use hyper::Client; use hyper::header::{ContentType}; use hyper::status::StatusCode; use hyper::error::Error; use std::io::Read; pub struct HttpResponse { pub status: StatusCode, pub body: String }
pub fn get(url: &Url) -> Result<HttpResponse, Error> { let mut client = Client::new(); let result_response = client.get(&url.to_string()).send(); //TODO: use try! macro here match result_response { Ok(mut res) => { let mut body = String::new(); let result = res.read_to_string(&mut body); match result { Ok(_) => { Ok(HttpResponse{status: res.status, body: body}) }, //TODO: review why we use Irror::Io here Err(err) => { Err(Error::Io(err)) } } }, Err(err) => Err(err) } } pub fn post_json(url: &Url, body: &str) -> Result<HttpResponse, Error> { let mut client = Client::new(); let result_response = client.post(&url.to_string()) .header(ContentType::json()) .body(body) .send(); match result_response { Ok(mut res) => { let mut body = String::new(); let result = res.read_to_string(&mut body); match result { Ok(_) => { Ok(HttpResponse{status: res.status, body: body}) }, Err(err) => { Err(Error::Io(err)) } } }, Err(err) => Err(err) } }
random_line_split
warn_corner_cases.rs
// run-pass // This test is checking our logic for structural match checking by enumerating // the different kinds of const expressions. This test is collecting cases where // we have accepted the const expression as a pattern in the past but we want // to begin warning the user that a future version of Rust may start rejecting // such const expressions. // The specific corner cases we are exploring here are instances where the // const-evaluator computes a value that *does* meet the conditions for // structural-match, but the const expression itself has abstractions (like // calls to const functions) that may fit better with a type-based analysis // rather than a commitment to a specific value. #![warn(indirect_structural_match)] #[derive(Copy, Clone, Debug)] struct NoDerive(u32); // This impl makes `NoDerive` irreflexive. impl PartialEq for NoDerive { fn eq(&self, _: &Self) -> bool { false } } impl Eq for NoDerive { } fn
() { const INDEX: Option<NoDerive> = [None, Some(NoDerive(10))][0]; match None { Some(_) => panic!("whoops"), INDEX => dbg!(INDEX), }; //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted const fn build() -> Option<NoDerive> { None } const CALL: Option<NoDerive> = build(); match None { Some(_) => panic!("whoops"), CALL => dbg!(CALL), }; //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted impl NoDerive { const fn none() -> Option<NoDerive> { None } } const METHOD_CALL: Option<NoDerive> = NoDerive::none(); match None { Some(_) => panic!("whoops"), METHOD_CALL => dbg!(METHOD_CALL), }; //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted }
main
identifier_name
warn_corner_cases.rs
// run-pass // This test is checking our logic for structural match checking by enumerating // the different kinds of const expressions. This test is collecting cases where // we have accepted the const expression as a pattern in the past but we want // to begin warning the user that a future version of Rust may start rejecting // such const expressions. // The specific corner cases we are exploring here are instances where the // const-evaluator computes a value that *does* meet the conditions for // structural-match, but the const expression itself has abstractions (like // calls to const functions) that may fit better with a type-based analysis // rather than a commitment to a specific value. #![warn(indirect_structural_match)] #[derive(Copy, Clone, Debug)] struct NoDerive(u32); // This impl makes `NoDerive` irreflexive. impl PartialEq for NoDerive { fn eq(&self, _: &Self) -> bool { false } } impl Eq for NoDerive { } fn main() { const INDEX: Option<NoDerive> = [None, Some(NoDerive(10))][0]; match None { Some(_) => panic!("whoops"), INDEX => dbg!(INDEX), }; //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted const fn build() -> Option<NoDerive> { None } const CALL: Option<NoDerive> = build(); match None { Some(_) => panic!("whoops"), CALL => dbg!(CALL), }; //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted impl NoDerive { const fn none() -> Option<NoDerive> { None } } const METHOD_CALL: Option<NoDerive> = NoDerive::none();
}
match None { Some(_) => panic!("whoops"), METHOD_CALL => dbg!(METHOD_CALL), }; //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted
random_line_split
issue-6128.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. #![allow(unknown_features)] #![feature(box_syntax)] extern crate collections; use std::collections::HashMap; trait Graph<Node, Edge> { fn f(&self, Edge); } impl<E> Graph<int, E> for HashMap<int, int> { fn f(&self, _e: E) { panic!(); } } pub fn main()
{ let g : Box<HashMap<int,int>> = box HashMap::new(); let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>; }
identifier_body
issue-6128.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. #![allow(unknown_features)] #![feature(box_syntax)] extern crate collections; use std::collections::HashMap; trait Graph<Node, Edge> { fn f(&self, Edge); } impl<E> Graph<int, E> for HashMap<int, int> { fn f(&self, _e: E) { panic!(); } } pub fn main() { let g : Box<HashMap<int,int>> = box HashMap::new(); let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>; }
random_line_split
issue-6128.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. #![allow(unknown_features)] #![feature(box_syntax)] extern crate collections; use std::collections::HashMap; trait Graph<Node, Edge> { fn f(&self, Edge); } impl<E> Graph<int, E> for HashMap<int, int> { fn f(&self, _e: E) { panic!(); } } pub fn
() { let g : Box<HashMap<int,int>> = box HashMap::new(); let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>; }
main
identifier_name
simple.rs
use std::convert::Infallible; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; use lazy_static::lazy_static; use reroute::{Captures, RouterBuilder}; lazy_static! { static ref ROUTER: reroute::Router = { let mut builder = RouterBuilder::new(); // Use raw strings so you don't need to escape patterns. builder.get(r"/(\d+)", digit_handler); builder.post(r"/body", body_handler); // Using a closure also works! builder.delete(r"/closure", |_: Request<Body>, _: Captures| { Response::new(Body::from( "You used a closure here, and called a delete. How neat.", )) }); // Add your own not found handler. builder.not_found(not_found); builder.finalize().unwrap() }; } fn digit_handler(_: Request<Body>, c: Captures) -> Response<Body> { // We know there are captures because that is the only way this function is triggered. let caps = c.unwrap(); let digits = &caps[1]; if digits.len() > 5 { Response::new(Body::from("that's a big number!")) } else { Response::new(Body::from("not a big number")) } } // You can ignore captures if you don't want to use them. fn
(req: Request<Body>, _: Captures) -> Response<Body> { Response::new(req.into_body()) } // A custom 404 handler. fn not_found(req: Request<Body>, _: Captures) -> Response<Body> { let message = format!("why you calling {}?", req.uri()); Response::new(Body::from(message)) } async fn handler(req: Request<Body>) -> Result<Response<Body>, Infallible> { Ok(ROUTER.handle(req)) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let addr = ([127, 0, 0, 1], 3000).into(); let svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handler)) }); let server = Server::bind(&addr).serve(svc); server.await?; Ok(()) }
body_handler
identifier_name
simple.rs
use std::convert::Infallible; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; use lazy_static::lazy_static; use reroute::{Captures, RouterBuilder}; lazy_static! {
static ref ROUTER: reroute::Router = { let mut builder = RouterBuilder::new(); // Use raw strings so you don't need to escape patterns. builder.get(r"/(\d+)", digit_handler); builder.post(r"/body", body_handler); // Using a closure also works! builder.delete(r"/closure", |_: Request<Body>, _: Captures| { Response::new(Body::from( "You used a closure here, and called a delete. How neat.", )) }); // Add your own not found handler. builder.not_found(not_found); builder.finalize().unwrap() }; } fn digit_handler(_: Request<Body>, c: Captures) -> Response<Body> { // We know there are captures because that is the only way this function is triggered. let caps = c.unwrap(); let digits = &caps[1]; if digits.len() > 5 { Response::new(Body::from("that's a big number!")) } else { Response::new(Body::from("not a big number")) } } // You can ignore captures if you don't want to use them. fn body_handler(req: Request<Body>, _: Captures) -> Response<Body> { Response::new(req.into_body()) } // A custom 404 handler. fn not_found(req: Request<Body>, _: Captures) -> Response<Body> { let message = format!("why you calling {}?", req.uri()); Response::new(Body::from(message)) } async fn handler(req: Request<Body>) -> Result<Response<Body>, Infallible> { Ok(ROUTER.handle(req)) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let addr = ([127, 0, 0, 1], 3000).into(); let svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handler)) }); let server = Server::bind(&addr).serve(svc); server.await?; Ok(()) }
random_line_split
simple.rs
use std::convert::Infallible; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; use lazy_static::lazy_static; use reroute::{Captures, RouterBuilder}; lazy_static! { static ref ROUTER: reroute::Router = { let mut builder = RouterBuilder::new(); // Use raw strings so you don't need to escape patterns. builder.get(r"/(\d+)", digit_handler); builder.post(r"/body", body_handler); // Using a closure also works! builder.delete(r"/closure", |_: Request<Body>, _: Captures| { Response::new(Body::from( "You used a closure here, and called a delete. How neat.", )) }); // Add your own not found handler. builder.not_found(not_found); builder.finalize().unwrap() }; } fn digit_handler(_: Request<Body>, c: Captures) -> Response<Body> { // We know there are captures because that is the only way this function is triggered. let caps = c.unwrap(); let digits = &caps[1]; if digits.len() > 5 { Response::new(Body::from("that's a big number!")) } else { Response::new(Body::from("not a big number")) } } // You can ignore captures if you don't want to use them. fn body_handler(req: Request<Body>, _: Captures) -> Response<Body> { Response::new(req.into_body()) } // A custom 404 handler. fn not_found(req: Request<Body>, _: Captures) -> Response<Body>
async fn handler(req: Request<Body>) -> Result<Response<Body>, Infallible> { Ok(ROUTER.handle(req)) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let addr = ([127, 0, 0, 1], 3000).into(); let svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handler)) }); let server = Server::bind(&addr).serve(svc); server.await?; Ok(()) }
{ let message = format!("why you calling {}?", req.uri()); Response::new(Body::from(message)) }
identifier_body
simple.rs
use std::convert::Infallible; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; use lazy_static::lazy_static; use reroute::{Captures, RouterBuilder}; lazy_static! { static ref ROUTER: reroute::Router = { let mut builder = RouterBuilder::new(); // Use raw strings so you don't need to escape patterns. builder.get(r"/(\d+)", digit_handler); builder.post(r"/body", body_handler); // Using a closure also works! builder.delete(r"/closure", |_: Request<Body>, _: Captures| { Response::new(Body::from( "You used a closure here, and called a delete. How neat.", )) }); // Add your own not found handler. builder.not_found(not_found); builder.finalize().unwrap() }; } fn digit_handler(_: Request<Body>, c: Captures) -> Response<Body> { // We know there are captures because that is the only way this function is triggered. let caps = c.unwrap(); let digits = &caps[1]; if digits.len() > 5
else { Response::new(Body::from("not a big number")) } } // You can ignore captures if you don't want to use them. fn body_handler(req: Request<Body>, _: Captures) -> Response<Body> { Response::new(req.into_body()) } // A custom 404 handler. fn not_found(req: Request<Body>, _: Captures) -> Response<Body> { let message = format!("why you calling {}?", req.uri()); Response::new(Body::from(message)) } async fn handler(req: Request<Body>) -> Result<Response<Body>, Infallible> { Ok(ROUTER.handle(req)) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let addr = ([127, 0, 0, 1], 3000).into(); let svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handler)) }); let server = Server::bind(&addr).serve(svc); server.await?; Ok(()) }
{ Response::new(Body::from("that's a big number!")) }
conditional_block
session.rs
// Copyright (C) 2015 Wire Swiss GmbH <[email protected]> // Based on libsignal-protocol-java by Open Whisper Systems // https://github.com/WhisperSystems/libsignal-protocol-java. // // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of
// GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pub use internal::session::Error; pub use internal::session::PreKeyStore; pub use internal::session::Session;
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
random_line_split
lib.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/. */ #![cfg(test)] extern crate cookie as cookie_rs; extern crate devtools_traits; extern crate flate2; extern crate hyper; extern crate hyper_openssl; extern crate hyper_serde; extern crate ipc_channel; extern crate msg; extern crate net; extern crate net_traits; extern crate profile_traits; extern crate servo_config; extern crate servo_url; extern crate time; extern crate unicase; extern crate url; mod chrome_loader; mod cookie; mod cookie_http_state; mod data_loader; mod fetch; mod file_loader; mod filemanager_thread; mod hsts; mod http_loader; mod mime_classifier; mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; use hyper::server::{Handler, Listening, Server}; use net::connector::create_ssl_client; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; use net_traits::FetchTaskTarget; use net_traits::request::Request; use net_traits::response::Response; use servo_config::resource_files::resources_dir_path; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{Sender, channel}; const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; struct FetchResponseCollector { sender: Sender<Response>, } fn new_fetch_context(dc: Option<Sender<DevtoolsControlMsg>>) -> FetchContext { let ca_file = resources_dir_path().unwrap().join("certs"); let ssl_client = create_ssl_client(&ca_file); FetchContext { state: Arc::new(HttpState::new(ssl_client)), user_agent: DEFAULT_USER_AGENT.into(), devtools_chan: dc, filemanager: FileManager::new(), cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(None))), } } impl FetchTaskTarget for FetchResponseCollector { fn process_request_body(&mut self, _: &Request) {} fn process_request_eof(&mut self, _: &Request) {} fn process_response(&mut self, _: &Response) {} fn process_response_chunk(&mut self, _: Vec<u8>) {} /// Fired when the response is fully fetched fn process_response_eof(&mut self, response: &Response) { let _ = self.sender.send(response.clone()); } } fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsControlMsg>>) -> Response { fetch_with_context(request, &new_fetch_context(dc)) } fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender, }; methods::fetch(request, &mut target, context); receiver.recv().unwrap() } fn
(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender, }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None)); receiver.recv().unwrap() } fn make_server<H: Handler +'static>(handler: H) -> (Listening, ServoUrl) { // this is a Listening server because of handle_threads() let server = Server::http("0.0.0.0:0").unwrap().handle_threads(handler, 2).unwrap(); let url_string = format!("http://localhost:{}", server.socket.port()); let url = ServoUrl::parse(&url_string).unwrap(); (server, url) }
fetch_with_cors_cache
identifier_name
lib.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/. */ #![cfg(test)] extern crate cookie as cookie_rs; extern crate devtools_traits; extern crate flate2; extern crate hyper; extern crate hyper_openssl; extern crate hyper_serde; extern crate ipc_channel; extern crate msg; extern crate net; extern crate net_traits;
extern crate servo_config; extern crate servo_url; extern crate time; extern crate unicase; extern crate url; mod chrome_loader; mod cookie; mod cookie_http_state; mod data_loader; mod fetch; mod file_loader; mod filemanager_thread; mod hsts; mod http_loader; mod mime_classifier; mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; use hyper::server::{Handler, Listening, Server}; use net::connector::create_ssl_client; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; use net_traits::FetchTaskTarget; use net_traits::request::Request; use net_traits::response::Response; use servo_config::resource_files::resources_dir_path; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{Sender, channel}; const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; struct FetchResponseCollector { sender: Sender<Response>, } fn new_fetch_context(dc: Option<Sender<DevtoolsControlMsg>>) -> FetchContext { let ca_file = resources_dir_path().unwrap().join("certs"); let ssl_client = create_ssl_client(&ca_file); FetchContext { state: Arc::new(HttpState::new(ssl_client)), user_agent: DEFAULT_USER_AGENT.into(), devtools_chan: dc, filemanager: FileManager::new(), cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(None))), } } impl FetchTaskTarget for FetchResponseCollector { fn process_request_body(&mut self, _: &Request) {} fn process_request_eof(&mut self, _: &Request) {} fn process_response(&mut self, _: &Response) {} fn process_response_chunk(&mut self, _: Vec<u8>) {} /// Fired when the response is fully fetched fn process_response_eof(&mut self, response: &Response) { let _ = self.sender.send(response.clone()); } } fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsControlMsg>>) -> Response { fetch_with_context(request, &new_fetch_context(dc)) } fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender, }; methods::fetch(request, &mut target, context); receiver.recv().unwrap() } fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender, }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None)); receiver.recv().unwrap() } fn make_server<H: Handler +'static>(handler: H) -> (Listening, ServoUrl) { // this is a Listening server because of handle_threads() let server = Server::http("0.0.0.0:0").unwrap().handle_threads(handler, 2).unwrap(); let url_string = format!("http://localhost:{}", server.socket.port()); let url = ServoUrl::parse(&url_string).unwrap(); (server, url) }
extern crate profile_traits;
random_line_split
lib.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/. */ #![cfg(test)] extern crate cookie as cookie_rs; extern crate devtools_traits; extern crate flate2; extern crate hyper; extern crate hyper_openssl; extern crate hyper_serde; extern crate ipc_channel; extern crate msg; extern crate net; extern crate net_traits; extern crate profile_traits; extern crate servo_config; extern crate servo_url; extern crate time; extern crate unicase; extern crate url; mod chrome_loader; mod cookie; mod cookie_http_state; mod data_loader; mod fetch; mod file_loader; mod filemanager_thread; mod hsts; mod http_loader; mod mime_classifier; mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; use hyper::server::{Handler, Listening, Server}; use net::connector::create_ssl_client; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; use net_traits::FetchTaskTarget; use net_traits::request::Request; use net_traits::response::Response; use servo_config::resource_files::resources_dir_path; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{Sender, channel}; const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; struct FetchResponseCollector { sender: Sender<Response>, } fn new_fetch_context(dc: Option<Sender<DevtoolsControlMsg>>) -> FetchContext { let ca_file = resources_dir_path().unwrap().join("certs"); let ssl_client = create_ssl_client(&ca_file); FetchContext { state: Arc::new(HttpState::new(ssl_client)), user_agent: DEFAULT_USER_AGENT.into(), devtools_chan: dc, filemanager: FileManager::new(), cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(None))), } } impl FetchTaskTarget for FetchResponseCollector { fn process_request_body(&mut self, _: &Request) {} fn process_request_eof(&mut self, _: &Request)
fn process_response(&mut self, _: &Response) {} fn process_response_chunk(&mut self, _: Vec<u8>) {} /// Fired when the response is fully fetched fn process_response_eof(&mut self, response: &Response) { let _ = self.sender.send(response.clone()); } } fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsControlMsg>>) -> Response { fetch_with_context(request, &new_fetch_context(dc)) } fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender, }; methods::fetch(request, &mut target, context); receiver.recv().unwrap() } fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender, }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None)); receiver.recv().unwrap() } fn make_server<H: Handler +'static>(handler: H) -> (Listening, ServoUrl) { // this is a Listening server because of handle_threads() let server = Server::http("0.0.0.0:0").unwrap().handle_threads(handler, 2).unwrap(); let url_string = format!("http://localhost:{}", server.socket.port()); let url = ServoUrl::parse(&url_string).unwrap(); (server, url) }
{}
identifier_body
utf8_idents.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast feature doesn't work. #[feature(non_ascii_idents)]; use std::num; pub fn main() { let ε = 0.00001; let Π = 3.14; let लंच = Π * Π + 1.54; assert!(num::abs((लंच - 1.54) - (Π * Π)) < ε); assert_eq!(საჭმელად_გემრიელი_სადილი(), 0); } fn საჭმელად_გემრიელი_სადილი() -> int { // Lunch in several la
10; let غداء = 10; let լանչ = 10; let обед = 10; let абед = 10; let μεσημεριανό = 10; let hádegismatur = 10; let ручек = 10; let ăn_trưa = 10; let อาหารกลางวัน = 10; // Lunchy arithmetic, mm. assert_eq!(hádegismatur * ручек * обед, 1000); assert_eq!(10, ארוחת_צהריי); assert_eq!(ランチ + 午餐 + μεσημεριανό, 30); assert_eq!(ăn_trưa + อาหารกลางวัน, 20); return (абед + լանչ) >> غداء; }
nguages. let ランチ = 10; let 午餐 = 10; let ארוחת_צהריי =
identifier_name
utf8_idents.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast feature doesn't work. #[feature(non_ascii_idents)]; use std::num; pub fn main() { let ε = 0.00001; let Π = 3.14; let लंच = Π * Π + 1.54; assert!(num::abs((लंच - 1.54) - (Π * Π)) < ε); assert_eq!(საჭმელად_გემრიელი_სადილი(), 0); } fn საჭმელად_გემრიელი_სადილი() -> int { // Lunch in several languages. let ランチ = 10; let 午餐 = 10; let ארוחת_צהריי = 10; le
t غداء = 10; let լանչ = 10; let обед = 10; let абед = 10; let μεσημεριανό = 10; let hádegismatur = 10; let ручек = 10; let ăn_trưa = 10; let อาหารกลางวัน = 10; // Lunchy arithmetic, mm. assert_eq!(hádegismatur * ручек * обед, 1000); assert_eq!(10, ארוחת_צהריי); assert_eq!(ランチ + 午餐 + μεσημεριανό, 30); assert_eq!(ăn_trưa + อาหารกลางวัน, 20); return (абед + լանչ) >> غداء; }
identifier_body
utf8_idents.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast feature doesn't work. #[feature(non_ascii_idents)]; use std::num; pub fn main() { let ε = 0.00001; let Π = 3.14; let लंच = Π * Π + 1.54; assert!(num::abs((लंच - 1.54) - (Π * Π)) < ε); assert_eq!(საჭმელად_გემრიელი_სადილი(), 0); }
fn საჭმელად_გემრიელი_სადილი() -> int { // Lunch in several languages. let ランチ = 10; let 午餐 = 10; let ארוחת_צהריי = 10; let غداء = 10; let լանչ = 10; let обед = 10; let абед = 10; let μεσημεριανό = 10; let hádegismatur = 10; let ручек = 10; let ăn_trưa = 10; let อาหารกลางวัน = 10; // Lunchy arithmetic, mm. assert_eq!(hádegismatur * ручек * обед, 1000); assert_eq!(10, ארוחת_צהריי); assert_eq!(ランチ + 午餐 + μεσημεριανό, 30); assert_eq!(ăn_trưa + อาหารกลางวัน, 20); return (абед + լանչ) >> غداء; }
random_line_split
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{MutNullableJS, Root}; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmlformelement::{FormControl, HTMLFormElement}; use dom::htmllegendelement::HTMLLegendElement; use dom::node::{Node, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::default::Default; use style::element_state::*; #[dom_struct] pub struct HTMLFieldSetElement { htmlelement: HTMLElement, form_owner: MutNullableJS<HTMLFormElement>, } impl HTMLFieldSetElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLFieldSetElement { HTMLFieldSetElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLFieldSetElement> { Node::reflect_node(box HTMLFieldSetElement::new_inherited(local_name, prefix, document), document, HTMLFieldSetElementBinding::Wrap) } } impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://html.spec.whatwg.org/multipage/#dom-fieldset-elements fn Elements(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { elem.downcast::<HTMLElement>() .map_or(false, HTMLElement::is_listed_element) } } let filter = box ElementsFilter; let window = window_from_node(self); HTMLCollection::create(&window, self.upcast(), filter) } // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn
(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(&window, self.upcast()) } // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } } impl VirtualMethods for HTMLFieldSetElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("disabled") => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Fieldset was already disabled before. return; }, AttributeMutation::Removed => false, }; let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); el.set_disabled_state(disabled_state); el.set_enabled_state(!disabled_state); let mut found_legend = false; let children = node.children().filter(|node| { if found_legend { true } else if node.is::<HTMLLegendElement>() { found_legend = true; false } else { true } }); let fields = children.flat_map(|child| { child.traverse_preorder().filter(|descendant| { match descendant.type_id() { NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTextAreaElement)) => { true }, _ => false, } }) }); if disabled_state { for field in fields { let el = field.downcast::<Element>().unwrap(); el.set_disabled_state(true); el.set_enabled_state(false); } } else { for field in fields { let el = field.downcast::<Element>().unwrap(); el.check_disabled_attribute(); el.check_ancestors_disabled_state_for_form_control(); } } }, &local_name!("form") => { self.form_attribute_mutated(mutation); }, _ => {}, } } } impl FormControl for HTMLFieldSetElement { fn form_owner(&self) -> Option<Root<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
Validity
identifier_name
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{MutNullableJS, Root}; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmlformelement::{FormControl, HTMLFormElement}; use dom::htmllegendelement::HTMLLegendElement; use dom::node::{Node, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::default::Default; use style::element_state::*; #[dom_struct] pub struct HTMLFieldSetElement { htmlelement: HTMLElement, form_owner: MutNullableJS<HTMLFormElement>, } impl HTMLFieldSetElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLFieldSetElement { HTMLFieldSetElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLFieldSetElement> { Node::reflect_node(box HTMLFieldSetElement::new_inherited(local_name, prefix, document), document, HTMLFieldSetElementBinding::Wrap) } } impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://html.spec.whatwg.org/multipage/#dom-fieldset-elements fn Elements(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { elem.downcast::<HTMLElement>() .map_or(false, HTMLElement::is_listed_element) } } let filter = box ElementsFilter; let window = window_from_node(self); HTMLCollection::create(&window, self.upcast(), filter) } // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(&window, self.upcast()) } // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } } impl VirtualMethods for HTMLFieldSetElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation)
} else if node.is::<HTMLLegendElement>() { found_legend = true; false } else { true } }); let fields = children.flat_map(|child| { child.traverse_preorder().filter(|descendant| { match descendant.type_id() { NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTextAreaElement)) => { true }, _ => false, } }) }); if disabled_state { for field in fields { let el = field.downcast::<Element>().unwrap(); el.set_disabled_state(true); el.set_enabled_state(false); } } else { for field in fields { let el = field.downcast::<Element>().unwrap(); el.check_disabled_attribute(); el.check_ancestors_disabled_state_for_form_control(); } } }, &local_name!("form") => { self.form_attribute_mutated(mutation); }, _ => {}, } } } impl FormControl for HTMLFieldSetElement { fn form_owner(&self) -> Option<Root<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
{ self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("disabled") => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Fieldset was already disabled before. return; }, AttributeMutation::Removed => false, }; let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); el.set_disabled_state(disabled_state); el.set_enabled_state(!disabled_state); let mut found_legend = false; let children = node.children().filter(|node| { if found_legend { true
identifier_body
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{MutNullableJS, Root}; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmlformelement::{FormControl, HTMLFormElement}; use dom::htmllegendelement::HTMLLegendElement; use dom::node::{Node, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::default::Default; use style::element_state::*; #[dom_struct] pub struct HTMLFieldSetElement { htmlelement: HTMLElement, form_owner: MutNullableJS<HTMLFormElement>, } impl HTMLFieldSetElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLFieldSetElement { HTMLFieldSetElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLFieldSetElement> { Node::reflect_node(box HTMLFieldSetElement::new_inherited(local_name, prefix, document), document, HTMLFieldSetElementBinding::Wrap) } } impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://html.spec.whatwg.org/multipage/#dom-fieldset-elements fn Elements(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { elem.downcast::<HTMLElement>() .map_or(false, HTMLElement::is_listed_element) } } let filter = box ElementsFilter; let window = window_from_node(self); HTMLCollection::create(&window, self.upcast(), filter) } // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(&window, self.upcast()) } // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } } impl VirtualMethods for HTMLFieldSetElement {
Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("disabled") => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Fieldset was already disabled before. return; }, AttributeMutation::Removed => false, }; let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); el.set_disabled_state(disabled_state); el.set_enabled_state(!disabled_state); let mut found_legend = false; let children = node.children().filter(|node| { if found_legend { true } else if node.is::<HTMLLegendElement>() { found_legend = true; false } else { true } }); let fields = children.flat_map(|child| { child.traverse_preorder().filter(|descendant| { match descendant.type_id() { NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTextAreaElement)) => { true }, _ => false, } }) }); if disabled_state { for field in fields { let el = field.downcast::<Element>().unwrap(); el.set_disabled_state(true); el.set_enabled_state(false); } } else { for field in fields { let el = field.downcast::<Element>().unwrap(); el.check_disabled_attribute(); el.check_ancestors_disabled_state_for_form_control(); } } }, &local_name!("form") => { self.form_attribute_mutated(mutation); }, _ => {}, } } } impl FormControl for HTMLFieldSetElement { fn form_owner(&self) -> Option<Root<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
fn super_type(&self) -> Option<&VirtualMethods> {
random_line_split
editor.rs
use rand; use rand::Rng; use std::process::Command; use std::io::prelude::*; use std::fs::File; const TEMP_FILE_LENGTH: usize = 16; pub fn text_from_editor() -> String
Err(_) => String::new() } } /// TODO Return proper editor from env / config fn editor() -> String { return "vim".to_string(); } /// TODO Ensure real unique names fn temp_file() -> String { let result = String::from("/tmp/"); let file = rand::thread_rng() .gen_ascii_chars() .take(TEMP_FILE_LENGTH) .collect::<String>(); result + &file }
{ let temp_file = temp_file(); let status = Command::new(editor()) .arg(temp_file.clone()) .status(); match status { Ok(status) => { if !status.success() { return String::new(); } let mut file = File::open(temp_file).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); buffer },
identifier_body
editor.rs
use rand; use rand::Rng; use std::process::Command; use std::io::prelude::*; use std::fs::File; const TEMP_FILE_LENGTH: usize = 16; pub fn text_from_editor() -> String { let temp_file = temp_file(); let status = Command::new(editor()) .arg(temp_file.clone()) .status(); match status { Ok(status) => { if!status.success() { return String::new(); } let mut file = File::open(temp_file).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); buffer }, Err(_) => String::new() } } /// TODO Return proper editor from env / config fn
() -> String { return "vim".to_string(); } /// TODO Ensure real unique names fn temp_file() -> String { let result = String::from("/tmp/"); let file = rand::thread_rng() .gen_ascii_chars() .take(TEMP_FILE_LENGTH) .collect::<String>(); result + &file }
editor
identifier_name
editor.rs
use rand; use rand::Rng; use std::process::Command; use std::io::prelude::*; use std::fs::File; const TEMP_FILE_LENGTH: usize = 16; pub fn text_from_editor() -> String { let temp_file = temp_file(); let status = Command::new(editor()) .arg(temp_file.clone()) .status(); match status { Ok(status) => { if!status.success() { return String::new(); } let mut file = File::open(temp_file).unwrap(); let mut buffer = String::new(); file.read_to_string(&mut buffer).unwrap(); buffer }, Err(_) => String::new() } }
fn editor() -> String { return "vim".to_string(); } /// TODO Ensure real unique names fn temp_file() -> String { let result = String::from("/tmp/"); let file = rand::thread_rng() .gen_ascii_chars() .take(TEMP_FILE_LENGTH) .collect::<String>(); result + &file }
/// TODO Return proper editor from env / config
random_line_split
mod.rs
/// The spend tree stores the location of transactions in the block-tree /// /// It is tracks the tree of blocks and is used to verify whether a block can be inserted at a /// certain location in the tree /// /// A block consists of the chain of records: /// /// [start-of-block] <- [transaction] <- [spend-output] <- [spend-output] <- [transaction] <- [end-of-block]... /// /// One [spend-output] record is added per input of a transaction. /// /// Blocks are connected with the [start-of-block] record which points to the [end-of-block] of previous block. /// Often this is the previous records, but blocks can also be added in different order. /// The [start-of-block] then point to NULL until the previous block comes in. /// use itertools::Itertools; use buffer::*; use config; use rayon::prelude::*; use slog; use store; use store::{TxPtr,BlockHeaderPtr}; use store::flatfileset::FlatFileSet; use store::hash_index::{HashIndex,HashIndexGuard}; use store::spend_index::SpendIndex; use transaction::Transaction; pub mod record; pub use self::record::{Record,RecordPtr}; const MB: u64 = 1024 * 1024; const FILE_SIZE: u64 = 16 * 1024 * MB ; const MAX_CONTENT_SIZE: u64 = FILE_SIZE - 10 * MB ; const SUBPATH: &'static str = "spend-tree"; const PREFIX: &'static str = "st-"; // temporarily we use a vec instead of the dynamic growing flatfileset // this isn't a big problem because the OS will not allocate the trailing zeros const VEC_SIZE: usize = 800_000_000; #[derive(Debug, PartialEq)] pub enum SpendingError { OutputNotFound, OutputAlreadySpend, } /// A pointer into the spend-tree. /// This always points to a `start-of-block` record /// These objects are stored in the block-index, to lookup blocks #[derive(Debug, PartialEq, Clone, Copy)] pub struct BlockPtr { pub start: RecordPtr, pub length: u64, // A guard is used for wrongly ordered block-insertion. See [hash_index.rs] for details pub is_guard: bool }
impl BlockPtr { pub fn to_guard(self) -> BlockPtr { BlockPtr { start: self.start, length: self.length, is_guard: true } } pub fn to_non_guard(self) -> BlockPtr { BlockPtr { start: self.start, length: self.length, is_guard: false } } pub fn end(self ) -> RecordPtr { RecordPtr::new(self.start.to_index() + self.length -1) } } pub struct SpendTree { fileset: FlatFileSet<RecordPtr> } /// Stats are passed around on success for performance monitoring #[derive(Debug, Default)] pub struct SpendTreeStats { pub blocks: i64, pub inputs: i64, pub seeks: i64, pub total_move: i64, pub total_diff: i64, pub jumps: i64, } // Make stats additive impl ::std::ops::Add for SpendTreeStats { type Output = SpendTreeStats; fn add(self, other: SpendTreeStats) -> SpendTreeStats { SpendTreeStats { blocks: self.blocks + other.blocks, inputs: self.inputs + other.inputs, seeks: self.seeks + other.seeks, total_move: self.total_move + other.total_move, total_diff: self.total_diff+ other.total_diff, jumps: self.jumps + other.jumps, } } } /// This is the algorithm to check double-spends and the existence of outputs /// It will call the verify_spend function on Record in parallel for each output fn seek_and_set_inputs( records: &[Record], block: &mut [Record], block_idx: usize, spend_index: &SpendIndex, logger: &slog::Logger) -> Result<usize, SpendingError> { // we use the block minus the first and last record (which are just markers let len = block.len()-1; let results: Vec<Result<usize, SpendingError>> = block[1..len] .par_iter_mut() .enumerate() .map(|(i,rec)| { debug_assert!(rec.is_transaction() || rec.is_output()); rec.verify_spend(spend_index, block_idx+i+1, records, logger) }) .collect(); // Return the input_count, or an error if any results.into_iter().fold_results(Default::default(), |a,b| { a+b } ) } impl SpendTree { pub fn new(cfg: &config::Config) -> SpendTree { let dir = &cfg.root.clone().join(SUBPATH); SpendTree { fileset: FlatFileSet::new( dir, PREFIX, FILE_SIZE, MAX_CONTENT_SIZE) } } // Returns the full spend-tree as record-slice. pub fn get_all_records(&mut self) -> &[Record] { self.fileset.read_mut_slice(RecordPtr::new(0), VEC_SIZE) } // Returns the given block as a mutable slice pub fn get_block_mut(&mut self, block_ptr: BlockPtr) -> &mut [Record] { self.fileset.read_mut_slice(block_ptr.start, block_ptr.length as usize) } /// Retrieves a single record from the spend-tree pub fn get_record(&mut self, ptr: RecordPtr) -> Record { * self.fileset.read_fixed(ptr) } /// Stores a block in the spend_tree. The block will be initially orphan. /// /// The result is a BlockPtr that can be stored in the hash-index pub fn store_block(&mut self, block_header_ptr: BlockHeaderPtr, file_ptrs: Vec<Record>) -> BlockPtr { let count = file_ptrs.len(); let block: Vec<Record> = vec![ Record::new_orphan_block_start()] .into_iter() .chain(file_ptrs.into_iter()) .chain(vec![Record::new_block_end(block_header_ptr, count)]).into_iter() .collect(); let result_ptr = self.fileset.write_all(&block); BlockPtr { start: result_ptr, length: block.len() as u64, is_guard: false } } /// If an orphan block is stored in the spend-tree, some transaction-inputs might not be resolved /// to their outputs. These will still be unmatched_output records instead of output-pointers /// /// This looks up the corresponding outputs; needs to be called before connect_block pub fn revolve_orphan_pointers(&mut self, transactions: &mut store::Transactions, tx_index: &mut HashIndex<TxPtr>, block: BlockPtr) { let mut input_idx = 0; let mut last_tx_ptr: Option<TxPtr> = None; for record in self.get_block_mut(block) { if record.is_unmatched_input() { let bytes = transactions.read(last_tx_ptr.unwrap()); let mut buf = Buffer::new(&bytes); let tx = Transaction::parse(&mut buf).unwrap(); let input = &tx.txs_in[input_idx]; // find the matching output let tx_ptr: TxPtr = *tx_index .get(input.prev_tx_out) .iter() .find(|ptr|!ptr.is_guard()) .expect("Could not find input; this must have been resolved before connecting the block!"); let output_record = Record::new_output(tx_ptr, input.prev_tx_out_idx); *record = output_record; input_idx += 1; } else if record.is_transaction() { last_tx_ptr = Some(record.get_transaction_ptr()); input_idx = 0; } else if record.is_output() { input_idx += 1; } } } /// Verifies of each output in the block at target_start /// Then lays the connection between previous_end and target_start pub fn connect_block(&mut self, spend_index: &mut SpendIndex, logger: &slog::Logger, previous_block: BlockPtr, target_block: BlockPtr) -> Result<(), SpendingError> { let timer = ::std::time::Instant::now(); let block_idx = target_block.start.to_index(); let block: &mut [Record] = self.fileset.read_mut_slice(target_block.start, target_block.length as usize); let records: &[Record] = self.get_all_records(); // Make the link, block[0] = Record::new_block_start(previous_block); // Update the spend-index // TODO this should jump more blocks back; and register its parent-requirement. // This is important once we allow forks let s = previous_block.start.to_index() as usize; let l = previous_block.length as usize; let immutable_block: &[Record] = &records[s+1..s+l-1]; for rec in immutable_block.iter() { spend_index.set(rec.hash()); } // verify all inputs in the spend tree and spend-index let input_count = seek_and_set_inputs(records, block, block_idx as usize, spend_index, logger)?; let elapsed : isize = timer.elapsed().as_secs() as isize * 1000 + timer.elapsed().subsec_nanos() as isize / 1_000_000 as isize; info!(logger, "connected"; "records" => block.len(), "inputs" => input_count, "ms/input" => (elapsed+1) as f64 / input_count as f64, ); Ok(()) } } #[cfg(test)] mod tests { extern crate tempdir; use slog_term; use slog; use slog::DrainExt; use store::flatfileset::FlatFilePtr; use super::*; use store::spend_index::SpendIndex; use store::{BlockHeaderPtr, TxPtr}; /// Macro to create a block for the spend_tree tests /// blockheaders and txs are unqiue numbers (fileptrs but where they point to doesn't matter /// for the spend_tree). /// /// Construct a block as /// /// ``` /// (blk 1 => /* blocknr */ /// [tx 2], /* tx with no inputs */ /// [tx 3 => (2;0),(2;1)] /* tx with two inputs referencing tx 2 ouput 0 and 1 /// ) /// macro_rules! block { (blk $header:expr => $( [tx $tx:expr $( => $( ($tx_in:expr;$tx_in_idx:expr) ),* ),* ] ),* ) => ( ( BlockHeaderPtr::new(0,$header), vec![ $( Record::new_transaction(TxPtr::new(0,$tx)) $(, $( Record::new_output(TxPtr::new(0,$tx_in),$tx_in_idx) ),* ),* ),* ]) ) } impl SpendTree { // wrapper around store_block that accepts a tuple instead of two params // for easier testing with block! macros fn store(&mut self, tuple: (BlockHeaderPtr, Vec<Record>)) -> BlockPtr { self.store_block(tuple.0, tuple.1) } } #[test] fn test_spend_tree_connect() { let log = slog::Logger::root(slog_term::streamer().compact().build().fuse(), o!()); let mut st = SpendTree::new(& test_cfg!()); let mut si = SpendIndex::new(& test_cfg!()); let block1 = st.store(block!(blk 1 => [tx 2] )); let block2a = st.store(block!(blk 3 => [tx 4 => (2;0)] )); let block2b = st.store(block!(blk 5 => [tx 6 => (2;0)] )); // create a tree, both 2a and 2b attached to 1 st.connect_block(&mut si, &log, block1, block2a).unwrap(); st.connect_block(&mut si, &log, block1, block2b).unwrap(); // this one should only "fit" onto 2b let block3b = st.store(block!(blk 7 => [tx 8 => (6;1)], [tx 9 => (2;1)] )); assert_eq!( st.connect_block(&mut si, &log, block2a, block3b).unwrap_err(), SpendingError::OutputNotFound); let block3b = st.store(block!(blk 7 => [tx 8 => (6;1)], [tx 9 => (2;1)] )); st.connect_block(&mut si, &log, block2b, block3b).unwrap(); // now this should only fir on 2a and not on 3b as at 3b it is already spend let block4a = st.store(block!(blk 10 => [tx 11 => (2;1)], [tx 12 => (2;2)] )); assert_eq!( st.connect_block(&mut si, &log, block3b, block4a).unwrap_err(), SpendingError::OutputAlreadySpend); let block4a = st.store(block!(blk 10 => [tx 11 => (2;1)], [tx 12 => (2;2)] )); st.connect_block(&mut si, &log, block2b, block4a).unwrap(); } #[test] fn test_spend_tree1() { let log = slog::Logger::root(slog_term::streamer().compact().build().fuse(), o!()); let block1 = block!(blk 1 => [tx 2 => (2;1),(2;0)], [tx 3] ); let mut st = SpendTree::new(& test_cfg!() ); let mut si = SpendIndex::new(& test_cfg!()); let block_ptr = st.store_block(block1.0, block1.1); let block2 = block!(blk 4 => [tx 5 => (2;2),(2;3)], [tx 6 ] ); let block_ptr2 = st.store_block(block2.0, block2.1); println!("{:?}", block_ptr2.start); st.connect_block(&mut si, &log, block_ptr, block_ptr2).unwrap(); let recs = st.get_all_records(); assert!( recs[0].is_block_start() ); assert!( recs[1].is_transaction() ); assert_eq!(recs[1].get_file_offset(), 2); assert!( recs[2].is_output() ); assert!( recs[3].is_output() ); assert!( recs[4].is_transaction() ); assert!( recs[5].is_block_end() ); assert_eq!(recs[5].get_file_offset(), 1); assert!( recs[6].is_block_start() ); assert!( recs[7].is_transaction() ); assert!( recs[8].is_output() ); assert!( recs[9].is_output() ); assert!( recs[10].is_transaction() ); assert!( recs[11].is_block_end() ); } #[test] fn test_orphan_block() { // care must be taken that when a block is added to the spend-tree before one of its // predecessors, it may not be complete. // This because in the spend tree, the inputs are stored as the outputs they reference, // but these inputs may not have been available. // The resolve orphan block checks and fixes these "left-out" references. } }
impl HashIndexGuard for BlockPtr { fn is_guard(self) -> bool { self.is_guard } }
random_line_split
mod.rs
/// The spend tree stores the location of transactions in the block-tree /// /// It is tracks the tree of blocks and is used to verify whether a block can be inserted at a /// certain location in the tree /// /// A block consists of the chain of records: /// /// [start-of-block] <- [transaction] <- [spend-output] <- [spend-output] <- [transaction] <- [end-of-block]... /// /// One [spend-output] record is added per input of a transaction. /// /// Blocks are connected with the [start-of-block] record which points to the [end-of-block] of previous block. /// Often this is the previous records, but blocks can also be added in different order. /// The [start-of-block] then point to NULL until the previous block comes in. /// use itertools::Itertools; use buffer::*; use config; use rayon::prelude::*; use slog; use store; use store::{TxPtr,BlockHeaderPtr}; use store::flatfileset::FlatFileSet; use store::hash_index::{HashIndex,HashIndexGuard}; use store::spend_index::SpendIndex; use transaction::Transaction; pub mod record; pub use self::record::{Record,RecordPtr}; const MB: u64 = 1024 * 1024; const FILE_SIZE: u64 = 16 * 1024 * MB ; const MAX_CONTENT_SIZE: u64 = FILE_SIZE - 10 * MB ; const SUBPATH: &'static str = "spend-tree"; const PREFIX: &'static str = "st-"; // temporarily we use a vec instead of the dynamic growing flatfileset // this isn't a big problem because the OS will not allocate the trailing zeros const VEC_SIZE: usize = 800_000_000; #[derive(Debug, PartialEq)] pub enum SpendingError { OutputNotFound, OutputAlreadySpend, } /// A pointer into the spend-tree. /// This always points to a `start-of-block` record /// These objects are stored in the block-index, to lookup blocks #[derive(Debug, PartialEq, Clone, Copy)] pub struct BlockPtr { pub start: RecordPtr, pub length: u64, // A guard is used for wrongly ordered block-insertion. See [hash_index.rs] for details pub is_guard: bool } impl HashIndexGuard for BlockPtr { fn is_guard(self) -> bool { self.is_guard } } impl BlockPtr { pub fn to_guard(self) -> BlockPtr { BlockPtr { start: self.start, length: self.length, is_guard: true } } pub fn to_non_guard(self) -> BlockPtr { BlockPtr { start: self.start, length: self.length, is_guard: false } } pub fn end(self ) -> RecordPtr { RecordPtr::new(self.start.to_index() + self.length -1) } } pub struct SpendTree { fileset: FlatFileSet<RecordPtr> } /// Stats are passed around on success for performance monitoring #[derive(Debug, Default)] pub struct
{ pub blocks: i64, pub inputs: i64, pub seeks: i64, pub total_move: i64, pub total_diff: i64, pub jumps: i64, } // Make stats additive impl ::std::ops::Add for SpendTreeStats { type Output = SpendTreeStats; fn add(self, other: SpendTreeStats) -> SpendTreeStats { SpendTreeStats { blocks: self.blocks + other.blocks, inputs: self.inputs + other.inputs, seeks: self.seeks + other.seeks, total_move: self.total_move + other.total_move, total_diff: self.total_diff+ other.total_diff, jumps: self.jumps + other.jumps, } } } /// This is the algorithm to check double-spends and the existence of outputs /// It will call the verify_spend function on Record in parallel for each output fn seek_and_set_inputs( records: &[Record], block: &mut [Record], block_idx: usize, spend_index: &SpendIndex, logger: &slog::Logger) -> Result<usize, SpendingError> { // we use the block minus the first and last record (which are just markers let len = block.len()-1; let results: Vec<Result<usize, SpendingError>> = block[1..len] .par_iter_mut() .enumerate() .map(|(i,rec)| { debug_assert!(rec.is_transaction() || rec.is_output()); rec.verify_spend(spend_index, block_idx+i+1, records, logger) }) .collect(); // Return the input_count, or an error if any results.into_iter().fold_results(Default::default(), |a,b| { a+b } ) } impl SpendTree { pub fn new(cfg: &config::Config) -> SpendTree { let dir = &cfg.root.clone().join(SUBPATH); SpendTree { fileset: FlatFileSet::new( dir, PREFIX, FILE_SIZE, MAX_CONTENT_SIZE) } } // Returns the full spend-tree as record-slice. pub fn get_all_records(&mut self) -> &[Record] { self.fileset.read_mut_slice(RecordPtr::new(0), VEC_SIZE) } // Returns the given block as a mutable slice pub fn get_block_mut(&mut self, block_ptr: BlockPtr) -> &mut [Record] { self.fileset.read_mut_slice(block_ptr.start, block_ptr.length as usize) } /// Retrieves a single record from the spend-tree pub fn get_record(&mut self, ptr: RecordPtr) -> Record { * self.fileset.read_fixed(ptr) } /// Stores a block in the spend_tree. The block will be initially orphan. /// /// The result is a BlockPtr that can be stored in the hash-index pub fn store_block(&mut self, block_header_ptr: BlockHeaderPtr, file_ptrs: Vec<Record>) -> BlockPtr { let count = file_ptrs.len(); let block: Vec<Record> = vec![ Record::new_orphan_block_start()] .into_iter() .chain(file_ptrs.into_iter()) .chain(vec![Record::new_block_end(block_header_ptr, count)]).into_iter() .collect(); let result_ptr = self.fileset.write_all(&block); BlockPtr { start: result_ptr, length: block.len() as u64, is_guard: false } } /// If an orphan block is stored in the spend-tree, some transaction-inputs might not be resolved /// to their outputs. These will still be unmatched_output records instead of output-pointers /// /// This looks up the corresponding outputs; needs to be called before connect_block pub fn revolve_orphan_pointers(&mut self, transactions: &mut store::Transactions, tx_index: &mut HashIndex<TxPtr>, block: BlockPtr) { let mut input_idx = 0; let mut last_tx_ptr: Option<TxPtr> = None; for record in self.get_block_mut(block) { if record.is_unmatched_input() { let bytes = transactions.read(last_tx_ptr.unwrap()); let mut buf = Buffer::new(&bytes); let tx = Transaction::parse(&mut buf).unwrap(); let input = &tx.txs_in[input_idx]; // find the matching output let tx_ptr: TxPtr = *tx_index .get(input.prev_tx_out) .iter() .find(|ptr|!ptr.is_guard()) .expect("Could not find input; this must have been resolved before connecting the block!"); let output_record = Record::new_output(tx_ptr, input.prev_tx_out_idx); *record = output_record; input_idx += 1; } else if record.is_transaction() { last_tx_ptr = Some(record.get_transaction_ptr()); input_idx = 0; } else if record.is_output() { input_idx += 1; } } } /// Verifies of each output in the block at target_start /// Then lays the connection between previous_end and target_start pub fn connect_block(&mut self, spend_index: &mut SpendIndex, logger: &slog::Logger, previous_block: BlockPtr, target_block: BlockPtr) -> Result<(), SpendingError> { let timer = ::std::time::Instant::now(); let block_idx = target_block.start.to_index(); let block: &mut [Record] = self.fileset.read_mut_slice(target_block.start, target_block.length as usize); let records: &[Record] = self.get_all_records(); // Make the link, block[0] = Record::new_block_start(previous_block); // Update the spend-index // TODO this should jump more blocks back; and register its parent-requirement. // This is important once we allow forks let s = previous_block.start.to_index() as usize; let l = previous_block.length as usize; let immutable_block: &[Record] = &records[s+1..s+l-1]; for rec in immutable_block.iter() { spend_index.set(rec.hash()); } // verify all inputs in the spend tree and spend-index let input_count = seek_and_set_inputs(records, block, block_idx as usize, spend_index, logger)?; let elapsed : isize = timer.elapsed().as_secs() as isize * 1000 + timer.elapsed().subsec_nanos() as isize / 1_000_000 as isize; info!(logger, "connected"; "records" => block.len(), "inputs" => input_count, "ms/input" => (elapsed+1) as f64 / input_count as f64, ); Ok(()) } } #[cfg(test)] mod tests { extern crate tempdir; use slog_term; use slog; use slog::DrainExt; use store::flatfileset::FlatFilePtr; use super::*; use store::spend_index::SpendIndex; use store::{BlockHeaderPtr, TxPtr}; /// Macro to create a block for the spend_tree tests /// blockheaders and txs are unqiue numbers (fileptrs but where they point to doesn't matter /// for the spend_tree). /// /// Construct a block as /// /// ``` /// (blk 1 => /* blocknr */ /// [tx 2], /* tx with no inputs */ /// [tx 3 => (2;0),(2;1)] /* tx with two inputs referencing tx 2 ouput 0 and 1 /// ) /// macro_rules! block { (blk $header:expr => $( [tx $tx:expr $( => $( ($tx_in:expr;$tx_in_idx:expr) ),* ),* ] ),* ) => ( ( BlockHeaderPtr::new(0,$header), vec![ $( Record::new_transaction(TxPtr::new(0,$tx)) $(, $( Record::new_output(TxPtr::new(0,$tx_in),$tx_in_idx) ),* ),* ),* ]) ) } impl SpendTree { // wrapper around store_block that accepts a tuple instead of two params // for easier testing with block! macros fn store(&mut self, tuple: (BlockHeaderPtr, Vec<Record>)) -> BlockPtr { self.store_block(tuple.0, tuple.1) } } #[test] fn test_spend_tree_connect() { let log = slog::Logger::root(slog_term::streamer().compact().build().fuse(), o!()); let mut st = SpendTree::new(& test_cfg!()); let mut si = SpendIndex::new(& test_cfg!()); let block1 = st.store(block!(blk 1 => [tx 2] )); let block2a = st.store(block!(blk 3 => [tx 4 => (2;0)] )); let block2b = st.store(block!(blk 5 => [tx 6 => (2;0)] )); // create a tree, both 2a and 2b attached to 1 st.connect_block(&mut si, &log, block1, block2a).unwrap(); st.connect_block(&mut si, &log, block1, block2b).unwrap(); // this one should only "fit" onto 2b let block3b = st.store(block!(blk 7 => [tx 8 => (6;1)], [tx 9 => (2;1)] )); assert_eq!( st.connect_block(&mut si, &log, block2a, block3b).unwrap_err(), SpendingError::OutputNotFound); let block3b = st.store(block!(blk 7 => [tx 8 => (6;1)], [tx 9 => (2;1)] )); st.connect_block(&mut si, &log, block2b, block3b).unwrap(); // now this should only fir on 2a and not on 3b as at 3b it is already spend let block4a = st.store(block!(blk 10 => [tx 11 => (2;1)], [tx 12 => (2;2)] )); assert_eq!( st.connect_block(&mut si, &log, block3b, block4a).unwrap_err(), SpendingError::OutputAlreadySpend); let block4a = st.store(block!(blk 10 => [tx 11 => (2;1)], [tx 12 => (2;2)] )); st.connect_block(&mut si, &log, block2b, block4a).unwrap(); } #[test] fn test_spend_tree1() { let log = slog::Logger::root(slog_term::streamer().compact().build().fuse(), o!()); let block1 = block!(blk 1 => [tx 2 => (2;1),(2;0)], [tx 3] ); let mut st = SpendTree::new(& test_cfg!() ); let mut si = SpendIndex::new(& test_cfg!()); let block_ptr = st.store_block(block1.0, block1.1); let block2 = block!(blk 4 => [tx 5 => (2;2),(2;3)], [tx 6 ] ); let block_ptr2 = st.store_block(block2.0, block2.1); println!("{:?}", block_ptr2.start); st.connect_block(&mut si, &log, block_ptr, block_ptr2).unwrap(); let recs = st.get_all_records(); assert!( recs[0].is_block_start() ); assert!( recs[1].is_transaction() ); assert_eq!(recs[1].get_file_offset(), 2); assert!( recs[2].is_output() ); assert!( recs[3].is_output() ); assert!( recs[4].is_transaction() ); assert!( recs[5].is_block_end() ); assert_eq!(recs[5].get_file_offset(), 1); assert!( recs[6].is_block_start() ); assert!( recs[7].is_transaction() ); assert!( recs[8].is_output() ); assert!( recs[9].is_output() ); assert!( recs[10].is_transaction() ); assert!( recs[11].is_block_end() ); } #[test] fn test_orphan_block() { // care must be taken that when a block is added to the spend-tree before one of its // predecessors, it may not be complete. // This because in the spend tree, the inputs are stored as the outputs they reference, // but these inputs may not have been available. // The resolve orphan block checks and fixes these "left-out" references. } }
SpendTreeStats
identifier_name
mod.rs
/// The spend tree stores the location of transactions in the block-tree /// /// It is tracks the tree of blocks and is used to verify whether a block can be inserted at a /// certain location in the tree /// /// A block consists of the chain of records: /// /// [start-of-block] <- [transaction] <- [spend-output] <- [spend-output] <- [transaction] <- [end-of-block]... /// /// One [spend-output] record is added per input of a transaction. /// /// Blocks are connected with the [start-of-block] record which points to the [end-of-block] of previous block. /// Often this is the previous records, but blocks can also be added in different order. /// The [start-of-block] then point to NULL until the previous block comes in. /// use itertools::Itertools; use buffer::*; use config; use rayon::prelude::*; use slog; use store; use store::{TxPtr,BlockHeaderPtr}; use store::flatfileset::FlatFileSet; use store::hash_index::{HashIndex,HashIndexGuard}; use store::spend_index::SpendIndex; use transaction::Transaction; pub mod record; pub use self::record::{Record,RecordPtr}; const MB: u64 = 1024 * 1024; const FILE_SIZE: u64 = 16 * 1024 * MB ; const MAX_CONTENT_SIZE: u64 = FILE_SIZE - 10 * MB ; const SUBPATH: &'static str = "spend-tree"; const PREFIX: &'static str = "st-"; // temporarily we use a vec instead of the dynamic growing flatfileset // this isn't a big problem because the OS will not allocate the trailing zeros const VEC_SIZE: usize = 800_000_000; #[derive(Debug, PartialEq)] pub enum SpendingError { OutputNotFound, OutputAlreadySpend, } /// A pointer into the spend-tree. /// This always points to a `start-of-block` record /// These objects are stored in the block-index, to lookup blocks #[derive(Debug, PartialEq, Clone, Copy)] pub struct BlockPtr { pub start: RecordPtr, pub length: u64, // A guard is used for wrongly ordered block-insertion. See [hash_index.rs] for details pub is_guard: bool } impl HashIndexGuard for BlockPtr { fn is_guard(self) -> bool { self.is_guard } } impl BlockPtr { pub fn to_guard(self) -> BlockPtr { BlockPtr { start: self.start, length: self.length, is_guard: true } } pub fn to_non_guard(self) -> BlockPtr { BlockPtr { start: self.start, length: self.length, is_guard: false } } pub fn end(self ) -> RecordPtr { RecordPtr::new(self.start.to_index() + self.length -1) } } pub struct SpendTree { fileset: FlatFileSet<RecordPtr> } /// Stats are passed around on success for performance monitoring #[derive(Debug, Default)] pub struct SpendTreeStats { pub blocks: i64, pub inputs: i64, pub seeks: i64, pub total_move: i64, pub total_diff: i64, pub jumps: i64, } // Make stats additive impl ::std::ops::Add for SpendTreeStats { type Output = SpendTreeStats; fn add(self, other: SpendTreeStats) -> SpendTreeStats { SpendTreeStats { blocks: self.blocks + other.blocks, inputs: self.inputs + other.inputs, seeks: self.seeks + other.seeks, total_move: self.total_move + other.total_move, total_diff: self.total_diff+ other.total_diff, jumps: self.jumps + other.jumps, } } } /// This is the algorithm to check double-spends and the existence of outputs /// It will call the verify_spend function on Record in parallel for each output fn seek_and_set_inputs( records: &[Record], block: &mut [Record], block_idx: usize, spend_index: &SpendIndex, logger: &slog::Logger) -> Result<usize, SpendingError> { // we use the block minus the first and last record (which are just markers let len = block.len()-1; let results: Vec<Result<usize, SpendingError>> = block[1..len] .par_iter_mut() .enumerate() .map(|(i,rec)| { debug_assert!(rec.is_transaction() || rec.is_output()); rec.verify_spend(spend_index, block_idx+i+1, records, logger) }) .collect(); // Return the input_count, or an error if any results.into_iter().fold_results(Default::default(), |a,b| { a+b } ) } impl SpendTree { pub fn new(cfg: &config::Config) -> SpendTree { let dir = &cfg.root.clone().join(SUBPATH); SpendTree { fileset: FlatFileSet::new( dir, PREFIX, FILE_SIZE, MAX_CONTENT_SIZE) } } // Returns the full spend-tree as record-slice. pub fn get_all_records(&mut self) -> &[Record] { self.fileset.read_mut_slice(RecordPtr::new(0), VEC_SIZE) } // Returns the given block as a mutable slice pub fn get_block_mut(&mut self, block_ptr: BlockPtr) -> &mut [Record] { self.fileset.read_mut_slice(block_ptr.start, block_ptr.length as usize) } /// Retrieves a single record from the spend-tree pub fn get_record(&mut self, ptr: RecordPtr) -> Record { * self.fileset.read_fixed(ptr) } /// Stores a block in the spend_tree. The block will be initially orphan. /// /// The result is a BlockPtr that can be stored in the hash-index pub fn store_block(&mut self, block_header_ptr: BlockHeaderPtr, file_ptrs: Vec<Record>) -> BlockPtr { let count = file_ptrs.len(); let block: Vec<Record> = vec![ Record::new_orphan_block_start()] .into_iter() .chain(file_ptrs.into_iter()) .chain(vec![Record::new_block_end(block_header_ptr, count)]).into_iter() .collect(); let result_ptr = self.fileset.write_all(&block); BlockPtr { start: result_ptr, length: block.len() as u64, is_guard: false } } /// If an orphan block is stored in the spend-tree, some transaction-inputs might not be resolved /// to their outputs. These will still be unmatched_output records instead of output-pointers /// /// This looks up the corresponding outputs; needs to be called before connect_block pub fn revolve_orphan_pointers(&mut self, transactions: &mut store::Transactions, tx_index: &mut HashIndex<TxPtr>, block: BlockPtr) { let mut input_idx = 0; let mut last_tx_ptr: Option<TxPtr> = None; for record in self.get_block_mut(block) { if record.is_unmatched_input() { let bytes = transactions.read(last_tx_ptr.unwrap()); let mut buf = Buffer::new(&bytes); let tx = Transaction::parse(&mut buf).unwrap(); let input = &tx.txs_in[input_idx]; // find the matching output let tx_ptr: TxPtr = *tx_index .get(input.prev_tx_out) .iter() .find(|ptr|!ptr.is_guard()) .expect("Could not find input; this must have been resolved before connecting the block!"); let output_record = Record::new_output(tx_ptr, input.prev_tx_out_idx); *record = output_record; input_idx += 1; } else if record.is_transaction() { last_tx_ptr = Some(record.get_transaction_ptr()); input_idx = 0; } else if record.is_output() { input_idx += 1; } } } /// Verifies of each output in the block at target_start /// Then lays the connection between previous_end and target_start pub fn connect_block(&mut self, spend_index: &mut SpendIndex, logger: &slog::Logger, previous_block: BlockPtr, target_block: BlockPtr) -> Result<(), SpendingError> { let timer = ::std::time::Instant::now(); let block_idx = target_block.start.to_index(); let block: &mut [Record] = self.fileset.read_mut_slice(target_block.start, target_block.length as usize); let records: &[Record] = self.get_all_records(); // Make the link, block[0] = Record::new_block_start(previous_block); // Update the spend-index // TODO this should jump more blocks back; and register its parent-requirement. // This is important once we allow forks let s = previous_block.start.to_index() as usize; let l = previous_block.length as usize; let immutable_block: &[Record] = &records[s+1..s+l-1]; for rec in immutable_block.iter() { spend_index.set(rec.hash()); } // verify all inputs in the spend tree and spend-index let input_count = seek_and_set_inputs(records, block, block_idx as usize, spend_index, logger)?; let elapsed : isize = timer.elapsed().as_secs() as isize * 1000 + timer.elapsed().subsec_nanos() as isize / 1_000_000 as isize; info!(logger, "connected"; "records" => block.len(), "inputs" => input_count, "ms/input" => (elapsed+1) as f64 / input_count as f64, ); Ok(()) } } #[cfg(test)] mod tests { extern crate tempdir; use slog_term; use slog; use slog::DrainExt; use store::flatfileset::FlatFilePtr; use super::*; use store::spend_index::SpendIndex; use store::{BlockHeaderPtr, TxPtr}; /// Macro to create a block for the spend_tree tests /// blockheaders and txs are unqiue numbers (fileptrs but where they point to doesn't matter /// for the spend_tree). /// /// Construct a block as /// /// ``` /// (blk 1 => /* blocknr */ /// [tx 2], /* tx with no inputs */ /// [tx 3 => (2;0),(2;1)] /* tx with two inputs referencing tx 2 ouput 0 and 1 /// ) /// macro_rules! block { (blk $header:expr => $( [tx $tx:expr $( => $( ($tx_in:expr;$tx_in_idx:expr) ),* ),* ] ),* ) => ( ( BlockHeaderPtr::new(0,$header), vec![ $( Record::new_transaction(TxPtr::new(0,$tx)) $(, $( Record::new_output(TxPtr::new(0,$tx_in),$tx_in_idx) ),* ),* ),* ]) ) } impl SpendTree { // wrapper around store_block that accepts a tuple instead of two params // for easier testing with block! macros fn store(&mut self, tuple: (BlockHeaderPtr, Vec<Record>)) -> BlockPtr { self.store_block(tuple.0, tuple.1) } } #[test] fn test_spend_tree_connect() { let log = slog::Logger::root(slog_term::streamer().compact().build().fuse(), o!()); let mut st = SpendTree::new(& test_cfg!()); let mut si = SpendIndex::new(& test_cfg!()); let block1 = st.store(block!(blk 1 => [tx 2] )); let block2a = st.store(block!(blk 3 => [tx 4 => (2;0)] )); let block2b = st.store(block!(blk 5 => [tx 6 => (2;0)] )); // create a tree, both 2a and 2b attached to 1 st.connect_block(&mut si, &log, block1, block2a).unwrap(); st.connect_block(&mut si, &log, block1, block2b).unwrap(); // this one should only "fit" onto 2b let block3b = st.store(block!(blk 7 => [tx 8 => (6;1)], [tx 9 => (2;1)] )); assert_eq!( st.connect_block(&mut si, &log, block2a, block3b).unwrap_err(), SpendingError::OutputNotFound); let block3b = st.store(block!(blk 7 => [tx 8 => (6;1)], [tx 9 => (2;1)] )); st.connect_block(&mut si, &log, block2b, block3b).unwrap(); // now this should only fir on 2a and not on 3b as at 3b it is already spend let block4a = st.store(block!(blk 10 => [tx 11 => (2;1)], [tx 12 => (2;2)] )); assert_eq!( st.connect_block(&mut si, &log, block3b, block4a).unwrap_err(), SpendingError::OutputAlreadySpend); let block4a = st.store(block!(blk 10 => [tx 11 => (2;1)], [tx 12 => (2;2)] )); st.connect_block(&mut si, &log, block2b, block4a).unwrap(); } #[test] fn test_spend_tree1() { let log = slog::Logger::root(slog_term::streamer().compact().build().fuse(), o!()); let block1 = block!(blk 1 => [tx 2 => (2;1),(2;0)], [tx 3] ); let mut st = SpendTree::new(& test_cfg!() ); let mut si = SpendIndex::new(& test_cfg!()); let block_ptr = st.store_block(block1.0, block1.1); let block2 = block!(blk 4 => [tx 5 => (2;2),(2;3)], [tx 6 ] ); let block_ptr2 = st.store_block(block2.0, block2.1); println!("{:?}", block_ptr2.start); st.connect_block(&mut si, &log, block_ptr, block_ptr2).unwrap(); let recs = st.get_all_records(); assert!( recs[0].is_block_start() ); assert!( recs[1].is_transaction() ); assert_eq!(recs[1].get_file_offset(), 2); assert!( recs[2].is_output() ); assert!( recs[3].is_output() ); assert!( recs[4].is_transaction() ); assert!( recs[5].is_block_end() ); assert_eq!(recs[5].get_file_offset(), 1); assert!( recs[6].is_block_start() ); assert!( recs[7].is_transaction() ); assert!( recs[8].is_output() ); assert!( recs[9].is_output() ); assert!( recs[10].is_transaction() ); assert!( recs[11].is_block_end() ); } #[test] fn test_orphan_block()
}
{ // care must be taken that when a block is added to the spend-tree before one of its // predecessors, it may not be complete. // This because in the spend tree, the inputs are stored as the outputs they reference, // but these inputs may not have been available. // The resolve orphan block checks and fixes these "left-out" references. }
identifier_body
options.rs
//! This module contains the configuration of the application. //! //! All options are passed individually to each function and are not bundled //! together. //! //! # Examples //! //! ```no_run //! # use doh::Options; //! let options = Options::parse(); //! println!("Showing {}", options.remote_dir); //! ``` use clap::{AppSettings, Arg}; use reqwest::Url; /// Representation of the application's all configurable values. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Options { /// Remote directory to start on. pub remote_dir: Url, } impl Options { /// Parse `env`-wide command-line arguments into an `Options` instance pub fn
() -> Options { let matches = app_from_crate!("\n") .setting(AppSettings::ColoredHelp) .arg(Arg::from_usage("<URL> 'Remote directory to browse'").validator(Options::url_validator)) .get_matches(); let u = matches.value_of("URL").unwrap(); Options { remote_dir: Url::parse(u) .or_else(|_| Url::parse(&format!("http://{}", u))) .unwrap(), } } fn url_validator(s: String) -> Result<(), String> { Url::parse(&s) .or_else(|_| Url::parse(&format!("http://{}", s))) .map(|_| ()) .map_err(|e| e.to_string()) } }
parse
identifier_name
options.rs
//! This module contains the configuration of the application. //! //! All options are passed individually to each function and are not bundled //! together. //! //! # Examples //! //! ```no_run //! # use doh::Options; //! let options = Options::parse(); //! println!("Showing {}", options.remote_dir); //! ``` use clap::{AppSettings, Arg};
#[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Options { /// Remote directory to start on. pub remote_dir: Url, } impl Options { /// Parse `env`-wide command-line arguments into an `Options` instance pub fn parse() -> Options { let matches = app_from_crate!("\n") .setting(AppSettings::ColoredHelp) .arg(Arg::from_usage("<URL> 'Remote directory to browse'").validator(Options::url_validator)) .get_matches(); let u = matches.value_of("URL").unwrap(); Options { remote_dir: Url::parse(u) .or_else(|_| Url::parse(&format!("http://{}", u))) .unwrap(), } } fn url_validator(s: String) -> Result<(), String> { Url::parse(&s) .or_else(|_| Url::parse(&format!("http://{}", s))) .map(|_| ()) .map_err(|e| e.to_string()) } }
use reqwest::Url; /// Representation of the application's all configurable values.
random_line_split
options.rs
//! This module contains the configuration of the application. //! //! All options are passed individually to each function and are not bundled //! together. //! //! # Examples //! //! ```no_run //! # use doh::Options; //! let options = Options::parse(); //! println!("Showing {}", options.remote_dir); //! ``` use clap::{AppSettings, Arg}; use reqwest::Url; /// Representation of the application's all configurable values. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Options { /// Remote directory to start on. pub remote_dir: Url, } impl Options { /// Parse `env`-wide command-line arguments into an `Options` instance pub fn parse() -> Options { let matches = app_from_crate!("\n") .setting(AppSettings::ColoredHelp) .arg(Arg::from_usage("<URL> 'Remote directory to browse'").validator(Options::url_validator)) .get_matches(); let u = matches.value_of("URL").unwrap(); Options { remote_dir: Url::parse(u) .or_else(|_| Url::parse(&format!("http://{}", u))) .unwrap(), } } fn url_validator(s: String) -> Result<(), String>
}
{ Url::parse(&s) .or_else(|_| Url::parse(&format!("http://{}", s))) .map(|_| ()) .map_err(|e| e.to_string()) }
identifier_body
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::global::GlobalRef; use dom::domexception::{DOMException, DOMErrorName}; use util::mem::HeapSizeOf; use util::str::DOMString; use js::jsapi::{JSContext, JSObject, RootedValue}; use js::jsapi::{JS_IsExceptionPending, JS_SetPendingException, JS_ReportPendingException}; use js::jsapi::{JS_ReportErrorNumber1, JSErrorFormatString, JSExnType}; use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain}; use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; use libc; use std::ffi::CString; use std::ptr; use std::mem; /// DOM exceptions that can be thrown by a native DOM method. #[derive(Debug, Clone, HeapSizeOf)] pub enum Error { /// IndexSizeError DOMException IndexSize, /// NotFoundError DOMException NotFound, /// HierarchyRequestError DOMException HierarchyRequest, /// WrongDocumentError DOMException WrongDocument, /// InvalidCharacterError DOMException InvalidCharacter, /// NotSupportedError DOMException NotSupported, /// InUseAttributeError DOMException InUseAttribute, /// InvalidStateError DOMException InvalidState, /// SyntaxError DOMException Syntax, /// NamespaceError DOMException Namespace, /// InvalidAccessError DOMException InvalidAccess, /// SecurityError DOMException Security, /// NetworkError DOMException Network, /// AbortError DOMException Abort, /// TimeoutError DOMException Timeout, /// InvalidNodeTypeError DOMException InvalidNodeType, /// DataCloneError DOMException DataClone, /// NoModificationAllowedError DOMException NoModificationAllowed, /// QuotaExceededError DOMException QuotaExceeded, /// TypeMismatchError DOMException TypeMismatch, /// TypeError JavaScript Error Type(DOMString), /// RangeError JavaScript Error Range(DOMString), /// A JavaScript exception is already pending. JSFailed, } /// The return type for IDL operations that can throw DOM exceptions. pub type Fallible<T> = Result<T, Error>; /// The return type for IDL operations that can throw DOM exceptions and /// return `()`. pub type ErrorResult = Fallible<()>; /// Set a pending exception for the given `result` on `cx`. pub fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef, result: Error) { let code = match result { Error::IndexSize => DOMErrorName::IndexSizeError, Error::NotFound => DOMErrorName::NotFoundError, Error::HierarchyRequest => DOMErrorName::HierarchyRequestError, Error::WrongDocument => DOMErrorName::WrongDocumentError, Error::InvalidCharacter => DOMErrorName::InvalidCharacterError, Error::NotSupported => DOMErrorName::NotSupportedError, Error::InUseAttribute => DOMErrorName::InUseAttributeError, Error::InvalidState => DOMErrorName::InvalidStateError, Error::Syntax => DOMErrorName::SyntaxError, Error::Namespace => DOMErrorName::NamespaceError, Error::InvalidAccess => DOMErrorName::InvalidAccessError, Error::Security => DOMErrorName::SecurityError, Error::Network => DOMErrorName::NetworkError, Error::Abort => DOMErrorName::AbortError, Error::Timeout => DOMErrorName::TimeoutError, Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError, Error::DataClone => DOMErrorName::DataCloneError, Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError, Error::QuotaExceeded => DOMErrorName::QuotaExceededError, Error::TypeMismatch => DOMErrorName::TypeMismatchError, Error::Type(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_type_error(cx, &message); return; }, Error::Range(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_range_error(cx, &message); return; }, Error::JSFailed => { assert!(unsafe { JS_IsExceptionPending(cx) } == 1); return; } }; assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let exception = DOMException::new(global, code); let mut thrown = RootedValue::new(cx, UndefinedValue()); exception.to_jsval(cx, thrown.handle_mut()); unsafe { JS_SetPendingException(cx, thrown.handle()); } } /// Report a pending exception, thereby clearing it. pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) { unsafe { if JS_IsExceptionPending(cx)!= 0 { let saved = JS_SaveFrameChain(cx); { let _ac = JSAutoCompartment::new(cx, obj); JS_ReportPendingException(cx); } if saved!= 0 { JS_RestoreFrameChain(cx); } } } } /// Throw an exception to signal that a `JSVal` can not be converted to any of /// the types in an IDL union type. pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("argument could not be converted to any of: {}", names); throw_type_error(cx, &error); } /// Throw an exception to signal that a `JSObject` can not be converted to a /// given DOM type. pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) { debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("\"this\" object does not implement interface {}.", proto_id_to_name(proto_id)); throw_type_error(cx, &error); } /// Format string used to throw javascript errors. static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [ '{' as libc::c_char, '0' as libc::c_char, '}' as libc::c_char, 0 as libc::c_char, ]; /// Format string struct used to throw `TypeError`s. static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char, argCount: 1, exnType: JSExnType::JSEXN_TYPEERR as i16, }; /// Format string struct used to throw `RangeError`s. static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char, argCount: 1, exnType: JSExnType::JSEXN_RANGEERR as i16, }; /// Callback used to throw javascript errors. /// See throw_js_error for info about error_number. unsafe extern fn get_error_message(_user_ref: *mut libc::c_void, error_number: libc::c_uint) -> *const JSErrorFormatString { let num: JSExnType = mem::transmute(error_number); match num { JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString, JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString, _ => panic!("Bad js error number given to get_error_message: {}", error_number) } } /// Helper fn to throw a javascript error with the given message and number. /// Reuse the jsapi error codes to distinguish the error_number /// passed back to the get_error_message callback. /// c_uint is u32, so this cast is safe, as is casting to/from i32 from there. fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) { let error = CString::new(error).unwrap(); unsafe { JS_ReportErrorNumber1(cx, Some(get_error_message), ptr::null_mut(), error_number, error.as_ptr()); } } /// Throw a `TypeError` with the given message. pub fn
(cx: *mut JSContext, error: &str) { throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32); } /// Throw a `RangeError` with the given message. pub fn throw_range_error(cx: *mut JSContext, error: &str) { throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32); }
throw_type_error
identifier_name
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::global::GlobalRef; use dom::domexception::{DOMException, DOMErrorName}; use util::mem::HeapSizeOf; use util::str::DOMString; use js::jsapi::{JSContext, JSObject, RootedValue}; use js::jsapi::{JS_IsExceptionPending, JS_SetPendingException, JS_ReportPendingException}; use js::jsapi::{JS_ReportErrorNumber1, JSErrorFormatString, JSExnType}; use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain}; use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; use libc; use std::ffi::CString; use std::ptr; use std::mem; /// DOM exceptions that can be thrown by a native DOM method. #[derive(Debug, Clone, HeapSizeOf)] pub enum Error { /// IndexSizeError DOMException IndexSize, /// NotFoundError DOMException NotFound, /// HierarchyRequestError DOMException HierarchyRequest, /// WrongDocumentError DOMException WrongDocument, /// InvalidCharacterError DOMException InvalidCharacter, /// NotSupportedError DOMException NotSupported, /// InUseAttributeError DOMException InUseAttribute, /// InvalidStateError DOMException InvalidState, /// SyntaxError DOMException Syntax, /// NamespaceError DOMException Namespace, /// InvalidAccessError DOMException InvalidAccess, /// SecurityError DOMException Security, /// NetworkError DOMException Network, /// AbortError DOMException Abort, /// TimeoutError DOMException Timeout, /// InvalidNodeTypeError DOMException InvalidNodeType, /// DataCloneError DOMException DataClone, /// NoModificationAllowedError DOMException NoModificationAllowed, /// QuotaExceededError DOMException QuotaExceeded, /// TypeMismatchError DOMException TypeMismatch, /// TypeError JavaScript Error Type(DOMString), /// RangeError JavaScript Error Range(DOMString), /// A JavaScript exception is already pending. JSFailed, } /// The return type for IDL operations that can throw DOM exceptions. pub type Fallible<T> = Result<T, Error>; /// The return type for IDL operations that can throw DOM exceptions and /// return `()`. pub type ErrorResult = Fallible<()>; /// Set a pending exception for the given `result` on `cx`. pub fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef, result: Error) { let code = match result { Error::IndexSize => DOMErrorName::IndexSizeError, Error::NotFound => DOMErrorName::NotFoundError, Error::HierarchyRequest => DOMErrorName::HierarchyRequestError, Error::WrongDocument => DOMErrorName::WrongDocumentError, Error::InvalidCharacter => DOMErrorName::InvalidCharacterError, Error::NotSupported => DOMErrorName::NotSupportedError, Error::InUseAttribute => DOMErrorName::InUseAttributeError, Error::InvalidState => DOMErrorName::InvalidStateError, Error::Syntax => DOMErrorName::SyntaxError, Error::Namespace => DOMErrorName::NamespaceError, Error::InvalidAccess => DOMErrorName::InvalidAccessError, Error::Security => DOMErrorName::SecurityError, Error::Network => DOMErrorName::NetworkError, Error::Abort => DOMErrorName::AbortError, Error::Timeout => DOMErrorName::TimeoutError, Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError, Error::DataClone => DOMErrorName::DataCloneError, Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError, Error::QuotaExceeded => DOMErrorName::QuotaExceededError, Error::TypeMismatch => DOMErrorName::TypeMismatchError, Error::Type(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_type_error(cx, &message); return; }, Error::Range(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_range_error(cx, &message); return; }, Error::JSFailed => { assert!(unsafe { JS_IsExceptionPending(cx) } == 1); return; } }; assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let exception = DOMException::new(global, code); let mut thrown = RootedValue::new(cx, UndefinedValue()); exception.to_jsval(cx, thrown.handle_mut()); unsafe { JS_SetPendingException(cx, thrown.handle()); } } /// Report a pending exception, thereby clearing it. pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) { unsafe { if JS_IsExceptionPending(cx)!= 0 { let saved = JS_SaveFrameChain(cx); { let _ac = JSAutoCompartment::new(cx, obj); JS_ReportPendingException(cx); } if saved!= 0 { JS_RestoreFrameChain(cx); } } } } /// Throw an exception to signal that a `JSVal` can not be converted to any of /// the types in an IDL union type. pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) { assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
} /// Throw an exception to signal that a `JSObject` can not be converted to a /// given DOM type. pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) { debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("\"this\" object does not implement interface {}.", proto_id_to_name(proto_id)); throw_type_error(cx, &error); } /// Format string used to throw javascript errors. static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [ '{' as libc::c_char, '0' as libc::c_char, '}' as libc::c_char, 0 as libc::c_char, ]; /// Format string struct used to throw `TypeError`s. static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char, argCount: 1, exnType: JSExnType::JSEXN_TYPEERR as i16, }; /// Format string struct used to throw `RangeError`s. static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char, argCount: 1, exnType: JSExnType::JSEXN_RANGEERR as i16, }; /// Callback used to throw javascript errors. /// See throw_js_error for info about error_number. unsafe extern fn get_error_message(_user_ref: *mut libc::c_void, error_number: libc::c_uint) -> *const JSErrorFormatString { let num: JSExnType = mem::transmute(error_number); match num { JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString, JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString, _ => panic!("Bad js error number given to get_error_message: {}", error_number) } } /// Helper fn to throw a javascript error with the given message and number. /// Reuse the jsapi error codes to distinguish the error_number /// passed back to the get_error_message callback. /// c_uint is u32, so this cast is safe, as is casting to/from i32 from there. fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) { let error = CString::new(error).unwrap(); unsafe { JS_ReportErrorNumber1(cx, Some(get_error_message), ptr::null_mut(), error_number, error.as_ptr()); } } /// Throw a `TypeError` with the given message. pub fn throw_type_error(cx: *mut JSContext, error: &str) { throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32); } /// Throw a `RangeError` with the given message. pub fn throw_range_error(cx: *mut JSContext, error: &str) { throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32); }
let error = format!("argument could not be converted to any of: {}", names); throw_type_error(cx, &error);
random_line_split
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::global::GlobalRef; use dom::domexception::{DOMException, DOMErrorName}; use util::mem::HeapSizeOf; use util::str::DOMString; use js::jsapi::{JSContext, JSObject, RootedValue}; use js::jsapi::{JS_IsExceptionPending, JS_SetPendingException, JS_ReportPendingException}; use js::jsapi::{JS_ReportErrorNumber1, JSErrorFormatString, JSExnType}; use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain}; use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; use libc; use std::ffi::CString; use std::ptr; use std::mem; /// DOM exceptions that can be thrown by a native DOM method. #[derive(Debug, Clone, HeapSizeOf)] pub enum Error { /// IndexSizeError DOMException IndexSize, /// NotFoundError DOMException NotFound, /// HierarchyRequestError DOMException HierarchyRequest, /// WrongDocumentError DOMException WrongDocument, /// InvalidCharacterError DOMException InvalidCharacter, /// NotSupportedError DOMException NotSupported, /// InUseAttributeError DOMException InUseAttribute, /// InvalidStateError DOMException InvalidState, /// SyntaxError DOMException Syntax, /// NamespaceError DOMException Namespace, /// InvalidAccessError DOMException InvalidAccess, /// SecurityError DOMException Security, /// NetworkError DOMException Network, /// AbortError DOMException Abort, /// TimeoutError DOMException Timeout, /// InvalidNodeTypeError DOMException InvalidNodeType, /// DataCloneError DOMException DataClone, /// NoModificationAllowedError DOMException NoModificationAllowed, /// QuotaExceededError DOMException QuotaExceeded, /// TypeMismatchError DOMException TypeMismatch, /// TypeError JavaScript Error Type(DOMString), /// RangeError JavaScript Error Range(DOMString), /// A JavaScript exception is already pending. JSFailed, } /// The return type for IDL operations that can throw DOM exceptions. pub type Fallible<T> = Result<T, Error>; /// The return type for IDL operations that can throw DOM exceptions and /// return `()`. pub type ErrorResult = Fallible<()>; /// Set a pending exception for the given `result` on `cx`. pub fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef, result: Error) { let code = match result { Error::IndexSize => DOMErrorName::IndexSizeError, Error::NotFound => DOMErrorName::NotFoundError, Error::HierarchyRequest => DOMErrorName::HierarchyRequestError, Error::WrongDocument => DOMErrorName::WrongDocumentError, Error::InvalidCharacter => DOMErrorName::InvalidCharacterError, Error::NotSupported => DOMErrorName::NotSupportedError, Error::InUseAttribute => DOMErrorName::InUseAttributeError, Error::InvalidState => DOMErrorName::InvalidStateError, Error::Syntax => DOMErrorName::SyntaxError, Error::Namespace => DOMErrorName::NamespaceError, Error::InvalidAccess => DOMErrorName::InvalidAccessError, Error::Security => DOMErrorName::SecurityError, Error::Network => DOMErrorName::NetworkError, Error::Abort => DOMErrorName::AbortError, Error::Timeout => DOMErrorName::TimeoutError, Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError, Error::DataClone => DOMErrorName::DataCloneError, Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError, Error::QuotaExceeded => DOMErrorName::QuotaExceededError, Error::TypeMismatch => DOMErrorName::TypeMismatchError, Error::Type(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_type_error(cx, &message); return; }, Error::Range(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_range_error(cx, &message); return; }, Error::JSFailed => { assert!(unsafe { JS_IsExceptionPending(cx) } == 1); return; } }; assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let exception = DOMException::new(global, code); let mut thrown = RootedValue::new(cx, UndefinedValue()); exception.to_jsval(cx, thrown.handle_mut()); unsafe { JS_SetPendingException(cx, thrown.handle()); } } /// Report a pending exception, thereby clearing it. pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) { unsafe { if JS_IsExceptionPending(cx)!= 0 { let saved = JS_SaveFrameChain(cx); { let _ac = JSAutoCompartment::new(cx, obj); JS_ReportPendingException(cx); } if saved!= 0 { JS_RestoreFrameChain(cx); } } } } /// Throw an exception to signal that a `JSVal` can not be converted to any of /// the types in an IDL union type. pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("argument could not be converted to any of: {}", names); throw_type_error(cx, &error); } /// Throw an exception to signal that a `JSObject` can not be converted to a /// given DOM type. pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16)
/// Format string used to throw javascript errors. static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [ '{' as libc::c_char, '0' as libc::c_char, '}' as libc::c_char, 0 as libc::c_char, ]; /// Format string struct used to throw `TypeError`s. static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char, argCount: 1, exnType: JSExnType::JSEXN_TYPEERR as i16, }; /// Format string struct used to throw `RangeError`s. static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char, argCount: 1, exnType: JSExnType::JSEXN_RANGEERR as i16, }; /// Callback used to throw javascript errors. /// See throw_js_error for info about error_number. unsafe extern fn get_error_message(_user_ref: *mut libc::c_void, error_number: libc::c_uint) -> *const JSErrorFormatString { let num: JSExnType = mem::transmute(error_number); match num { JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString, JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString, _ => panic!("Bad js error number given to get_error_message: {}", error_number) } } /// Helper fn to throw a javascript error with the given message and number. /// Reuse the jsapi error codes to distinguish the error_number /// passed back to the get_error_message callback. /// c_uint is u32, so this cast is safe, as is casting to/from i32 from there. fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) { let error = CString::new(error).unwrap(); unsafe { JS_ReportErrorNumber1(cx, Some(get_error_message), ptr::null_mut(), error_number, error.as_ptr()); } } /// Throw a `TypeError` with the given message. pub fn throw_type_error(cx: *mut JSContext, error: &str) { throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32); } /// Throw a `RangeError` with the given message. pub fn throw_range_error(cx: *mut JSContext, error: &str) { throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32); }
{ debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("\"this\" object does not implement interface {}.", proto_id_to_name(proto_id)); throw_type_error(cx, &error); }
identifier_body
bigint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! benchmarking for rlp //! should be started with: //! ```bash //! multirust run nightly cargo bench //! ``` #![feature(test)] #![feature(asm)] extern crate test; extern crate ethcore_util; extern crate rand; use test::{Bencher, black_box}; use ethcore_util::numbers::*; #[bench] fn u256_add(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_add(U256::from(new)).0 }) }); } #[bench] fn u256_sub(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_sub(U256::from(new)).0 }) }); } #[bench] fn u512_sub(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold( U512([ rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>() ]), |old, new| { let p = new % 2; old.overflowing_sub(U512([p, p, p, p, p, p, p, new])).0 } ) }); } #[bench] fn u512_add(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U512([0, 0, 0, 0, 0, 0, 0, 0]), |old, new| { old.overflowing_add(U512([new, new, new, new, new, new, new, new])).0 }) }); } #[bench] fn u256_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_mul(U256::from(new)).0 }) }); } #[bench] fn u256_full_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, _new| { let U512(ref u512words) = old.full_mul(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()])); U256([u512words[0], u512words[2], u512words[2], u512words[3]]) }) }); } #[bench] fn u128_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U128([12345u64, 0u64]), |old, new| { old.overflowing_mul(U128::from(new)).0 }) }); }
// Parity 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.
random_line_split
bigint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! benchmarking for rlp //! should be started with: //! ```bash //! multirust run nightly cargo bench //! ``` #![feature(test)] #![feature(asm)] extern crate test; extern crate ethcore_util; extern crate rand; use test::{Bencher, black_box}; use ethcore_util::numbers::*; #[bench] fn u256_add(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_add(U256::from(new)).0 }) }); } #[bench] fn u256_sub(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_sub(U256::from(new)).0 }) }); } #[bench] fn u512_sub(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold( U512([ rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>() ]), |old, new| { let p = new % 2; old.overflowing_sub(U512([p, p, p, p, p, p, p, new])).0 } ) }); } #[bench] fn u512_add(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U512([0, 0, 0, 0, 0, 0, 0, 0]), |old, new| { old.overflowing_add(U512([new, new, new, new, new, new, new, new])).0 }) }); } #[bench] fn u256_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_mul(U256::from(new)).0 }) }); } #[bench] fn u256_full_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, _new| { let U512(ref u512words) = old.full_mul(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()])); U256([u512words[0], u512words[2], u512words[2], u512words[3]]) }) }); } #[bench] fn
(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U128([12345u64, 0u64]), |old, new| { old.overflowing_mul(U128::from(new)).0 }) }); }
u128_mul
identifier_name
bigint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! benchmarking for rlp //! should be started with: //! ```bash //! multirust run nightly cargo bench //! ``` #![feature(test)] #![feature(asm)] extern crate test; extern crate ethcore_util; extern crate rand; use test::{Bencher, black_box}; use ethcore_util::numbers::*; #[bench] fn u256_add(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_add(U256::from(new)).0 }) }); } #[bench] fn u256_sub(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_sub(U256::from(new)).0 }) }); } #[bench] fn u512_sub(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold( U512([ rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>() ]), |old, new| { let p = new % 2; old.overflowing_sub(U512([p, p, p, p, p, p, p, new])).0 } ) }); } #[bench] fn u512_add(b: &mut Bencher)
#[bench] fn u256_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_mul(U256::from(new)).0 }) }); } #[bench] fn u256_full_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, _new| { let U512(ref u512words) = old.full_mul(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()])); U256([u512words[0], u512words[2], u512words[2], u512words[3]]) }) }); } #[bench] fn u128_mul(b: &mut Bencher) { b.iter(|| { let n = black_box(10000); (0..n).fold(U128([12345u64, 0u64]), |old, new| { old.overflowing_mul(U128::from(new)).0 }) }); }
{ b.iter(|| { let n = black_box(10000); (0..n).fold(U512([0, 0, 0, 0, 0, 0, 0, 0]), |old, new| { old.overflowing_add(U512([new, new, new, new, new, new, new, new])).0 }) }); }
identifier_body
basket.rs
use rocket_contrib::Template; use rocket::State; use model::{AuthUser, Basket}; use context::Context; use db::Db; #[get("/<username>/<basket>", rank = 10)] pub fn index( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, ) -> Option<Template> { handler(username, basket, auth_user, db, None) } #[get("/<username>/<basket>/<facade>", rank = 10)] pub fn facade( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, facade: &str, ) -> Option<Template> { handler(username, basket, auth_user, db, Some(facade)) } fn handler( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, facade: Option<&str>, ) -> Option<Template> { Basket::load(basket, username, auth_user.as_ref(), &db) .map(|basket| { // TODO: load facade let active_facade = facade.unwrap_or("settings"); let context = Context { auth_user, content: Some(json!({ "owner": basket.owner(), "name": basket.name(), "description": basket.description(), "basket_url": basket.url(), "facade_bar": facade_bar(&basket, active_facade, &db), })), .. Context::default() }; let template = "basket/settings"; Template::render(template, &context) }) } fn facade_bar(basket: &Basket, active_facade: &str, _db: &Db) -> String
name, ).unwrap(); } s }
{ use std::fmt::Write; let mut s = String::new(); let facades = [ ("foo", "Foo", ""), ("bar", "Bar", ""), ("baz", "Baz", ""), ("settings", "Settings", "float-right"), ]; for &(id, name, classes) in &facades { write!( s, r#"<li class="{} {}" ><a href="{}/{}">{}</a></li>"#, if active_facade == id { "active" } else { "" }, classes, basket.url(), id,
identifier_body
basket.rs
use rocket_contrib::Template; use rocket::State; use model::{AuthUser, Basket}; use context::Context; use db::Db; #[get("/<username>/<basket>", rank = 10)] pub fn index( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, ) -> Option<Template> { handler(username, basket, auth_user, db, None) } #[get("/<username>/<basket>/<facade>", rank = 10)] pub fn facade( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, facade: &str, ) -> Option<Template> { handler(username, basket, auth_user, db, Some(facade)) } fn
( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, facade: Option<&str>, ) -> Option<Template> { Basket::load(basket, username, auth_user.as_ref(), &db) .map(|basket| { // TODO: load facade let active_facade = facade.unwrap_or("settings"); let context = Context { auth_user, content: Some(json!({ "owner": basket.owner(), "name": basket.name(), "description": basket.description(), "basket_url": basket.url(), "facade_bar": facade_bar(&basket, active_facade, &db), })), .. Context::default() }; let template = "basket/settings"; Template::render(template, &context) }) } fn facade_bar(basket: &Basket, active_facade: &str, _db: &Db) -> String { use std::fmt::Write; let mut s = String::new(); let facades = [ ("foo", "Foo", ""), ("bar", "Bar", ""), ("baz", "Baz", ""), ("settings", "Settings", "float-right"), ]; for &(id, name, classes) in &facades { write!( s, r#"<li class="{} {}" ><a href="{}/{}">{}</a></li>"#, if active_facade == id { "active" } else { "" }, classes, basket.url(), id, name, ).unwrap(); } s }
handler
identifier_name
basket.rs
use rocket_contrib::Template; use rocket::State; use model::{AuthUser, Basket}; use context::Context;
use db::Db; #[get("/<username>/<basket>", rank = 10)] pub fn index( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, ) -> Option<Template> { handler(username, basket, auth_user, db, None) } #[get("/<username>/<basket>/<facade>", rank = 10)] pub fn facade( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, facade: &str, ) -> Option<Template> { handler(username, basket, auth_user, db, Some(facade)) } fn handler( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, facade: Option<&str>, ) -> Option<Template> { Basket::load(basket, username, auth_user.as_ref(), &db) .map(|basket| { // TODO: load facade let active_facade = facade.unwrap_or("settings"); let context = Context { auth_user, content: Some(json!({ "owner": basket.owner(), "name": basket.name(), "description": basket.description(), "basket_url": basket.url(), "facade_bar": facade_bar(&basket, active_facade, &db), })), .. Context::default() }; let template = "basket/settings"; Template::render(template, &context) }) } fn facade_bar(basket: &Basket, active_facade: &str, _db: &Db) -> String { use std::fmt::Write; let mut s = String::new(); let facades = [ ("foo", "Foo", ""), ("bar", "Bar", ""), ("baz", "Baz", ""), ("settings", "Settings", "float-right"), ]; for &(id, name, classes) in &facades { write!( s, r#"<li class="{} {}" ><a href="{}/{}">{}</a></li>"#, if active_facade == id { "active" } else { "" }, classes, basket.url(), id, name, ).unwrap(); } s }
random_line_split
clock.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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::time::{Instant, SystemTime}; #[no_mangle] pub extern "C" fn proxy_abi_version_0_2_0() {} #[no_mangle] pub extern "C" fn proxy_on_memory_allocate(_: usize) -> *mut u8 { std::ptr::null_mut() } #[no_mangle] pub extern "C" fn run() { println!("monotonic: {:?}", Instant::now()); println!("realtime: {:?}", SystemTime::now());
}
random_line_split
clock.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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::time::{Instant, SystemTime}; #[no_mangle] pub extern "C" fn
() {} #[no_mangle] pub extern "C" fn proxy_on_memory_allocate(_: usize) -> *mut u8 { std::ptr::null_mut() } #[no_mangle] pub extern "C" fn run() { println!("monotonic: {:?}", Instant::now()); println!("realtime: {:?}", SystemTime::now()); }
proxy_abi_version_0_2_0
identifier_name
clock.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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::time::{Instant, SystemTime}; #[no_mangle] pub extern "C" fn proxy_abi_version_0_2_0() {} #[no_mangle] pub extern "C" fn proxy_on_memory_allocate(_: usize) -> *mut u8 { std::ptr::null_mut() } #[no_mangle] pub extern "C" fn run()
{ println!("monotonic: {:?}", Instant::now()); println!("realtime: {:?}", SystemTime::now()); }
identifier_body
crate_map.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 libc::{c_void, c_char}; use ptr; use ptr::RawPtr; use vec; use hashmap::HashSet; use container::MutableSet; // Need to tell the linker on OS X to not barf on undefined symbols // and instead look them up at runtime, which we need to resolve // the crate_map properly. #[cfg(target_os = "macos")] #[link_args = "-undefined dynamic_lookup"] extern {} #[cfg(not(windows))] extern { #[weak_linkage] #[link_name = "_rust_crate_map_toplevel"] static CRATE_MAP: CrateMap; } pub struct ModEntry { name: *c_char, log_level: *mut u32 } struct CrateMapV0 { entries: *ModEntry, children: [*CrateMap,..1] } struct CrateMap { version: i32, annihilate_fn: *c_void, entries: *ModEntry, /// a dynamically sized struct, where all pointers to children are listed adjacent /// to the struct, terminated with NULL children: [*CrateMap,..1] } #[cfg(not(windows))] pub fn get_crate_map() -> *CrateMap { &'static CRATE_MAP as *CrateMap } #[cfg(windows)] #[fixed_stack_segment] #[inline(never)] pub fn get_crate_map() -> *CrateMap { use c_str::ToCStr; use unstable::dynamic_lib::dl; let sym = unsafe { let module = dl::open_internal(); let sym = do "__rust_crate_map_toplevel".with_c_str |buf| { dl::symbol(module, buf) }; dl::close(module); sym }; sym as *CrateMap } unsafe fn version(crate_map: *CrateMap) -> i32 { match (*crate_map).version { 1 => return 1, _ => return 0 } } /// Returns a pointer to the annihilate function of the CrateMap pub unsafe fn annihilate_fn(crate_map: *CrateMap) -> *c_void { match version(crate_map) { 0 => return ptr::null(), 1 => return (*crate_map).annihilate_fn, _ => fail!("Unknown crate map version!") } } unsafe fn entries(crate_map: *CrateMap) -> *ModEntry { match version(crate_map) { 0 => { let v0 = crate_map as (*CrateMapV0); return (*v0).entries; } 1 => return (*crate_map).entries, _ => fail!("Unknown crate map version!") } } unsafe fn iterator(crate_map: *CrateMap) -> **CrateMap { match version(crate_map) { 0 => { let v0 = crate_map as (*CrateMapV0); return vec::raw::to_ptr((*v0).children); } 1 => return vec::raw::to_ptr((*crate_map).children), _ => fail!("Unknown crate map version!") } } unsafe fn iter_module_map(mod_entries: *ModEntry, f: &fn(*mut ModEntry)) { let mut curr = mod_entries; while!(*curr).name.is_null() { f(curr as *mut ModEntry); curr = curr.offset(1); } } unsafe fn do_iter_crate_map(crate_map: *CrateMap, f: &fn(*mut ModEntry), visited: &mut HashSet<*CrateMap>) { if visited.insert(crate_map) { iter_module_map(entries(crate_map), |x| f(x)); let child_crates = iterator(crate_map); do ptr::array_each(child_crates) |child| { do_iter_crate_map(child, |x| f(x), visited); } } } /// Iterates recursively over `crate_map` and all child crate maps pub unsafe fn iter_crate_map(crate_map: *CrateMap, f: &fn(*mut ModEntry)) { // XXX: use random numbers as keys from the OS-level RNG when there is a nice // way to do this let mut v: HashSet<*CrateMap> = HashSet::with_capacity_and_keys(0, 0, 32); do_iter_crate_map(crate_map, f, &mut v); } #[test] fn iter_crate_map_duplicates() { use c_str::ToCStr; use cast::transmute; struct CrateMapT3 { version: i32, annihilate_fn: *c_void, entries: *ModEntry, children: [*CrateMap,..3] } unsafe { let mod_name1 = "c::m1".to_c_str(); let mut level3: u32 = 3; let entries: ~[ModEntry] = ~[ ModEntry { name: mod_name1.with_ref(|buf| buf), log_level: &mut level3}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]; let child_crate = CrateMap { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr(entries), children: [ptr::null()] }; let root_crate = CrateMapT3 { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ModEntry { name: ptr::null(), log_level: ptr::mut_null()}]), children: [&child_crate as *CrateMap, &child_crate as *CrateMap, ptr::null()] }; let mut cnt = 0; do iter_crate_map(transmute(&root_crate)) |entry| { assert!(*(*entry).log_level == 3); cnt += 1; } assert!(cnt == 1); } } #[test] fn iter_crate_map_follow_children() { use c_str::ToCStr; use cast::transmute; struct CrateMapT2 { version: i32, annihilate_fn: *c_void, entries: *ModEntry, children: [*CrateMap,..2] } unsafe { let mod_name1 = "c::m1".to_c_str(); let mod_name2 = "c::m2".to_c_str(); let mut level2: u32 = 2; let mut level3: u32 = 3; let child_crate2 = CrateMap { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ ModEntry { name: mod_name1.with_ref(|buf| buf), log_level: &mut level2}, ModEntry { name: mod_name2.with_ref(|buf| buf), log_level: &mut level3}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]), children: [ptr::null()] }; let child_crate1 = CrateMapT2 { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ ModEntry { name: "t::f1".to_c_str().with_ref(|buf| buf), log_level: &mut 1}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]), children: [&child_crate2 as *CrateMap, ptr::null()] };
let root_crate = CrateMapT2 { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ ModEntry { name: "t::f1".to_c_str().with_ref(|buf| buf), log_level: &mut 0}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]), children: [child_crate1_ptr, ptr::null()] }; let mut cnt = 0; do iter_crate_map(transmute(&root_crate)) |entry| { assert!(*(*entry).log_level == cnt); cnt += 1; } assert!(cnt == 4); } }
let child_crate1_ptr: *CrateMap = transmute(&child_crate1);
random_line_split
crate_map.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 libc::{c_void, c_char}; use ptr; use ptr::RawPtr; use vec; use hashmap::HashSet; use container::MutableSet; // Need to tell the linker on OS X to not barf on undefined symbols // and instead look them up at runtime, which we need to resolve // the crate_map properly. #[cfg(target_os = "macos")] #[link_args = "-undefined dynamic_lookup"] extern {} #[cfg(not(windows))] extern { #[weak_linkage] #[link_name = "_rust_crate_map_toplevel"] static CRATE_MAP: CrateMap; } pub struct ModEntry { name: *c_char, log_level: *mut u32 } struct CrateMapV0 { entries: *ModEntry, children: [*CrateMap,..1] } struct CrateMap { version: i32, annihilate_fn: *c_void, entries: *ModEntry, /// a dynamically sized struct, where all pointers to children are listed adjacent /// to the struct, terminated with NULL children: [*CrateMap,..1] } #[cfg(not(windows))] pub fn get_crate_map() -> *CrateMap { &'static CRATE_MAP as *CrateMap } #[cfg(windows)] #[fixed_stack_segment] #[inline(never)] pub fn get_crate_map() -> *CrateMap { use c_str::ToCStr; use unstable::dynamic_lib::dl; let sym = unsafe { let module = dl::open_internal(); let sym = do "__rust_crate_map_toplevel".with_c_str |buf| { dl::symbol(module, buf) }; dl::close(module); sym }; sym as *CrateMap } unsafe fn version(crate_map: *CrateMap) -> i32 { match (*crate_map).version { 1 => return 1, _ => return 0 } } /// Returns a pointer to the annihilate function of the CrateMap pub unsafe fn annihilate_fn(crate_map: *CrateMap) -> *c_void { match version(crate_map) { 0 => return ptr::null(), 1 => return (*crate_map).annihilate_fn, _ => fail!("Unknown crate map version!") } } unsafe fn
(crate_map: *CrateMap) -> *ModEntry { match version(crate_map) { 0 => { let v0 = crate_map as (*CrateMapV0); return (*v0).entries; } 1 => return (*crate_map).entries, _ => fail!("Unknown crate map version!") } } unsafe fn iterator(crate_map: *CrateMap) -> **CrateMap { match version(crate_map) { 0 => { let v0 = crate_map as (*CrateMapV0); return vec::raw::to_ptr((*v0).children); } 1 => return vec::raw::to_ptr((*crate_map).children), _ => fail!("Unknown crate map version!") } } unsafe fn iter_module_map(mod_entries: *ModEntry, f: &fn(*mut ModEntry)) { let mut curr = mod_entries; while!(*curr).name.is_null() { f(curr as *mut ModEntry); curr = curr.offset(1); } } unsafe fn do_iter_crate_map(crate_map: *CrateMap, f: &fn(*mut ModEntry), visited: &mut HashSet<*CrateMap>) { if visited.insert(crate_map) { iter_module_map(entries(crate_map), |x| f(x)); let child_crates = iterator(crate_map); do ptr::array_each(child_crates) |child| { do_iter_crate_map(child, |x| f(x), visited); } } } /// Iterates recursively over `crate_map` and all child crate maps pub unsafe fn iter_crate_map(crate_map: *CrateMap, f: &fn(*mut ModEntry)) { // XXX: use random numbers as keys from the OS-level RNG when there is a nice // way to do this let mut v: HashSet<*CrateMap> = HashSet::with_capacity_and_keys(0, 0, 32); do_iter_crate_map(crate_map, f, &mut v); } #[test] fn iter_crate_map_duplicates() { use c_str::ToCStr; use cast::transmute; struct CrateMapT3 { version: i32, annihilate_fn: *c_void, entries: *ModEntry, children: [*CrateMap,..3] } unsafe { let mod_name1 = "c::m1".to_c_str(); let mut level3: u32 = 3; let entries: ~[ModEntry] = ~[ ModEntry { name: mod_name1.with_ref(|buf| buf), log_level: &mut level3}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]; let child_crate = CrateMap { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr(entries), children: [ptr::null()] }; let root_crate = CrateMapT3 { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ModEntry { name: ptr::null(), log_level: ptr::mut_null()}]), children: [&child_crate as *CrateMap, &child_crate as *CrateMap, ptr::null()] }; let mut cnt = 0; do iter_crate_map(transmute(&root_crate)) |entry| { assert!(*(*entry).log_level == 3); cnt += 1; } assert!(cnt == 1); } } #[test] fn iter_crate_map_follow_children() { use c_str::ToCStr; use cast::transmute; struct CrateMapT2 { version: i32, annihilate_fn: *c_void, entries: *ModEntry, children: [*CrateMap,..2] } unsafe { let mod_name1 = "c::m1".to_c_str(); let mod_name2 = "c::m2".to_c_str(); let mut level2: u32 = 2; let mut level3: u32 = 3; let child_crate2 = CrateMap { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ ModEntry { name: mod_name1.with_ref(|buf| buf), log_level: &mut level2}, ModEntry { name: mod_name2.with_ref(|buf| buf), log_level: &mut level3}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]), children: [ptr::null()] }; let child_crate1 = CrateMapT2 { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ ModEntry { name: "t::f1".to_c_str().with_ref(|buf| buf), log_level: &mut 1}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]), children: [&child_crate2 as *CrateMap, ptr::null()] }; let child_crate1_ptr: *CrateMap = transmute(&child_crate1); let root_crate = CrateMapT2 { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ ModEntry { name: "t::f1".to_c_str().with_ref(|buf| buf), log_level: &mut 0}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]), children: [child_crate1_ptr, ptr::null()] }; let mut cnt = 0; do iter_crate_map(transmute(&root_crate)) |entry| { assert!(*(*entry).log_level == cnt); cnt += 1; } assert!(cnt == 4); } }
entries
identifier_name
simdint.rs
// Copyright 2015 blake2-rfc Developers //
// http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![allow(dead_code)] #[cfg(feature = "simd")] extern "platform-intrinsic" { pub fn simd_add<T>(x: T, y: T) -> T; pub fn simd_shl<T>(x: T, y: T) -> T; pub fn simd_shr<T>(x: T, y: T) -> T; pub fn simd_xor<T>(x: T, y: T) -> T; pub fn simd_shuffle2<T, U>(v: T, w: T, idx: [u32; 2]) -> U; pub fn simd_shuffle4<T, U>(v: T, w: T, idx: [u32; 4]) -> U; pub fn simd_shuffle8<T, U>(v: T, w: T, idx: [u32; 8]) -> U; pub fn simd_shuffle16<T, U>(v: T, w: T, idx: [u32; 16]) -> U; pub fn simd_shuffle32<T, U>(v: T, w: T, idx: [u32; 32]) -> U; }
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
random_line_split
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test #7340 fails on 32-bit linux use std::ptr; enum a_tag<A,B> { varA(A), varB(B) } struct t_rec<A,B> { chA: u8, tA: a_tag<A,B>,
tB: a_tag<A,B> } fn mk_rec<A,B>(a: A, b: B) -> t_rec<A,B> { return t_rec{ chA:0u8, tA:varA(a), chB:1u8, tB:varB(b) }; } fn is_aligned<A>(amnt: uint, u: &A) -> bool { let p = ptr::to_unsafe_ptr(u) as uint; return (p & (amnt-1u)) == 0u; } fn variant_data_is_aligned<A,B>(amnt: uint, u: &a_tag<A,B>) -> bool { match u { &varA(ref a) => is_aligned(amnt, a), &varB(ref b) => is_aligned(amnt, b) } } pub fn main() { let x = mk_rec(22u64, 23u64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); let x = mk_rec(22u64, 23u32); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(4u, &x.tB)); let x = mk_rec(22u32, 23u64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(4u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); let x = mk_rec(22u32, 23u32); assert!(is_aligned(4u, &x.tA)); assert!(variant_data_is_aligned(4u, &x.tA)); assert!(is_aligned(4u, &x.tB)); assert!(variant_data_is_aligned(4u, &x.tB)); let x = mk_rec(22f64, 23f64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); }
chB: u8,
random_line_split
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test #7340 fails on 32-bit linux use std::ptr; enum
<A,B> { varA(A), varB(B) } struct t_rec<A,B> { chA: u8, tA: a_tag<A,B>, chB: u8, tB: a_tag<A,B> } fn mk_rec<A,B>(a: A, b: B) -> t_rec<A,B> { return t_rec{ chA:0u8, tA:varA(a), chB:1u8, tB:varB(b) }; } fn is_aligned<A>(amnt: uint, u: &A) -> bool { let p = ptr::to_unsafe_ptr(u) as uint; return (p & (amnt-1u)) == 0u; } fn variant_data_is_aligned<A,B>(amnt: uint, u: &a_tag<A,B>) -> bool { match u { &varA(ref a) => is_aligned(amnt, a), &varB(ref b) => is_aligned(amnt, b) } } pub fn main() { let x = mk_rec(22u64, 23u64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); let x = mk_rec(22u64, 23u32); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(4u, &x.tB)); let x = mk_rec(22u32, 23u64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(4u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); let x = mk_rec(22u32, 23u32); assert!(is_aligned(4u, &x.tA)); assert!(variant_data_is_aligned(4u, &x.tA)); assert!(is_aligned(4u, &x.tB)); assert!(variant_data_is_aligned(4u, &x.tB)); let x = mk_rec(22f64, 23f64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); }
a_tag
identifier_name
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test #7340 fails on 32-bit linux use std::ptr; enum a_tag<A,B> { varA(A), varB(B) } struct t_rec<A,B> { chA: u8, tA: a_tag<A,B>, chB: u8, tB: a_tag<A,B> } fn mk_rec<A,B>(a: A, b: B) -> t_rec<A,B> { return t_rec{ chA:0u8, tA:varA(a), chB:1u8, tB:varB(b) }; } fn is_aligned<A>(amnt: uint, u: &A) -> bool { let p = ptr::to_unsafe_ptr(u) as uint; return (p & (amnt-1u)) == 0u; } fn variant_data_is_aligned<A,B>(amnt: uint, u: &a_tag<A,B>) -> bool
pub fn main() { let x = mk_rec(22u64, 23u64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); let x = mk_rec(22u64, 23u32); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(4u, &x.tB)); let x = mk_rec(22u32, 23u64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(4u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); let x = mk_rec(22u32, 23u32); assert!(is_aligned(4u, &x.tA)); assert!(variant_data_is_aligned(4u, &x.tA)); assert!(is_aligned(4u, &x.tB)); assert!(variant_data_is_aligned(4u, &x.tB)); let x = mk_rec(22f64, 23f64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); }
{ match u { &varA(ref a) => is_aligned(amnt, a), &varB(ref b) => is_aligned(amnt, b) } }
identifier_body
memory.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. #[cfg(not(feature = "std"))] use alloc::prelude::*; use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Shared}; use crate::mem::{BaseAddr, Mmio}; // Spec: COMMODORE 64 MEMORY MAPS p. 263 // Design: // Inspired by UAE memory address64k/bank concepts. // We define Addressable trait to represent a bank of memory and use memory configuration // based on zones that can be mapped to different banks. CPU uses IoPort @ 0x0001 to reconfigure // memory layout. pub struct Memory { mmu: Shared<dyn Mmu>, expansion_port: Shared<dyn AddressableFaded>, io: Mmio, ram: Shared<Ram>, basic: Shared<Rom>, charset: Shared<Rom>, kernal: Shared<Rom>, } impl Memory { pub fn new( mmu: Shared<dyn Mmu>, expansion_port: Shared<dyn AddressableFaded>, io: Mmio, ram: Shared<Ram>, rom_basic: Shared<Rom>, rom_charset: Shared<Rom>, rom_kernal: Shared<Rom>, ) -> Self { Memory { mmu, expansion_port, io, ram, basic: rom_basic, charset: rom_charset, kernal: rom_kernal, } } } impl Addressable for Memory { fn read(&self, address: u16) -> u8 { let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow().read(address), Bank::Basic => self.basic.borrow().read(address), Bank::Charset => self .charset .borrow() .read(address - BaseAddr::Charset.addr()), Bank::Kernal => self.kernal.borrow().read(address), Bank::RomL => self .expansion_port .borrow_mut() .read(address) .unwrap_or(self.ram.borrow().read(address)), Bank::RomH => self .expansion_port .borrow_mut() .read(address) .unwrap_or(self.ram.borrow().read(address)), Bank::Io => self.io.read(address), Bank::Disabled => 0, } } fn write(&mut self, address: u16, value: u8)
} #[cfg(test)] mod tests { /* FIXME nostd: enable test use super::*; use zinc64_core::{new_shared, Addressable, Ram, Rom}; impl Addressable for Ram { fn read(&self, address: u16) -> u8 { self.read(address) } fn write(&mut self, address: u16, value: u8) { self.write(address, value); } } fn setup_memory() -> Memory { let basic = new_shared(Rom::new(0x1000, BaseAddr::Basic.addr(), 0x10)); let charset = new_shared(Rom::new(0x1000, 0x0000, 0x11)); let kernal = new_shared(Rom::new(0x1000, BaseAddr::Kernal.addr(), 0x12)); let mut mmio = Box::new(Ram::new(0x10000)); mmio.fill(0x22); let expansion_port = new_shared(Ram::new(0x1000)); expansion_port.borrow_mut().fill(0x33); let ram = new_shared(Ram::new(0x10000)); ram.borrow_mut().fill(0x44); Memory::new(expansion_port, mmio, ram, basic, charset, kernal) } #[test] fn read_basic() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x10, mem.read(BaseAddr::Basic.addr())); } #[test] fn read_charset() { let mut mem = setup_memory(); mem.switch_banks(27); assert_eq!(0x11, mem.read(BaseAddr::Charset.addr())); } #[test] fn read_io() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x22, mem.read(0xd000)); } #[test] fn read_kernal() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x12, mem.read(BaseAddr::Kernal.addr())); } #[test] fn write_page_0() { let mut mem = setup_memory(); mem.write(0x00f0, 0xff); assert_eq!(0xff, mem.ram.borrow().read(0x00f0)); } #[test] fn write_page_1() { let mut mem = setup_memory(); mem.write(0x0100, 0xff); assert_eq!(0xff, mem.ram.borrow().read(0x0100)); } */ }
{ let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow_mut().write(address, value), Bank::Basic => self.ram.borrow_mut().write(address, value), Bank::Charset => self.ram.borrow_mut().write(address, value), Bank::Kernal => self.ram.borrow_mut().write(address, value), Bank::RomL => self.ram.borrow_mut().write(address, value), Bank::RomH => self.ram.borrow_mut().write(address, value), Bank::Io => self.io.write(address, value), Bank::Disabled => {} } }
identifier_body
memory.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. #[cfg(not(feature = "std"))] use alloc::prelude::*; use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Shared}; use crate::mem::{BaseAddr, Mmio}; // Spec: COMMODORE 64 MEMORY MAPS p. 263 // Design: // Inspired by UAE memory address64k/bank concepts. // We define Addressable trait to represent a bank of memory and use memory configuration // based on zones that can be mapped to different banks. CPU uses IoPort @ 0x0001 to reconfigure // memory layout. pub struct Memory { mmu: Shared<dyn Mmu>, expansion_port: Shared<dyn AddressableFaded>, io: Mmio, ram: Shared<Ram>, basic: Shared<Rom>, charset: Shared<Rom>, kernal: Shared<Rom>, } impl Memory { pub fn new( mmu: Shared<dyn Mmu>, expansion_port: Shared<dyn AddressableFaded>, io: Mmio, ram: Shared<Ram>, rom_basic: Shared<Rom>, rom_charset: Shared<Rom>, rom_kernal: Shared<Rom>, ) -> Self { Memory { mmu, expansion_port, io, ram, basic: rom_basic, charset: rom_charset, kernal: rom_kernal, } } } impl Addressable for Memory { fn
(&self, address: u16) -> u8 { let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow().read(address), Bank::Basic => self.basic.borrow().read(address), Bank::Charset => self .charset .borrow() .read(address - BaseAddr::Charset.addr()), Bank::Kernal => self.kernal.borrow().read(address), Bank::RomL => self .expansion_port .borrow_mut() .read(address) .unwrap_or(self.ram.borrow().read(address)), Bank::RomH => self .expansion_port .borrow_mut() .read(address) .unwrap_or(self.ram.borrow().read(address)), Bank::Io => self.io.read(address), Bank::Disabled => 0, } } fn write(&mut self, address: u16, value: u8) { let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow_mut().write(address, value), Bank::Basic => self.ram.borrow_mut().write(address, value), Bank::Charset => self.ram.borrow_mut().write(address, value), Bank::Kernal => self.ram.borrow_mut().write(address, value), Bank::RomL => self.ram.borrow_mut().write(address, value), Bank::RomH => self.ram.borrow_mut().write(address, value), Bank::Io => self.io.write(address, value), Bank::Disabled => {} } } } #[cfg(test)] mod tests { /* FIXME nostd: enable test use super::*; use zinc64_core::{new_shared, Addressable, Ram, Rom}; impl Addressable for Ram { fn read(&self, address: u16) -> u8 { self.read(address) } fn write(&mut self, address: u16, value: u8) { self.write(address, value); } } fn setup_memory() -> Memory { let basic = new_shared(Rom::new(0x1000, BaseAddr::Basic.addr(), 0x10)); let charset = new_shared(Rom::new(0x1000, 0x0000, 0x11)); let kernal = new_shared(Rom::new(0x1000, BaseAddr::Kernal.addr(), 0x12)); let mut mmio = Box::new(Ram::new(0x10000)); mmio.fill(0x22); let expansion_port = new_shared(Ram::new(0x1000)); expansion_port.borrow_mut().fill(0x33); let ram = new_shared(Ram::new(0x10000)); ram.borrow_mut().fill(0x44); Memory::new(expansion_port, mmio, ram, basic, charset, kernal) } #[test] fn read_basic() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x10, mem.read(BaseAddr::Basic.addr())); } #[test] fn read_charset() { let mut mem = setup_memory(); mem.switch_banks(27); assert_eq!(0x11, mem.read(BaseAddr::Charset.addr())); } #[test] fn read_io() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x22, mem.read(0xd000)); } #[test] fn read_kernal() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x12, mem.read(BaseAddr::Kernal.addr())); } #[test] fn write_page_0() { let mut mem = setup_memory(); mem.write(0x00f0, 0xff); assert_eq!(0xff, mem.ram.borrow().read(0x00f0)); } #[test] fn write_page_1() { let mut mem = setup_memory(); mem.write(0x0100, 0xff); assert_eq!(0xff, mem.ram.borrow().read(0x0100)); } */ }
read
identifier_name
memory.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. #[cfg(not(feature = "std"))] use alloc::prelude::*; use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Shared}; use crate::mem::{BaseAddr, Mmio}; // Spec: COMMODORE 64 MEMORY MAPS p. 263 // Design: // Inspired by UAE memory address64k/bank concepts. // We define Addressable trait to represent a bank of memory and use memory configuration // based on zones that can be mapped to different banks. CPU uses IoPort @ 0x0001 to reconfigure // memory layout. pub struct Memory { mmu: Shared<dyn Mmu>, expansion_port: Shared<dyn AddressableFaded>, io: Mmio, ram: Shared<Ram>, basic: Shared<Rom>, charset: Shared<Rom>, kernal: Shared<Rom>, } impl Memory { pub fn new( mmu: Shared<dyn Mmu>, expansion_port: Shared<dyn AddressableFaded>, io: Mmio, ram: Shared<Ram>, rom_basic: Shared<Rom>, rom_charset: Shared<Rom>, rom_kernal: Shared<Rom>, ) -> Self { Memory { mmu, expansion_port, io, ram, basic: rom_basic, charset: rom_charset, kernal: rom_kernal, } } } impl Addressable for Memory { fn read(&self, address: u16) -> u8 { let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow().read(address), Bank::Basic => self.basic.borrow().read(address), Bank::Charset => self .charset .borrow() .read(address - BaseAddr::Charset.addr()), Bank::Kernal => self.kernal.borrow().read(address), Bank::RomL => self .expansion_port .borrow_mut() .read(address) .unwrap_or(self.ram.borrow().read(address)), Bank::RomH => self .expansion_port .borrow_mut() .read(address) .unwrap_or(self.ram.borrow().read(address)), Bank::Io => self.io.read(address), Bank::Disabled => 0, } } fn write(&mut self, address: u16, value: u8) { let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow_mut().write(address, value), Bank::Basic => self.ram.borrow_mut().write(address, value), Bank::Charset => self.ram.borrow_mut().write(address, value), Bank::Kernal => self.ram.borrow_mut().write(address, value), Bank::RomL => self.ram.borrow_mut().write(address, value), Bank::RomH => self.ram.borrow_mut().write(address, value), Bank::Io => self.io.write(address, value), Bank::Disabled => {} } } } #[cfg(test)] mod tests { /* FIXME nostd: enable test use super::*; use zinc64_core::{new_shared, Addressable, Ram, Rom};
} fn write(&mut self, address: u16, value: u8) { self.write(address, value); } } fn setup_memory() -> Memory { let basic = new_shared(Rom::new(0x1000, BaseAddr::Basic.addr(), 0x10)); let charset = new_shared(Rom::new(0x1000, 0x0000, 0x11)); let kernal = new_shared(Rom::new(0x1000, BaseAddr::Kernal.addr(), 0x12)); let mut mmio = Box::new(Ram::new(0x10000)); mmio.fill(0x22); let expansion_port = new_shared(Ram::new(0x1000)); expansion_port.borrow_mut().fill(0x33); let ram = new_shared(Ram::new(0x10000)); ram.borrow_mut().fill(0x44); Memory::new(expansion_port, mmio, ram, basic, charset, kernal) } #[test] fn read_basic() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x10, mem.read(BaseAddr::Basic.addr())); } #[test] fn read_charset() { let mut mem = setup_memory(); mem.switch_banks(27); assert_eq!(0x11, mem.read(BaseAddr::Charset.addr())); } #[test] fn read_io() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x22, mem.read(0xd000)); } #[test] fn read_kernal() { let mut mem = setup_memory(); mem.switch_banks(31); assert_eq!(0x12, mem.read(BaseAddr::Kernal.addr())); } #[test] fn write_page_0() { let mut mem = setup_memory(); mem.write(0x00f0, 0xff); assert_eq!(0xff, mem.ram.borrow().read(0x00f0)); } #[test] fn write_page_1() { let mut mem = setup_memory(); mem.write(0x0100, 0xff); assert_eq!(0xff, mem.ram.borrow().read(0x0100)); } */ }
impl Addressable for Ram { fn read(&self, address: u16) -> u8 { self.read(address)
random_line_split
arithmetic.rs
#[macro_use] extern crate nom; use nom::{IResult,digit, multispace}; use std::str; use std::str::FromStr; named!(parens<i64>, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), expr, delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor<i64>, alt!( map_res!( map_res!( delimited!(opt!(multispace), digit, opt!(multispace)), str::from_utf8 ), FromStr::from_str ) | parens ) ); named!(term <i64>, chain!( mut acc: factor ~ many0!( alt!( tap!(mul: preceded!(tag!("*"), factor) => acc = acc * mul) | tap!(div: preceded!(tag!("/"), factor) => acc = acc / div) ) ), || { return acc } ) ); named!(expr <i64>, chain!( mut acc: term ~ many0!( alt!( tap!(add: preceded!(tag!("+"), term) => acc = acc + add) | tap!(sub: preceded!(tag!("-"), term) => acc = acc - sub) ) ), || { return acc } ) ); #[test] fn factor_test() { assert_eq!(factor(&b"3"[..]), IResult::Done(&b""[..], 3)); assert_eq!(factor(&b" 12"[..]), IResult::Done(&b""[..], 12)); assert_eq!(factor(&b"537 "[..]), IResult::Done(&b""[..], 537)); assert_eq!(factor(&b" 24 "[..]), IResult::Done(&b""[..], 24)); } #[test] fn term_test() { assert_eq!(term(&b" 12 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 2* 3 *2 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 48 / 3/2"[..]), IResult::Done(&b""[..], 8)); } #[test] fn
() { assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&b""[..], 3)); assert_eq!(expr(&b" 12 + 6 - 4+ 3"[..]), IResult::Done(&b""[..], 17)); assert_eq!(expr(&b" 1 + 2*3 + 4"[..]), IResult::Done(&b""[..], 11)); } #[test] fn parens_test() { assert_eq!(expr(&b" ( 2 )"[..]), IResult::Done(&b""[..], 2)); assert_eq!(expr(&b" 2* ( 3 + 4 ) "[..]), IResult::Done(&b""[..], 14)); assert_eq!(expr(&b" 2*2 / ( 5 - 1) + 3"[..]), IResult::Done(&b""[..], 4)); }
expr_test
identifier_name
arithmetic.rs
#[macro_use] extern crate nom; use nom::{IResult,digit, multispace}; use std::str; use std::str::FromStr; named!(parens<i64>, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), expr, delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor<i64>, alt!( map_res!( map_res!( delimited!(opt!(multispace), digit, opt!(multispace)), str::from_utf8 ), FromStr::from_str ) | parens ) ); named!(term <i64>, chain!( mut acc: factor ~ many0!( alt!( tap!(mul: preceded!(tag!("*"), factor) => acc = acc * mul) | tap!(div: preceded!(tag!("/"), factor) => acc = acc / div) ) ), || { return acc } ) ); named!(expr <i64>, chain!( mut acc: term ~ many0!( alt!( tap!(add: preceded!(tag!("+"), term) => acc = acc + add) | tap!(sub: preceded!(tag!("-"), term) => acc = acc - sub) ) ), || { return acc } ) ); #[test] fn factor_test()
#[test] fn term_test() { assert_eq!(term(&b" 12 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 2* 3 *2 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 48 / 3/2"[..]), IResult::Done(&b""[..], 8)); } #[test] fn expr_test() { assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&b""[..], 3)); assert_eq!(expr(&b" 12 + 6 - 4+ 3"[..]), IResult::Done(&b""[..], 17)); assert_eq!(expr(&b" 1 + 2*3 + 4"[..]), IResult::Done(&b""[..], 11)); } #[test] fn parens_test() { assert_eq!(expr(&b" ( 2 )"[..]), IResult::Done(&b""[..], 2)); assert_eq!(expr(&b" 2* ( 3 + 4 ) "[..]), IResult::Done(&b""[..], 14)); assert_eq!(expr(&b" 2*2 / ( 5 - 1) + 3"[..]), IResult::Done(&b""[..], 4)); }
{ assert_eq!(factor(&b"3"[..]), IResult::Done(&b""[..], 3)); assert_eq!(factor(&b" 12"[..]), IResult::Done(&b""[..], 12)); assert_eq!(factor(&b"537 "[..]), IResult::Done(&b""[..], 537)); assert_eq!(factor(&b" 24 "[..]), IResult::Done(&b""[..], 24)); }
identifier_body
arithmetic.rs
#[macro_use] extern crate nom; use nom::{IResult,digit, multispace}; use std::str; use std::str::FromStr; named!(parens<i64>, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), expr, delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor<i64>, alt!( map_res!( map_res!( delimited!(opt!(multispace), digit, opt!(multispace)), str::from_utf8 ), FromStr::from_str
) | parens ) ); named!(term <i64>, chain!( mut acc: factor ~ many0!( alt!( tap!(mul: preceded!(tag!("*"), factor) => acc = acc * mul) | tap!(div: preceded!(tag!("/"), factor) => acc = acc / div) ) ), || { return acc } ) ); named!(expr <i64>, chain!( mut acc: term ~ many0!( alt!( tap!(add: preceded!(tag!("+"), term) => acc = acc + add) | tap!(sub: preceded!(tag!("-"), term) => acc = acc - sub) ) ), || { return acc } ) ); #[test] fn factor_test() { assert_eq!(factor(&b"3"[..]), IResult::Done(&b""[..], 3)); assert_eq!(factor(&b" 12"[..]), IResult::Done(&b""[..], 12)); assert_eq!(factor(&b"537 "[..]), IResult::Done(&b""[..], 537)); assert_eq!(factor(&b" 24 "[..]), IResult::Done(&b""[..], 24)); } #[test] fn term_test() { assert_eq!(term(&b" 12 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 2* 3 *2 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 48 / 3/2"[..]), IResult::Done(&b""[..], 8)); } #[test] fn expr_test() { assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&b""[..], 3)); assert_eq!(expr(&b" 12 + 6 - 4+ 3"[..]), IResult::Done(&b""[..], 17)); assert_eq!(expr(&b" 1 + 2*3 + 4"[..]), IResult::Done(&b""[..], 11)); } #[test] fn parens_test() { assert_eq!(expr(&b" ( 2 )"[..]), IResult::Done(&b""[..], 2)); assert_eq!(expr(&b" 2* ( 3 + 4 ) "[..]), IResult::Done(&b""[..], 14)); assert_eq!(expr(&b" 2*2 / ( 5 - 1) + 3"[..]), IResult::Done(&b""[..], 4)); }
random_line_split
inner-attrs-on-impl.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.
#[cfg(cfg_that_surely_doesnt_exist)]; fn method(&self) -> bool { false } } impl Foo { #[cfg(not(cfg_that_surely_doesnt_exist))]; // check that we don't eat attributes too eagerly. #[cfg(cfg_that_surely_doesnt_exist)] fn method(&self) -> bool { false } fn method(&self) -> bool { true } } pub fn main() { assert!(Foo.method()); }
struct Foo; impl Foo {
random_line_split
inner-attrs-on-impl.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. struct Foo; impl Foo { #[cfg(cfg_that_surely_doesnt_exist)]; fn method(&self) -> bool { false } } impl Foo { #[cfg(not(cfg_that_surely_doesnt_exist))]; // check that we don't eat attributes too eagerly. #[cfg(cfg_that_surely_doesnt_exist)] fn method(&self) -> bool { false } fn method(&self) -> bool
} pub fn main() { assert!(Foo.method()); }
{ true }
identifier_body
inner-attrs-on-impl.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. struct Foo; impl Foo { #[cfg(cfg_that_surely_doesnt_exist)]; fn method(&self) -> bool { false } } impl Foo { #[cfg(not(cfg_that_surely_doesnt_exist))]; // check that we don't eat attributes too eagerly. #[cfg(cfg_that_surely_doesnt_exist)] fn method(&self) -> bool { false } fn
(&self) -> bool { true } } pub fn main() { assert!(Foo.method()); }
method
identifier_name
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. use util::{U256, Uint}; pub trait Memory { /// Retrieve current size of the memory fn size(&self) -> usize; /// Resize (shrink or expand) the memory to specified size (fills 0) fn resize(&mut self, new_size: usize); /// Resize the memory only if its smaller fn expand(&mut self, new_size: usize); /// Write single byte to memory fn write_byte(&mut self, offset: U256, value: U256); /// Write a word to memory. Does not resize memory! fn write(&mut self, offset: U256, value: U256); /// Read a word from memory fn read(&self, offset: U256) -> U256; /// Write slice of bytes to memory. Does not resize memory! fn write_slice(&mut self, offset: U256, &[u8]); /// Retrieve part of the memory between offset and offset + size fn read_slice(&self, offset: U256, size: U256) -> &[u8]; /// Retrieve writeable part of memory fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut[u8]; fn dump(&self); } /// Checks whether offset and size is valid memory range fn is_valid_range(off: usize, size: usize) -> bool { // When size is zero we haven't actually expanded the memory let overflow = off.overflowing_add(size).1; size > 0 &&!overflow } impl Memory for Vec<u8> { fn dump(&self)
fn size(&self) -> usize { self.len() } fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] { let off = init_off_u.low_u64() as usize; let size = init_size_u.low_u64() as usize; if!is_valid_range(off, size) { &self[0..0] } else { &self[off..off+size] } } fn read(&self, offset: U256) -> U256 { let off = offset.low_u64() as usize; U256::from(&self[off..off+32]) } fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] { let off = offset.low_u64() as usize; let s = size.low_u64() as usize; if!is_valid_range(off, s) { &mut self[0..0] } else { &mut self[off..off+s] } } fn write_slice(&mut self, offset: U256, slice: &[u8]) { let off = offset.low_u64() as usize; // TODO [todr] Optimize? for pos in off..off+slice.len() { self[pos] = slice[pos - off]; } } fn write(&mut self, offset: U256, value: U256) { let off = offset.low_u64() as usize; value.to_big_endian(&mut self[off..off+32]); } fn write_byte(&mut self, offset: U256, value: U256) { let off = offset.low_u64() as usize; let val = value.low_u64() as u64; self[off] = val as u8; } fn resize(&mut self, new_size: usize) { self.resize(new_size, 0); } fn expand(&mut self, size: usize) { if size > self.len() { Memory::resize(self, size) } } } #[test] fn test_memory_read_and_write() { // given let mem: &mut Memory = &mut vec![]; mem.resize(0x80 + 32); // when mem.write(U256::from(0x80), U256::from(0xabcdef)); // then assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef)); } #[test] fn test_memory_read_and_write_byte() { // given let mem: &mut Memory = &mut vec![]; mem.resize(32); // when mem.write_byte(U256::from(0x1d), U256::from(0xab)); mem.write_byte(U256::from(0x1e), U256::from(0xcd)); mem.write_byte(U256::from(0x1f), U256::from(0xef)); // then assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef)); }
{ println!("MemoryDump:"); for i in self.iter() { println!("{:02x} ", i); } println!(""); }
identifier_body
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. use util::{U256, Uint}; pub trait Memory { /// Retrieve current size of the memory fn size(&self) -> usize; /// Resize (shrink or expand) the memory to specified size (fills 0) fn resize(&mut self, new_size: usize); /// Resize the memory only if its smaller fn expand(&mut self, new_size: usize); /// Write single byte to memory fn write_byte(&mut self, offset: U256, value: U256); /// Write a word to memory. Does not resize memory! fn write(&mut self, offset: U256, value: U256); /// Read a word from memory fn read(&self, offset: U256) -> U256; /// Write slice of bytes to memory. Does not resize memory! fn write_slice(&mut self, offset: U256, &[u8]); /// Retrieve part of the memory between offset and offset + size fn read_slice(&self, offset: U256, size: U256) -> &[u8]; /// Retrieve writeable part of memory fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut[u8]; fn dump(&self); } /// Checks whether offset and size is valid memory range fn is_valid_range(off: usize, size: usize) -> bool { // When size is zero we haven't actually expanded the memory let overflow = off.overflowing_add(size).1; size > 0 &&!overflow } impl Memory for Vec<u8> { fn dump(&self) { println!("MemoryDump:"); for i in self.iter() { println!("{:02x} ", i); } println!(""); } fn size(&self) -> usize { self.len() } fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] { let off = init_off_u.low_u64() as usize; let size = init_size_u.low_u64() as usize; if!is_valid_range(off, size)
else { &self[off..off+size] } } fn read(&self, offset: U256) -> U256 { let off = offset.low_u64() as usize; U256::from(&self[off..off+32]) } fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] { let off = offset.low_u64() as usize; let s = size.low_u64() as usize; if!is_valid_range(off, s) { &mut self[0..0] } else { &mut self[off..off+s] } } fn write_slice(&mut self, offset: U256, slice: &[u8]) { let off = offset.low_u64() as usize; // TODO [todr] Optimize? for pos in off..off+slice.len() { self[pos] = slice[pos - off]; } } fn write(&mut self, offset: U256, value: U256) { let off = offset.low_u64() as usize; value.to_big_endian(&mut self[off..off+32]); } fn write_byte(&mut self, offset: U256, value: U256) { let off = offset.low_u64() as usize; let val = value.low_u64() as u64; self[off] = val as u8; } fn resize(&mut self, new_size: usize) { self.resize(new_size, 0); } fn expand(&mut self, size: usize) { if size > self.len() { Memory::resize(self, size) } } } #[test] fn test_memory_read_and_write() { // given let mem: &mut Memory = &mut vec![]; mem.resize(0x80 + 32); // when mem.write(U256::from(0x80), U256::from(0xabcdef)); // then assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef)); } #[test] fn test_memory_read_and_write_byte() { // given let mem: &mut Memory = &mut vec![]; mem.resize(32); // when mem.write_byte(U256::from(0x1d), U256::from(0xab)); mem.write_byte(U256::from(0x1e), U256::from(0xcd)); mem.write_byte(U256::from(0x1f), U256::from(0xef)); // then assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef)); }
{ &self[0..0] }
conditional_block