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
#![allow(clippy::float_cmp)] #![allow(clippy::inline_always)] #![allow(clippy::many_single_char_names)] #![allow(clippy::needless_lifetimes)] #![allow(clippy::needless_return)] #![allow(clippy::or_fun_call)] #![allow(clippy::too_many_arguments)] #![allow(clippy::redundant_field_names)] #![allow(clippy::enum_variant_names)] #![allow(clippy::cast_lossless)] #![allow(clippy::needless_range_loop)] #![allow(clippy::excessive_precision)] #![allow(clippy::transmute_ptr_to_ptr)] extern crate lazy_static; mod accel; mod algorithm; mod bbox; mod bbox4; mod boundable; mod camera; mod color; mod fp_utils; mod hash; mod hilbert; mod image; mod lerp; mod light; mod math; mod mis; mod parse; mod ray; mod renderer; mod sampling; mod scene; mod shading; mod surface; mod timer; mod tracer; mod transform_stack; use std::{fs::File, io, io::Read, mem, path::Path, str::FromStr}; use clap::{App, Arg}; use nom::bytes::complete::take_until; use kioku::Arena; use crate::{ accel::BVH4Node, bbox::BBox, parse::{parse_scene, DataTree}, renderer::LightPath, surface::SurfaceIntersection, timer::Timer, }; const VERSION: &str = env!("CARGO_PKG_VERSION"); #[allow(clippy::cognitive_complexity)] fn main()
.value_name("N") .help("Number of samples per pixel") .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("max_bucket_samples") .short("b") .long("spb") .value_name("N") .help("Target number of samples per bucket (determines bucket size)") .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("crop") .long("crop") .value_name("X1 Y1 X2 Y2") .help( "Only render the image between pixel coordinates (X1, Y1) \ and (X2, Y2). Coordinates are zero-indexed and inclusive.", ) .takes_value(true) .number_of_values(4) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be four integers".to_string())) }), ) .arg( Arg::with_name("threads") .short("t") .long("threads") .value_name("N") .help( "Number of threads to render with. Defaults to the number of logical \ cores on the system.", ) .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("stats") .long("stats") .help("Print additional statistics about rendering"), ) .arg( Arg::with_name("dev") .long("dev") .help("Show useful dev/debug info."), ) .arg( Arg::with_name("serialized_output") .long("serialized_output") .help("Serialize and send render output to standard output.") .hidden(true), ) .arg( Arg::with_name("use_stdin") .long("use_stdin") .help("Take scene file in from stdin instead of a file path.") .hidden(true), ) .get_matches(); // Print some misc useful dev info. if args.is_present("dev") { println!( "SurfaceIntersection size: {} bytes", mem::size_of::<SurfaceIntersection>() ); println!("LightPath size: {} bytes", mem::size_of::<LightPath>()); println!("BBox size: {} bytes", mem::size_of::<BBox>()); // println!("BVHNode size: {} bytes", mem::size_of::<BVHNode>()); println!("BVH4Node size: {} bytes", mem::size_of::<BVH4Node>()); return; } let crop = args.values_of("crop").map(|mut vals| { let coords = ( u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), ); if coords.0 > coords.2 { panic!("Argument '--crop': X1 must be less than or equal to X2"); } if coords.1 > coords.3 { panic!("Argument '--crop': Y1 must be less than or equal to Y2"); } coords }); // Parse data tree of scene file if!args.is_present("serialized_output") { println!("Parsing scene file...",); } t.tick(); let psy_contents = if args.is_present("use_stdin") { // Read from stdin let mut input = Vec::new(); let tmp = std::io::stdin(); let mut stdin = tmp.lock(); let mut buf = vec![0u8; 4096]; loop { let count = stdin .read(&mut buf) .expect("Unexpected end of scene input."); let start = if input.len() < 11 { 0 } else { input.len() - 11 }; let end = input.len() + count; input.extend(&buf[..count]); let mut done = false; let mut trunc_len = 0; if let nom::IResult::Ok((remaining, _)) = take_until::<&str, &[u8], ()>("__PSY_EOF__")(&input[start..end]) { done = true; trunc_len = input.len() - remaining.len(); } if done { input.truncate(trunc_len); break; } } String::from_utf8(input).unwrap() } else { // Read from file let mut input = String::new(); let fp = args.value_of("input").unwrap(); let mut f = io::BufReader::new(File::open(fp).unwrap()); let _ = f.read_to_string(&mut input); input }; let dt = DataTree::from_str(&psy_contents).unwrap(); if!args.is_present("serialized_output") { println!("\tParsed scene file in {:.3}s", t.tick()); } // Iterate through scenes and render them if let DataTree::Internal { ref children,.. } = dt { for child in children { t.tick(); if child.type_name() == "Scene" { if!args.is_present("serialized_output") { println!("Building scene..."); } let arena = Arena::new().with_block_size((1 << 20) * 4); let mut r = parse_scene(&arena, child).unwrap_or_else(|e| { e.print(&psy_contents); panic!("Parse error."); }); if let Some(spp) = args.value_of("spp") { if!args.is_present("serialized_output") { println!("\tOverriding scene spp: {}", spp); } r.spp = usize::from_str(spp).unwrap(); } let max_samples_per_bucket = if let Some(max_samples_per_bucket) = args.value_of("max_bucket_samples") { u32::from_str(max_samples_per_bucket).unwrap() } else { 4096 }; let thread_count = if let Some(threads) = args.value_of("threads") { u32::from_str(threads).unwrap() } else { num_cpus::get() as u32 }; if!args.is_present("serialized_output") { println!("\tBuilt scene in {:.3}s", t.tick()); } if!args.is_present("serialized_output") { println!("Rendering scene with {} threads...", thread_count); } let (mut image, rstats) = r.render( max_samples_per_bucket, crop, thread_count, args.is_present("serialized_output"), ); // Print render stats if!args.is_present("serialized_output") { let rtime = t.tick(); let ntime = rtime as f64 / rstats.total_time; println!("\tRendered scene in {:.3}s", rtime); println!( "\t\tTrace: {:.3}s", ntime * rstats.trace_time ); println!("\t\t\tRays traced: {}", rstats.ray_count); println!( "\t\t\tRays/sec: {}", (rstats.ray_count as f64 / (ntime * rstats.trace_time) as f64) as u64 ); println!("\t\t\tRay/node tests: {}", rstats.accel_node_visits); println!( "\t\tInitial ray generation: {:.3}s", ntime * rstats.initial_ray_generation_time ); println!( "\t\tRay generation: {:.3}s", ntime * rstats.ray_generation_time ); println!( "\t\tSample writing: {:.3}s", ntime * rstats.sample_writing_time ); } // Write to disk if!args.is_present("serialized_output") { println!("Writing image to disk into '{}'...", r.output_file); if r.output_file.ends_with(".png") { image .write_png(Path::new(&r.output_file)) .expect("Failed to write png..."); } else if r.output_file.ends_with(".exr") { image.write_exr(Path::new(&r.output_file)); } else { panic!("Unknown output file extension."); } println!("\tWrote image in {:.3}s", t.tick()); } // Print memory stats if stats are wanted. if args.is_present("stats") { // let arena_stats = arena.stats(); // let mib_occupied = arena_stats.0 as f64 / 1_048_576.0; // let mib_allocated = arena_stats.1 as f64 / 1_048_576.0; // println!("MemArena stats:"); // if mib_occupied >= 1.0 { // println!("\tOccupied: {:.1} MiB", mib_occupied); // } else { // println!("\tOccupied: {:.4} MiB", mib_occupied); // } // if mib_allocated >= 1.0 { // println!("\tUsed: {:.1} MiB", mib_allocated); // } else { // println!("\tUsed: {:.4} MiB", mib_allocated); // } // println!("\tTotal blocks: {}", arena_stats.2); } } } } // End with blank line println!(); }
{ let mut t = Timer::new(); // Parse command line arguments. let args = App::new("Psychopath") .version(VERSION) .about("A slightly psychotic path tracer") .arg( Arg::with_name("input") .short("i") .long("input") .value_name("FILE") .help("Input .psy file") .takes_value(true) .required_unless_one(&["dev", "use_stdin"]), ) .arg( Arg::with_name("spp") .short("s") .long("spp")
identifier_body
main.rs
#![allow(clippy::float_cmp)] #![allow(clippy::inline_always)] #![allow(clippy::many_single_char_names)] #![allow(clippy::needless_lifetimes)] #![allow(clippy::needless_return)] #![allow(clippy::or_fun_call)] #![allow(clippy::too_many_arguments)] #![allow(clippy::redundant_field_names)] #![allow(clippy::enum_variant_names)] #![allow(clippy::cast_lossless)] #![allow(clippy::needless_range_loop)] #![allow(clippy::excessive_precision)] #![allow(clippy::transmute_ptr_to_ptr)] extern crate lazy_static; mod accel; mod algorithm; mod bbox; mod bbox4; mod boundable; mod camera; mod color; mod fp_utils; mod hash; mod hilbert; mod image; mod lerp; mod light; mod math; mod mis; mod parse; mod ray; mod renderer; mod sampling; mod scene; mod shading; mod surface; mod timer; mod tracer; mod transform_stack; use std::{fs::File, io, io::Read, mem, path::Path, str::FromStr}; use clap::{App, Arg}; use nom::bytes::complete::take_until; use kioku::Arena; use crate::{ accel::BVH4Node, bbox::BBox, parse::{parse_scene, DataTree}, renderer::LightPath, surface::SurfaceIntersection, timer::Timer, }; const VERSION: &str = env!("CARGO_PKG_VERSION"); #[allow(clippy::cognitive_complexity)] fn
() { let mut t = Timer::new(); // Parse command line arguments. let args = App::new("Psychopath") .version(VERSION) .about("A slightly psychotic path tracer") .arg( Arg::with_name("input") .short("i") .long("input") .value_name("FILE") .help("Input.psy file") .takes_value(true) .required_unless_one(&["dev", "use_stdin"]), ) .arg( Arg::with_name("spp") .short("s") .long("spp") .value_name("N") .help("Number of samples per pixel") .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("max_bucket_samples") .short("b") .long("spb") .value_name("N") .help("Target number of samples per bucket (determines bucket size)") .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("crop") .long("crop") .value_name("X1 Y1 X2 Y2") .help( "Only render the image between pixel coordinates (X1, Y1) \ and (X2, Y2). Coordinates are zero-indexed and inclusive.", ) .takes_value(true) .number_of_values(4) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be four integers".to_string())) }), ) .arg( Arg::with_name("threads") .short("t") .long("threads") .value_name("N") .help( "Number of threads to render with. Defaults to the number of logical \ cores on the system.", ) .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("stats") .long("stats") .help("Print additional statistics about rendering"), ) .arg( Arg::with_name("dev") .long("dev") .help("Show useful dev/debug info."), ) .arg( Arg::with_name("serialized_output") .long("serialized_output") .help("Serialize and send render output to standard output.") .hidden(true), ) .arg( Arg::with_name("use_stdin") .long("use_stdin") .help("Take scene file in from stdin instead of a file path.") .hidden(true), ) .get_matches(); // Print some misc useful dev info. if args.is_present("dev") { println!( "SurfaceIntersection size: {} bytes", mem::size_of::<SurfaceIntersection>() ); println!("LightPath size: {} bytes", mem::size_of::<LightPath>()); println!("BBox size: {} bytes", mem::size_of::<BBox>()); // println!("BVHNode size: {} bytes", mem::size_of::<BVHNode>()); println!("BVH4Node size: {} bytes", mem::size_of::<BVH4Node>()); return; } let crop = args.values_of("crop").map(|mut vals| { let coords = ( u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), ); if coords.0 > coords.2 { panic!("Argument '--crop': X1 must be less than or equal to X2"); } if coords.1 > coords.3 { panic!("Argument '--crop': Y1 must be less than or equal to Y2"); } coords }); // Parse data tree of scene file if!args.is_present("serialized_output") { println!("Parsing scene file...",); } t.tick(); let psy_contents = if args.is_present("use_stdin") { // Read from stdin let mut input = Vec::new(); let tmp = std::io::stdin(); let mut stdin = tmp.lock(); let mut buf = vec![0u8; 4096]; loop { let count = stdin .read(&mut buf) .expect("Unexpected end of scene input."); let start = if input.len() < 11 { 0 } else { input.len() - 11 }; let end = input.len() + count; input.extend(&buf[..count]); let mut done = false; let mut trunc_len = 0; if let nom::IResult::Ok((remaining, _)) = take_until::<&str, &[u8], ()>("__PSY_EOF__")(&input[start..end]) { done = true; trunc_len = input.len() - remaining.len(); } if done { input.truncate(trunc_len); break; } } String::from_utf8(input).unwrap() } else { // Read from file let mut input = String::new(); let fp = args.value_of("input").unwrap(); let mut f = io::BufReader::new(File::open(fp).unwrap()); let _ = f.read_to_string(&mut input); input }; let dt = DataTree::from_str(&psy_contents).unwrap(); if!args.is_present("serialized_output") { println!("\tParsed scene file in {:.3}s", t.tick()); } // Iterate through scenes and render them if let DataTree::Internal { ref children,.. } = dt { for child in children { t.tick(); if child.type_name() == "Scene" { if!args.is_present("serialized_output") { println!("Building scene..."); } let arena = Arena::new().with_block_size((1 << 20) * 4); let mut r = parse_scene(&arena, child).unwrap_or_else(|e| { e.print(&psy_contents); panic!("Parse error."); }); if let Some(spp) = args.value_of("spp") { if!args.is_present("serialized_output") { println!("\tOverriding scene spp: {}", spp); } r.spp = usize::from_str(spp).unwrap(); } let max_samples_per_bucket = if let Some(max_samples_per_bucket) = args.value_of("max_bucket_samples") { u32::from_str(max_samples_per_bucket).unwrap() } else { 4096 }; let thread_count = if let Some(threads) = args.value_of("threads") { u32::from_str(threads).unwrap() } else { num_cpus::get() as u32 }; if!args.is_present("serialized_output") { println!("\tBuilt scene in {:.3}s", t.tick()); } if!args.is_present("serialized_output") { println!("Rendering scene with {} threads...", thread_count); } let (mut image, rstats) = r.render( max_samples_per_bucket, crop, thread_count, args.is_present("serialized_output"), ); // Print render stats if!args.is_present("serialized_output") { let rtime = t.tick(); let ntime = rtime as f64 / rstats.total_time; println!("\tRendered scene in {:.3}s", rtime); println!( "\t\tTrace: {:.3}s", ntime * rstats.trace_time ); println!("\t\t\tRays traced: {}", rstats.ray_count); println!( "\t\t\tRays/sec: {}", (rstats.ray_count as f64 / (ntime * rstats.trace_time) as f64) as u64 ); println!("\t\t\tRay/node tests: {}", rstats.accel_node_visits); println!( "\t\tInitial ray generation: {:.3}s", ntime * rstats.initial_ray_generation_time ); println!( "\t\tRay generation: {:.3}s", ntime * rstats.ray_generation_time ); println!( "\t\tSample writing: {:.3}s", ntime * rstats.sample_writing_time ); } // Write to disk if!args.is_present("serialized_output") { println!("Writing image to disk into '{}'...", r.output_file); if r.output_file.ends_with(".png") { image .write_png(Path::new(&r.output_file)) .expect("Failed to write png..."); } else if r.output_file.ends_with(".exr") { image.write_exr(Path::new(&r.output_file)); } else { panic!("Unknown output file extension."); } println!("\tWrote image in {:.3}s", t.tick()); } // Print memory stats if stats are wanted. if args.is_present("stats") { // let arena_stats = arena.stats(); // let mib_occupied = arena_stats.0 as f64 / 1_048_576.0; // let mib_allocated = arena_stats.1 as f64 / 1_048_576.0; // println!("MemArena stats:"); // if mib_occupied >= 1.0 { // println!("\tOccupied: {:.1} MiB", mib_occupied); // } else { // println!("\tOccupied: {:.4} MiB", mib_occupied); // } // if mib_allocated >= 1.0 { // println!("\tUsed: {:.1} MiB", mib_allocated); // } else { // println!("\tUsed: {:.4} MiB", mib_allocated); // } // println!("\tTotal blocks: {}", arena_stats.2); } } } } // End with blank line println!(); }
main
identifier_name
main.rs
#![allow(clippy::float_cmp)] #![allow(clippy::inline_always)] #![allow(clippy::many_single_char_names)] #![allow(clippy::needless_lifetimes)] #![allow(clippy::needless_return)] #![allow(clippy::or_fun_call)] #![allow(clippy::too_many_arguments)] #![allow(clippy::redundant_field_names)] #![allow(clippy::enum_variant_names)] #![allow(clippy::cast_lossless)] #![allow(clippy::needless_range_loop)] #![allow(clippy::excessive_precision)] #![allow(clippy::transmute_ptr_to_ptr)] extern crate lazy_static; mod accel; mod algorithm; mod bbox; mod bbox4; mod boundable; mod camera; mod color; mod fp_utils; mod hash; mod hilbert; mod image; mod lerp; mod light; mod math; mod mis; mod parse; mod ray; mod renderer; mod sampling; mod scene; mod shading; mod surface; mod timer; mod tracer; mod transform_stack; use std::{fs::File, io, io::Read, mem, path::Path, str::FromStr}; use clap::{App, Arg}; use nom::bytes::complete::take_until; use kioku::Arena; use crate::{ accel::BVH4Node, bbox::BBox, parse::{parse_scene, DataTree}, renderer::LightPath, surface::SurfaceIntersection, timer::Timer, }; const VERSION: &str = env!("CARGO_PKG_VERSION"); #[allow(clippy::cognitive_complexity)] fn main() { let mut t = Timer::new(); // Parse command line arguments. let args = App::new("Psychopath") .version(VERSION) .about("A slightly psychotic path tracer") .arg( Arg::with_name("input") .short("i") .long("input") .value_name("FILE") .help("Input.psy file") .takes_value(true) .required_unless_one(&["dev", "use_stdin"]), ) .arg( Arg::with_name("spp") .short("s") .long("spp") .value_name("N") .help("Number of samples per pixel") .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("max_bucket_samples") .short("b") .long("spb") .value_name("N") .help("Target number of samples per bucket (determines bucket size)") .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("crop") .long("crop") .value_name("X1 Y1 X2 Y2") .help( "Only render the image between pixel coordinates (X1, Y1) \ and (X2, Y2). Coordinates are zero-indexed and inclusive.", ) .takes_value(true) .number_of_values(4) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be four integers".to_string())) }), ) .arg( Arg::with_name("threads") .short("t") .long("threads") .value_name("N") .help( "Number of threads to render with. Defaults to the number of logical \ cores on the system.", ) .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ) .arg( Arg::with_name("stats") .long("stats") .help("Print additional statistics about rendering"), ) .arg( Arg::with_name("dev") .long("dev") .help("Show useful dev/debug info."), ) .arg( Arg::with_name("serialized_output") .long("serialized_output") .help("Serialize and send render output to standard output.") .hidden(true), ) .arg( Arg::with_name("use_stdin") .long("use_stdin") .help("Take scene file in from stdin instead of a file path.") .hidden(true), ) .get_matches(); // Print some misc useful dev info. if args.is_present("dev") { println!( "SurfaceIntersection size: {} bytes", mem::size_of::<SurfaceIntersection>() ); println!("LightPath size: {} bytes", mem::size_of::<LightPath>()); println!("BBox size: {} bytes", mem::size_of::<BBox>()); // println!("BVHNode size: {} bytes", mem::size_of::<BVHNode>()); println!("BVH4Node size: {} bytes", mem::size_of::<BVH4Node>()); return; } let crop = args.values_of("crop").map(|mut vals| { let coords = ( u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), u32::from_str(vals.next().unwrap()).unwrap(), ); if coords.0 > coords.2 { panic!("Argument '--crop': X1 must be less than or equal to X2"); } if coords.1 > coords.3 { panic!("Argument '--crop': Y1 must be less than or equal to Y2"); } coords }); // Parse data tree of scene file if!args.is_present("serialized_output") { println!("Parsing scene file...",); } t.tick(); let psy_contents = if args.is_present("use_stdin") { // Read from stdin let mut input = Vec::new(); let tmp = std::io::stdin(); let mut stdin = tmp.lock(); let mut buf = vec![0u8; 4096]; loop { let count = stdin .read(&mut buf) .expect("Unexpected end of scene input."); let start = if input.len() < 11 { 0 } else { input.len() - 11 }; let end = input.len() + count; input.extend(&buf[..count]); let mut done = false; let mut trunc_len = 0; if let nom::IResult::Ok((remaining, _)) = take_until::<&str, &[u8], ()>("__PSY_EOF__")(&input[start..end]) { done = true; trunc_len = input.len() - remaining.len(); } if done { input.truncate(trunc_len); break; } } String::from_utf8(input).unwrap() } else { // Read from file let mut input = String::new(); let fp = args.value_of("input").unwrap(); let mut f = io::BufReader::new(File::open(fp).unwrap()); let _ = f.read_to_string(&mut input); input }; let dt = DataTree::from_str(&psy_contents).unwrap(); if!args.is_present("serialized_output") { println!("\tParsed scene file in {:.3}s", t.tick()); } // Iterate through scenes and render them if let DataTree::Internal { ref children,.. } = dt { for child in children { t.tick(); if child.type_name() == "Scene" {
let arena = Arena::new().with_block_size((1 << 20) * 4); let mut r = parse_scene(&arena, child).unwrap_or_else(|e| { e.print(&psy_contents); panic!("Parse error."); }); if let Some(spp) = args.value_of("spp") { if!args.is_present("serialized_output") { println!("\tOverriding scene spp: {}", spp); } r.spp = usize::from_str(spp).unwrap(); } let max_samples_per_bucket = if let Some(max_samples_per_bucket) = args.value_of("max_bucket_samples") { u32::from_str(max_samples_per_bucket).unwrap() } else { 4096 }; let thread_count = if let Some(threads) = args.value_of("threads") { u32::from_str(threads).unwrap() } else { num_cpus::get() as u32 }; if!args.is_present("serialized_output") { println!("\tBuilt scene in {:.3}s", t.tick()); } if!args.is_present("serialized_output") { println!("Rendering scene with {} threads...", thread_count); } let (mut image, rstats) = r.render( max_samples_per_bucket, crop, thread_count, args.is_present("serialized_output"), ); // Print render stats if!args.is_present("serialized_output") { let rtime = t.tick(); let ntime = rtime as f64 / rstats.total_time; println!("\tRendered scene in {:.3}s", rtime); println!( "\t\tTrace: {:.3}s", ntime * rstats.trace_time ); println!("\t\t\tRays traced: {}", rstats.ray_count); println!( "\t\t\tRays/sec: {}", (rstats.ray_count as f64 / (ntime * rstats.trace_time) as f64) as u64 ); println!("\t\t\tRay/node tests: {}", rstats.accel_node_visits); println!( "\t\tInitial ray generation: {:.3}s", ntime * rstats.initial_ray_generation_time ); println!( "\t\tRay generation: {:.3}s", ntime * rstats.ray_generation_time ); println!( "\t\tSample writing: {:.3}s", ntime * rstats.sample_writing_time ); } // Write to disk if!args.is_present("serialized_output") { println!("Writing image to disk into '{}'...", r.output_file); if r.output_file.ends_with(".png") { image .write_png(Path::new(&r.output_file)) .expect("Failed to write png..."); } else if r.output_file.ends_with(".exr") { image.write_exr(Path::new(&r.output_file)); } else { panic!("Unknown output file extension."); } println!("\tWrote image in {:.3}s", t.tick()); } // Print memory stats if stats are wanted. if args.is_present("stats") { // let arena_stats = arena.stats(); // let mib_occupied = arena_stats.0 as f64 / 1_048_576.0; // let mib_allocated = arena_stats.1 as f64 / 1_048_576.0; // println!("MemArena stats:"); // if mib_occupied >= 1.0 { // println!("\tOccupied: {:.1} MiB", mib_occupied); // } else { // println!("\tOccupied: {:.4} MiB", mib_occupied); // } // if mib_allocated >= 1.0 { // println!("\tUsed: {:.1} MiB", mib_allocated); // } else { // println!("\tUsed: {:.4} MiB", mib_allocated); // } // println!("\tTotal blocks: {}", arena_stats.2); } } } } // End with blank line println!(); }
if !args.is_present("serialized_output") { println!("Building scene..."); }
random_line_split
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::{ BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, ValType, }; use std::ops::Range; /// Represents a core WebAssembly element segment. #[derive(Clone)] pub struct Element<'a> { /// The kind of the element segment. pub kind: ElementKind<'a>, /// The initial elements of the element segment. pub items: ElementItems<'a>, /// The type of the elements. pub ty: ValType, /// The range of the the element segment. pub range: Range<usize>, } /// The kind of element segment. #[derive(Clone)] pub enum ElementKind<'a> { /// The element segment is passive. Passive, /// The element segment is active. Active { /// The index of the table being initialized. table_index: u32, /// The initial expression of the element segment. offset_expr: ConstExpr<'a>, }, /// The element segment is declared. Declared, } /// Represents the items of an element segment. #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { exprs: bool, offset: usize, data: &'a [u8], } /// Represents an individual item of an element segment. #[derive(Debug)] pub enum ElementItem<'a> { /// The item is a function index. Func(u32), /// The item is an initialization expression. Expr(ConstExpr<'a>), } impl<'a> ElementItems<'a> { /// Gets an items reader for the items in an element segment. pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset, self.exprs) } } /// A reader for element items in an element segment. pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, exprs: bool, } impl<'a> ElementItemsReader<'a> { /// Constructs a new `ElementItemsReader` for the given data and offset. pub fn new(data: &[u8], offset: usize, exprs: bool) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count, exprs, }) } /// Gets the original position of the reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of element items in the segment. pub fn get_count(&self) -> u32 { self.count } /// Whether or not initialization expressions are used. pub fn uses_exprs(&self) -> bool { self.exprs } /// Reads an element item from the segment. pub fn read(&mut self) -> Result<ElementItem<'a>> { if self.exprs { let expr = self.reader.read_const_expr()?; Ok(ElementItem::Expr(expr)) } else { let idx = self.reader.read_var_u32()?; Ok(ElementItem::Func(idx)) } } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<ElementItem<'a>>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } /// An iterator over element items in an element segment. pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<ElementItem<'a>>; fn next(&mut self) -> Option<Self::Item>
fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } /// A reader for the element section of a WebAssembly module. #[derive(Clone)] pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { /// Constructs a new `ElementSectionReader` for the given data and offset. pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) } /// Gets the original position of the section reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of items in the section. pub fn get_count(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// /// ```no_run /// # let data: &[u8] = &[]; /// use wasmparser::{ElementSectionReader, ElementKind}; /// let mut element_reader = ElementSectionReader::new(data, 0).unwrap(); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// if let ElementKind::Active { offset_expr,.. } = element.kind { /// let mut offset_expr_reader = offset_expr.get_binary_reader(); /// let op = offset_expr_reader.read_operator().expect("op"); /// println!("offset expression: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader"); /// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {:?}", item); /// } /// } /// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let elem_start = self.reader.original_position(); // The current handling of the flags is largely specified in the `bulk-memory` proposal, // which at the time this commend is written has been merged to the main specification // draft. // // Notably, this proposal allows multiple different encodings of the table index 0. `00` // and `02 00` are both valid ways to specify the 0-th table. However it also makes // another encoding of the 0-th memory `80 00` no longer valid. // // We, however maintain this support by parsing `flags` as a LEB128 integer. In that case, // `80 00` encoding is parsed out as `0` and is therefore assigned a `tableidx` 0, even // though the current specification draft does not allow for this. // // See also https://github.com/WebAssembly/spec/issues/1439 let flags = self.reader.read_var_u32()?; if (flags &!0b111)!= 0 { return Err(BinaryReaderError::new( "invalid flags byte in element segment", self.reader.original_position() - 1, )); } let kind = if flags & 0b001!= 0 { if flags & 0b010!= 0 { ElementKind::Declared } else { ElementKind::Passive } } else { let table_index = if flags & 0b010 == 0 { 0 } else { self.reader.read_var_u32()? }; let offset_expr = { let expr_offset = self.reader.position; self.reader.skip_const_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; ConstExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, offset_expr, } }; let exprs = flags & 0b100!= 0; let ty = if flags & 0b011!= 0 { if exprs { self.reader.read_val_type()? } else { match self.reader.read_external_kind()? { ExternalKind::Func => ValType::FuncRef, _ => { return Err(BinaryReaderError::new( "only the function external type is supported in elem segment", self.reader.original_position() - 1, )); } } } } else { ValType::FuncRef }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; if exprs { for _ in 0..items_count { self.reader.skip_const_expr()?; } } else { for _ in 0..items_count { self.reader.read_var_u32()?; } } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], exprs, }; let elem_end = self.reader.original_position(); let range = elem_start..elem_end; Ok(Element { kind, items, ty, range, }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } fn range(&self) -> Range<usize> { self.reader.range() } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32 { ElementSectionReader::get_count(self) } } impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
{ if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) }
identifier_body
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::{ BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, ValType, }; use std::ops::Range; /// Represents a core WebAssembly element segment. #[derive(Clone)] pub struct Element<'a> { /// The kind of the element segment. pub kind: ElementKind<'a>, /// The initial elements of the element segment. pub items: ElementItems<'a>, /// The type of the elements. pub ty: ValType, /// The range of the the element segment. pub range: Range<usize>, } /// The kind of element segment. #[derive(Clone)] pub enum ElementKind<'a> { /// The element segment is passive. Passive, /// The element segment is active. Active { /// The index of the table being initialized. table_index: u32, /// The initial expression of the element segment. offset_expr: ConstExpr<'a>, }, /// The element segment is declared. Declared, } /// Represents the items of an element segment. #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { exprs: bool, offset: usize, data: &'a [u8], } /// Represents an individual item of an element segment. #[derive(Debug)] pub enum ElementItem<'a> { /// The item is a function index. Func(u32), /// The item is an initialization expression. Expr(ConstExpr<'a>), } impl<'a> ElementItems<'a> { /// Gets an items reader for the items in an element segment. pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset, self.exprs) } } /// A reader for element items in an element segment. pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, exprs: bool, } impl<'a> ElementItemsReader<'a> { /// Constructs a new `ElementItemsReader` for the given data and offset. pub fn new(data: &[u8], offset: usize, exprs: bool) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count, exprs, }) } /// Gets the original position of the reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of element items in the segment. pub fn get_count(&self) -> u32 { self.count } /// Whether or not initialization expressions are used. pub fn uses_exprs(&self) -> bool { self.exprs } /// Reads an element item from the segment. pub fn read(&mut self) -> Result<ElementItem<'a>> { if self.exprs { let expr = self.reader.read_const_expr()?; Ok(ElementItem::Expr(expr)) } else { let idx = self.reader.read_var_u32()?; Ok(ElementItem::Func(idx)) } } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<ElementItem<'a>>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } /// An iterator over element items in an element segment. pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<ElementItem<'a>>; fn next(&mut self) -> Option<Self::Item> { if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) } fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } /// A reader for the element section of a WebAssembly module. #[derive(Clone)] pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { /// Constructs a new `ElementSectionReader` for the given data and offset. pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) } /// Gets the original position of the section reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of items in the section. pub fn get_count(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// /// ```no_run /// # let data: &[u8] = &[]; /// use wasmparser::{ElementSectionReader, ElementKind}; /// let mut element_reader = ElementSectionReader::new(data, 0).unwrap(); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// if let ElementKind::Active { offset_expr,.. } = element.kind { /// let mut offset_expr_reader = offset_expr.get_binary_reader(); /// let op = offset_expr_reader.read_operator().expect("op"); /// println!("offset expression: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader");
/// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let elem_start = self.reader.original_position(); // The current handling of the flags is largely specified in the `bulk-memory` proposal, // which at the time this commend is written has been merged to the main specification // draft. // // Notably, this proposal allows multiple different encodings of the table index 0. `00` // and `02 00` are both valid ways to specify the 0-th table. However it also makes // another encoding of the 0-th memory `80 00` no longer valid. // // We, however maintain this support by parsing `flags` as a LEB128 integer. In that case, // `80 00` encoding is parsed out as `0` and is therefore assigned a `tableidx` 0, even // though the current specification draft does not allow for this. // // See also https://github.com/WebAssembly/spec/issues/1439 let flags = self.reader.read_var_u32()?; if (flags &!0b111)!= 0 { return Err(BinaryReaderError::new( "invalid flags byte in element segment", self.reader.original_position() - 1, )); } let kind = if flags & 0b001!= 0 { if flags & 0b010!= 0 { ElementKind::Declared } else { ElementKind::Passive } } else { let table_index = if flags & 0b010 == 0 { 0 } else { self.reader.read_var_u32()? }; let offset_expr = { let expr_offset = self.reader.position; self.reader.skip_const_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; ConstExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, offset_expr, } }; let exprs = flags & 0b100!= 0; let ty = if flags & 0b011!= 0 { if exprs { self.reader.read_val_type()? } else { match self.reader.read_external_kind()? { ExternalKind::Func => ValType::FuncRef, _ => { return Err(BinaryReaderError::new( "only the function external type is supported in elem segment", self.reader.original_position() - 1, )); } } } } else { ValType::FuncRef }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; if exprs { for _ in 0..items_count { self.reader.skip_const_expr()?; } } else { for _ in 0..items_count { self.reader.read_var_u32()?; } } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], exprs, }; let elem_end = self.reader.original_position(); let range = elem_start..elem_end; Ok(Element { kind, items, ty, range, }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } fn range(&self) -> Range<usize> { self.reader.range() } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32 { ElementSectionReader::get_count(self) } } impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
/// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {:?}", item); /// } /// }
random_line_split
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::{ BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, ValType, }; use std::ops::Range; /// Represents a core WebAssembly element segment. #[derive(Clone)] pub struct Element<'a> { /// The kind of the element segment. pub kind: ElementKind<'a>, /// The initial elements of the element segment. pub items: ElementItems<'a>, /// The type of the elements. pub ty: ValType, /// The range of the the element segment. pub range: Range<usize>, } /// The kind of element segment. #[derive(Clone)] pub enum ElementKind<'a> { /// The element segment is passive. Passive, /// The element segment is active. Active { /// The index of the table being initialized. table_index: u32, /// The initial expression of the element segment. offset_expr: ConstExpr<'a>, }, /// The element segment is declared. Declared, } /// Represents the items of an element segment. #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { exprs: bool, offset: usize, data: &'a [u8], } /// Represents an individual item of an element segment. #[derive(Debug)] pub enum ElementItem<'a> { /// The item is a function index. Func(u32), /// The item is an initialization expression. Expr(ConstExpr<'a>), } impl<'a> ElementItems<'a> { /// Gets an items reader for the items in an element segment. pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset, self.exprs) } } /// A reader for element items in an element segment. pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, exprs: bool, } impl<'a> ElementItemsReader<'a> { /// Constructs a new `ElementItemsReader` for the given data and offset. pub fn new(data: &[u8], offset: usize, exprs: bool) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count, exprs, }) } /// Gets the original position of the reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of element items in the segment. pub fn get_count(&self) -> u32 { self.count } /// Whether or not initialization expressions are used. pub fn uses_exprs(&self) -> bool { self.exprs } /// Reads an element item from the segment. pub fn read(&mut self) -> Result<ElementItem<'a>> { if self.exprs { let expr = self.reader.read_const_expr()?; Ok(ElementItem::Expr(expr)) } else { let idx = self.reader.read_var_u32()?; Ok(ElementItem::Func(idx)) } } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<ElementItem<'a>>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } /// An iterator over element items in an element segment. pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<ElementItem<'a>>; fn next(&mut self) -> Option<Self::Item> { if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) } fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } /// A reader for the element section of a WebAssembly module. #[derive(Clone)] pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { /// Constructs a new `ElementSectionReader` for the given data and offset. pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) } /// Gets the original position of the section reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of items in the section. pub fn get_count(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// /// ```no_run /// # let data: &[u8] = &[]; /// use wasmparser::{ElementSectionReader, ElementKind}; /// let mut element_reader = ElementSectionReader::new(data, 0).unwrap(); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// if let ElementKind::Active { offset_expr,.. } = element.kind { /// let mut offset_expr_reader = offset_expr.get_binary_reader(); /// let op = offset_expr_reader.read_operator().expect("op"); /// println!("offset expression: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader"); /// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {:?}", item); /// } /// } /// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let elem_start = self.reader.original_position(); // The current handling of the flags is largely specified in the `bulk-memory` proposal, // which at the time this commend is written has been merged to the main specification // draft. // // Notably, this proposal allows multiple different encodings of the table index 0. `00` // and `02 00` are both valid ways to specify the 0-th table. However it also makes // another encoding of the 0-th memory `80 00` no longer valid. // // We, however maintain this support by parsing `flags` as a LEB128 integer. In that case, // `80 00` encoding is parsed out as `0` and is therefore assigned a `tableidx` 0, even // though the current specification draft does not allow for this. // // See also https://github.com/WebAssembly/spec/issues/1439 let flags = self.reader.read_var_u32()?; if (flags &!0b111)!= 0
let kind = if flags & 0b001!= 0 { if flags & 0b010!= 0 { ElementKind::Declared } else { ElementKind::Passive } } else { let table_index = if flags & 0b010 == 0 { 0 } else { self.reader.read_var_u32()? }; let offset_expr = { let expr_offset = self.reader.position; self.reader.skip_const_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; ConstExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, offset_expr, } }; let exprs = flags & 0b100!= 0; let ty = if flags & 0b011!= 0 { if exprs { self.reader.read_val_type()? } else { match self.reader.read_external_kind()? { ExternalKind::Func => ValType::FuncRef, _ => { return Err(BinaryReaderError::new( "only the function external type is supported in elem segment", self.reader.original_position() - 1, )); } } } } else { ValType::FuncRef }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; if exprs { for _ in 0..items_count { self.reader.skip_const_expr()?; } } else { for _ in 0..items_count { self.reader.read_var_u32()?; } } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], exprs, }; let elem_end = self.reader.original_position(); let range = elem_start..elem_end; Ok(Element { kind, items, ty, range, }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } fn range(&self) -> Range<usize> { self.reader.range() } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32 { ElementSectionReader::get_count(self) } } impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
{ return Err(BinaryReaderError::new( "invalid flags byte in element segment", self.reader.original_position() - 1, )); }
conditional_block
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::{ BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, ValType, }; use std::ops::Range; /// Represents a core WebAssembly element segment. #[derive(Clone)] pub struct Element<'a> { /// The kind of the element segment. pub kind: ElementKind<'a>, /// The initial elements of the element segment. pub items: ElementItems<'a>, /// The type of the elements. pub ty: ValType, /// The range of the the element segment. pub range: Range<usize>, } /// The kind of element segment. #[derive(Clone)] pub enum ElementKind<'a> { /// The element segment is passive. Passive, /// The element segment is active. Active { /// The index of the table being initialized. table_index: u32, /// The initial expression of the element segment. offset_expr: ConstExpr<'a>, }, /// The element segment is declared. Declared, } /// Represents the items of an element segment. #[derive(Debug, Copy, Clone)] pub struct ElementItems<'a> { exprs: bool, offset: usize, data: &'a [u8], } /// Represents an individual item of an element segment. #[derive(Debug)] pub enum ElementItem<'a> { /// The item is a function index. Func(u32), /// The item is an initialization expression. Expr(ConstExpr<'a>), } impl<'a> ElementItems<'a> { /// Gets an items reader for the items in an element segment. pub fn get_items_reader<'b>(&self) -> Result<ElementItemsReader<'b>> where 'a: 'b, { ElementItemsReader::new(self.data, self.offset, self.exprs) } } /// A reader for element items in an element segment. pub struct ElementItemsReader<'a> { reader: BinaryReader<'a>, count: u32, exprs: bool, } impl<'a> ElementItemsReader<'a> { /// Constructs a new `ElementItemsReader` for the given data and offset. pub fn new(data: &[u8], offset: usize, exprs: bool) -> Result<ElementItemsReader> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementItemsReader { reader, count, exprs, }) } /// Gets the original position of the reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of element items in the segment. pub fn get_count(&self) -> u32 { self.count } /// Whether or not initialization expressions are used. pub fn uses_exprs(&self) -> bool { self.exprs } /// Reads an element item from the segment. pub fn read(&mut self) -> Result<ElementItem<'a>> { if self.exprs { let expr = self.reader.read_const_expr()?; Ok(ElementItem::Expr(expr)) } else { let idx = self.reader.read_var_u32()?; Ok(ElementItem::Func(idx)) } } } impl<'a> IntoIterator for ElementItemsReader<'a> { type Item = Result<ElementItem<'a>>; type IntoIter = ElementItemsIterator<'a>; fn into_iter(self) -> Self::IntoIter { let count = self.count; ElementItemsIterator { reader: self, left: count, err: false, } } } /// An iterator over element items in an element segment. pub struct ElementItemsIterator<'a> { reader: ElementItemsReader<'a>, left: u32, err: bool, } impl<'a> Iterator for ElementItemsIterator<'a> { type Item = Result<ElementItem<'a>>; fn next(&mut self) -> Option<Self::Item> { if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) } fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } /// A reader for the element section of a WebAssembly module. #[derive(Clone)] pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ElementSectionReader<'a> { /// Constructs a new `ElementSectionReader` for the given data and offset. pub fn new(data: &'a [u8], offset: usize) -> Result<ElementSectionReader<'a>> { let mut reader = BinaryReader::new_with_offset(data, offset); let count = reader.read_var_u32()?; Ok(ElementSectionReader { reader, count }) } /// Gets the original position of the section reader. pub fn original_position(&self) -> usize { self.reader.original_position() } /// Gets the count of items in the section. pub fn
(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// /// ```no_run /// # let data: &[u8] = &[]; /// use wasmparser::{ElementSectionReader, ElementKind}; /// let mut element_reader = ElementSectionReader::new(data, 0).unwrap(); /// for _ in 0..element_reader.get_count() { /// let element = element_reader.read().expect("element"); /// if let ElementKind::Active { offset_expr,.. } = element.kind { /// let mut offset_expr_reader = offset_expr.get_binary_reader(); /// let op = offset_expr_reader.read_operator().expect("op"); /// println!("offset expression: {:?}", op); /// } /// let mut items_reader = element.items.get_items_reader().expect("items reader"); /// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {:?}", item); /// } /// } /// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let elem_start = self.reader.original_position(); // The current handling of the flags is largely specified in the `bulk-memory` proposal, // which at the time this commend is written has been merged to the main specification // draft. // // Notably, this proposal allows multiple different encodings of the table index 0. `00` // and `02 00` are both valid ways to specify the 0-th table. However it also makes // another encoding of the 0-th memory `80 00` no longer valid. // // We, however maintain this support by parsing `flags` as a LEB128 integer. In that case, // `80 00` encoding is parsed out as `0` and is therefore assigned a `tableidx` 0, even // though the current specification draft does not allow for this. // // See also https://github.com/WebAssembly/spec/issues/1439 let flags = self.reader.read_var_u32()?; if (flags &!0b111)!= 0 { return Err(BinaryReaderError::new( "invalid flags byte in element segment", self.reader.original_position() - 1, )); } let kind = if flags & 0b001!= 0 { if flags & 0b010!= 0 { ElementKind::Declared } else { ElementKind::Passive } } else { let table_index = if flags & 0b010 == 0 { 0 } else { self.reader.read_var_u32()? }; let offset_expr = { let expr_offset = self.reader.position; self.reader.skip_const_expr()?; let data = &self.reader.buffer[expr_offset..self.reader.position]; ConstExpr::new(data, self.reader.original_offset + expr_offset) }; ElementKind::Active { table_index, offset_expr, } }; let exprs = flags & 0b100!= 0; let ty = if flags & 0b011!= 0 { if exprs { self.reader.read_val_type()? } else { match self.reader.read_external_kind()? { ExternalKind::Func => ValType::FuncRef, _ => { return Err(BinaryReaderError::new( "only the function external type is supported in elem segment", self.reader.original_position() - 1, )); } } } } else { ValType::FuncRef }; let data_start = self.reader.position; let items_count = self.reader.read_var_u32()?; if exprs { for _ in 0..items_count { self.reader.skip_const_expr()?; } } else { for _ in 0..items_count { self.reader.read_var_u32()?; } } let data_end = self.reader.position; let items = ElementItems { offset: self.reader.original_offset + data_start, data: &self.reader.buffer[data_start..data_end], exprs, }; let elem_end = self.reader.original_position(); let range = elem_start..elem_end; Ok(Element { kind, items, ty, range, }) } } impl<'a> SectionReader for ElementSectionReader<'a> { type Item = Element<'a>; fn read(&mut self) -> Result<Self::Item> { ElementSectionReader::read(self) } fn eof(&self) -> bool { self.reader.eof() } fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } fn range(&self) -> Range<usize> { self.reader.range() } } impl<'a> SectionWithLimitedItems for ElementSectionReader<'a> { fn get_count(&self) -> u32 { ElementSectionReader::get_count(self) } } impl<'a> IntoIterator for ElementSectionReader<'a> { type Item = Result<Element<'a>>; type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>; fn into_iter(self) -> Self::IntoIter { SectionIteratorLimited::new(self) } }
get_count
identifier_name
framebuffer.rs
// Copyright (c) 2016 The vulkano developers // 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. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::error; use std::fmt; use std::marker::PhantomData; use std::mem; use std::ptr; use std::sync::Arc; use smallvec::SmallVec; use device::Device; use device::DeviceOwned; use format::ClearValue; use framebuffer::AttachmentsList; use framebuffer::FramebufferAbstract; use framebuffer::IncompatibleRenderPassAttachmentError; use framebuffer::LayoutAttachmentDescription; use framebuffer::LayoutPassDependencyDescription; use framebuffer::LayoutPassDescription; use framebuffer::RenderPassAbstract; use framebuffer::RenderPassDescClearValues; use framebuffer::RenderPassDescAttachmentsList; use framebuffer::RenderPassDesc; use framebuffer::RenderPassSys; use image::ImageViewAccess; use Error; use OomError; use VulkanObject; use VulkanPointers; use check_errors; use vk; /// Contains the list of images attached to a render pass. /// /// Creating a framebuffer is done by passing the render pass object, the dimensions of the /// framebuffer, and the list of attachments to `Framebuffer::new()`. /// /// Just like all render pass objects implement the `RenderPassAbstract` trait, all framebuffer /// objects implement the `FramebufferAbstract` trait. This means that you can cast any /// `Arc<Framebuffer<..>>` into an `Arc<FramebufferAbstract + Send + Sync>` for easier storage. /// /// ## With a generic list of attachments /// /// The list of attachments passed to `Framebuffer::new()` can be of various types, but one of the /// possibilities is to pass an object of type `Vec<Arc<ImageView + Send + Sync>>`. /// /// > **Note**: If you access a render pass object through the `RenderPassAbstract` trait, passing /// > a `Vec<Arc<ImageView + Send + Sync>>` is the only possible method. /// /// The framebuffer constructor will perform various checks to make sure that the number of images /// is correct and that each image can be used with this render pass. /// /// ```ignore // FIXME: unignore /// # use std::sync::Arc; /// # use vulkano::framebuffer::RenderPassAbstract; /// use vulkano::framebuffer::Framebuffer; /// /// # let render_pass: Arc<RenderPassAbstract + Send + Sync> = return; /// # let my_image: Arc<vulkano::image::ImageViewAccess> = return; /// // let render_pass: Arc<RenderPassAbstract + Send + Sync> =...; /// let framebuffer = Framebuffer::new(render_pass.clone(), [1024, 768, 1], /// vec![my_image.clone() as Arc<_>]).unwrap(); /// ``` /// /// ## With a specialized list of attachments /// /// The list of attachments can also be of any type `T`, as long as the render pass description /// implements the trait `RenderPassDescAttachmentsList<T>`. /// /// For example if you pass a render pass object that implements /// `RenderPassDescAttachmentsList<Foo>`, then you can pass a `Foo` as the list of attachments. /// /// > **Note**: The reason why `Vec<Arc<ImageView + Send + Sync>>` always works (see previous section) is that /// > render pass descriptions are required to always implement /// > `RenderPassDescAttachmentsList<Vec<Arc<ImageViewAccess + Send + Sync>>>`. /// /// When it comes to the `single_pass_renderpass!` and `ordered_passes_renderpass!` macros, you can /// build a list of attachments by calling `start_attachments()` on the render pass description, /// which will return an object that has a method whose name is the name of the first attachment /// and that can be used to specify it. This method will return another object that has a method /// whose name is the name of the second attachment, and so on. See the documentation of the macros /// for more details. TODO: put link here /// /// ```ignore // FIXME: unignore /// # #[macro_use] extern crate vulkano; /// # fn main() { /// # let device: std::sync::Arc<vulkano::device::Device> = return; /// use std::sync::Arc; /// use vulkano::format::Format; /// use vulkano::framebuffer::Framebuffer; /// /// let render_pass = single_pass_renderpass!(device.clone(), /// attachments: { /// // `foo` is a custom name we give to the first and only attachment. /// foo: { /// load: Clear, /// store: Store, /// format: Format::R8G8B8A8Unorm, /// samples: 1, /// } /// }, /// pass: { /// color: [foo], // Repeat the attachment name here. /// depth_stencil: {} /// } /// ).unwrap(); /// /// # let my_image: Arc<vulkano::image::ImageViewAccess> = return; /// let framebuffer = { /// let atch = render_pass.desc().start_attachments().foo(my_image.clone() as Arc<_>); /// Framebuffer::new(render_pass, [1024, 768, 1], atch).unwrap() /// }; /// # } /// ``` #[derive(Debug)] pub struct Framebuffer<Rp, A> { device: Arc<Device>, render_pass: Rp, framebuffer: vk::Framebuffer, dimensions: [u32; 3], resources: A, } impl<Rp> Framebuffer<Rp, Box<AttachmentsList + Send + Sync>> { /// Builds a new framebuffer. /// /// The `attachments` parameter depends on which render pass implementation is used. // TODO: allow ImageView pub fn new<Ia>(render_pass: Rp, dimensions: [u32; 3], attachments: Ia) -> Result<Arc<Framebuffer<Rp, Box<AttachmentsList + Send + Sync>>>, FramebufferCreationError> where Rp: RenderPassAbstract + RenderPassDescAttachmentsList<Ia> { let device = render_pass.device().clone(); // This function call is supposed to check whether the attachments are valid. // For more safety, we do some additional `debug_assert`s below. let attachments = try!(render_pass.check_attachments_list(attachments)); // TODO: add a debug assertion that checks whether the attachments are compatible // with the RP ; this should be checked by the RenderPassDescAttachmentsList trait // impl, but we can double-check in debug mode // Checking the dimensions against the limits. { let limits = render_pass.device().physical_device().limits(); let limits = [limits.max_framebuffer_width(), limits.max_framebuffer_height(), limits.max_framebuffer_layers()]; if dimensions[0] > limits[0] || dimensions[1] > limits[1] || dimensions[2] > limits[2] { return Err(FramebufferCreationError::DimensionsTooLarge); } } // Checking the dimensions against the attachments. if let Some(dims_constraints) = attachments.intersection_dimensions() { if dims_constraints[0] < dimensions[0] || dims_constraints[1] < dimensions[1] || dims_constraints[2] < dimensions[2] { return Err(FramebufferCreationError::AttachmentTooSmall); } } let ids: SmallVec<[vk::ImageView; 8]> = attachments.raw_image_view_handles().into_iter().map(|v| v.internal_object()).collect(); let framebuffer = unsafe { let vk = render_pass.device().pointers(); let infos = vk::FramebufferCreateInfo { sType: vk::STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, pNext: ptr::null(), flags: 0, // reserved renderPass: render_pass.inner().internal_object(), attachmentCount: ids.len() as u32, pAttachments: ids.as_ptr(), width: dimensions[0], height: dimensions[1], layers: dimensions[2], }; let mut output = mem::uninitialized(); try!(check_errors(vk.CreateFramebuffer(device.internal_object(), &infos, ptr::null(), &mut output))); output }; Ok(Arc::new(Framebuffer { device: device, render_pass: render_pass, framebuffer: framebuffer, dimensions: dimensions, resources: attachments, })) } } impl<Rp, A> Framebuffer<Rp, A> { /// Returns the width, height and layers of this framebuffer. #[inline] pub fn dimensions(&self) -> [u32; 3] { self.dimensions } /// Returns the width of the framebuffer in pixels. #[inline] pub fn width(&self) -> u32 { self.dimensions[0] } /// Returns the height of the framebuffer in pixels. #[inline] pub fn height(&self) -> u32 { self.dimensions[1] } /// Returns the number of layers (or depth) of the framebuffer. #[inline] pub fn layers(&self) -> u32 { self.dimensions[2] } /// Returns the device that was used to create this framebuffer. #[inline] pub fn device(&self) -> &Arc<Device> { &self.device } /// Returns the renderpass that was used to create this framebuffer. #[inline] pub fn render_pass(&self) -> &Rp { &self.render_pass } } unsafe impl<Rp, A> FramebufferAbstract for Framebuffer<Rp, A> where Rp: RenderPassAbstract, A: AttachmentsList { #[inline] fn inner(&self) -> FramebufferSys { FramebufferSys(self.framebuffer, PhantomData) } #[inline] fn dimensions(&self) -> [u32; 3] { self.dimensions } #[inline] fn attachments(&self) -> Vec<&ImageViewAccess> { self.resources.as_image_view_accesses() } } unsafe impl<Rp, A> RenderPassDesc for Framebuffer<Rp, A> where Rp: RenderPassDesc { #[inline] fn num_attachments(&self) -> usize { self.render_pass.num_attachments() } #[inline] fn attachment_desc(&self, num: usize) -> Option<LayoutAttachmentDescription> { self.render_pass.attachment_desc(num) } #[inline] fn num_subpasses(&self) -> usize { self.render_pass.num_subpasses() } #[inline] fn subpass_desc(&self, num: usize) -> Option<LayoutPassDescription> { self.render_pass.subpass_desc(num) } #[inline] fn num_dependencies(&self) -> usize { self.render_pass.num_dependencies() } #[inline] fn dependency_desc(&self, num: usize) -> Option<LayoutPassDependencyDescription> { self.render_pass.dependency_desc(num)
where Rp: RenderPassDescAttachmentsList<At> { #[inline] fn check_attachments_list(&self, atch: At) -> Result<Box<AttachmentsList + Send + Sync>, FramebufferCreationError> { self.render_pass.check_attachments_list(atch) } } unsafe impl<C, Rp, A> RenderPassDescClearValues<C> for Framebuffer<Rp, A> where Rp: RenderPassDescClearValues<C> { #[inline] fn convert_clear_values(&self, vals: C) -> Box<Iterator<Item = ClearValue>> { self.render_pass.convert_clear_values(vals) } } unsafe impl<Rp, A> RenderPassAbstract for Framebuffer<Rp, A> where Rp: RenderPassAbstract { #[inline] fn inner(&self) -> RenderPassSys { self.render_pass.inner() } } unsafe impl<Rp, A> DeviceOwned for Framebuffer<Rp, A> { #[inline] fn device(&self) -> &Arc<Device> { &self.device } } impl<Rp, A> Drop for Framebuffer<Rp, A> { #[inline] fn drop(&mut self) { unsafe { let vk = self.device.pointers(); vk.DestroyFramebuffer(self.device.internal_object(), self.framebuffer, ptr::null()); } } } /// Opaque object that represents the internals of a framebuffer. #[derive(Debug, Copy, Clone)] pub struct FramebufferSys<'a>(vk::Framebuffer, PhantomData<&'a ()>); unsafe impl<'a> VulkanObject for FramebufferSys<'a> { type Object = vk::Framebuffer; #[inline] fn internal_object(&self) -> vk::Framebuffer { self.0 } } /// Error that can happen when creating a framebuffer object. #[derive(Copy, Clone, Debug)] pub enum FramebufferCreationError { /// Out of memory. OomError(OomError), /// The requested dimensions exceed the device's limits. DimensionsTooLarge, /// One of the attachments is too small compared to the requested framebuffer dimensions. AttachmentTooSmall, /// The number of attachments doesn't match the number expected by the render pass. AttachmentsCountMismatch { /// Expected number of attachments. expected: usize, /// Number of attachments that were given. obtained: usize, }, /// One of the images cannot be used as the requested attachment. IncompatibleAttachment { /// Zero-based id of the attachment. attachment_num: usize, /// The problem. error: IncompatibleRenderPassAttachmentError, }, } impl From<OomError> for FramebufferCreationError { #[inline] fn from(err: OomError) -> FramebufferCreationError { FramebufferCreationError::OomError(err) } } impl error::Error for FramebufferCreationError { #[inline] fn description(&self) -> &str { match *self { FramebufferCreationError::OomError(_) => "no memory available", FramebufferCreationError::DimensionsTooLarge => "the dimensions of the framebuffer \ are too large", FramebufferCreationError::AttachmentTooSmall => { "one of the attachments is too small compared to the requested framebuffer \ dimensions" }, FramebufferCreationError::AttachmentsCountMismatch {.. } => { "the number of attachments doesn't match the number expected by the render pass" }, FramebufferCreationError::IncompatibleAttachment {.. } => { "one of the images cannot be used as the requested attachment" }, } } #[inline] fn cause(&self) -> Option<&error::Error> { match *self { FramebufferCreationError::OomError(ref err) => Some(err), FramebufferCreationError::IncompatibleAttachment { ref error,.. } => Some(error), _ => None, } } } impl fmt::Display for FramebufferCreationError { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "{}", error::Error::description(self)) } } impl From<Error> for FramebufferCreationError { #[inline] fn from(err: Error) -> FramebufferCreationError { FramebufferCreationError::from(OomError::from(err)) } } /* FIXME: restore #[cfg(test)] mod tests { use format::R8G8B8A8Unorm; use framebuffer::Framebuffer; use framebuffer::FramebufferCreationError; use image::attachment::AttachmentImage; #[test] fn simple_create() { let (device, _) = gfx_dev_and_queue!(); let render_pass = single_pass_renderpass! { attachments: { color: { load: Clear, store: DontCare, format: R8G8B8A8Unorm, } }, pass: { color: [color], depth_stencil: {} } }.unwrap(); let image = AttachmentImage::new(&device, [1024, 768], R8G8B8A8Unorm).unwrap(); let _ = Framebuffer::new(render_pass, [1024, 768, 1], example::AList { color: image.clone() }).unwrap(); } #[test] fn framebuffer_too_large() { let (device, _) = gfx_dev_and_queue!(); let render_pass = example::CustomRenderPass::new(&device, &example::Formats { color: (R8G8B8A8Unorm, 1) }).unwrap(); let image = AttachmentImage::new(&device, [1024, 768], R8G8B8A8Unorm).unwrap(); let alist = example::AList { color: image.clone() }; match Framebuffer::new(render_pass, [0xffffffff, 0xffffffff, 0xffffffff], alist) { Err(FramebufferCreationError::DimensionsTooLarge) => (), _ => panic!() } } #[test] fn attachment_too_small() { let (device, _) = gfx_dev_and_queue!(); let render_pass = example::CustomRenderPass::new(&device, &example::Formats { color: (R8G8B8A8Unorm, 1) }).unwrap(); let image = AttachmentImage::new(&device, [512, 512], R8G8B8A8Unorm).unwrap(); let alist = example::AList { color: image.clone() }; match Framebuffer::new(render_pass, [600, 600, 1], alist) { Err(FramebufferCreationError::AttachmentTooSmall) => (), _ => panic!() } } }*/
} } unsafe impl<At, Rp, A> RenderPassDescAttachmentsList<At> for Framebuffer<Rp, A>
random_line_split
framebuffer.rs
// Copyright (c) 2016 The vulkano developers // 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. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::error; use std::fmt; use std::marker::PhantomData; use std::mem; use std::ptr; use std::sync::Arc; use smallvec::SmallVec; use device::Device; use device::DeviceOwned; use format::ClearValue; use framebuffer::AttachmentsList; use framebuffer::FramebufferAbstract; use framebuffer::IncompatibleRenderPassAttachmentError; use framebuffer::LayoutAttachmentDescription; use framebuffer::LayoutPassDependencyDescription; use framebuffer::LayoutPassDescription; use framebuffer::RenderPassAbstract; use framebuffer::RenderPassDescClearValues; use framebuffer::RenderPassDescAttachmentsList; use framebuffer::RenderPassDesc; use framebuffer::RenderPassSys; use image::ImageViewAccess; use Error; use OomError; use VulkanObject; use VulkanPointers; use check_errors; use vk; /// Contains the list of images attached to a render pass. /// /// Creating a framebuffer is done by passing the render pass object, the dimensions of the /// framebuffer, and the list of attachments to `Framebuffer::new()`. /// /// Just like all render pass objects implement the `RenderPassAbstract` trait, all framebuffer /// objects implement the `FramebufferAbstract` trait. This means that you can cast any /// `Arc<Framebuffer<..>>` into an `Arc<FramebufferAbstract + Send + Sync>` for easier storage. /// /// ## With a generic list of attachments /// /// The list of attachments passed to `Framebuffer::new()` can be of various types, but one of the /// possibilities is to pass an object of type `Vec<Arc<ImageView + Send + Sync>>`. /// /// > **Note**: If you access a render pass object through the `RenderPassAbstract` trait, passing /// > a `Vec<Arc<ImageView + Send + Sync>>` is the only possible method. /// /// The framebuffer constructor will perform various checks to make sure that the number of images /// is correct and that each image can be used with this render pass. /// /// ```ignore // FIXME: unignore /// # use std::sync::Arc; /// # use vulkano::framebuffer::RenderPassAbstract; /// use vulkano::framebuffer::Framebuffer; /// /// # let render_pass: Arc<RenderPassAbstract + Send + Sync> = return; /// # let my_image: Arc<vulkano::image::ImageViewAccess> = return; /// // let render_pass: Arc<RenderPassAbstract + Send + Sync> =...; /// let framebuffer = Framebuffer::new(render_pass.clone(), [1024, 768, 1], /// vec![my_image.clone() as Arc<_>]).unwrap(); /// ``` /// /// ## With a specialized list of attachments /// /// The list of attachments can also be of any type `T`, as long as the render pass description /// implements the trait `RenderPassDescAttachmentsList<T>`. /// /// For example if you pass a render pass object that implements /// `RenderPassDescAttachmentsList<Foo>`, then you can pass a `Foo` as the list of attachments. /// /// > **Note**: The reason why `Vec<Arc<ImageView + Send + Sync>>` always works (see previous section) is that /// > render pass descriptions are required to always implement /// > `RenderPassDescAttachmentsList<Vec<Arc<ImageViewAccess + Send + Sync>>>`. /// /// When it comes to the `single_pass_renderpass!` and `ordered_passes_renderpass!` macros, you can /// build a list of attachments by calling `start_attachments()` on the render pass description, /// which will return an object that has a method whose name is the name of the first attachment /// and that can be used to specify it. This method will return another object that has a method /// whose name is the name of the second attachment, and so on. See the documentation of the macros /// for more details. TODO: put link here /// /// ```ignore // FIXME: unignore /// # #[macro_use] extern crate vulkano; /// # fn main() { /// # let device: std::sync::Arc<vulkano::device::Device> = return; /// use std::sync::Arc; /// use vulkano::format::Format; /// use vulkano::framebuffer::Framebuffer; /// /// let render_pass = single_pass_renderpass!(device.clone(), /// attachments: { /// // `foo` is a custom name we give to the first and only attachment. /// foo: { /// load: Clear, /// store: Store, /// format: Format::R8G8B8A8Unorm, /// samples: 1, /// } /// }, /// pass: { /// color: [foo], // Repeat the attachment name here. /// depth_stencil: {} /// } /// ).unwrap(); /// /// # let my_image: Arc<vulkano::image::ImageViewAccess> = return; /// let framebuffer = { /// let atch = render_pass.desc().start_attachments().foo(my_image.clone() as Arc<_>); /// Framebuffer::new(render_pass, [1024, 768, 1], atch).unwrap() /// }; /// # } /// ``` #[derive(Debug)] pub struct Framebuffer<Rp, A> { device: Arc<Device>, render_pass: Rp, framebuffer: vk::Framebuffer, dimensions: [u32; 3], resources: A, } impl<Rp> Framebuffer<Rp, Box<AttachmentsList + Send + Sync>> { /// Builds a new framebuffer. /// /// The `attachments` parameter depends on which render pass implementation is used. // TODO: allow ImageView pub fn
<Ia>(render_pass: Rp, dimensions: [u32; 3], attachments: Ia) -> Result<Arc<Framebuffer<Rp, Box<AttachmentsList + Send + Sync>>>, FramebufferCreationError> where Rp: RenderPassAbstract + RenderPassDescAttachmentsList<Ia> { let device = render_pass.device().clone(); // This function call is supposed to check whether the attachments are valid. // For more safety, we do some additional `debug_assert`s below. let attachments = try!(render_pass.check_attachments_list(attachments)); // TODO: add a debug assertion that checks whether the attachments are compatible // with the RP ; this should be checked by the RenderPassDescAttachmentsList trait // impl, but we can double-check in debug mode // Checking the dimensions against the limits. { let limits = render_pass.device().physical_device().limits(); let limits = [limits.max_framebuffer_width(), limits.max_framebuffer_height(), limits.max_framebuffer_layers()]; if dimensions[0] > limits[0] || dimensions[1] > limits[1] || dimensions[2] > limits[2] { return Err(FramebufferCreationError::DimensionsTooLarge); } } // Checking the dimensions against the attachments. if let Some(dims_constraints) = attachments.intersection_dimensions() { if dims_constraints[0] < dimensions[0] || dims_constraints[1] < dimensions[1] || dims_constraints[2] < dimensions[2] { return Err(FramebufferCreationError::AttachmentTooSmall); } } let ids: SmallVec<[vk::ImageView; 8]> = attachments.raw_image_view_handles().into_iter().map(|v| v.internal_object()).collect(); let framebuffer = unsafe { let vk = render_pass.device().pointers(); let infos = vk::FramebufferCreateInfo { sType: vk::STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, pNext: ptr::null(), flags: 0, // reserved renderPass: render_pass.inner().internal_object(), attachmentCount: ids.len() as u32, pAttachments: ids.as_ptr(), width: dimensions[0], height: dimensions[1], layers: dimensions[2], }; let mut output = mem::uninitialized(); try!(check_errors(vk.CreateFramebuffer(device.internal_object(), &infos, ptr::null(), &mut output))); output }; Ok(Arc::new(Framebuffer { device: device, render_pass: render_pass, framebuffer: framebuffer, dimensions: dimensions, resources: attachments, })) } } impl<Rp, A> Framebuffer<Rp, A> { /// Returns the width, height and layers of this framebuffer. #[inline] pub fn dimensions(&self) -> [u32; 3] { self.dimensions } /// Returns the width of the framebuffer in pixels. #[inline] pub fn width(&self) -> u32 { self.dimensions[0] } /// Returns the height of the framebuffer in pixels. #[inline] pub fn height(&self) -> u32 { self.dimensions[1] } /// Returns the number of layers (or depth) of the framebuffer. #[inline] pub fn layers(&self) -> u32 { self.dimensions[2] } /// Returns the device that was used to create this framebuffer. #[inline] pub fn device(&self) -> &Arc<Device> { &self.device } /// Returns the renderpass that was used to create this framebuffer. #[inline] pub fn render_pass(&self) -> &Rp { &self.render_pass } } unsafe impl<Rp, A> FramebufferAbstract for Framebuffer<Rp, A> where Rp: RenderPassAbstract, A: AttachmentsList { #[inline] fn inner(&self) -> FramebufferSys { FramebufferSys(self.framebuffer, PhantomData) } #[inline] fn dimensions(&self) -> [u32; 3] { self.dimensions } #[inline] fn attachments(&self) -> Vec<&ImageViewAccess> { self.resources.as_image_view_accesses() } } unsafe impl<Rp, A> RenderPassDesc for Framebuffer<Rp, A> where Rp: RenderPassDesc { #[inline] fn num_attachments(&self) -> usize { self.render_pass.num_attachments() } #[inline] fn attachment_desc(&self, num: usize) -> Option<LayoutAttachmentDescription> { self.render_pass.attachment_desc(num) } #[inline] fn num_subpasses(&self) -> usize { self.render_pass.num_subpasses() } #[inline] fn subpass_desc(&self, num: usize) -> Option<LayoutPassDescription> { self.render_pass.subpass_desc(num) } #[inline] fn num_dependencies(&self) -> usize { self.render_pass.num_dependencies() } #[inline] fn dependency_desc(&self, num: usize) -> Option<LayoutPassDependencyDescription> { self.render_pass.dependency_desc(num) } } unsafe impl<At, Rp, A> RenderPassDescAttachmentsList<At> for Framebuffer<Rp, A> where Rp: RenderPassDescAttachmentsList<At> { #[inline] fn check_attachments_list(&self, atch: At) -> Result<Box<AttachmentsList + Send + Sync>, FramebufferCreationError> { self.render_pass.check_attachments_list(atch) } } unsafe impl<C, Rp, A> RenderPassDescClearValues<C> for Framebuffer<Rp, A> where Rp: RenderPassDescClearValues<C> { #[inline] fn convert_clear_values(&self, vals: C) -> Box<Iterator<Item = ClearValue>> { self.render_pass.convert_clear_values(vals) } } unsafe impl<Rp, A> RenderPassAbstract for Framebuffer<Rp, A> where Rp: RenderPassAbstract { #[inline] fn inner(&self) -> RenderPassSys { self.render_pass.inner() } } unsafe impl<Rp, A> DeviceOwned for Framebuffer<Rp, A> { #[inline] fn device(&self) -> &Arc<Device> { &self.device } } impl<Rp, A> Drop for Framebuffer<Rp, A> { #[inline] fn drop(&mut self) { unsafe { let vk = self.device.pointers(); vk.DestroyFramebuffer(self.device.internal_object(), self.framebuffer, ptr::null()); } } } /// Opaque object that represents the internals of a framebuffer. #[derive(Debug, Copy, Clone)] pub struct FramebufferSys<'a>(vk::Framebuffer, PhantomData<&'a ()>); unsafe impl<'a> VulkanObject for FramebufferSys<'a> { type Object = vk::Framebuffer; #[inline] fn internal_object(&self) -> vk::Framebuffer { self.0 } } /// Error that can happen when creating a framebuffer object. #[derive(Copy, Clone, Debug)] pub enum FramebufferCreationError { /// Out of memory. OomError(OomError), /// The requested dimensions exceed the device's limits. DimensionsTooLarge, /// One of the attachments is too small compared to the requested framebuffer dimensions. AttachmentTooSmall, /// The number of attachments doesn't match the number expected by the render pass. AttachmentsCountMismatch { /// Expected number of attachments. expected: usize, /// Number of attachments that were given. obtained: usize, }, /// One of the images cannot be used as the requested attachment. IncompatibleAttachment { /// Zero-based id of the attachment. attachment_num: usize, /// The problem. error: IncompatibleRenderPassAttachmentError, }, } impl From<OomError> for FramebufferCreationError { #[inline] fn from(err: OomError) -> FramebufferCreationError { FramebufferCreationError::OomError(err) } } impl error::Error for FramebufferCreationError { #[inline] fn description(&self) -> &str { match *self { FramebufferCreationError::OomError(_) => "no memory available", FramebufferCreationError::DimensionsTooLarge => "the dimensions of the framebuffer \ are too large", FramebufferCreationError::AttachmentTooSmall => { "one of the attachments is too small compared to the requested framebuffer \ dimensions" }, FramebufferCreationError::AttachmentsCountMismatch {.. } => { "the number of attachments doesn't match the number expected by the render pass" }, FramebufferCreationError::IncompatibleAttachment {.. } => { "one of the images cannot be used as the requested attachment" }, } } #[inline] fn cause(&self) -> Option<&error::Error> { match *self { FramebufferCreationError::OomError(ref err) => Some(err), FramebufferCreationError::IncompatibleAttachment { ref error,.. } => Some(error), _ => None, } } } impl fmt::Display for FramebufferCreationError { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "{}", error::Error::description(self)) } } impl From<Error> for FramebufferCreationError { #[inline] fn from(err: Error) -> FramebufferCreationError { FramebufferCreationError::from(OomError::from(err)) } } /* FIXME: restore #[cfg(test)] mod tests { use format::R8G8B8A8Unorm; use framebuffer::Framebuffer; use framebuffer::FramebufferCreationError; use image::attachment::AttachmentImage; #[test] fn simple_create() { let (device, _) = gfx_dev_and_queue!(); let render_pass = single_pass_renderpass! { attachments: { color: { load: Clear, store: DontCare, format: R8G8B8A8Unorm, } }, pass: { color: [color], depth_stencil: {} } }.unwrap(); let image = AttachmentImage::new(&device, [1024, 768], R8G8B8A8Unorm).unwrap(); let _ = Framebuffer::new(render_pass, [1024, 768, 1], example::AList { color: image.clone() }).unwrap(); } #[test] fn framebuffer_too_large() { let (device, _) = gfx_dev_and_queue!(); let render_pass = example::CustomRenderPass::new(&device, &example::Formats { color: (R8G8B8A8Unorm, 1) }).unwrap(); let image = AttachmentImage::new(&device, [1024, 768], R8G8B8A8Unorm).unwrap(); let alist = example::AList { color: image.clone() }; match Framebuffer::new(render_pass, [0xffffffff, 0xffffffff, 0xffffffff], alist) { Err(FramebufferCreationError::DimensionsTooLarge) => (), _ => panic!() } } #[test] fn attachment_too_small() { let (device, _) = gfx_dev_and_queue!(); let render_pass = example::CustomRenderPass::new(&device, &example::Formats { color: (R8G8B8A8Unorm, 1) }).unwrap(); let image = AttachmentImage::new(&device, [512, 512], R8G8B8A8Unorm).unwrap(); let alist = example::AList { color: image.clone() }; match Framebuffer::new(render_pass, [600, 600, 1], alist) { Err(FramebufferCreationError::AttachmentTooSmall) => (), _ => panic!() } } }*/
new
identifier_name
framebuffer.rs
// Copyright (c) 2016 The vulkano developers // 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. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::error; use std::fmt; use std::marker::PhantomData; use std::mem; use std::ptr; use std::sync::Arc; use smallvec::SmallVec; use device::Device; use device::DeviceOwned; use format::ClearValue; use framebuffer::AttachmentsList; use framebuffer::FramebufferAbstract; use framebuffer::IncompatibleRenderPassAttachmentError; use framebuffer::LayoutAttachmentDescription; use framebuffer::LayoutPassDependencyDescription; use framebuffer::LayoutPassDescription; use framebuffer::RenderPassAbstract; use framebuffer::RenderPassDescClearValues; use framebuffer::RenderPassDescAttachmentsList; use framebuffer::RenderPassDesc; use framebuffer::RenderPassSys; use image::ImageViewAccess; use Error; use OomError; use VulkanObject; use VulkanPointers; use check_errors; use vk; /// Contains the list of images attached to a render pass. /// /// Creating a framebuffer is done by passing the render pass object, the dimensions of the /// framebuffer, and the list of attachments to `Framebuffer::new()`. /// /// Just like all render pass objects implement the `RenderPassAbstract` trait, all framebuffer /// objects implement the `FramebufferAbstract` trait. This means that you can cast any /// `Arc<Framebuffer<..>>` into an `Arc<FramebufferAbstract + Send + Sync>` for easier storage. /// /// ## With a generic list of attachments /// /// The list of attachments passed to `Framebuffer::new()` can be of various types, but one of the /// possibilities is to pass an object of type `Vec<Arc<ImageView + Send + Sync>>`. /// /// > **Note**: If you access a render pass object through the `RenderPassAbstract` trait, passing /// > a `Vec<Arc<ImageView + Send + Sync>>` is the only possible method. /// /// The framebuffer constructor will perform various checks to make sure that the number of images /// is correct and that each image can be used with this render pass. /// /// ```ignore // FIXME: unignore /// # use std::sync::Arc; /// # use vulkano::framebuffer::RenderPassAbstract; /// use vulkano::framebuffer::Framebuffer; /// /// # let render_pass: Arc<RenderPassAbstract + Send + Sync> = return; /// # let my_image: Arc<vulkano::image::ImageViewAccess> = return; /// // let render_pass: Arc<RenderPassAbstract + Send + Sync> =...; /// let framebuffer = Framebuffer::new(render_pass.clone(), [1024, 768, 1], /// vec![my_image.clone() as Arc<_>]).unwrap(); /// ``` /// /// ## With a specialized list of attachments /// /// The list of attachments can also be of any type `T`, as long as the render pass description /// implements the trait `RenderPassDescAttachmentsList<T>`. /// /// For example if you pass a render pass object that implements /// `RenderPassDescAttachmentsList<Foo>`, then you can pass a `Foo` as the list of attachments. /// /// > **Note**: The reason why `Vec<Arc<ImageView + Send + Sync>>` always works (see previous section) is that /// > render pass descriptions are required to always implement /// > `RenderPassDescAttachmentsList<Vec<Arc<ImageViewAccess + Send + Sync>>>`. /// /// When it comes to the `single_pass_renderpass!` and `ordered_passes_renderpass!` macros, you can /// build a list of attachments by calling `start_attachments()` on the render pass description, /// which will return an object that has a method whose name is the name of the first attachment /// and that can be used to specify it. This method will return another object that has a method /// whose name is the name of the second attachment, and so on. See the documentation of the macros /// for more details. TODO: put link here /// /// ```ignore // FIXME: unignore /// # #[macro_use] extern crate vulkano; /// # fn main() { /// # let device: std::sync::Arc<vulkano::device::Device> = return; /// use std::sync::Arc; /// use vulkano::format::Format; /// use vulkano::framebuffer::Framebuffer; /// /// let render_pass = single_pass_renderpass!(device.clone(), /// attachments: { /// // `foo` is a custom name we give to the first and only attachment. /// foo: { /// load: Clear, /// store: Store, /// format: Format::R8G8B8A8Unorm, /// samples: 1, /// } /// }, /// pass: { /// color: [foo], // Repeat the attachment name here. /// depth_stencil: {} /// } /// ).unwrap(); /// /// # let my_image: Arc<vulkano::image::ImageViewAccess> = return; /// let framebuffer = { /// let atch = render_pass.desc().start_attachments().foo(my_image.clone() as Arc<_>); /// Framebuffer::new(render_pass, [1024, 768, 1], atch).unwrap() /// }; /// # } /// ``` #[derive(Debug)] pub struct Framebuffer<Rp, A> { device: Arc<Device>, render_pass: Rp, framebuffer: vk::Framebuffer, dimensions: [u32; 3], resources: A, } impl<Rp> Framebuffer<Rp, Box<AttachmentsList + Send + Sync>> { /// Builds a new framebuffer. /// /// The `attachments` parameter depends on which render pass implementation is used. // TODO: allow ImageView pub fn new<Ia>(render_pass: Rp, dimensions: [u32; 3], attachments: Ia) -> Result<Arc<Framebuffer<Rp, Box<AttachmentsList + Send + Sync>>>, FramebufferCreationError> where Rp: RenderPassAbstract + RenderPassDescAttachmentsList<Ia> { let device = render_pass.device().clone(); // This function call is supposed to check whether the attachments are valid. // For more safety, we do some additional `debug_assert`s below. let attachments = try!(render_pass.check_attachments_list(attachments)); // TODO: add a debug assertion that checks whether the attachments are compatible // with the RP ; this should be checked by the RenderPassDescAttachmentsList trait // impl, but we can double-check in debug mode // Checking the dimensions against the limits. { let limits = render_pass.device().physical_device().limits(); let limits = [limits.max_framebuffer_width(), limits.max_framebuffer_height(), limits.max_framebuffer_layers()]; if dimensions[0] > limits[0] || dimensions[1] > limits[1] || dimensions[2] > limits[2]
} // Checking the dimensions against the attachments. if let Some(dims_constraints) = attachments.intersection_dimensions() { if dims_constraints[0] < dimensions[0] || dims_constraints[1] < dimensions[1] || dims_constraints[2] < dimensions[2] { return Err(FramebufferCreationError::AttachmentTooSmall); } } let ids: SmallVec<[vk::ImageView; 8]> = attachments.raw_image_view_handles().into_iter().map(|v| v.internal_object()).collect(); let framebuffer = unsafe { let vk = render_pass.device().pointers(); let infos = vk::FramebufferCreateInfo { sType: vk::STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, pNext: ptr::null(), flags: 0, // reserved renderPass: render_pass.inner().internal_object(), attachmentCount: ids.len() as u32, pAttachments: ids.as_ptr(), width: dimensions[0], height: dimensions[1], layers: dimensions[2], }; let mut output = mem::uninitialized(); try!(check_errors(vk.CreateFramebuffer(device.internal_object(), &infos, ptr::null(), &mut output))); output }; Ok(Arc::new(Framebuffer { device: device, render_pass: render_pass, framebuffer: framebuffer, dimensions: dimensions, resources: attachments, })) } } impl<Rp, A> Framebuffer<Rp, A> { /// Returns the width, height and layers of this framebuffer. #[inline] pub fn dimensions(&self) -> [u32; 3] { self.dimensions } /// Returns the width of the framebuffer in pixels. #[inline] pub fn width(&self) -> u32 { self.dimensions[0] } /// Returns the height of the framebuffer in pixels. #[inline] pub fn height(&self) -> u32 { self.dimensions[1] } /// Returns the number of layers (or depth) of the framebuffer. #[inline] pub fn layers(&self) -> u32 { self.dimensions[2] } /// Returns the device that was used to create this framebuffer. #[inline] pub fn device(&self) -> &Arc<Device> { &self.device } /// Returns the renderpass that was used to create this framebuffer. #[inline] pub fn render_pass(&self) -> &Rp { &self.render_pass } } unsafe impl<Rp, A> FramebufferAbstract for Framebuffer<Rp, A> where Rp: RenderPassAbstract, A: AttachmentsList { #[inline] fn inner(&self) -> FramebufferSys { FramebufferSys(self.framebuffer, PhantomData) } #[inline] fn dimensions(&self) -> [u32; 3] { self.dimensions } #[inline] fn attachments(&self) -> Vec<&ImageViewAccess> { self.resources.as_image_view_accesses() } } unsafe impl<Rp, A> RenderPassDesc for Framebuffer<Rp, A> where Rp: RenderPassDesc { #[inline] fn num_attachments(&self) -> usize { self.render_pass.num_attachments() } #[inline] fn attachment_desc(&self, num: usize) -> Option<LayoutAttachmentDescription> { self.render_pass.attachment_desc(num) } #[inline] fn num_subpasses(&self) -> usize { self.render_pass.num_subpasses() } #[inline] fn subpass_desc(&self, num: usize) -> Option<LayoutPassDescription> { self.render_pass.subpass_desc(num) } #[inline] fn num_dependencies(&self) -> usize { self.render_pass.num_dependencies() } #[inline] fn dependency_desc(&self, num: usize) -> Option<LayoutPassDependencyDescription> { self.render_pass.dependency_desc(num) } } unsafe impl<At, Rp, A> RenderPassDescAttachmentsList<At> for Framebuffer<Rp, A> where Rp: RenderPassDescAttachmentsList<At> { #[inline] fn check_attachments_list(&self, atch: At) -> Result<Box<AttachmentsList + Send + Sync>, FramebufferCreationError> { self.render_pass.check_attachments_list(atch) } } unsafe impl<C, Rp, A> RenderPassDescClearValues<C> for Framebuffer<Rp, A> where Rp: RenderPassDescClearValues<C> { #[inline] fn convert_clear_values(&self, vals: C) -> Box<Iterator<Item = ClearValue>> { self.render_pass.convert_clear_values(vals) } } unsafe impl<Rp, A> RenderPassAbstract for Framebuffer<Rp, A> where Rp: RenderPassAbstract { #[inline] fn inner(&self) -> RenderPassSys { self.render_pass.inner() } } unsafe impl<Rp, A> DeviceOwned for Framebuffer<Rp, A> { #[inline] fn device(&self) -> &Arc<Device> { &self.device } } impl<Rp, A> Drop for Framebuffer<Rp, A> { #[inline] fn drop(&mut self) { unsafe { let vk = self.device.pointers(); vk.DestroyFramebuffer(self.device.internal_object(), self.framebuffer, ptr::null()); } } } /// Opaque object that represents the internals of a framebuffer. #[derive(Debug, Copy, Clone)] pub struct FramebufferSys<'a>(vk::Framebuffer, PhantomData<&'a ()>); unsafe impl<'a> VulkanObject for FramebufferSys<'a> { type Object = vk::Framebuffer; #[inline] fn internal_object(&self) -> vk::Framebuffer { self.0 } } /// Error that can happen when creating a framebuffer object. #[derive(Copy, Clone, Debug)] pub enum FramebufferCreationError { /// Out of memory. OomError(OomError), /// The requested dimensions exceed the device's limits. DimensionsTooLarge, /// One of the attachments is too small compared to the requested framebuffer dimensions. AttachmentTooSmall, /// The number of attachments doesn't match the number expected by the render pass. AttachmentsCountMismatch { /// Expected number of attachments. expected: usize, /// Number of attachments that were given. obtained: usize, }, /// One of the images cannot be used as the requested attachment. IncompatibleAttachment { /// Zero-based id of the attachment. attachment_num: usize, /// The problem. error: IncompatibleRenderPassAttachmentError, }, } impl From<OomError> for FramebufferCreationError { #[inline] fn from(err: OomError) -> FramebufferCreationError { FramebufferCreationError::OomError(err) } } impl error::Error for FramebufferCreationError { #[inline] fn description(&self) -> &str { match *self { FramebufferCreationError::OomError(_) => "no memory available", FramebufferCreationError::DimensionsTooLarge => "the dimensions of the framebuffer \ are too large", FramebufferCreationError::AttachmentTooSmall => { "one of the attachments is too small compared to the requested framebuffer \ dimensions" }, FramebufferCreationError::AttachmentsCountMismatch {.. } => { "the number of attachments doesn't match the number expected by the render pass" }, FramebufferCreationError::IncompatibleAttachment {.. } => { "one of the images cannot be used as the requested attachment" }, } } #[inline] fn cause(&self) -> Option<&error::Error> { match *self { FramebufferCreationError::OomError(ref err) => Some(err), FramebufferCreationError::IncompatibleAttachment { ref error,.. } => Some(error), _ => None, } } } impl fmt::Display for FramebufferCreationError { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "{}", error::Error::description(self)) } } impl From<Error> for FramebufferCreationError { #[inline] fn from(err: Error) -> FramebufferCreationError { FramebufferCreationError::from(OomError::from(err)) } } /* FIXME: restore #[cfg(test)] mod tests { use format::R8G8B8A8Unorm; use framebuffer::Framebuffer; use framebuffer::FramebufferCreationError; use image::attachment::AttachmentImage; #[test] fn simple_create() { let (device, _) = gfx_dev_and_queue!(); let render_pass = single_pass_renderpass! { attachments: { color: { load: Clear, store: DontCare, format: R8G8B8A8Unorm, } }, pass: { color: [color], depth_stencil: {} } }.unwrap(); let image = AttachmentImage::new(&device, [1024, 768], R8G8B8A8Unorm).unwrap(); let _ = Framebuffer::new(render_pass, [1024, 768, 1], example::AList { color: image.clone() }).unwrap(); } #[test] fn framebuffer_too_large() { let (device, _) = gfx_dev_and_queue!(); let render_pass = example::CustomRenderPass::new(&device, &example::Formats { color: (R8G8B8A8Unorm, 1) }).unwrap(); let image = AttachmentImage::new(&device, [1024, 768], R8G8B8A8Unorm).unwrap(); let alist = example::AList { color: image.clone() }; match Framebuffer::new(render_pass, [0xffffffff, 0xffffffff, 0xffffffff], alist) { Err(FramebufferCreationError::DimensionsTooLarge) => (), _ => panic!() } } #[test] fn attachment_too_small() { let (device, _) = gfx_dev_and_queue!(); let render_pass = example::CustomRenderPass::new(&device, &example::Formats { color: (R8G8B8A8Unorm, 1) }).unwrap(); let image = AttachmentImage::new(&device, [512, 512], R8G8B8A8Unorm).unwrap(); let alist = example::AList { color: image.clone() }; match Framebuffer::new(render_pass, [600, 600, 1], alist) { Err(FramebufferCreationError::AttachmentTooSmall) => (), _ => panic!() } } }*/
{ return Err(FramebufferCreationError::DimensionsTooLarge); }
conditional_block
main.rs
!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_slice(slice: &[Matrix]) { println!("first element of the slice: \n{}", slice[0]); println!("the slice has {} elements.", slice.len()); } fn arrays_slices() { let x: [Matrix; 2] = [ Matrix(10.2f32, 2.1f32, 3.1f32, 4.5f32), Matrix(5.2f32, 6.1f32, 2.1f32, 8.5f32), ]; println!("Array occupies: {:?} bytes", mem::size_of_val(&x)); analyze_slice(&x[1..2]); } #[derive(Debug, Copy, Clone)] struct Person<'a> { name: &'a str, age: u8, } impl<'a> Person<'a> { fn changeName(&mut self, new_name: &'a str) -> &'a Person { self.name = new_name; self } } #[derive(Debug)] struct Point { x: f32, y: f32, } #[derive(Debug)] struct Triangle { top_left: Point, bottom_right: Point, } struct Unit; struct Pair(i32, i32); fn square(point: Point, val: f32) -> Triangle { Triangle { bottom_right: Point { x: point.x + val, y: point.y - val, }, top_left: point, } } fn struct_test() { let mut person = Person { name: "Peter", age: 30u8, }; let new_name = "Janez"; let changedPerson = person.changeName(new_name); println!("Person: {:?}", changedPerson); let point = Point { x: 20.2, y: 30.3 }; println!("Point: {:?}", point); let bottom_right = Point { x: 10.2,..point }; println!("bottom_right: {:?}", bottom_right); let top_left = Point { x: 2.2, y: 5.3 }; let triangle = Triangle { bottom_right: bottom_right, top_left: top_left, }; println!("{:?}", triangle); let Triangle { bottom_right: Point { x: x1, y: y1 }, top_left: Point { x: x2, y: y2 }, } = triangle; println!("x1: {}, y1: {}, x2: {}, y2:{}", x1, y1, x2, y2); println!("Area:{}", (x2 - x1) * (y2 - y1)); let unit = Unit; let pair = Pair(20, 30); println!("pair contains {:?} and {:?}", pair.0, pair.1); let Pair(x, y) = pair; println!("pair contains {:?} and {:?}", x, y); println!("{:?}", square(point, 20.2)); } enum WebEvent { PageLoad, PageUnload, KeyPress(char), Paste(String), Click { x: i64, y: i64 }, } use crate::WebEvent::*; impl WebEvent { fn run(&self, m: i32) -> String { match self { PageLoad => return format!("Page loaded in {} seconds.", m), PageUnload => format!("PageUnloaded"), KeyPress(c) => format!("KeyPressed: {}", c), Paste(s) => format!("Pasted: {}", s), Click { x, y } => format!("Clicked on position: {}, {}", x, y), } } } fn inspect(event: WebEvent) { match event { PageLoad => println!("PageLoaded"), PageUnload => println!("PageUnloaded"), KeyPress(c) => println!("KeyPressed: {}", c), Paste(s) => println!("Pasted: {}", s), Click { x, y } => println!("Clicked on position: {}, {}", x, y), } } enum Number_enum { Zero, One, Two, } // enum with explicit discriminator enum Color { Red = 0xff0000, Green = 0x00ff00, Blue = 0x0000ff, } fn test_enum() { let pressed = KeyPress('x'); // `to_owned()` creates an owned `String` from a string slice. let pasted = Paste("my text".to_owned()); let click = Click { x: 20, y: 80 }; let load = PageLoad; let unload = PageUnload; inspect(pressed); inspect(pasted); inspect(click); inspect(load); inspect(unload); let loadSec = WebEvent::PageLoad; println!("{}", &loadSec.run(20)); println!("zero is {}", Number_enum::Zero as i32); println!("one is {}", Number_enum::One as i32); println!("roses are #{:06x}", Color::Red as i32); println!("violets are #{:06x}", Color::Blue as i32); } fn test_var_bind() { let mut x = 2; { let x = "4"; } x = 4; } fn casting() { let decimal = 22.8832_f32; let integer = decimal as u8; println!("Integer: {}", integer); let character = integer as char; println!("character: {}", character); println!("1000 as a u16 is: {:b}", 1000 as u16); let num = 1000; println!("1000 as a u8 is : {:b}", num as u8); println!(" -1 as a u8 is : {:b}", (-1i8) as u8); println!("1000 mod 256 is : {:b}", 1000 % 256); // Unless it already fits, of course. println!(" 128 as a i16 is: {:b} ({})", 128 as i16, 128 as i16); // 128 as u8 -> 128, whose two's complement in eight bits is: let num: i16 = 128; println!(" 128 as a i8 is : {:b} ({})", num as i8, num as i8); println!("127={:b}", 127_i8); println!("-128={:b}", -128_i8); println!("255={:b}", 255_u8); println!("0={:b}", 0_u8); println!("255= {}", 127_u8 as i8); println!("0={:b}", 0_u8 as i8); let x = 1u8; let y = 2u32; let z = 3f32; // Unsuffixed literal, their types depend on how they are used let i = 1; let f = 1.0; // `size_of_val` returns the size of a variable in bytes println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); let elem = 5u8; // Create an empty vector (a growable array). let mut vec = Vec::new(); // At this point the compiler doesn't know the exact type of `vec`, it // just knows that it's a vector of something (`Vec<_>`). // Insert `elem` in the vector. vec.push(elem); // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec<u8>`) // TODO ^ Try commenting out the `vec.push(elem)` line println!("{:?}", vec); } use std::convert::From; use std::convert::Into; use std::convert::TryFrom; use std::convert::TryInto; #[derive(Debug)] struct Number { value: i32, } impl From<i32> for Number { fn from(item: i32) -> Self { Number { value: item } } } impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Number is: {}", self.value) } } #[derive(Debug, PartialEq)] struct EvenNumber(i32); impl TryFrom<i32> for EvenNumber { type Error = (); fn try_from(value: i32) -> Result<Self, Self::Error> { if value % 2 == 0 { Ok(EvenNumber(value)) } else { Err(()) } } } fn conversion() { let s = "Test"; let myString = String::from(s); let b = myString.into_boxed_str(); let ptr = b.as_ptr(); println!("b:{:?}", ptr); let ref_b = b.as_ref(); println!("s:{:?}", ref_b); let number = Number::from(34_i32); println!("{}", number); let n = 5; let num: i32 = n.into(); println!("My number is {:?}", num); assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8))); assert_eq!(EvenNumber::try_from(5), Err(())); println!("{:?}", EvenNumber::try_from(5)); let result: Result<EvenNumber, ()> = 8i32.try_into(); assert_eq!(result, Ok(EvenNumber(8))); let result: Result<EvenNumber, ()> = 5i32.try_into(); assert_eq!(result, Err(())); let parsed: i32 = "5".parse().unwrap(); let turbo_parsed = "10".parse::<i32>().unwrap(); let sum = parsed + turbo_parsed; println!("Sum: {:?}", sum); } fn expression() { let x0 = 2; let sum = { let x = 20_i8; let y = 12; x + y + x0 }; println!("Sum: {:?}", sum) } fn flowControl() { let mut count = 0; loop { count += 1; if count % 2 == 0 { continue; } println!("Count: {}", count); if count > 6 { break; } } let mut optional = Some(20); match optional { Some(i) => { println!("Number: {:?}", i); } _ => { println!("Not present"); } } if let Some(i) = Some(20) { println!("Number is indeed: {}", i); } while let Some(i) = optional { if i == 25
else { println!("`i` is `{:?}`. Try again.", i); optional = Some(i + 1); } } } fn isDivisibleBy(lhs: u32, rhs: u32) -> bool { if (rhs == 0) { return false; } lhs % rhs == 0 } impl Point { fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn new(x: f32, y: f32) -> Point { Point { x: x, y: y } } fn distance(&self, p: &Point) -> f32 { let dx = self.x - p.x; let dy: f32 = self.y - p.y; (dx * dy + dy + dy).sqrt() } fn translate(&mut self, dx: f32, dy: f32) { self.x += dx; self.y += dy; } } fn functions() { println!("isD: {:?}", isDivisibleBy(20, 4)); println!("isD: {:?}", isDivisibleBy(20, 3)); let mut point = Point::new(22.2, 32.3); let mut origin = Point::origin(); println!("Distance: {:?}", point.distance(&origin)); point.translate(3.0, -2.0); println!("Point: {:?}", point); println!("Distance: {:?}", point.distance(&origin)); let x = 20; let fun1 = |i: i32| -> i32 { i + 1 + x }; let fun2 = |i| i + 1 + x; let i = 1; println!("Inc1: {:?}", fun1(i)); println!("Inc2: {:?}", fun2(i)); let one = || 1; println!("One: {:?}", one()); let color = "Green"; let print = || println!("Color: {:?}", color); print(); let _reborow = &color; print(); let mut count = 0; let mut inc = || { count += 1; println!("Count: {:?}", count); }; inc(); inc(); let reborrow = &mut count; let movable = Box::new(3); let consume = || { println!("Movable: {:?}", movable); mem::drop(movable); }; consume(); let haystack = vec![1, 2, 3]; let contains = move |needle| haystack.contains(needle); println!("{}", contains(&1)); println!("{}", contains(&2)); } fn apply<F>(f: F) where F: FnOnce(), { f(); } fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32, { f(3) } fn call_me<F: Fn()>(f: F) { f(); } fn function() { println!("I am function"); } fn functions2() { let x = 30; println!("x: {:?}", x); let y = apply_to_3(|x| x + 20); println!("y: {:?}", y); let greeting = "Hello"; let mut farewel = "Goodby".to_owned(); let diary = || { println!("I said {}", greeting); farewel.push_str("!!!!!"); println!("Than I screemed {}", farewel); println!("Than I sleep"); mem::drop(farewel); }; apply(diary); let double = |x| 2 * x; println!("3 doubled: {}", apply_to_3(double)); let closure = || println!("I am closure"); call_me(function); call_me(closure); } fn create_fn() -> impl Fn() { let text = "Fn".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_mut() -> impl FnMut() { let text = "FnMut".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_once() -> impl FnOnce() { let text = "FnOnce".to_owned(); move || println!("This is a: {}", text) } fn functions3() { let x = create_fn(); x(); let mut y = create_fn_mut(); y(); let z = create_fn_once(); z(); let v1 = vec![1, 2, 3]; let v2 = vec![4, 5, 6]; println!("2 in v1: {}", v1.iter().any(|&x| x == 2)); println!("2 in v2: {}", v2.iter().any(|&x| x == 2)); let a1 = [1, 2, 3]; let a2 = [4, 5, 6]; println!("2 in v1: {}", a1.iter().any(|&x| x == 2)); println!("2 in v2: {}", a2.iter().any(|&x| x == 2)); let mut iter1 = v1.iter(); let mut into_iter = v2.into_iter(); println!("Find 2 in v1: {:?}", iter1.find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", into_iter.find(|&x| x == 2)); let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; println!("Find 2 in v1: {:?}", array1.iter().find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", array2.into_iter().find(|&&x| x == 2)); let index_of_first_even_number = array1.iter().position(|x| x % 2 == 0); println!( "index_of_first_even_number: {}", index_of_first_even_number.unwrap() ); } fn is_odd(n: u32) -> bool { n % 2 == 1 } fn foo() -> () { () } fn higherOrder() { let upper = 1000; let mut acc = 0; for n in 0.. { let n_squared = n * n; if n_squared > upper { break; } else if is_odd(n_squared) { acc += n_squared; } } println!("Sum1: {:?}", acc); let sum2 = (0..) .map(|n| n * n) .take_while(|&n_squared| n_squared < upper) .filter(|&n_squared| n_squared % 2 == 1) .fold(0, |acc, n_squared| acc + n_squared); println!("Sum2: {:?}", sum2); fn sum_odd_numbers(up_to: u32) -> u32 { let mut acc = 0; for i in 0..up_to { // Notice that the return type of this match expression must be u32 // because of the type of the "addition" variable. let addition: u32 = match i % 2 == 1 { // The "i" variable is of type u32, which is perfectly fine. true => i, // On the other hand, the "continue" expression does not return // u32, but it is still fine, because it never returns and therefore // does not violate the type requirements of the match expression. false => continue, }; acc += addition; } acc } println!( "Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9) ); } struct S; struct GenericVal<T>(T); impl GenericVal<i32> {} impl GenericVal<S> {} impl<T> GenericVal<T> {} struct Val { val: f64, } struct GenVal<T> { gen_val: T, } // impl of Val impl Val { fn value(&self) -> &f64 { &self.val } } // impl of GenVal for a generic type `T` impl<T> GenVal<T> { fn value(&self) -> &T { &self.gen_val } } fn generics() { let x = Val { val: 3.0 }; let y = GenVal { gen_val: 3i32 }; println!("{}, {}", x.value(), y.value()); } fn create_box() { let _box = Box::new(3i32); } struct ToDrop; impl Drop for ToDrop { fn drop(&mut self) { println!("ToDrop is being dropped"); } } fn destroy_box(c: Box<i32>) { println!("Destroying a box that contains {}", c); // `c` is destroyed and the memory freed } fn scoping() { /* create_box(); let _box2 = Box::new(5i32); { let _box3 = Box::new(4i32); } let x = ToDrop; { let y = ToDrop; }*/ let x = 5u32; let y = x; println!("x is {}, and y is {}", x, y); let a = Box::new(5i32); let mut b = a; *b = 30i32; //destroy_box(b); println!("{}", b); } fn ownership() { let a = Box::new(5i32); let mut b = a; *b = 4; println!("{}", b); } fn eat_box(boxed: Box<i32>) { println!("{}", boxed); } fn borrow(borrowed: &i32) { println!("{}", borrowed); } fn borrowing() { let boxed = Box::new(5_i32); let stacked = 6_i32; borrow(&boxed); borrow(&stacked); { let refTo: &i32 = &boxed; borrow(refTo); } eat_box(boxed); } #[derive(Clone, Copy)] struct Book { author: &'static str, title: &'static str, year: u32, } fn borrow_book(book: &Book) { println!("I immutably borrowed {} - {}", book.author, book.title); } fn new_edition(book: &mut Book) { book.year = 2014; println!("I mutably borrowed {} - {} edition", book.title, book.year); } fn mutability() { let immutable_book = Book { author: "Ivan Cankar", title: "Hlapci", year: 1910, }; let mut mutable_book = immutable_book; borrow_book(&immutable_book); borrow_book(&mutable_book); new_edition(&mut mutable_book); } struct Location { x: i32, y: i32, z: i32, } fn aliasing() { let mut location = Location { x: 0, y: 0, z: 0 }; let borrow1 = &location; let borrow2 = &location; println!("{} {}", location.x, borrow1.x); //let mut_borow = &mut location; println!( "Location has coordinates: ({}, {}, {})", borrow1.x, borrow2.y, location.z ); let mut_borow = &mut location; mut_borow.x = 10; mut_borow.y = 23; mut_borow.z = 29; let borrow3 = &location; } #[derive(PartialEq, PartialOrd)] struct Centimeters(f64); #[derive(Debug)] struct Inches(i32); impl Inches { fn to_centimeters(&self) -> Centimeters { let &Inches(inches) = self; Centimeters(inches as f64 * 2.54) } } struct Seconds(i32); fn deriveTest() { let one_second = Seconds(1); let foot = Inches(12); println!("One foot equals: {:?}", foot); let meter = Centimeters(100.0); let cmp = if foot.to_centimeters() < meter { "smaller" } else { "bigger" }; println!("One foot is {} than one meter.", cmp); } struct Sheep {} struct Cow {} trait Animal { fn noise(&self) -> &'static str; } impl Animal for Sheep { fn noise(&self) -> &'static str { "baaah" } } impl Animal for Cow { fn noise(&self) -> &'static str { "moooooo" } } fn random_animal(random_number: f64) -> Box<dyn Animal> { if random_number < 0.5 { Box::new(Sheep {}) } else { Box::new(Cow {}) } } fn dyReturn() { let random_number = 0.3444; let animal = random_animal(random_number); println!( "You've randomly chosen an animal, and it says {}", animal.noise() ); } use std::ops; struct Foo; struct Bar; #[derive(Debug)] struct FooBar; #[derive(Debug)] struct BarFoo; impl ops::Add<Bar> for Foo { type Output = FooBar; fn add(self, _rhs: Bar) -> FooBar { println!("> Foo.add(Bar) was called"); FooBar } } impl ops::Add<Foo> for Bar
{ println!("Number is: {}", i); optional = None; }
conditional_block
main.rs
println!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_slice(slice: &[Matrix]) { println!("first element of the slice: \n{}", slice[0]); println!("the slice has {} elements.", slice.len()); } fn arrays_slices() { let x: [Matrix; 2] = [ Matrix(10.2f32, 2.1f32, 3.1f32, 4.5f32), Matrix(5.2f32, 6.1f32, 2.1f32, 8.5f32), ]; println!("Array occupies: {:?} bytes", mem::size_of_val(&x)); analyze_slice(&x[1..2]); } #[derive(Debug, Copy, Clone)] struct Person<'a> { name: &'a str, age: u8, } impl<'a> Person<'a> { fn changeName(&mut self, new_name: &'a str) -> &'a Person { self.name = new_name; self } } #[derive(Debug)] struct Point { x: f32, y: f32, } #[derive(Debug)] struct Triangle { top_left: Point, bottom_right: Point, } struct Unit; struct Pair(i32, i32); fn square(point: Point, val: f32) -> Triangle { Triangle { bottom_right: Point { x: point.x + val, y: point.y - val, }, top_left: point, } } fn struct_test() { let mut person = Person { name: "Peter", age: 30u8, }; let new_name = "Janez"; let changedPerson = person.changeName(new_name); println!("Person: {:?}", changedPerson); let point = Point { x: 20.2, y: 30.3 }; println!("Point: {:?}", point); let bottom_right = Point { x: 10.2,..point }; println!("bottom_right: {:?}", bottom_right); let top_left = Point { x: 2.2, y: 5.3 }; let triangle = Triangle { bottom_right: bottom_right, top_left: top_left, }; println!("{:?}", triangle); let Triangle { bottom_right: Point { x: x1, y: y1 }, top_left: Point { x: x2, y: y2 }, } = triangle; println!("x1: {}, y1: {}, x2: {}, y2:{}", x1, y1, x2, y2); println!("Area:{}", (x2 - x1) * (y2 - y1)); let unit = Unit; let pair = Pair(20, 30); println!("pair contains {:?} and {:?}", pair.0, pair.1); let Pair(x, y) = pair; println!("pair contains {:?} and {:?}", x, y); println!("{:?}", square(point, 20.2)); } enum WebEvent { PageLoad, PageUnload, KeyPress(char), Paste(String), Click { x: i64, y: i64 }, } use crate::WebEvent::*; impl WebEvent { fn run(&self, m: i32) -> String { match self { PageLoad => return format!("Page loaded in {} seconds.", m), PageUnload => format!("PageUnloaded"), KeyPress(c) => format!("KeyPressed: {}", c), Paste(s) => format!("Pasted: {}", s), Click { x, y } => format!("Clicked on position: {}, {}", x, y), } } } fn inspect(event: WebEvent) { match event { PageLoad => println!("PageLoaded"), PageUnload => println!("PageUnloaded"), KeyPress(c) => println!("KeyPressed: {}", c), Paste(s) => println!("Pasted: {}", s), Click { x, y } => println!("Clicked on position: {}, {}", x, y), } } enum Number_enum { Zero, One, Two, } // enum with explicit discriminator enum Color { Red = 0xff0000, Green = 0x00ff00, Blue = 0x0000ff, } fn test_enum() { let pressed = KeyPress('x'); // `to_owned()` creates an owned `String` from a string slice. let pasted = Paste("my text".to_owned()); let click = Click { x: 20, y: 80 }; let load = PageLoad; let unload = PageUnload; inspect(pressed); inspect(pasted); inspect(click); inspect(load); inspect(unload); let loadSec = WebEvent::PageLoad; println!("{}", &loadSec.run(20)); println!("zero is {}", Number_enum::Zero as i32); println!("one is {}", Number_enum::One as i32); println!("roses are #{:06x}", Color::Red as i32); println!("violets are #{:06x}", Color::Blue as i32); } fn test_var_bind() { let mut x = 2; { let x = "4"; } x = 4; } fn casting() { let decimal = 22.8832_f32; let integer = decimal as u8; println!("Integer: {}", integer); let character = integer as char; println!("character: {}", character); println!("1000 as a u16 is: {:b}", 1000 as u16); let num = 1000; println!("1000 as a u8 is : {:b}", num as u8); println!(" -1 as a u8 is : {:b}", (-1i8) as u8); println!("1000 mod 256 is : {:b}", 1000 % 256); // Unless it already fits, of course. println!(" 128 as a i16 is: {:b} ({})", 128 as i16, 128 as i16); // 128 as u8 -> 128, whose two's complement in eight bits is: let num: i16 = 128; println!(" 128 as a i8 is : {:b} ({})", num as i8, num as i8); println!("127={:b}", 127_i8); println!("-128={:b}", -128_i8); println!("255={:b}", 255_u8); println!("0={:b}", 0_u8); println!("255= {}", 127_u8 as i8); println!("0={:b}", 0_u8 as i8); let x = 1u8; let y = 2u32; let z = 3f32; // Unsuffixed literal, their types depend on how they are used let i = 1; let f = 1.0; // `size_of_val` returns the size of a variable in bytes println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); let elem = 5u8; // Create an empty vector (a growable array). let mut vec = Vec::new(); // At this point the compiler doesn't know the exact type of `vec`, it // just knows that it's a vector of something (`Vec<_>`). // Insert `elem` in the vector. vec.push(elem); // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec<u8>`) // TODO ^ Try commenting out the `vec.push(elem)` line println!("{:?}", vec); } use std::convert::From; use std::convert::Into; use std::convert::TryFrom; use std::convert::TryInto; #[derive(Debug)] struct Number { value: i32, } impl From<i32> for Number { fn from(item: i32) -> Self { Number { value: item } } } impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Number is: {}", self.value) } } #[derive(Debug, PartialEq)] struct EvenNumber(i32); impl TryFrom<i32> for EvenNumber { type Error = (); fn try_from(value: i32) -> Result<Self, Self::Error> { if value % 2 == 0 { Ok(EvenNumber(value)) } else { Err(()) } } } fn conversion() { let s = "Test"; let myString = String::from(s); let b = myString.into_boxed_str(); let ptr = b.as_ptr(); println!("b:{:?}", ptr); let ref_b = b.as_ref(); println!("s:{:?}", ref_b); let number = Number::from(34_i32); println!("{}", number); let n = 5; let num: i32 = n.into(); println!("My number is {:?}", num); assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8))); assert_eq!(EvenNumber::try_from(5), Err(())); println!("{:?}", EvenNumber::try_from(5)); let result: Result<EvenNumber, ()> = 8i32.try_into(); assert_eq!(result, Ok(EvenNumber(8))); let result: Result<EvenNumber, ()> = 5i32.try_into(); assert_eq!(result, Err(())); let parsed: i32 = "5".parse().unwrap(); let turbo_parsed = "10".parse::<i32>().unwrap(); let sum = parsed + turbo_parsed; println!("Sum: {:?}", sum); } fn expression() { let x0 = 2; let sum = { let x = 20_i8; let y = 12; x + y + x0 }; println!("Sum: {:?}", sum) } fn flowControl() { let mut count = 0; loop { count += 1; if count % 2 == 0 { continue; } println!("Count: {}", count); if count > 6 { break; } } let mut optional = Some(20); match optional { Some(i) => { println!("Number: {:?}", i); } _ => { println!("Not present"); } } if let Some(i) = Some(20) { println!("Number is indeed: {}", i); } while let Some(i) = optional { if i == 25 { println!("Number is: {}", i); optional = None; } else { println!("`i` is `{:?}`. Try again.", i); optional = Some(i + 1); } } } fn isDivisibleBy(lhs: u32, rhs: u32) -> bool { if (rhs == 0) { return false; } lhs % rhs == 0 } impl Point { fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn new(x: f32, y: f32) -> Point { Point { x: x, y: y } } fn distance(&self, p: &Point) -> f32 { let dx = self.x - p.x; let dy: f32 = self.y - p.y; (dx * dy + dy + dy).sqrt() } fn translate(&mut self, dx: f32, dy: f32) { self.x += dx; self.y += dy; } } fn functions() { println!("isD: {:?}", isDivisibleBy(20, 4)); println!("isD: {:?}", isDivisibleBy(20, 3)); let mut point = Point::new(22.2, 32.3); let mut origin = Point::origin(); println!("Distance: {:?}", point.distance(&origin)); point.translate(3.0, -2.0); println!("Point: {:?}", point); println!("Distance: {:?}", point.distance(&origin)); let x = 20; let fun1 = |i: i32| -> i32 { i + 1 + x }; let fun2 = |i| i + 1 + x; let i = 1; println!("Inc1: {:?}", fun1(i)); println!("Inc2: {:?}", fun2(i)); let one = || 1; println!("One: {:?}", one()); let color = "Green"; let print = || println!("Color: {:?}", color); print(); let _reborow = &color; print(); let mut count = 0; let mut inc = || { count += 1; println!("Count: {:?}", count); }; inc(); inc(); let reborrow = &mut count; let movable = Box::new(3); let consume = || { println!("Movable: {:?}", movable); mem::drop(movable); }; consume(); let haystack = vec![1, 2, 3]; let contains = move |needle| haystack.contains(needle); println!("{}", contains(&1)); println!("{}", contains(&2)); } fn apply<F>(f: F) where F: FnOnce(), { f(); } fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32, { f(3) } fn call_me<F: Fn()>(f: F) { f(); } fn function() { println!("I am function"); } fn functions2() { let x = 30; println!("x: {:?}", x); let y = apply_to_3(|x| x + 20); println!("y: {:?}", y); let greeting = "Hello"; let mut farewel = "Goodby".to_owned(); let diary = || { println!("I said {}", greeting); farewel.push_str("!!!!!"); println!("Than I screemed {}", farewel); println!("Than I sleep"); mem::drop(farewel); }; apply(diary); let double = |x| 2 * x; println!("3 doubled: {}", apply_to_3(double)); let closure = || println!("I am closure"); call_me(function); call_me(closure); } fn create_fn() -> impl Fn() { let text = "Fn".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_mut() -> impl FnMut() { let text = "FnMut".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_once() -> impl FnOnce() { let text = "FnOnce".to_owned(); move || println!("This is a: {}", text) } fn functions3() { let x = create_fn(); x(); let mut y = create_fn_mut(); y(); let z = create_fn_once(); z(); let v1 = vec![1, 2, 3]; let v2 = vec![4, 5, 6]; println!("2 in v1: {}", v1.iter().any(|&x| x == 2)); println!("2 in v2: {}", v2.iter().any(|&x| x == 2)); let a1 = [1, 2, 3]; let a2 = [4, 5, 6];
println!("2 in v1: {}", a1.iter().any(|&x| x == 2)); println!("2 in v2: {}", a2.iter().any(|&x| x == 2)); let mut iter1 = v1.iter(); let mut into_iter = v2.into_iter(); println!("Find 2 in v1: {:?}", iter1.find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", into_iter.find(|&x| x == 2)); let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; println!("Find 2 in v1: {:?}", array1.iter().find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", array2.into_iter().find(|&&x| x == 2)); let index_of_first_even_number = array1.iter().position(|x| x % 2 == 0); println!( "index_of_first_even_number: {}", index_of_first_even_number.unwrap() ); } fn is_odd(n: u32) -> bool { n % 2 == 1 } fn foo() -> () { () } fn higherOrder() { let upper = 1000; let mut acc = 0; for n in 0.. { let n_squared = n * n; if n_squared > upper { break; } else if is_odd(n_squared) { acc += n_squared; } } println!("Sum1: {:?}", acc); let sum2 = (0..) .map(|n| n * n) .take_while(|&n_squared| n_squared < upper) .filter(|&n_squared| n_squared % 2 == 1) .fold(0, |acc, n_squared| acc + n_squared); println!("Sum2: {:?}", sum2); fn sum_odd_numbers(up_to: u32) -> u32 { let mut acc = 0; for i in 0..up_to { // Notice that the return type of this match expression must be u32 // because of the type of the "addition" variable. let addition: u32 = match i % 2 == 1 { // The "i" variable is of type u32, which is perfectly fine. true => i, // On the other hand, the "continue" expression does not return // u32, but it is still fine, because it never returns and therefore // does not violate the type requirements of the match expression. false => continue, }; acc += addition; } acc } println!( "Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9) ); } struct S; struct GenericVal<T>(T); impl GenericVal<i32> {} impl GenericVal<S> {} impl<T> GenericVal<T> {} struct Val { val: f64, } struct GenVal<T> { gen_val: T, } // impl of Val impl Val { fn value(&self) -> &f64 { &self.val } } // impl of GenVal for a generic type `T` impl<T> GenVal<T> { fn value(&self) -> &T { &self.gen_val } } fn generics() { let x = Val { val: 3.0 }; let y = GenVal { gen_val: 3i32 }; println!("{}, {}", x.value(), y.value()); } fn create_box() { let _box = Box::new(3i32); } struct ToDrop; impl Drop for ToDrop { fn drop(&mut self) { println!("ToDrop is being dropped"); } } fn destroy_box(c: Box<i32>) { println!("Destroying a box that contains {}", c); // `c` is destroyed and the memory freed } fn scoping() { /* create_box(); let _box2 = Box::new(5i32); { let _box3 = Box::new(4i32); } let x = ToDrop; { let y = ToDrop; }*/ let x = 5u32; let y = x; println!("x is {}, and y is {}", x, y); let a = Box::new(5i32); let mut b = a; *b = 30i32; //destroy_box(b); println!("{}", b); } fn ownership() { let a = Box::new(5i32); let mut b = a; *b = 4; println!("{}", b); } fn eat_box(boxed: Box<i32>) { println!("{}", boxed); } fn borrow(borrowed: &i32) { println!("{}", borrowed); } fn borrowing() { let boxed = Box::new(5_i32); let stacked = 6_i32; borrow(&boxed); borrow(&stacked); { let refTo: &i32 = &boxed; borrow(refTo); } eat_box(boxed); } #[derive(Clone, Copy)] struct Book { author: &'static str, title: &'static str, year: u32, } fn borrow_book(book: &Book) { println!("I immutably borrowed {} - {}", book.author, book.title); } fn new_edition(book: &mut Book) { book.year = 2014; println!("I mutably borrowed {} - {} edition", book.title, book.year); } fn mutability() { let immutable_book = Book { author: "Ivan Cankar", title: "Hlapci", year: 1910, }; let mut mutable_book = immutable_book; borrow_book(&immutable_book); borrow_book(&mutable_book); new_edition(&mut mutable_book); } struct Location { x: i32, y: i32, z: i32, } fn aliasing() { let mut location = Location { x: 0, y: 0, z: 0 }; let borrow1 = &location; let borrow2 = &location; println!("{} {}", location.x, borrow1.x); //let mut_borow = &mut location; println!( "Location has coordinates: ({}, {}, {})", borrow1.x, borrow2.y, location.z ); let mut_borow = &mut location; mut_borow.x = 10; mut_borow.y = 23; mut_borow.z = 29; let borrow3 = &location; } #[derive(PartialEq, PartialOrd)] struct Centimeters(f64); #[derive(Debug)] struct Inches(i32); impl Inches { fn to_centimeters(&self) -> Centimeters { let &Inches(inches) = self; Centimeters(inches as f64 * 2.54) } } struct Seconds(i32); fn deriveTest() { let one_second = Seconds(1); let foot = Inches(12); println!("One foot equals: {:?}", foot); let meter = Centimeters(100.0); let cmp = if foot.to_centimeters() < meter { "smaller" } else { "bigger" }; println!("One foot is {} than one meter.", cmp); } struct Sheep {} struct Cow {} trait Animal { fn noise(&self) -> &'static str; } impl Animal for Sheep { fn noise(&self) -> &'static str { "baaah" } } impl Animal for Cow { fn noise(&self) -> &'static str { "moooooo" } } fn random_animal(random_number: f64) -> Box<dyn Animal> { if random_number < 0.5 { Box::new(Sheep {}) } else { Box::new(Cow {}) } } fn dyReturn() { let random_number = 0.3444; let animal = random_animal(random_number); println!( "You've randomly chosen an animal, and it says {}", animal.noise() ); } use std::ops; struct Foo; struct Bar; #[derive(Debug)] struct FooBar; #[derive(Debug)] struct BarFoo; impl ops::Add<Bar> for Foo { type Output = FooBar; fn add(self, _rhs: Bar) -> FooBar { println!("> Foo.add(Bar) was called"); FooBar } } impl ops::Add<Foo> for Bar {
random_line_split
main.rs
!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_slice(slice: &[Matrix]) { println!("first element of the slice: \n{}", slice[0]); println!("the slice has {} elements.", slice.len()); } fn arrays_slices() { let x: [Matrix; 2] = [ Matrix(10.2f32, 2.1f32, 3.1f32, 4.5f32), Matrix(5.2f32, 6.1f32, 2.1f32, 8.5f32), ]; println!("Array occupies: {:?} bytes", mem::size_of_val(&x)); analyze_slice(&x[1..2]); } #[derive(Debug, Copy, Clone)] struct Person<'a> { name: &'a str, age: u8, } impl<'a> Person<'a> { fn changeName(&mut self, new_name: &'a str) -> &'a Person { self.name = new_name; self } } #[derive(Debug)] struct Point { x: f32, y: f32, } #[derive(Debug)] struct Triangle { top_left: Point, bottom_right: Point, } struct Unit; struct Pair(i32, i32); fn square(point: Point, val: f32) -> Triangle { Triangle { bottom_right: Point { x: point.x + val, y: point.y - val, }, top_left: point, } } fn struct_test() { let mut person = Person { name: "Peter", age: 30u8, }; let new_name = "Janez"; let changedPerson = person.changeName(new_name); println!("Person: {:?}", changedPerson); let point = Point { x: 20.2, y: 30.3 }; println!("Point: {:?}", point); let bottom_right = Point { x: 10.2,..point }; println!("bottom_right: {:?}", bottom_right); let top_left = Point { x: 2.2, y: 5.3 }; let triangle = Triangle { bottom_right: bottom_right, top_left: top_left, }; println!("{:?}", triangle); let Triangle { bottom_right: Point { x: x1, y: y1 }, top_left: Point { x: x2, y: y2 }, } = triangle; println!("x1: {}, y1: {}, x2: {}, y2:{}", x1, y1, x2, y2); println!("Area:{}", (x2 - x1) * (y2 - y1)); let unit = Unit; let pair = Pair(20, 30); println!("pair contains {:?} and {:?}", pair.0, pair.1); let Pair(x, y) = pair; println!("pair contains {:?} and {:?}", x, y); println!("{:?}", square(point, 20.2)); } enum WebEvent { PageLoad, PageUnload, KeyPress(char), Paste(String), Click { x: i64, y: i64 }, } use crate::WebEvent::*; impl WebEvent { fn run(&self, m: i32) -> String { match self { PageLoad => return format!("Page loaded in {} seconds.", m), PageUnload => format!("PageUnloaded"), KeyPress(c) => format!("KeyPressed: {}", c), Paste(s) => format!("Pasted: {}", s), Click { x, y } => format!("Clicked on position: {}, {}", x, y), } } } fn inspect(event: WebEvent) { match event { PageLoad => println!("PageLoaded"), PageUnload => println!("PageUnloaded"), KeyPress(c) => println!("KeyPressed: {}", c), Paste(s) => println!("Pasted: {}", s), Click { x, y } => println!("Clicked on position: {}, {}", x, y), } } enum Number_enum { Zero, One, Two, } // enum with explicit discriminator enum Color { Red = 0xff0000, Green = 0x00ff00, Blue = 0x0000ff, } fn test_enum() { let pressed = KeyPress('x'); // `to_owned()` creates an owned `String` from a string slice. let pasted = Paste("my text".to_owned()); let click = Click { x: 20, y: 80 }; let load = PageLoad; let unload = PageUnload; inspect(pressed); inspect(pasted); inspect(click); inspect(load); inspect(unload); let loadSec = WebEvent::PageLoad; println!("{}", &loadSec.run(20)); println!("zero is {}", Number_enum::Zero as i32); println!("one is {}", Number_enum::One as i32); println!("roses are #{:06x}", Color::Red as i32); println!("violets are #{:06x}", Color::Blue as i32); } fn test_var_bind() { let mut x = 2; { let x = "4"; } x = 4; } fn casting() { let decimal = 22.8832_f32; let integer = decimal as u8; println!("Integer: {}", integer); let character = integer as char; println!("character: {}", character); println!("1000 as a u16 is: {:b}", 1000 as u16); let num = 1000; println!("1000 as a u8 is : {:b}", num as u8); println!(" -1 as a u8 is : {:b}", (-1i8) as u8); println!("1000 mod 256 is : {:b}", 1000 % 256); // Unless it already fits, of course. println!(" 128 as a i16 is: {:b} ({})", 128 as i16, 128 as i16); // 128 as u8 -> 128, whose two's complement in eight bits is: let num: i16 = 128; println!(" 128 as a i8 is : {:b} ({})", num as i8, num as i8); println!("127={:b}", 127_i8); println!("-128={:b}", -128_i8); println!("255={:b}", 255_u8); println!("0={:b}", 0_u8); println!("255= {}", 127_u8 as i8); println!("0={:b}", 0_u8 as i8); let x = 1u8; let y = 2u32; let z = 3f32; // Unsuffixed literal, their types depend on how they are used let i = 1; let f = 1.0; // `size_of_val` returns the size of a variable in bytes println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); let elem = 5u8; // Create an empty vector (a growable array). let mut vec = Vec::new(); // At this point the compiler doesn't know the exact type of `vec`, it // just knows that it's a vector of something (`Vec<_>`). // Insert `elem` in the vector. vec.push(elem); // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec<u8>`) // TODO ^ Try commenting out the `vec.push(elem)` line println!("{:?}", vec); } use std::convert::From; use std::convert::Into; use std::convert::TryFrom; use std::convert::TryInto; #[derive(Debug)] struct Number { value: i32, } impl From<i32> for Number { fn from(item: i32) -> Self { Number { value: item } } } impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Number is: {}", self.value) } } #[derive(Debug, PartialEq)] struct EvenNumber(i32); impl TryFrom<i32> for EvenNumber { type Error = (); fn try_from(value: i32) -> Result<Self, Self::Error> { if value % 2 == 0 { Ok(EvenNumber(value)) } else { Err(()) } } } fn conversion() { let s = "Test"; let myString = String::from(s); let b = myString.into_boxed_str(); let ptr = b.as_ptr(); println!("b:{:?}", ptr); let ref_b = b.as_ref(); println!("s:{:?}", ref_b); let number = Number::from(34_i32); println!("{}", number); let n = 5; let num: i32 = n.into(); println!("My number is {:?}", num); assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8))); assert_eq!(EvenNumber::try_from(5), Err(())); println!("{:?}", EvenNumber::try_from(5)); let result: Result<EvenNumber, ()> = 8i32.try_into(); assert_eq!(result, Ok(EvenNumber(8))); let result: Result<EvenNumber, ()> = 5i32.try_into(); assert_eq!(result, Err(())); let parsed: i32 = "5".parse().unwrap(); let turbo_parsed = "10".parse::<i32>().unwrap(); let sum = parsed + turbo_parsed; println!("Sum: {:?}", sum); } fn expression() { let x0 = 2; let sum = { let x = 20_i8; let y = 12; x + y + x0 }; println!("Sum: {:?}", sum) } fn flowControl() { let mut count = 0; loop { count += 1; if count % 2 == 0 { continue; } println!("Count: {}", count); if count > 6 { break; } } let mut optional = Some(20); match optional { Some(i) => { println!("Number: {:?}", i); } _ => { println!("Not present"); } } if let Some(i) = Some(20) { println!("Number is indeed: {}", i); } while let Some(i) = optional { if i == 25 { println!("Number is: {}", i); optional = None; } else { println!("`i` is `{:?}`. Try again.", i); optional = Some(i + 1); } } } fn isDivisibleBy(lhs: u32, rhs: u32) -> bool { if (rhs == 0) { return false; } lhs % rhs == 0 } impl Point { fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn new(x: f32, y: f32) -> Point { Point { x: x, y: y } } fn distance(&self, p: &Point) -> f32 { let dx = self.x - p.x; let dy: f32 = self.y - p.y; (dx * dy + dy + dy).sqrt() } fn translate(&mut self, dx: f32, dy: f32) { self.x += dx; self.y += dy; } } fn functions() { println!("isD: {:?}", isDivisibleBy(20, 4)); println!("isD: {:?}", isDivisibleBy(20, 3)); let mut point = Point::new(22.2, 32.3); let mut origin = Point::origin(); println!("Distance: {:?}", point.distance(&origin)); point.translate(3.0, -2.0); println!("Point: {:?}", point); println!("Distance: {:?}", point.distance(&origin)); let x = 20; let fun1 = |i: i32| -> i32 { i + 1 + x }; let fun2 = |i| i + 1 + x; let i = 1; println!("Inc1: {:?}", fun1(i)); println!("Inc2: {:?}", fun2(i)); let one = || 1; println!("One: {:?}", one()); let color = "Green"; let print = || println!("Color: {:?}", color); print(); let _reborow = &color; print(); let mut count = 0; let mut inc = || { count += 1; println!("Count: {:?}", count); }; inc(); inc(); let reborrow = &mut count; let movable = Box::new(3); let consume = || { println!("Movable: {:?}", movable); mem::drop(movable); }; consume(); let haystack = vec![1, 2, 3]; let contains = move |needle| haystack.contains(needle); println!("{}", contains(&1)); println!("{}", contains(&2)); } fn apply<F>(f: F) where F: FnOnce(), { f(); } fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32, { f(3) } fn call_me<F: Fn()>(f: F) { f(); } fn function() { println!("I am function"); } fn functions2() { let x = 30; println!("x: {:?}", x); let y = apply_to_3(|x| x + 20); println!("y: {:?}", y); let greeting = "Hello"; let mut farewel = "Goodby".to_owned(); let diary = || { println!("I said {}", greeting); farewel.push_str("!!!!!"); println!("Than I screemed {}", farewel); println!("Than I sleep"); mem::drop(farewel); }; apply(diary); let double = |x| 2 * x; println!("3 doubled: {}", apply_to_3(double)); let closure = || println!("I am closure"); call_me(function); call_me(closure); } fn create_fn() -> impl Fn() { let text = "Fn".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_mut() -> impl FnMut() { let text = "FnMut".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_once() -> impl FnOnce() { let text = "FnOnce".to_owned(); move || println!("This is a: {}", text) } fn functions3() { let x = create_fn(); x(); let mut y = create_fn_mut(); y(); let z = create_fn_once(); z(); let v1 = vec![1, 2, 3]; let v2 = vec![4, 5, 6]; println!("2 in v1: {}", v1.iter().any(|&x| x == 2)); println!("2 in v2: {}", v2.iter().any(|&x| x == 2)); let a1 = [1, 2, 3]; let a2 = [4, 5, 6]; println!("2 in v1: {}", a1.iter().any(|&x| x == 2)); println!("2 in v2: {}", a2.iter().any(|&x| x == 2)); let mut iter1 = v1.iter(); let mut into_iter = v2.into_iter(); println!("Find 2 in v1: {:?}", iter1.find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", into_iter.find(|&x| x == 2)); let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; println!("Find 2 in v1: {:?}", array1.iter().find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", array2.into_iter().find(|&&x| x == 2)); let index_of_first_even_number = array1.iter().position(|x| x % 2 == 0); println!( "index_of_first_even_number: {}", index_of_first_even_number.unwrap() ); } fn is_odd(n: u32) -> bool { n % 2 == 1 } fn foo() -> () { () } fn higherOrder() { let upper = 1000; let mut acc = 0; for n in 0.. { let n_squared = n * n; if n_squared > upper { break; } else if is_odd(n_squared) { acc += n_squared; } } println!("Sum1: {:?}", acc); let sum2 = (0..) .map(|n| n * n) .take_while(|&n_squared| n_squared < upper) .filter(|&n_squared| n_squared % 2 == 1) .fold(0, |acc, n_squared| acc + n_squared); println!("Sum2: {:?}", sum2); fn sum_odd_numbers(up_to: u32) -> u32 { let mut acc = 0; for i in 0..up_to { // Notice that the return type of this match expression must be u32 // because of the type of the "addition" variable. let addition: u32 = match i % 2 == 1 { // The "i" variable is of type u32, which is perfectly fine. true => i, // On the other hand, the "continue" expression does not return // u32, but it is still fine, because it never returns and therefore // does not violate the type requirements of the match expression. false => continue, }; acc += addition; } acc } println!( "Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9) ); } struct S; struct GenericVal<T>(T); impl GenericVal<i32> {} impl GenericVal<S> {} impl<T> GenericVal<T> {} struct Val { val: f64, } struct GenVal<T> { gen_val: T, } // impl of Val impl Val { fn value(&self) -> &f64 { &self.val } } // impl of GenVal for a generic type `T` impl<T> GenVal<T> { fn value(&self) -> &T { &self.gen_val } } fn generics() { let x = Val { val: 3.0 }; let y = GenVal { gen_val: 3i32 }; println!("{}, {}", x.value(), y.value()); } fn create_box() { let _box = Box::new(3i32); } struct ToDrop; impl Drop for ToDrop { fn drop(&mut self) { println!("ToDrop is being dropped"); } } fn destroy_box(c: Box<i32>) { println!("Destroying a box that contains {}", c); // `c` is destroyed and the memory freed } fn scoping() { /* create_box(); let _box2 = Box::new(5i32); { let _box3 = Box::new(4i32); } let x = ToDrop; { let y = ToDrop; }*/ let x = 5u32; let y = x; println!("x is {}, and y is {}", x, y); let a = Box::new(5i32); let mut b = a; *b = 30i32; //destroy_box(b); println!("{}", b); } fn ownership() { let a = Box::new(5i32); let mut b = a; *b = 4; println!("{}", b); } fn eat_box(boxed: Box<i32>) { println!("{}", boxed); } fn borrow(borrowed: &i32) { println!("{}", borrowed); } fn borrowing() { let boxed = Box::new(5_i32); let stacked = 6_i32; borrow(&boxed); borrow(&stacked); { let refTo: &i32 = &boxed; borrow(refTo); } eat_box(boxed); } #[derive(Clone, Copy)] struct Book { author: &'static str, title: &'static str, year: u32, } fn borrow_book(book: &Book) { println!("I immutably borrowed {} - {}", book.author, book.title); } fn new_edition(book: &mut Book) { book.year = 2014; println!("I mutably borrowed {} - {} edition", book.title, book.year); } fn mutability() { let immutable_book = Book { author: "Ivan Cankar", title: "Hlapci", year: 1910, }; let mut mutable_book = immutable_book; borrow_book(&immutable_book); borrow_book(&mutable_book); new_edition(&mut mutable_book); } struct Location { x: i32, y: i32, z: i32, } fn aliasing() { let mut location = Location { x: 0, y: 0, z: 0 }; let borrow1 = &location; let borrow2 = &location; println!("{} {}", location.x, borrow1.x); //let mut_borow = &mut location; println!( "Location has coordinates: ({}, {}, {})", borrow1.x, borrow2.y, location.z ); let mut_borow = &mut location; mut_borow.x = 10; mut_borow.y = 23; mut_borow.z = 29; let borrow3 = &location; } #[derive(PartialEq, PartialOrd)] struct Centimeters(f64); #[derive(Debug)] struct Inches(i32); impl Inches { fn to_centimeters(&self) -> Centimeters { let &Inches(inches) = self; Centimeters(inches as f64 * 2.54) } } struct Seconds(i32); fn deriveTest() { let one_second = Seconds(1); let foot = Inches(12); println!("One foot equals: {:?}", foot); let meter = Centimeters(100.0); let cmp = if foot.to_centimeters() < meter { "smaller" } else { "bigger" }; println!("One foot is {} than one meter.", cmp); } struct Sheep {} struct Cow {} trait Animal { fn noise(&self) -> &'static str; } impl Animal for Sheep { fn noise(&self) -> &'static str { "baaah" } } impl Animal for Cow { fn noise(&self) -> &'static str { "moooooo" } } fn random_animal(random_number: f64) -> Box<dyn Animal> { if random_number < 0.5 { Box::new(Sheep {}) } else { Box::new(Cow {}) } } fn
() { let random_number = 0.3444; let animal = random_animal(random_number); println!( "You've randomly chosen an animal, and it says {}", animal.noise() ); } use std::ops; struct Foo; struct Bar; #[derive(Debug)] struct FooBar; #[derive(Debug)] struct BarFoo; impl ops::Add<Bar> for Foo { type Output = FooBar; fn add(self, _rhs: Bar) -> FooBar { println!("> Foo.add(Bar) was called"); FooBar } } impl ops::Add<Foo> for Bar
dyReturn
identifier_name
main.rs
!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_slice(slice: &[Matrix]) { println!("first element of the slice: \n{}", slice[0]); println!("the slice has {} elements.", slice.len()); } fn arrays_slices() { let x: [Matrix; 2] = [ Matrix(10.2f32, 2.1f32, 3.1f32, 4.5f32), Matrix(5.2f32, 6.1f32, 2.1f32, 8.5f32), ]; println!("Array occupies: {:?} bytes", mem::size_of_val(&x)); analyze_slice(&x[1..2]); } #[derive(Debug, Copy, Clone)] struct Person<'a> { name: &'a str, age: u8, } impl<'a> Person<'a> { fn changeName(&mut self, new_name: &'a str) -> &'a Person { self.name = new_name; self } } #[derive(Debug)] struct Point { x: f32, y: f32, } #[derive(Debug)] struct Triangle { top_left: Point, bottom_right: Point, } struct Unit; struct Pair(i32, i32); fn square(point: Point, val: f32) -> Triangle { Triangle { bottom_right: Point { x: point.x + val, y: point.y - val, }, top_left: point, } } fn struct_test() { let mut person = Person { name: "Peter", age: 30u8, }; let new_name = "Janez"; let changedPerson = person.changeName(new_name); println!("Person: {:?}", changedPerson); let point = Point { x: 20.2, y: 30.3 }; println!("Point: {:?}", point); let bottom_right = Point { x: 10.2,..point }; println!("bottom_right: {:?}", bottom_right); let top_left = Point { x: 2.2, y: 5.3 }; let triangle = Triangle { bottom_right: bottom_right, top_left: top_left, }; println!("{:?}", triangle); let Triangle { bottom_right: Point { x: x1, y: y1 }, top_left: Point { x: x2, y: y2 }, } = triangle; println!("x1: {}, y1: {}, x2: {}, y2:{}", x1, y1, x2, y2); println!("Area:{}", (x2 - x1) * (y2 - y1)); let unit = Unit; let pair = Pair(20, 30); println!("pair contains {:?} and {:?}", pair.0, pair.1); let Pair(x, y) = pair; println!("pair contains {:?} and {:?}", x, y); println!("{:?}", square(point, 20.2)); } enum WebEvent { PageLoad, PageUnload, KeyPress(char), Paste(String), Click { x: i64, y: i64 }, } use crate::WebEvent::*; impl WebEvent { fn run(&self, m: i32) -> String { match self { PageLoad => return format!("Page loaded in {} seconds.", m), PageUnload => format!("PageUnloaded"), KeyPress(c) => format!("KeyPressed: {}", c), Paste(s) => format!("Pasted: {}", s), Click { x, y } => format!("Clicked on position: {}, {}", x, y), } } } fn inspect(event: WebEvent) { match event { PageLoad => println!("PageLoaded"), PageUnload => println!("PageUnloaded"), KeyPress(c) => println!("KeyPressed: {}", c), Paste(s) => println!("Pasted: {}", s), Click { x, y } => println!("Clicked on position: {}, {}", x, y), } } enum Number_enum { Zero, One, Two, } // enum with explicit discriminator enum Color { Red = 0xff0000, Green = 0x00ff00, Blue = 0x0000ff, } fn test_enum() { let pressed = KeyPress('x'); // `to_owned()` creates an owned `String` from a string slice. let pasted = Paste("my text".to_owned()); let click = Click { x: 20, y: 80 }; let load = PageLoad; let unload = PageUnload; inspect(pressed); inspect(pasted); inspect(click); inspect(load); inspect(unload); let loadSec = WebEvent::PageLoad; println!("{}", &loadSec.run(20)); println!("zero is {}", Number_enum::Zero as i32); println!("one is {}", Number_enum::One as i32); println!("roses are #{:06x}", Color::Red as i32); println!("violets are #{:06x}", Color::Blue as i32); } fn test_var_bind() { let mut x = 2; { let x = "4"; } x = 4; } fn casting() { let decimal = 22.8832_f32; let integer = decimal as u8; println!("Integer: {}", integer); let character = integer as char; println!("character: {}", character); println!("1000 as a u16 is: {:b}", 1000 as u16); let num = 1000; println!("1000 as a u8 is : {:b}", num as u8); println!(" -1 as a u8 is : {:b}", (-1i8) as u8); println!("1000 mod 256 is : {:b}", 1000 % 256); // Unless it already fits, of course. println!(" 128 as a i16 is: {:b} ({})", 128 as i16, 128 as i16); // 128 as u8 -> 128, whose two's complement in eight bits is: let num: i16 = 128; println!(" 128 as a i8 is : {:b} ({})", num as i8, num as i8); println!("127={:b}", 127_i8); println!("-128={:b}", -128_i8); println!("255={:b}", 255_u8); println!("0={:b}", 0_u8); println!("255= {}", 127_u8 as i8); println!("0={:b}", 0_u8 as i8); let x = 1u8; let y = 2u32; let z = 3f32; // Unsuffixed literal, their types depend on how they are used let i = 1; let f = 1.0; // `size_of_val` returns the size of a variable in bytes println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); let elem = 5u8; // Create an empty vector (a growable array). let mut vec = Vec::new(); // At this point the compiler doesn't know the exact type of `vec`, it // just knows that it's a vector of something (`Vec<_>`). // Insert `elem` in the vector. vec.push(elem); // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec<u8>`) // TODO ^ Try commenting out the `vec.push(elem)` line println!("{:?}", vec); } use std::convert::From; use std::convert::Into; use std::convert::TryFrom; use std::convert::TryInto; #[derive(Debug)] struct Number { value: i32, } impl From<i32> for Number { fn from(item: i32) -> Self { Number { value: item } } } impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Number is: {}", self.value) } } #[derive(Debug, PartialEq)] struct EvenNumber(i32); impl TryFrom<i32> for EvenNumber { type Error = (); fn try_from(value: i32) -> Result<Self, Self::Error> { if value % 2 == 0 { Ok(EvenNumber(value)) } else { Err(()) } } } fn conversion() { let s = "Test"; let myString = String::from(s); let b = myString.into_boxed_str(); let ptr = b.as_ptr(); println!("b:{:?}", ptr); let ref_b = b.as_ref(); println!("s:{:?}", ref_b); let number = Number::from(34_i32); println!("{}", number); let n = 5; let num: i32 = n.into(); println!("My number is {:?}", num); assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8))); assert_eq!(EvenNumber::try_from(5), Err(())); println!("{:?}", EvenNumber::try_from(5)); let result: Result<EvenNumber, ()> = 8i32.try_into(); assert_eq!(result, Ok(EvenNumber(8))); let result: Result<EvenNumber, ()> = 5i32.try_into(); assert_eq!(result, Err(())); let parsed: i32 = "5".parse().unwrap(); let turbo_parsed = "10".parse::<i32>().unwrap(); let sum = parsed + turbo_parsed; println!("Sum: {:?}", sum); } fn expression() { let x0 = 2; let sum = { let x = 20_i8; let y = 12; x + y + x0 }; println!("Sum: {:?}", sum) } fn flowControl() { let mut count = 0; loop { count += 1; if count % 2 == 0 { continue; } println!("Count: {}", count); if count > 6 { break; } } let mut optional = Some(20); match optional { Some(i) => { println!("Number: {:?}", i); } _ => { println!("Not present"); } } if let Some(i) = Some(20) { println!("Number is indeed: {}", i); } while let Some(i) = optional { if i == 25 { println!("Number is: {}", i); optional = None; } else { println!("`i` is `{:?}`. Try again.", i); optional = Some(i + 1); } } } fn isDivisibleBy(lhs: u32, rhs: u32) -> bool { if (rhs == 0) { return false; } lhs % rhs == 0 } impl Point { fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn new(x: f32, y: f32) -> Point { Point { x: x, y: y } } fn distance(&self, p: &Point) -> f32 { let dx = self.x - p.x; let dy: f32 = self.y - p.y; (dx * dy + dy + dy).sqrt() } fn translate(&mut self, dx: f32, dy: f32) { self.x += dx; self.y += dy; } } fn functions() { println!("isD: {:?}", isDivisibleBy(20, 4)); println!("isD: {:?}", isDivisibleBy(20, 3)); let mut point = Point::new(22.2, 32.3); let mut origin = Point::origin(); println!("Distance: {:?}", point.distance(&origin)); point.translate(3.0, -2.0); println!("Point: {:?}", point); println!("Distance: {:?}", point.distance(&origin)); let x = 20; let fun1 = |i: i32| -> i32 { i + 1 + x }; let fun2 = |i| i + 1 + x; let i = 1; println!("Inc1: {:?}", fun1(i)); println!("Inc2: {:?}", fun2(i)); let one = || 1; println!("One: {:?}", one()); let color = "Green"; let print = || println!("Color: {:?}", color); print(); let _reborow = &color; print(); let mut count = 0; let mut inc = || { count += 1; println!("Count: {:?}", count); }; inc(); inc(); let reborrow = &mut count; let movable = Box::new(3); let consume = || { println!("Movable: {:?}", movable); mem::drop(movable); }; consume(); let haystack = vec![1, 2, 3]; let contains = move |needle| haystack.contains(needle); println!("{}", contains(&1)); println!("{}", contains(&2)); } fn apply<F>(f: F) where F: FnOnce(), { f(); } fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32, { f(3) } fn call_me<F: Fn()>(f: F) { f(); } fn function() { println!("I am function"); } fn functions2()
mem::drop(farewel); }; apply(diary); let double = |x| 2 * x; println!("3 doubled: {}", apply_to_3(double)); let closure = || println!("I am closure"); call_me(function); call_me(closure); } fn create_fn() -> impl Fn() { let text = "Fn".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_mut() -> impl FnMut() { let text = "FnMut".to_owned(); move || println!("This is a text: {}", text) } fn create_fn_once() -> impl FnOnce() { let text = "FnOnce".to_owned(); move || println!("This is a: {}", text) } fn functions3() { let x = create_fn(); x(); let mut y = create_fn_mut(); y(); let z = create_fn_once(); z(); let v1 = vec![1, 2, 3]; let v2 = vec![4, 5, 6]; println!("2 in v1: {}", v1.iter().any(|&x| x == 2)); println!("2 in v2: {}", v2.iter().any(|&x| x == 2)); let a1 = [1, 2, 3]; let a2 = [4, 5, 6]; println!("2 in v1: {}", a1.iter().any(|&x| x == 2)); println!("2 in v2: {}", a2.iter().any(|&x| x == 2)); let mut iter1 = v1.iter(); let mut into_iter = v2.into_iter(); println!("Find 2 in v1: {:?}", iter1.find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", into_iter.find(|&x| x == 2)); let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; println!("Find 2 in v1: {:?}", array1.iter().find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", array2.into_iter().find(|&&x| x == 2)); let index_of_first_even_number = array1.iter().position(|x| x % 2 == 0); println!( "index_of_first_even_number: {}", index_of_first_even_number.unwrap() ); } fn is_odd(n: u32) -> bool { n % 2 == 1 } fn foo() -> () { () } fn higherOrder() { let upper = 1000; let mut acc = 0; for n in 0.. { let n_squared = n * n; if n_squared > upper { break; } else if is_odd(n_squared) { acc += n_squared; } } println!("Sum1: {:?}", acc); let sum2 = (0..) .map(|n| n * n) .take_while(|&n_squared| n_squared < upper) .filter(|&n_squared| n_squared % 2 == 1) .fold(0, |acc, n_squared| acc + n_squared); println!("Sum2: {:?}", sum2); fn sum_odd_numbers(up_to: u32) -> u32 { let mut acc = 0; for i in 0..up_to { // Notice that the return type of this match expression must be u32 // because of the type of the "addition" variable. let addition: u32 = match i % 2 == 1 { // The "i" variable is of type u32, which is perfectly fine. true => i, // On the other hand, the "continue" expression does not return // u32, but it is still fine, because it never returns and therefore // does not violate the type requirements of the match expression. false => continue, }; acc += addition; } acc } println!( "Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9) ); } struct S; struct GenericVal<T>(T); impl GenericVal<i32> {} impl GenericVal<S> {} impl<T> GenericVal<T> {} struct Val { val: f64, } struct GenVal<T> { gen_val: T, } // impl of Val impl Val { fn value(&self) -> &f64 { &self.val } } // impl of GenVal for a generic type `T` impl<T> GenVal<T> { fn value(&self) -> &T { &self.gen_val } } fn generics() { let x = Val { val: 3.0 }; let y = GenVal { gen_val: 3i32 }; println!("{}, {}", x.value(), y.value()); } fn create_box() { let _box = Box::new(3i32); } struct ToDrop; impl Drop for ToDrop { fn drop(&mut self) { println!("ToDrop is being dropped"); } } fn destroy_box(c: Box<i32>) { println!("Destroying a box that contains {}", c); // `c` is destroyed and the memory freed } fn scoping() { /* create_box(); let _box2 = Box::new(5i32); { let _box3 = Box::new(4i32); } let x = ToDrop; { let y = ToDrop; }*/ let x = 5u32; let y = x; println!("x is {}, and y is {}", x, y); let a = Box::new(5i32); let mut b = a; *b = 30i32; //destroy_box(b); println!("{}", b); } fn ownership() { let a = Box::new(5i32); let mut b = a; *b = 4; println!("{}", b); } fn eat_box(boxed: Box<i32>) { println!("{}", boxed); } fn borrow(borrowed: &i32) { println!("{}", borrowed); } fn borrowing() { let boxed = Box::new(5_i32); let stacked = 6_i32; borrow(&boxed); borrow(&stacked); { let refTo: &i32 = &boxed; borrow(refTo); } eat_box(boxed); } #[derive(Clone, Copy)] struct Book { author: &'static str, title: &'static str, year: u32, } fn borrow_book(book: &Book) { println!("I immutably borrowed {} - {}", book.author, book.title); } fn new_edition(book: &mut Book) { book.year = 2014; println!("I mutably borrowed {} - {} edition", book.title, book.year); } fn mutability() { let immutable_book = Book { author: "Ivan Cankar", title: "Hlapci", year: 1910, }; let mut mutable_book = immutable_book; borrow_book(&immutable_book); borrow_book(&mutable_book); new_edition(&mut mutable_book); } struct Location { x: i32, y: i32, z: i32, } fn aliasing() { let mut location = Location { x: 0, y: 0, z: 0 }; let borrow1 = &location; let borrow2 = &location; println!("{} {}", location.x, borrow1.x); //let mut_borow = &mut location; println!( "Location has coordinates: ({}, {}, {})", borrow1.x, borrow2.y, location.z ); let mut_borow = &mut location; mut_borow.x = 10; mut_borow.y = 23; mut_borow.z = 29; let borrow3 = &location; } #[derive(PartialEq, PartialOrd)] struct Centimeters(f64); #[derive(Debug)] struct Inches(i32); impl Inches { fn to_centimeters(&self) -> Centimeters { let &Inches(inches) = self; Centimeters(inches as f64 * 2.54) } } struct Seconds(i32); fn deriveTest() { let one_second = Seconds(1); let foot = Inches(12); println!("One foot equals: {:?}", foot); let meter = Centimeters(100.0); let cmp = if foot.to_centimeters() < meter { "smaller" } else { "bigger" }; println!("One foot is {} than one meter.", cmp); } struct Sheep {} struct Cow {} trait Animal { fn noise(&self) -> &'static str; } impl Animal for Sheep { fn noise(&self) -> &'static str { "baaah" } } impl Animal for Cow { fn noise(&self) -> &'static str { "moooooo" } } fn random_animal(random_number: f64) -> Box<dyn Animal> { if random_number < 0.5 { Box::new(Sheep {}) } else { Box::new(Cow {}) } } fn dyReturn() { let random_number = 0.3444; let animal = random_animal(random_number); println!( "You've randomly chosen an animal, and it says {}", animal.noise() ); } use std::ops; struct Foo; struct Bar; #[derive(Debug)] struct FooBar; #[derive(Debug)] struct BarFoo; impl ops::Add<Bar> for Foo { type Output = FooBar; fn add(self, _rhs: Bar) -> FooBar { println!("> Foo.add(Bar) was called"); FooBar } } impl ops::Add<Foo> for Bar
{ let x = 30; println!("x: {:?}", x); let y = apply_to_3(|x| x + 20); println!("y: {:?}", y); let greeting = "Hello"; let mut farewel = "Goodby".to_owned(); let diary = || { println!("I said {}", greeting); farewel.push_str("!!!!!"); println!("Than I screemed {}", farewel); println!("Than I sleep");
identifier_body
dec.rs
comment on this rule: "The instantiation of type schemes allows different occurrences of // a single longvid to assume different types." Exp::LongVid(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; Ok(instantiate(st, &val_info.ty_scheme)) } // SML Definition (3) Exp::Record(rows) => { let mut ty_rows = BTreeMap::new(); // SML Definition (6) for row in rows { let ty = ck_exp(cx, st, &row.val)?; if ty_rows.insert(row.lab.val, ty).is_some() { return Err(row.lab.loc.wrap(Error::DuplicateLabel(row.lab.val))); } } Ok(Ty::Record(ty_rows)) } Exp::Select(..) => Err(exp.loc.wrap(Error::Todo("record selectors"))), // SML Definition Appendix A - tuples are sugar for records Exp::Tuple(exps) => { let mut ty_rows = BTreeMap::new(); for (idx, exp) in exps.iter().enumerate() { let ty = ck_exp(cx, st, exp)?; assert!(ty_rows.insert(Label::tuple(idx), ty).is_none()); } Ok(Ty::Record(ty_rows)) } // SML Definition Appendix A - lists are sugar for cons + nil Exp::List(exps) => { let elem = Ty::Var(st.new_ty_var(false)); for exp in exps { let ty = ck_exp(cx, st, exp)?; st.unify(exp.loc, elem.clone(), ty)?; } Ok(Ty::list(elem)) } // SML Definition Appendix A - sequences ignore all but the last expression Exp::Sequence(exps) => { let mut ret = None; for exp in exps { ret = Some(ck_exp(cx, st, exp)?); } Ok(ret.unwrap()) } // SML Definition (4) Exp::Let(dec, exps) => { let gen_syms = st.generated_syms(); let env = ck(cx, st, dec)?; let mut cx = cx.clone(); cx.o_plus(env); let mut last = None; for exp in exps { last = Some((exp.loc, ck_exp(&cx, st, exp)?)); } let (loc, mut ty) = last.unwrap(); ty.apply(&st.subst); if!gen_syms.contains(&ty.ty_names()) { return Err(loc.wrap(Error::TyNameEscape)); } Ok(ty) } // SML Definition (8) Exp::App(func, arg) => { let func_ty = ck_exp(cx, st, func)?; let arg_ty = ck_exp(cx, st, arg)?; // we don't actually _need_ to case on func_ty, since the Var case is actually correct for // _all_ types. we just do this to produce better error messages in the Record and Ctor cases. match func_ty { Ty::Var(tv) => { if st.subst.is_bound(&tv) { Err(exp.loc.wrap(Error::NotArrowTy(func_ty))) } else { let ret_ty = Ty::Var(st.new_ty_var(false)); let arrow_ty = Ty::Arrow(arg_ty.into(), ret_ty.clone().into()); st.unify(exp.loc, func_ty, arrow_ty)?; Ok(ret_ty) } } Ty::Arrow(func_arg_ty, func_ret_ty) => { st.unify(exp.loc, *func_arg_ty, arg_ty)?; Ok(*func_ret_ty) } Ty::Record(_) | Ty::Ctor(_, _) => Err(exp.loc.wrap(Error::NotArrowTy(func_ty))), } } // SML Definition (8). Infix application is the same as `op`ing the infix operator and applying // it to a tuple (lhs, rhs). Exp::InfixApp(lhs, func, rhs) => { let val_info = get_val_info(&cx.env, *func)?; let func_ty = instantiate(st, &val_info.ty_scheme); let lhs_ty = ck_exp(cx, st, lhs)?; let rhs_ty = ck_exp(cx, st, rhs)?; let ret_ty = Ty::Var(st.new_ty_var(false)); let arrow_ty = Ty::Arrow(Ty::pair(lhs_ty, rhs_ty).into(), ret_ty.clone().into()); st.unify(exp.loc, func_ty, arrow_ty)?; Ok(ret_ty) } // SML Definition (9) Exp::Typed(inner, ty) => { let exp_ty = ck_exp(cx, st, inner)?; let ty_ty = ty::ck(cx, &st.tys, ty)?; st.unify(exp.loc, ty_ty, exp_ty.clone())?; Ok(exp_ty) } // SML Definition Appendix A - boolean operators are sugar for `if` Exp::Andalso(lhs, rhs) | Exp::Orelse(lhs, rhs) => { let lhs_ty = ck_exp(cx, st, lhs)?; let rhs_ty = ck_exp(cx, st, rhs)?; st.unify(lhs.loc, Ty::BOOL, lhs_ty)?; st.unify(rhs.loc, Ty::BOOL, rhs_ty)?; Ok(Ty::BOOL) } // SML Definition (10) Exp::Handle(head, cases) => { let head_ty = ck_exp(cx, st, head)?; let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_handle(pats)?; st.unify(exp.loc, Ty::EXN, arg_ty)?; st.unify(exp.loc, head_ty.clone(), res_ty)?; Ok(head_ty) } // SML Definition (11) Exp::Raise(exp) => { let exp_ty = ck_exp(cx, st, exp)?; st.unify(exp.loc, Ty::EXN, exp_ty)?; Ok(Ty::Var(st.new_ty_var(false))) } // SML Definition Appendix A - `if` is sugar for casing Exp::If(cond, then_e, else_e) => { let cond_ty = ck_exp(cx, st, cond)?; let then_ty = ck_exp(cx, st, then_e)?; let else_ty = ck_exp(cx, st, else_e)?; st.unify(cond.loc, Ty::BOOL, cond_ty)?; st.unify(exp.loc, then_ty.clone(), else_ty)?; Ok(then_ty) } Exp::While(..) => Err(exp.loc.wrap(Error::Todo("`while`"))), // SML Definition Appendix A - `case` is sugar for application to a `fn` Exp::Case(head, cases) => { let head_ty = ck_exp(cx, st, head)?; let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_match(pats, exp.loc)?; st.unify(exp.loc, head_ty, arg_ty)?; Ok(res_ty) } // SML Definition (12) Exp::Fn(cases) => { let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_match(pats, exp.loc)?; Ok(Ty::Arrow(arg_ty.into(), res_ty.into())) } } } /// SML Definition (13) fn ck_cases(cx: &Cx, st: &mut State, cases: &Cases<StrRef>) -> Result<(Vec<Located<Pat>>, Ty, Ty)> { let arg_ty = Ty::Var(st.new_ty_var(false)); let res_ty = Ty::Var(st.new_ty_var(false)); let mut pats = Vec::with_capacity(cases.arms.len()); // SML Definition (14) for arm in cases.arms.iter() { let (val_env, pat_ty, pat) = pat::ck(cx, st, &arm.pat)?; pats.push(arm.pat.loc.wrap(pat)); let mut cx = cx.clone(); cx.env.val_env.extend(val_env); let exp_ty = ck_exp(&cx, st, &arm.exp)?; st.unify(arm.pat.loc, arg_ty.clone(), pat_ty)?; st.unify(arm.exp.loc, res_ty.clone(), exp_ty)?; } Ok((pats, arg_ty, res_ty)) } /// Returns `Ok(())` iff `name` is not a forbidden binding name. TODO there are more of these in /// certain situations fn ck_binding(name: Located<StrRef>) -> Result<()> { let val = name.val; if val == StrRef::TRUE || val == StrRef::FALSE || val == StrRef::NIL || val == StrRef::CONS || val == StrRef::REF { return Err(name.loc.wrap(Error::ForbiddenBinding(name.val))); } Ok(()) } struct FunInfo { args: Vec<TyVar>, ret: TyVar, } fn fun_infos_to_ve(fun_infos: &HashMap<StrRef, FunInfo>) -> ValEnv
pub fn ck(cx: &Cx, st: &mut State, dec: &Located<Dec<StrRef>>) -> Result<Env> { match &dec.val { // SML Definition (15) Dec::Val(ty_vars, val_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, ty_vars)?; &cx_cl }; let mut val_env = ValEnv::new(); // SML Definition (25) for val_bind in val_binds { // SML Definition (26) if val_bind.rec { return Err(dec.loc.wrap(Error::Todo("recursive val binds"))); } let (other, pat_ty, pat) = pat::ck(cx, st, &val_bind.pat)?; for &name in other.keys() { ck_binding(val_bind.pat.loc.wrap(name))?; } let exp_ty = ck_exp(cx, st, &val_bind.exp)?; st.unify(dec.loc, pat_ty.clone(), exp_ty)?; exhaustive::ck_bind(pat, val_bind.pat.loc)?; for (name, mut val_info) in other { generalize(cx, st, ty_vars, &mut val_info.ty_scheme); let name = val_bind.pat.loc.wrap(name); env_ins(&mut val_env, name, val_info, Item::Val)?; } } Ok(val_env.into()) } // SML Definition Appendix A - `fun` is sugar for `val rec` and `case` Dec::Fun(ty_vars, fval_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, ty_vars)?; &cx_cl }; let mut fun_infos = HashMap::with_capacity(fval_binds.len()); for fval_bind in fval_binds { let first = fval_bind.cases.first().unwrap(); let info = FunInfo { args: first.pats.iter().map(|_| st.new_ty_var(false)).collect(), ret: st.new_ty_var(false), }; // copied from env_ins in util if fun_infos.insert(first.vid.val, info).is_some() { let err = Error::Duplicate(Item::Val, first.vid.val); return Err(first.vid.loc.wrap(err)); } } for fval_bind in fval_binds { let name = fval_bind.cases.first().unwrap().vid.val; let info = fun_infos.get(&name).unwrap(); let mut arg_pats = Vec::with_capacity(fval_bind.cases.len()); for case in fval_bind.cases.iter() { if name!= case.vid.val { let err = Error::FunDecNameMismatch(name, case.vid.val); return Err(case.vid.loc.wrap(err)); } if info.args.len()!= case.pats.len() { let err = Error::FunDecWrongNumPats(info.args.len(), case.pats.len()); let begin = case.pats.first().unwrap().loc; let end = case.pats.last().unwrap().loc; return Err(begin.span(end).wrap(err)); } let mut pats_val_env = ValEnv::new(); let mut arg_pat = Vec::with_capacity(info.args.len()); for (pat, &tv) in case.pats.iter().zip(info.args.iter()) { let (ve, pat_ty, new_pat) = pat::ck(cx, st, pat)?; st.unify(pat.loc, Ty::Var(tv), pat_ty)?; env_merge(&mut pats_val_env, ve, pat.loc, Item::Val)?; arg_pat.push(new_pat); } let begin = case.pats.first().unwrap().loc; let end = case.pats.last().unwrap().loc; arg_pats.push(begin.span(end).wrap(Pat::record(arg_pat))); if let Some(ty) = &case.ret_ty { let new_ty = ty::ck(cx, &st.tys, ty)?; st.unify(ty.loc, Ty::Var(info.ret), new_ty)?; } let mut cx = cx.clone(); // no dupe checking here - intentionally shadow. cx.env.val_env.extend(fun_infos_to_ve(&fun_infos)); cx.env.val_env.extend(pats_val_env); let body_ty = ck_exp(&cx, st, &case.body)?; st.unify(case.body.loc, Ty::Var(info.ret), body_ty)?; } let begin = fval_bind.cases.first().unwrap().vid.loc; let end = fval_bind.cases.last().unwrap().body.loc; exhaustive::ck_match(arg_pats, begin.span(end))?; } let mut val_env = fun_infos_to_ve(&fun_infos); for val_info in val_env.values_mut() { generalize(cx, st, ty_vars, &mut val_info.ty_scheme); } Ok(val_env.into()) } // SML Definition (16) Dec::Type(ty_binds) => ck_ty_binds(cx, st, ty_binds), // SML Definition (17) Dec::Datatype(dat_binds, ty_binds) => { let mut env = ck_dat_binds(cx.clone(), st, dat_binds)?; // SML Definition Appendix A - `datatype withtype` is sugar for `datatype; type` let mut cx = cx.clone(); cx.o_plus(env.clone()); env.extend(ck_ty_binds(&cx, st, ty_binds)?); Ok(env) } // SML Definition (18) Dec::DatatypeCopy(ty_con, long) => ck_dat_copy(cx, &st.tys, *ty_con, long), // SML Definition (19) Dec::Abstype(..) => Err(dec.loc.wrap(Error::Todo("`abstype`"))), // SML Definition (20) Dec::Exception(ex_binds) => { let mut val_env = ValEnv::new(); for ex_bind in ex_binds { let val_info = match &ex_bind.inner { // SML Definition (30) ExBindInner::Ty(ty) => match ty { None => ValInfo::exn(), Some(ty) => ValInfo::exn_fn(ty::ck(cx, &st.tys, ty)?), }, // SML Definition (31) ExBindInner::Long(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; if!val_info.id_status.is_exn() { return Err(vid.loc().wrap(Error::ExnWrongIdStatus(val_info.id_status))); } val_info.clone() } }; env_ins(&mut val_env, ex_bind.vid, val_info, Item::Val)?; } Ok(val_env.into()) } // SML Definition (21) Dec::Local(fst, snd) => { let fst_env = ck(cx, st, fst)?; let mut cx = cx.clone(); cx.o_plus(fst_env); ck(&cx, st, snd) } // SML Definition (22) Dec::Open(longs) => { let mut env = Env::default(); for long in longs { env.extend(get_env(&cx.env, long)?.clone()); } Ok(env) } // SML Definition (23), SML Definition (24) Dec::Seq(decs) => { let mut cx = cx.clone(); let mut ret = Env::default(); for dec in decs { cx.o_plus(ret.clone()); let env = ck(&cx, st, dec)?; ret.extend(env); } Ok(ret) } Dec::Infix(..) | Dec::Infixr(..) | Dec::Nonfix(..) => Ok(Env::default()), } } /// SML Definition (16) fn ck_ty_binds(cx: &Cx, st: &mut State, ty_binds: &[TyBind<StrRef>]) -> Result<Env> { let mut ty_env = TyEnv::default(); // SML Definition (27) for ty_bind in ty_binds { let mut cx_cl; let cx = if ty_bind.ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, &ty_bind.ty_vars)?; &cx_cl }; let ty = ty::ck(cx, &st.tys, &ty_bind.ty)?; let sym = st.new_sym(ty_bind.ty_con); env_ins(&mut ty_env.inner, ty_bind.ty_con, sym, Item::Ty)?; // TODO better equality checks let equality = ty.is_equality(&st.tys); let info = TyInfo { ty_fcn: TyScheme { ty_vars: ty_bind .ty_vars .iter() .map(|tv| { let tv = *cx.ty_vars.get(&tv.val).unwrap(); st.subst.remove_bound(&tv); tv }) .collect(), ty, overload: None, }, val_env: ValEnv::new(), equality, }; st.tys.insert(sym, info); } Ok(ty_env.into()) } /// SML Definition (17), SML Definition (71). The checking for {datatype, constructor} {bindings, /// descriptions} appear to be essentially identical, so we can unite the ASTs and static checking /// functions (i.e. this function). pub fn ck_dat_binds(mut cx: Cx, st: &mut State, dat_binds: &[DatBind<StrRef>]) -> Result<Env> { // these two are across all `DatBind`s. let mut ty_env = TyEnv::default(); let mut val_env = ValEnv::new(); // we must first generate new symbols for _all_ the types being defined, since they are allowed to // reference each other. (apparently? according to SML NJ, but it seems like the Definition does // not indicate this, according to my reading of e.g. SML Definition (28).) let mut syms = Vec::new(); for dat_bind in dat_binds { // create a new symbol for the type being generated with this `DatBind`. let sym = st.new_sym(dat_bind.ty_con); // tell the original context as well as the overall `TyEnv` that we return that this new // datatype does exist, but tell the State that it has just an empty `ValEnv`. also perform dupe // checking on the name of the new type and assert for sanity checking after the dupe check. env_ins(&mut ty_env.inner, dat_bind.ty_con, sym, Item::Ty)?; // no assert is_none since we may be shadowing something from an earlier Dec in this Cx. cx.env.ty_env.inner.insert(dat_bind.ty_con.val, sym); // no mapping from ast ty vars to statics ty vars here. we just need some ty vars to make the // `TyScheme`. pretty much copied from `insert_ty_vars`. let mut set = HashSet::new(); let mut ty_vars = Vec::new(); for tv in dat_bind.ty_vars.iter() { if!set.insert(tv.val.name) { return Err(tv.loc.wrap(Error::Duplicate(Item::TyVar, tv.val.name))); } let new_tv = st.new_ty_var(tv.val.equality); ty_vars.push(new_tv); // no need to `insert_bound` because no unifying occurs. } let ty_args: Vec<_> = ty_vars.iter().copied().map(Ty::Var).collect(); let ty_fcn = TyScheme { ty_vars, ty: Ty::Ctor(ty_args, sym), overload: None, }; st.tys.insert_datatype(sym, ty_fcn); syms.push(sym); } // SML Definition (28), SML Definition (81) for (dat_bind, sym) in dat_binds.iter().zip(syms) { // note that we have to `get` here and then `get_mut` again later because of the borrow checker. let ty_fcn = &st.tys.get(&sym).ty_fcn; let mut cx_cl; let cx = if dat_bind.ty_vars.is_empty() { &cx } else { // it is here that we introduce the mapping from ast ty vars to statics ty vars. we need to do // that in order to check the `ConBind`s. but we cannot introduce the mapping earlier, when we // were generating the statics ty vars and the `Sym`s, because there may be multiple // identically-named ty vars in different `DatBind`s. // // if we wanted we could generate new statics type variables here, but then we'd have to use // those new type variables in the return type of the ctor. it shouldn't matter whether we // generate new type variables here or not (as mentioned, we choose to not) because both the // type function and the ctors of the type will each have a `TyScheme` that binds the type // variables appropriately, so by the magic of alpha conversion they're all distinct anyway. cx_cl = cx.clone(); assert_eq!(dat_bind.ty_vars.len(), ty_fcn.ty_vars.len()); for (ast_tv, &tv
{ fun_infos .iter() .map(|(&name, fun_info)| { let ty = fun_info .args .iter() .rev() .fold(Ty::Var(fun_info.ret), |ac, &tv| { Ty::Arrow(Ty::Var(tv).into(), ac.into()) }); (name, ValInfo::val(TyScheme::mono(ty))) }) .collect() }
identifier_body
dec.rs
comment on this rule: "The instantiation of type schemes allows different occurrences of // a single longvid to assume different types." Exp::LongVid(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; Ok(instantiate(st, &val_info.ty_scheme)) } // SML Definition (3) Exp::Record(rows) => { let mut ty_rows = BTreeMap::new(); // SML Definition (6) for row in rows { let ty = ck_exp(cx, st, &row.val)?; if ty_rows.insert(row.lab.val, ty).is_some() { return Err(row.lab.loc.wrap(Error::DuplicateLabel(row.lab.val))); } } Ok(Ty::Record(ty_rows)) } Exp::Select(..) => Err(exp.loc.wrap(Error::Todo("record selectors"))), // SML Definition Appendix A - tuples are sugar for records Exp::Tuple(exps) => { let mut ty_rows = BTreeMap::new(); for (idx, exp) in exps.iter().enumerate() { let ty = ck_exp(cx, st, exp)?; assert!(ty_rows.insert(Label::tuple(idx), ty).is_none()); } Ok(Ty::Record(ty_rows)) } // SML Definition Appendix A - lists are sugar for cons + nil Exp::List(exps) => { let elem = Ty::Var(st.new_ty_var(false)); for exp in exps { let ty = ck_exp(cx, st, exp)?; st.unify(exp.loc, elem.clone(), ty)?; } Ok(Ty::list(elem)) } // SML Definition Appendix A - sequences ignore all but the last expression Exp::Sequence(exps) => { let mut ret = None; for exp in exps { ret = Some(ck_exp(cx, st, exp)?); } Ok(ret.unwrap()) } // SML Definition (4) Exp::Let(dec, exps) => { let gen_syms = st.generated_syms(); let env = ck(cx, st, dec)?; let mut cx = cx.clone(); cx.o_plus(env); let mut last = None; for exp in exps { last = Some((exp.loc, ck_exp(&cx, st, exp)?)); } let (loc, mut ty) = last.unwrap(); ty.apply(&st.subst); if!gen_syms.contains(&ty.ty_names()) { return Err(loc.wrap(Error::TyNameEscape)); } Ok(ty) } // SML Definition (8) Exp::App(func, arg) => { let func_ty = ck_exp(cx, st, func)?; let arg_ty = ck_exp(cx, st, arg)?; // we don't actually _need_ to case on func_ty, since the Var case is actually correct for // _all_ types. we just do this to produce better error messages in the Record and Ctor cases. match func_ty { Ty::Var(tv) => { if st.subst.is_bound(&tv) { Err(exp.loc.wrap(Error::NotArrowTy(func_ty))) } else { let ret_ty = Ty::Var(st.new_ty_var(false)); let arrow_ty = Ty::Arrow(arg_ty.into(), ret_ty.clone().into()); st.unify(exp.loc, func_ty, arrow_ty)?; Ok(ret_ty) } } Ty::Arrow(func_arg_ty, func_ret_ty) => { st.unify(exp.loc, *func_arg_ty, arg_ty)?; Ok(*func_ret_ty) } Ty::Record(_) | Ty::Ctor(_, _) => Err(exp.loc.wrap(Error::NotArrowTy(func_ty))), } } // SML Definition (8). Infix application is the same as `op`ing the infix operator and applying // it to a tuple (lhs, rhs). Exp::InfixApp(lhs, func, rhs) => { let val_info = get_val_info(&cx.env, *func)?; let func_ty = instantiate(st, &val_info.ty_scheme); let lhs_ty = ck_exp(cx, st, lhs)?; let rhs_ty = ck_exp(cx, st, rhs)?; let ret_ty = Ty::Var(st.new_ty_var(false)); let arrow_ty = Ty::Arrow(Ty::pair(lhs_ty, rhs_ty).into(), ret_ty.clone().into()); st.unify(exp.loc, func_ty, arrow_ty)?; Ok(ret_ty) } // SML Definition (9) Exp::Typed(inner, ty) => { let exp_ty = ck_exp(cx, st, inner)?; let ty_ty = ty::ck(cx, &st.tys, ty)?; st.unify(exp.loc, ty_ty, exp_ty.clone())?; Ok(exp_ty) } // SML Definition Appendix A - boolean operators are sugar for `if` Exp::Andalso(lhs, rhs) | Exp::Orelse(lhs, rhs) => { let lhs_ty = ck_exp(cx, st, lhs)?; let rhs_ty = ck_exp(cx, st, rhs)?; st.unify(lhs.loc, Ty::BOOL, lhs_ty)?; st.unify(rhs.loc, Ty::BOOL, rhs_ty)?; Ok(Ty::BOOL) } // SML Definition (10) Exp::Handle(head, cases) => { let head_ty = ck_exp(cx, st, head)?; let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_handle(pats)?; st.unify(exp.loc, Ty::EXN, arg_ty)?; st.unify(exp.loc, head_ty.clone(), res_ty)?; Ok(head_ty) } // SML Definition (11) Exp::Raise(exp) => { let exp_ty = ck_exp(cx, st, exp)?; st.unify(exp.loc, Ty::EXN, exp_ty)?; Ok(Ty::Var(st.new_ty_var(false))) } // SML Definition Appendix A - `if` is sugar for casing Exp::If(cond, then_e, else_e) => { let cond_ty = ck_exp(cx, st, cond)?; let then_ty = ck_exp(cx, st, then_e)?; let else_ty = ck_exp(cx, st, else_e)?; st.unify(cond.loc, Ty::BOOL, cond_ty)?; st.unify(exp.loc, then_ty.clone(), else_ty)?; Ok(then_ty) } Exp::While(..) => Err(exp.loc.wrap(Error::Todo("`while`"))), // SML Definition Appendix A - `case` is sugar for application to a `fn` Exp::Case(head, cases) => { let head_ty = ck_exp(cx, st, head)?; let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_match(pats, exp.loc)?; st.unify(exp.loc, head_ty, arg_ty)?; Ok(res_ty) } // SML Definition (12) Exp::Fn(cases) => { let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_match(pats, exp.loc)?; Ok(Ty::Arrow(arg_ty.into(), res_ty.into())) } } } /// SML Definition (13) fn ck_cases(cx: &Cx, st: &mut State, cases: &Cases<StrRef>) -> Result<(Vec<Located<Pat>>, Ty, Ty)> { let arg_ty = Ty::Var(st.new_ty_var(false)); let res_ty = Ty::Var(st.new_ty_var(false)); let mut pats = Vec::with_capacity(cases.arms.len()); // SML Definition (14) for arm in cases.arms.iter() { let (val_env, pat_ty, pat) = pat::ck(cx, st, &arm.pat)?; pats.push(arm.pat.loc.wrap(pat)); let mut cx = cx.clone(); cx.env.val_env.extend(val_env); let exp_ty = ck_exp(&cx, st, &arm.exp)?; st.unify(arm.pat.loc, arg_ty.clone(), pat_ty)?; st.unify(arm.exp.loc, res_ty.clone(), exp_ty)?; } Ok((pats, arg_ty, res_ty)) } /// Returns `Ok(())` iff `name` is not a forbidden binding name. TODO there are more of these in /// certain situations fn ck_binding(name: Located<StrRef>) -> Result<()> { let val = name.val; if val == StrRef::TRUE || val == StrRef::FALSE || val == StrRef::NIL || val == StrRef::CONS || val == StrRef::REF { return Err(name.loc.wrap(Error::ForbiddenBinding(name.val))); } Ok(()) } struct FunInfo { args: Vec<TyVar>, ret: TyVar, } fn fun_infos_to_ve(fun_infos: &HashMap<StrRef, FunInfo>) -> ValEnv { fun_infos .iter() .map(|(&name, fun_info)| { let ty = fun_info .args .iter() .rev() .fold(Ty::Var(fun_info.ret), |ac, &tv| { Ty::Arrow(Ty::Var(tv).into(), ac.into()) }); (name, ValInfo::val(TyScheme::mono(ty))) }) .collect() } pub fn ck(cx: &Cx, st: &mut State, dec: &Located<Dec<StrRef>>) -> Result<Env> { match &dec.val { // SML Definition (15) Dec::Val(ty_vars, val_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, ty_vars)?; &cx_cl }; let mut val_env = ValEnv::new(); // SML Definition (25) for val_bind in val_binds { // SML Definition (26) if val_bind.rec { return Err(dec.loc.wrap(Error::Todo("recursive val binds"))); } let (other, pat_ty, pat) = pat::ck(cx, st, &val_bind.pat)?; for &name in other.keys() { ck_binding(val_bind.pat.loc.wrap(name))?; } let exp_ty = ck_exp(cx, st, &val_bind.exp)?; st.unify(dec.loc, pat_ty.clone(), exp_ty)?; exhaustive::ck_bind(pat, val_bind.pat.loc)?; for (name, mut val_info) in other { generalize(cx, st, ty_vars, &mut val_info.ty_scheme); let name = val_bind.pat.loc.wrap(name); env_ins(&mut val_env, name, val_info, Item::Val)?; } } Ok(val_env.into()) } // SML Definition Appendix A - `fun` is sugar for `val rec` and `case`
Dec::Fun(ty_vars, fval_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, ty_vars)?; &cx_cl }; let mut fun_infos = HashMap::with_capacity(fval_binds.len()); for fval_bind in fval_binds { let first = fval_bind.cases.first().unwrap(); let info = FunInfo { args: first.pats.iter().map(|_| st.new_ty_var(false)).collect(), ret: st.new_ty_var(false), }; // copied from env_ins in util if fun_infos.insert(first.vid.val, info).is_some() { let err = Error::Duplicate(Item::Val, first.vid.val); return Err(first.vid.loc.wrap(err)); } } for fval_bind in fval_binds { let name = fval_bind.cases.first().unwrap().vid.val; let info = fun_infos.get(&name).unwrap(); let mut arg_pats = Vec::with_capacity(fval_bind.cases.len()); for case in fval_bind.cases.iter() { if name!= case.vid.val { let err = Error::FunDecNameMismatch(name, case.vid.val); return Err(case.vid.loc.wrap(err)); } if info.args.len()!= case.pats.len() { let err = Error::FunDecWrongNumPats(info.args.len(), case.pats.len()); let begin = case.pats.first().unwrap().loc; let end = case.pats.last().unwrap().loc; return Err(begin.span(end).wrap(err)); } let mut pats_val_env = ValEnv::new(); let mut arg_pat = Vec::with_capacity(info.args.len()); for (pat, &tv) in case.pats.iter().zip(info.args.iter()) { let (ve, pat_ty, new_pat) = pat::ck(cx, st, pat)?; st.unify(pat.loc, Ty::Var(tv), pat_ty)?; env_merge(&mut pats_val_env, ve, pat.loc, Item::Val)?; arg_pat.push(new_pat); } let begin = case.pats.first().unwrap().loc; let end = case.pats.last().unwrap().loc; arg_pats.push(begin.span(end).wrap(Pat::record(arg_pat))); if let Some(ty) = &case.ret_ty { let new_ty = ty::ck(cx, &st.tys, ty)?; st.unify(ty.loc, Ty::Var(info.ret), new_ty)?; } let mut cx = cx.clone(); // no dupe checking here - intentionally shadow. cx.env.val_env.extend(fun_infos_to_ve(&fun_infos)); cx.env.val_env.extend(pats_val_env); let body_ty = ck_exp(&cx, st, &case.body)?; st.unify(case.body.loc, Ty::Var(info.ret), body_ty)?; } let begin = fval_bind.cases.first().unwrap().vid.loc; let end = fval_bind.cases.last().unwrap().body.loc; exhaustive::ck_match(arg_pats, begin.span(end))?; } let mut val_env = fun_infos_to_ve(&fun_infos); for val_info in val_env.values_mut() { generalize(cx, st, ty_vars, &mut val_info.ty_scheme); } Ok(val_env.into()) } // SML Definition (16) Dec::Type(ty_binds) => ck_ty_binds(cx, st, ty_binds), // SML Definition (17) Dec::Datatype(dat_binds, ty_binds) => { let mut env = ck_dat_binds(cx.clone(), st, dat_binds)?; // SML Definition Appendix A - `datatype withtype` is sugar for `datatype; type` let mut cx = cx.clone(); cx.o_plus(env.clone()); env.extend(ck_ty_binds(&cx, st, ty_binds)?); Ok(env) } // SML Definition (18) Dec::DatatypeCopy(ty_con, long) => ck_dat_copy(cx, &st.tys, *ty_con, long), // SML Definition (19) Dec::Abstype(..) => Err(dec.loc.wrap(Error::Todo("`abstype`"))), // SML Definition (20) Dec::Exception(ex_binds) => { let mut val_env = ValEnv::new(); for ex_bind in ex_binds { let val_info = match &ex_bind.inner { // SML Definition (30) ExBindInner::Ty(ty) => match ty { None => ValInfo::exn(), Some(ty) => ValInfo::exn_fn(ty::ck(cx, &st.tys, ty)?), }, // SML Definition (31) ExBindInner::Long(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; if!val_info.id_status.is_exn() { return Err(vid.loc().wrap(Error::ExnWrongIdStatus(val_info.id_status))); } val_info.clone() } }; env_ins(&mut val_env, ex_bind.vid, val_info, Item::Val)?; } Ok(val_env.into()) } // SML Definition (21) Dec::Local(fst, snd) => { let fst_env = ck(cx, st, fst)?; let mut cx = cx.clone(); cx.o_plus(fst_env); ck(&cx, st, snd) } // SML Definition (22) Dec::Open(longs) => { let mut env = Env::default(); for long in longs { env.extend(get_env(&cx.env, long)?.clone()); } Ok(env) } // SML Definition (23), SML Definition (24) Dec::Seq(decs) => { let mut cx = cx.clone(); let mut ret = Env::default(); for dec in decs { cx.o_plus(ret.clone()); let env = ck(&cx, st, dec)?; ret.extend(env); } Ok(ret) } Dec::Infix(..) | Dec::Infixr(..) | Dec::Nonfix(..) => Ok(Env::default()), } } /// SML Definition (16) fn ck_ty_binds(cx: &Cx, st: &mut State, ty_binds: &[TyBind<StrRef>]) -> Result<Env> { let mut ty_env = TyEnv::default(); // SML Definition (27) for ty_bind in ty_binds { let mut cx_cl; let cx = if ty_bind.ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, &ty_bind.ty_vars)?; &cx_cl }; let ty = ty::ck(cx, &st.tys, &ty_bind.ty)?; let sym = st.new_sym(ty_bind.ty_con); env_ins(&mut ty_env.inner, ty_bind.ty_con, sym, Item::Ty)?; // TODO better equality checks let equality = ty.is_equality(&st.tys); let info = TyInfo { ty_fcn: TyScheme { ty_vars: ty_bind .ty_vars .iter() .map(|tv| { let tv = *cx.ty_vars.get(&tv.val).unwrap(); st.subst.remove_bound(&tv); tv }) .collect(), ty, overload: None, }, val_env: ValEnv::new(), equality, }; st.tys.insert(sym, info); } Ok(ty_env.into()) } /// SML Definition (17), SML Definition (71). The checking for {datatype, constructor} {bindings, /// descriptions} appear to be essentially identical, so we can unite the ASTs and static checking /// functions (i.e. this function). pub fn ck_dat_binds(mut cx: Cx, st: &mut State, dat_binds: &[DatBind<StrRef>]) -> Result<Env> { // these two are across all `DatBind`s. let mut ty_env = TyEnv::default(); let mut val_env = ValEnv::new(); // we must first generate new symbols for _all_ the types being defined, since they are allowed to // reference each other. (apparently? according to SML NJ, but it seems like the Definition does // not indicate this, according to my reading of e.g. SML Definition (28).) let mut syms = Vec::new(); for dat_bind in dat_binds { // create a new symbol for the type being generated with this `DatBind`. let sym = st.new_sym(dat_bind.ty_con); // tell the original context as well as the overall `TyEnv` that we return that this new // datatype does exist, but tell the State that it has just an empty `ValEnv`. also perform dupe // checking on the name of the new type and assert for sanity checking after the dupe check. env_ins(&mut ty_env.inner, dat_bind.ty_con, sym, Item::Ty)?; // no assert is_none since we may be shadowing something from an earlier Dec in this Cx. cx.env.ty_env.inner.insert(dat_bind.ty_con.val, sym); // no mapping from ast ty vars to statics ty vars here. we just need some ty vars to make the // `TyScheme`. pretty much copied from `insert_ty_vars`. let mut set = HashSet::new(); let mut ty_vars = Vec::new(); for tv in dat_bind.ty_vars.iter() { if!set.insert(tv.val.name) { return Err(tv.loc.wrap(Error::Duplicate(Item::TyVar, tv.val.name))); } let new_tv = st.new_ty_var(tv.val.equality); ty_vars.push(new_tv); // no need to `insert_bound` because no unifying occurs. } let ty_args: Vec<_> = ty_vars.iter().copied().map(Ty::Var).collect(); let ty_fcn = TyScheme { ty_vars, ty: Ty::Ctor(ty_args, sym), overload: None, }; st.tys.insert_datatype(sym, ty_fcn); syms.push(sym); } // SML Definition (28), SML Definition (81) for (dat_bind, sym) in dat_binds.iter().zip(syms) { // note that we have to `get` here and then `get_mut` again later because of the borrow checker. let ty_fcn = &st.tys.get(&sym).ty_fcn; let mut cx_cl; let cx = if dat_bind.ty_vars.is_empty() { &cx } else { // it is here that we introduce the mapping from ast ty vars to statics ty vars. we need to do // that in order to check the `ConBind`s. but we cannot introduce the mapping earlier, when we // were generating the statics ty vars and the `Sym`s, because there may be multiple // identically-named ty vars in different `DatBind`s. // // if we wanted we could generate new statics type variables here, but then we'd have to use // those new type variables in the return type of the ctor. it shouldn't matter whether we // generate new type variables here or not (as mentioned, we choose to not) because both the // type function and the ctors of the type will each have a `TyScheme` that binds the type // variables appropriately, so by the magic of alpha conversion they're all distinct anyway. cx_cl = cx.clone(); assert_eq!(dat_bind.ty_vars.len(), ty_fcn.ty_vars.len()); for (ast_tv, &tv) in
random_line_split
dec.rs
comment on this rule: "The instantiation of type schemes allows different occurrences of // a single longvid to assume different types." Exp::LongVid(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; Ok(instantiate(st, &val_info.ty_scheme)) } // SML Definition (3) Exp::Record(rows) => { let mut ty_rows = BTreeMap::new(); // SML Definition (6) for row in rows { let ty = ck_exp(cx, st, &row.val)?; if ty_rows.insert(row.lab.val, ty).is_some() { return Err(row.lab.loc.wrap(Error::DuplicateLabel(row.lab.val))); } } Ok(Ty::Record(ty_rows)) } Exp::Select(..) => Err(exp.loc.wrap(Error::Todo("record selectors"))), // SML Definition Appendix A - tuples are sugar for records Exp::Tuple(exps) => { let mut ty_rows = BTreeMap::new(); for (idx, exp) in exps.iter().enumerate() { let ty = ck_exp(cx, st, exp)?; assert!(ty_rows.insert(Label::tuple(idx), ty).is_none()); } Ok(Ty::Record(ty_rows)) } // SML Definition Appendix A - lists are sugar for cons + nil Exp::List(exps) => { let elem = Ty::Var(st.new_ty_var(false)); for exp in exps { let ty = ck_exp(cx, st, exp)?; st.unify(exp.loc, elem.clone(), ty)?; } Ok(Ty::list(elem)) } // SML Definition Appendix A - sequences ignore all but the last expression Exp::Sequence(exps) => { let mut ret = None; for exp in exps { ret = Some(ck_exp(cx, st, exp)?); } Ok(ret.unwrap()) } // SML Definition (4) Exp::Let(dec, exps) => { let gen_syms = st.generated_syms(); let env = ck(cx, st, dec)?; let mut cx = cx.clone(); cx.o_plus(env); let mut last = None; for exp in exps { last = Some((exp.loc, ck_exp(&cx, st, exp)?)); } let (loc, mut ty) = last.unwrap(); ty.apply(&st.subst); if!gen_syms.contains(&ty.ty_names()) { return Err(loc.wrap(Error::TyNameEscape)); } Ok(ty) } // SML Definition (8) Exp::App(func, arg) => { let func_ty = ck_exp(cx, st, func)?; let arg_ty = ck_exp(cx, st, arg)?; // we don't actually _need_ to case on func_ty, since the Var case is actually correct for // _all_ types. we just do this to produce better error messages in the Record and Ctor cases. match func_ty { Ty::Var(tv) => { if st.subst.is_bound(&tv) { Err(exp.loc.wrap(Error::NotArrowTy(func_ty))) } else { let ret_ty = Ty::Var(st.new_ty_var(false)); let arrow_ty = Ty::Arrow(arg_ty.into(), ret_ty.clone().into()); st.unify(exp.loc, func_ty, arrow_ty)?; Ok(ret_ty) } } Ty::Arrow(func_arg_ty, func_ret_ty) => { st.unify(exp.loc, *func_arg_ty, arg_ty)?; Ok(*func_ret_ty) } Ty::Record(_) | Ty::Ctor(_, _) => Err(exp.loc.wrap(Error::NotArrowTy(func_ty))), } } // SML Definition (8). Infix application is the same as `op`ing the infix operator and applying // it to a tuple (lhs, rhs). Exp::InfixApp(lhs, func, rhs) => { let val_info = get_val_info(&cx.env, *func)?; let func_ty = instantiate(st, &val_info.ty_scheme); let lhs_ty = ck_exp(cx, st, lhs)?; let rhs_ty = ck_exp(cx, st, rhs)?; let ret_ty = Ty::Var(st.new_ty_var(false)); let arrow_ty = Ty::Arrow(Ty::pair(lhs_ty, rhs_ty).into(), ret_ty.clone().into()); st.unify(exp.loc, func_ty, arrow_ty)?; Ok(ret_ty) } // SML Definition (9) Exp::Typed(inner, ty) => { let exp_ty = ck_exp(cx, st, inner)?; let ty_ty = ty::ck(cx, &st.tys, ty)?; st.unify(exp.loc, ty_ty, exp_ty.clone())?; Ok(exp_ty) } // SML Definition Appendix A - boolean operators are sugar for `if` Exp::Andalso(lhs, rhs) | Exp::Orelse(lhs, rhs) => { let lhs_ty = ck_exp(cx, st, lhs)?; let rhs_ty = ck_exp(cx, st, rhs)?; st.unify(lhs.loc, Ty::BOOL, lhs_ty)?; st.unify(rhs.loc, Ty::BOOL, rhs_ty)?; Ok(Ty::BOOL) } // SML Definition (10) Exp::Handle(head, cases) => { let head_ty = ck_exp(cx, st, head)?; let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_handle(pats)?; st.unify(exp.loc, Ty::EXN, arg_ty)?; st.unify(exp.loc, head_ty.clone(), res_ty)?; Ok(head_ty) } // SML Definition (11) Exp::Raise(exp) => { let exp_ty = ck_exp(cx, st, exp)?; st.unify(exp.loc, Ty::EXN, exp_ty)?; Ok(Ty::Var(st.new_ty_var(false))) } // SML Definition Appendix A - `if` is sugar for casing Exp::If(cond, then_e, else_e) => { let cond_ty = ck_exp(cx, st, cond)?; let then_ty = ck_exp(cx, st, then_e)?; let else_ty = ck_exp(cx, st, else_e)?; st.unify(cond.loc, Ty::BOOL, cond_ty)?; st.unify(exp.loc, then_ty.clone(), else_ty)?; Ok(then_ty) } Exp::While(..) => Err(exp.loc.wrap(Error::Todo("`while`"))), // SML Definition Appendix A - `case` is sugar for application to a `fn` Exp::Case(head, cases) => { let head_ty = ck_exp(cx, st, head)?; let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_match(pats, exp.loc)?; st.unify(exp.loc, head_ty, arg_ty)?; Ok(res_ty) } // SML Definition (12) Exp::Fn(cases) => { let (pats, arg_ty, res_ty) = ck_cases(cx, st, cases)?; exhaustive::ck_match(pats, exp.loc)?; Ok(Ty::Arrow(arg_ty.into(), res_ty.into())) } } } /// SML Definition (13) fn
(cx: &Cx, st: &mut State, cases: &Cases<StrRef>) -> Result<(Vec<Located<Pat>>, Ty, Ty)> { let arg_ty = Ty::Var(st.new_ty_var(false)); let res_ty = Ty::Var(st.new_ty_var(false)); let mut pats = Vec::with_capacity(cases.arms.len()); // SML Definition (14) for arm in cases.arms.iter() { let (val_env, pat_ty, pat) = pat::ck(cx, st, &arm.pat)?; pats.push(arm.pat.loc.wrap(pat)); let mut cx = cx.clone(); cx.env.val_env.extend(val_env); let exp_ty = ck_exp(&cx, st, &arm.exp)?; st.unify(arm.pat.loc, arg_ty.clone(), pat_ty)?; st.unify(arm.exp.loc, res_ty.clone(), exp_ty)?; } Ok((pats, arg_ty, res_ty)) } /// Returns `Ok(())` iff `name` is not a forbidden binding name. TODO there are more of these in /// certain situations fn ck_binding(name: Located<StrRef>) -> Result<()> { let val = name.val; if val == StrRef::TRUE || val == StrRef::FALSE || val == StrRef::NIL || val == StrRef::CONS || val == StrRef::REF { return Err(name.loc.wrap(Error::ForbiddenBinding(name.val))); } Ok(()) } struct FunInfo { args: Vec<TyVar>, ret: TyVar, } fn fun_infos_to_ve(fun_infos: &HashMap<StrRef, FunInfo>) -> ValEnv { fun_infos .iter() .map(|(&name, fun_info)| { let ty = fun_info .args .iter() .rev() .fold(Ty::Var(fun_info.ret), |ac, &tv| { Ty::Arrow(Ty::Var(tv).into(), ac.into()) }); (name, ValInfo::val(TyScheme::mono(ty))) }) .collect() } pub fn ck(cx: &Cx, st: &mut State, dec: &Located<Dec<StrRef>>) -> Result<Env> { match &dec.val { // SML Definition (15) Dec::Val(ty_vars, val_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, ty_vars)?; &cx_cl }; let mut val_env = ValEnv::new(); // SML Definition (25) for val_bind in val_binds { // SML Definition (26) if val_bind.rec { return Err(dec.loc.wrap(Error::Todo("recursive val binds"))); } let (other, pat_ty, pat) = pat::ck(cx, st, &val_bind.pat)?; for &name in other.keys() { ck_binding(val_bind.pat.loc.wrap(name))?; } let exp_ty = ck_exp(cx, st, &val_bind.exp)?; st.unify(dec.loc, pat_ty.clone(), exp_ty)?; exhaustive::ck_bind(pat, val_bind.pat.loc)?; for (name, mut val_info) in other { generalize(cx, st, ty_vars, &mut val_info.ty_scheme); let name = val_bind.pat.loc.wrap(name); env_ins(&mut val_env, name, val_info, Item::Val)?; } } Ok(val_env.into()) } // SML Definition Appendix A - `fun` is sugar for `val rec` and `case` Dec::Fun(ty_vars, fval_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, ty_vars)?; &cx_cl }; let mut fun_infos = HashMap::with_capacity(fval_binds.len()); for fval_bind in fval_binds { let first = fval_bind.cases.first().unwrap(); let info = FunInfo { args: first.pats.iter().map(|_| st.new_ty_var(false)).collect(), ret: st.new_ty_var(false), }; // copied from env_ins in util if fun_infos.insert(first.vid.val, info).is_some() { let err = Error::Duplicate(Item::Val, first.vid.val); return Err(first.vid.loc.wrap(err)); } } for fval_bind in fval_binds { let name = fval_bind.cases.first().unwrap().vid.val; let info = fun_infos.get(&name).unwrap(); let mut arg_pats = Vec::with_capacity(fval_bind.cases.len()); for case in fval_bind.cases.iter() { if name!= case.vid.val { let err = Error::FunDecNameMismatch(name, case.vid.val); return Err(case.vid.loc.wrap(err)); } if info.args.len()!= case.pats.len() { let err = Error::FunDecWrongNumPats(info.args.len(), case.pats.len()); let begin = case.pats.first().unwrap().loc; let end = case.pats.last().unwrap().loc; return Err(begin.span(end).wrap(err)); } let mut pats_val_env = ValEnv::new(); let mut arg_pat = Vec::with_capacity(info.args.len()); for (pat, &tv) in case.pats.iter().zip(info.args.iter()) { let (ve, pat_ty, new_pat) = pat::ck(cx, st, pat)?; st.unify(pat.loc, Ty::Var(tv), pat_ty)?; env_merge(&mut pats_val_env, ve, pat.loc, Item::Val)?; arg_pat.push(new_pat); } let begin = case.pats.first().unwrap().loc; let end = case.pats.last().unwrap().loc; arg_pats.push(begin.span(end).wrap(Pat::record(arg_pat))); if let Some(ty) = &case.ret_ty { let new_ty = ty::ck(cx, &st.tys, ty)?; st.unify(ty.loc, Ty::Var(info.ret), new_ty)?; } let mut cx = cx.clone(); // no dupe checking here - intentionally shadow. cx.env.val_env.extend(fun_infos_to_ve(&fun_infos)); cx.env.val_env.extend(pats_val_env); let body_ty = ck_exp(&cx, st, &case.body)?; st.unify(case.body.loc, Ty::Var(info.ret), body_ty)?; } let begin = fval_bind.cases.first().unwrap().vid.loc; let end = fval_bind.cases.last().unwrap().body.loc; exhaustive::ck_match(arg_pats, begin.span(end))?; } let mut val_env = fun_infos_to_ve(&fun_infos); for val_info in val_env.values_mut() { generalize(cx, st, ty_vars, &mut val_info.ty_scheme); } Ok(val_env.into()) } // SML Definition (16) Dec::Type(ty_binds) => ck_ty_binds(cx, st, ty_binds), // SML Definition (17) Dec::Datatype(dat_binds, ty_binds) => { let mut env = ck_dat_binds(cx.clone(), st, dat_binds)?; // SML Definition Appendix A - `datatype withtype` is sugar for `datatype; type` let mut cx = cx.clone(); cx.o_plus(env.clone()); env.extend(ck_ty_binds(&cx, st, ty_binds)?); Ok(env) } // SML Definition (18) Dec::DatatypeCopy(ty_con, long) => ck_dat_copy(cx, &st.tys, *ty_con, long), // SML Definition (19) Dec::Abstype(..) => Err(dec.loc.wrap(Error::Todo("`abstype`"))), // SML Definition (20) Dec::Exception(ex_binds) => { let mut val_env = ValEnv::new(); for ex_bind in ex_binds { let val_info = match &ex_bind.inner { // SML Definition (30) ExBindInner::Ty(ty) => match ty { None => ValInfo::exn(), Some(ty) => ValInfo::exn_fn(ty::ck(cx, &st.tys, ty)?), }, // SML Definition (31) ExBindInner::Long(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; if!val_info.id_status.is_exn() { return Err(vid.loc().wrap(Error::ExnWrongIdStatus(val_info.id_status))); } val_info.clone() } }; env_ins(&mut val_env, ex_bind.vid, val_info, Item::Val)?; } Ok(val_env.into()) } // SML Definition (21) Dec::Local(fst, snd) => { let fst_env = ck(cx, st, fst)?; let mut cx = cx.clone(); cx.o_plus(fst_env); ck(&cx, st, snd) } // SML Definition (22) Dec::Open(longs) => { let mut env = Env::default(); for long in longs { env.extend(get_env(&cx.env, long)?.clone()); } Ok(env) } // SML Definition (23), SML Definition (24) Dec::Seq(decs) => { let mut cx = cx.clone(); let mut ret = Env::default(); for dec in decs { cx.o_plus(ret.clone()); let env = ck(&cx, st, dec)?; ret.extend(env); } Ok(ret) } Dec::Infix(..) | Dec::Infixr(..) | Dec::Nonfix(..) => Ok(Env::default()), } } /// SML Definition (16) fn ck_ty_binds(cx: &Cx, st: &mut State, ty_binds: &[TyBind<StrRef>]) -> Result<Env> { let mut ty_env = TyEnv::default(); // SML Definition (27) for ty_bind in ty_binds { let mut cx_cl; let cx = if ty_bind.ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, &ty_bind.ty_vars)?; &cx_cl }; let ty = ty::ck(cx, &st.tys, &ty_bind.ty)?; let sym = st.new_sym(ty_bind.ty_con); env_ins(&mut ty_env.inner, ty_bind.ty_con, sym, Item::Ty)?; // TODO better equality checks let equality = ty.is_equality(&st.tys); let info = TyInfo { ty_fcn: TyScheme { ty_vars: ty_bind .ty_vars .iter() .map(|tv| { let tv = *cx.ty_vars.get(&tv.val).unwrap(); st.subst.remove_bound(&tv); tv }) .collect(), ty, overload: None, }, val_env: ValEnv::new(), equality, }; st.tys.insert(sym, info); } Ok(ty_env.into()) } /// SML Definition (17), SML Definition (71). The checking for {datatype, constructor} {bindings, /// descriptions} appear to be essentially identical, so we can unite the ASTs and static checking /// functions (i.e. this function). pub fn ck_dat_binds(mut cx: Cx, st: &mut State, dat_binds: &[DatBind<StrRef>]) -> Result<Env> { // these two are across all `DatBind`s. let mut ty_env = TyEnv::default(); let mut val_env = ValEnv::new(); // we must first generate new symbols for _all_ the types being defined, since they are allowed to // reference each other. (apparently? according to SML NJ, but it seems like the Definition does // not indicate this, according to my reading of e.g. SML Definition (28).) let mut syms = Vec::new(); for dat_bind in dat_binds { // create a new symbol for the type being generated with this `DatBind`. let sym = st.new_sym(dat_bind.ty_con); // tell the original context as well as the overall `TyEnv` that we return that this new // datatype does exist, but tell the State that it has just an empty `ValEnv`. also perform dupe // checking on the name of the new type and assert for sanity checking after the dupe check. env_ins(&mut ty_env.inner, dat_bind.ty_con, sym, Item::Ty)?; // no assert is_none since we may be shadowing something from an earlier Dec in this Cx. cx.env.ty_env.inner.insert(dat_bind.ty_con.val, sym); // no mapping from ast ty vars to statics ty vars here. we just need some ty vars to make the // `TyScheme`. pretty much copied from `insert_ty_vars`. let mut set = HashSet::new(); let mut ty_vars = Vec::new(); for tv in dat_bind.ty_vars.iter() { if!set.insert(tv.val.name) { return Err(tv.loc.wrap(Error::Duplicate(Item::TyVar, tv.val.name))); } let new_tv = st.new_ty_var(tv.val.equality); ty_vars.push(new_tv); // no need to `insert_bound` because no unifying occurs. } let ty_args: Vec<_> = ty_vars.iter().copied().map(Ty::Var).collect(); let ty_fcn = TyScheme { ty_vars, ty: Ty::Ctor(ty_args, sym), overload: None, }; st.tys.insert_datatype(sym, ty_fcn); syms.push(sym); } // SML Definition (28), SML Definition (81) for (dat_bind, sym) in dat_binds.iter().zip(syms) { // note that we have to `get` here and then `get_mut` again later because of the borrow checker. let ty_fcn = &st.tys.get(&sym).ty_fcn; let mut cx_cl; let cx = if dat_bind.ty_vars.is_empty() { &cx } else { // it is here that we introduce the mapping from ast ty vars to statics ty vars. we need to do // that in order to check the `ConBind`s. but we cannot introduce the mapping earlier, when we // were generating the statics ty vars and the `Sym`s, because there may be multiple // identically-named ty vars in different `DatBind`s. // // if we wanted we could generate new statics type variables here, but then we'd have to use // those new type variables in the return type of the ctor. it shouldn't matter whether we // generate new type variables here or not (as mentioned, we choose to not) because both the // type function and the ctors of the type will each have a `TyScheme` that binds the type // variables appropriately, so by the magic of alpha conversion they're all distinct anyway. cx_cl = cx.clone(); assert_eq!(dat_bind.ty_vars.len(), ty_fcn.ty_vars.len()); for (ast_tv, &tv
ck_cases
identifier_name
parser.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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.. //! A private parser implementation of IPv4, IPv6, and socket addresses. //! //! This module is "publicly exported" through the `FromStr` implementations //! below. use crate::error::Error; use crate::fmt; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::str::FromStr; trait ReadNumberHelper: crate::marker::Sized { const ZERO: Self; fn checked_mul(&self, other: u32) -> Option<Self>; fn checked_add(&self, other: u32) -> Option<Self>; } macro_rules! impl_helper { ($($t:ty)*) => ($(impl ReadNumberHelper for $t { const ZERO: Self = 0; #[inline] fn checked_mul(&self, other: u32) -> Option<Self> { Self::checked_mul(*self, other.try_into().ok()?) } #[inline] fn checked_add(&self, other: u32) -> Option<Self> { Self::checked_add(*self, other.try_into().ok()?) } })*) } impl_helper! { u8 u16 u32 } struct Parser<'a> { // Parsing as ASCII, so can use byte array. state: &'a [u8], } impl<'a> Parser<'a> { fn new(input: &'a [u8]) -> Parser<'a> { Parser { state: input } } /// Run a parser, and restore the pre-parse state if it fails. fn read_atomically<T, F>(&mut self, inner: F) -> Option<T> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { let state = self.state; let result = inner(self); if result.is_none() { self.state = state; } result } /// Run a parser, but fail if the entire input wasn't consumed. /// Doesn't run atomically. fn parse_with<T, F>(&mut self, inner: F, kind: AddrKind) -> Result<T, AddrParseError> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { let result = inner(self); if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind)) } /// Peek the next character from the input fn peek_char(&self) -> Option<char> { self.state.first().map(|&b| char::from(b)) } /// Read the next character from the input fn read_char(&mut self) -> Option<char> { self.state.split_first().map(|(&b, tail)| {
#[must_use] /// Read the next character from the input if it matches the target. fn read_given_char(&mut self, target: char) -> Option<()> { self.read_atomically(|p| { p.read_char().and_then(|c| if c == target { Some(()) } else { None }) }) } /// Helper for reading separators in an indexed loop. Reads the separator /// character iff index > 0, then runs the parser. When used in a loop, /// the separator character will only be read on index > 0 (see /// read_ipv4_addr for an example) fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { self.read_atomically(move |p| { if index > 0 { p.read_given_char(sep)?; } inner(p) }) } // Read a number off the front of the input in the given radix, stopping // at the first non-digit character or eof. Fails if the number has more // digits than max_digits or if there is no number. #[allow(clippy::if_same_then_else)] fn read_number<T: ReadNumberHelper>( &mut self, radix: u32, max_digits: Option<usize>, allow_zero_prefix: bool, ) -> Option<T> { self.read_atomically(move |p| { let mut result = T::ZERO; let mut digit_count = 0; let has_leading_zero = p.peek_char() == Some('0'); while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) { result = result.checked_mul(radix)?; result = result.checked_add(digit)?; digit_count += 1; if let Some(max_digits) = max_digits { if digit_count > max_digits { return None; } } } if digit_count == 0 { None } else if!allow_zero_prefix && has_leading_zero && digit_count > 1 { None } else { Some(result) } }) } /// Read an IPv4 address. fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> { self.read_atomically(|p| { let mut groups = [0; 4]; for (i, slot) in groups.iter_mut().enumerate() { *slot = p.read_separator('.', i, |p| { // Disallow octal number in IP string. // https://tools.ietf.org/html/rfc6943#section-3.1.1 p.read_number(10, Some(3), false) })?; } Some(groups.into()) }) } /// Read an IPv6 Address. fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> { /// Read a chunk of an IPv6 address into `groups`. Returns the number /// of groups read, along with a bool indicating if an embedded /// trailing IPv4 address was read. Specifically, read a series of /// colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional /// trailing embedded IPv4 address. fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) { let limit = groups.len(); for (i, slot) in groups.iter_mut().enumerate() { // Try to read a trailing embedded IPv4 address. There must be // at least two groups left. if i < limit - 1 { let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr()); if let Some(v4_addr) = ipv4 { let [one, two, three, four] = v4_addr.octets(); groups[i] = u16::from_be_bytes([one, two]); groups[i + 1] = u16::from_be_bytes([three, four]); return (i + 2, true); } } let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true)); match group { Some(g) => *slot = g, None => return (i, false), } } (groups.len(), false) } self.read_atomically(|p| { // Read the front part of the address; either the whole thing, or up // to the first :: let mut head = [0; 8]; let (head_size, head_ipv4) = read_groups(p, &mut head); if head_size == 8 { return Some(head.into()); } // IPv4 part is not allowed before `::` if head_ipv4 { return None; } // Read `::` if previous code parsed less than 8 groups. // `::` indicates one or more groups of 16 bits of zeros. p.read_given_char(':')?; p.read_given_char(':')?; // Read the back part of the address. The :: must contain at least one // set of zeroes, so our max length is 7. let mut tail = [0; 7]; let limit = 8 - (head_size + 1); let (tail_size, _) = read_groups(p, &mut tail[..limit]); // Concat the head and tail of the IP address head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]); Some(head.into()) }) } /// Read an IP Address, either IPv4 or IPv6. fn read_ip_addr(&mut self) -> Option<IpAddr> { self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6)) } /// Read a `:` followed by a port in base 10. fn read_port(&mut self) -> Option<u16> { self.read_atomically(|p| { p.read_given_char(':')?; p.read_number(10, None, true) }) } /// Read a `%` followed by a scope ID in base 10. fn read_scope_id(&mut self) -> Option<u32> { self.read_atomically(|p| { p.read_given_char('%')?; p.read_number(10, None, true) }) } /// Read an IPv4 address with a port. fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> { self.read_atomically(|p| { let ip = p.read_ipv4_addr()?; let port = p.read_port()?; Some(SocketAddrV4::new(ip, port)) }) } /// Read an IPv6 address with a port. fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> { self.read_atomically(|p| { p.read_given_char('[')?; let ip = p.read_ipv6_addr()?; let scope_id = p.read_scope_id().unwrap_or(0); p.read_given_char(']')?; let port = p.read_port()?; Some(SocketAddrV6::new(ip, port, 0, scope_id)) }) } /// Read an IP address with a port fn read_socket_addr(&mut self) -> Option<SocketAddr> { self.read_socket_addr_v4() .map(SocketAddr::V4) .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6)) } } impl IpAddr { /// Parse an IP address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); /// /// assert_eq!(IpAddr::parse_ascii(b"127.0.0.1"), Ok(localhost_v4)); /// assert_eq!(IpAddr::parse_ascii(b"::1"), Ok(localhost_v6)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_ip_addr(), AddrKind::Ip) } } impl FromStr for IpAddr { type Err = AddrParseError; fn from_str(s: &str) -> Result<IpAddr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl Ipv4Addr { /// Parse an IPv4 address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::Ipv4Addr; /// /// let localhost = Ipv4Addr::new(127, 0, 0, 1); /// /// assert_eq!(Ipv4Addr::parse_ascii(b"127.0.0.1"), Ok(localhost)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { // don't try to parse if too long if b.len() > 15 { Err(AddrParseError(AddrKind::Ipv4)) } else { Parser::new(b).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4) } } } impl FromStr for Ipv4Addr { type Err = AddrParseError; fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl Ipv6Addr { /// Parse an IPv6 address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::Ipv6Addr; /// /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); /// /// assert_eq!(Ipv6Addr::parse_ascii(b"::1"), Ok(localhost)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6) } } impl FromStr for Ipv6Addr { type Err = AddrParseError; fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddrV4 { /// Parse an IPv4 socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// /// assert_eq!(SocketAddrV4::parse_ascii(b"127.0.0.1:8080"), Ok(socket)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr_v4(), AddrKind::SocketV4) } } impl FromStr for SocketAddrV4 { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddrV6 { /// Parse an IPv6 socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// /// assert_eq!(SocketAddrV6::parse_ascii(b"[2001:db8::1]:8080"), Ok(socket)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr_v6(), AddrKind::SocketV6) } } impl FromStr for SocketAddrV6 { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddr { /// Parse a socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; /// /// let socket_v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); /// let socket_v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080); /// /// assert_eq!(SocketAddr::parse_ascii(b"127.0.0.1:8080"), Ok(socket_v4)); /// assert_eq!(SocketAddr::parse_ascii(b"[::1]:8080"), Ok(socket_v6)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr(), AddrKind::Socket) } } impl FromStr for SocketAddr { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } #[derive(Debug, Clone, PartialEq, Eq)] enum AddrKind { Ip, Ipv4, Ipv6, Socket, SocketV4, SocketV6, } /// An error which can be returned when parsing an IP address or a socket address. /// /// This error is used as the error type for the [`FromStr`] implementation for /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and /// [`SocketAddrV6`]. /// /// # Potential causes /// /// `AddrParseError` may be thrown because the provided string does not parse as the given type, /// often because it includes information only handled by a different address type. /// /// ```should_panic /// use std::net::IpAddr; /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port"); /// ``` /// /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead. /// /// ``` /// use std::net::SocketAddr; /// /// // No problem, the `panic!` message has disappeared. /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic"); /// ``` #[derive(Debug, Clone, PartialEq, Eq)] pub struct AddrParseError(AddrKind); impl fmt::Display for AddrParseError { #[allow(deprecated, deprecated_in_future)] fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str(self.description()) } } impl Error for AddrParseError { #[allow(deprecated)] fn description(&self) -> &str { match self.0 { AddrKind::Ip => "invalid IP address syntax", AddrKind::Ipv4 => "invalid IPv4 address syntax", AddrKind::Ipv6 => "invalid IPv6 address syntax", AddrKind::Socket => "invalid socket address syntax", AddrKind::SocketV4 => "invalid IPv4 socket address syntax", AddrKind::SocketV6 => "invalid IPv6 socket address syntax", } } }
self.state = tail; char::from(b) }) }
random_line_split
parser.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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.. //! A private parser implementation of IPv4, IPv6, and socket addresses. //! //! This module is "publicly exported" through the `FromStr` implementations //! below. use crate::error::Error; use crate::fmt; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::str::FromStr; trait ReadNumberHelper: crate::marker::Sized { const ZERO: Self; fn checked_mul(&self, other: u32) -> Option<Self>; fn checked_add(&self, other: u32) -> Option<Self>; } macro_rules! impl_helper { ($($t:ty)*) => ($(impl ReadNumberHelper for $t { const ZERO: Self = 0; #[inline] fn checked_mul(&self, other: u32) -> Option<Self> { Self::checked_mul(*self, other.try_into().ok()?) } #[inline] fn checked_add(&self, other: u32) -> Option<Self> { Self::checked_add(*self, other.try_into().ok()?) } })*) } impl_helper! { u8 u16 u32 } struct Parser<'a> { // Parsing as ASCII, so can use byte array. state: &'a [u8], } impl<'a> Parser<'a> { fn new(input: &'a [u8]) -> Parser<'a> { Parser { state: input } } /// Run a parser, and restore the pre-parse state if it fails. fn read_atomically<T, F>(&mut self, inner: F) -> Option<T> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { let state = self.state; let result = inner(self); if result.is_none() { self.state = state; } result } /// Run a parser, but fail if the entire input wasn't consumed. /// Doesn't run atomically. fn parse_with<T, F>(&mut self, inner: F, kind: AddrKind) -> Result<T, AddrParseError> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { let result = inner(self); if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind)) } /// Peek the next character from the input fn peek_char(&self) -> Option<char> { self.state.first().map(|&b| char::from(b)) } /// Read the next character from the input fn read_char(&mut self) -> Option<char> { self.state.split_first().map(|(&b, tail)| { self.state = tail; char::from(b) }) } #[must_use] /// Read the next character from the input if it matches the target. fn read_given_char(&mut self, target: char) -> Option<()> { self.read_atomically(|p| { p.read_char().and_then(|c| if c == target { Some(()) } else { None }) }) } /// Helper for reading separators in an indexed loop. Reads the separator /// character iff index > 0, then runs the parser. When used in a loop, /// the separator character will only be read on index > 0 (see /// read_ipv4_addr for an example) fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { self.read_atomically(move |p| { if index > 0 { p.read_given_char(sep)?; } inner(p) }) } // Read a number off the front of the input in the given radix, stopping // at the first non-digit character or eof. Fails if the number has more // digits than max_digits or if there is no number. #[allow(clippy::if_same_then_else)] fn read_number<T: ReadNumberHelper>( &mut self, radix: u32, max_digits: Option<usize>, allow_zero_prefix: bool, ) -> Option<T> { self.read_atomically(move |p| { let mut result = T::ZERO; let mut digit_count = 0; let has_leading_zero = p.peek_char() == Some('0'); while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) { result = result.checked_mul(radix)?; result = result.checked_add(digit)?; digit_count += 1; if let Some(max_digits) = max_digits { if digit_count > max_digits { return None; } } } if digit_count == 0 { None } else if!allow_zero_prefix && has_leading_zero && digit_count > 1 { None } else { Some(result) } }) } /// Read an IPv4 address. fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> { self.read_atomically(|p| { let mut groups = [0; 4]; for (i, slot) in groups.iter_mut().enumerate() { *slot = p.read_separator('.', i, |p| { // Disallow octal number in IP string. // https://tools.ietf.org/html/rfc6943#section-3.1.1 p.read_number(10, Some(3), false) })?; } Some(groups.into()) }) } /// Read an IPv6 Address. fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> { /// Read a chunk of an IPv6 address into `groups`. Returns the number /// of groups read, along with a bool indicating if an embedded /// trailing IPv4 address was read. Specifically, read a series of /// colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional /// trailing embedded IPv4 address. fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) { let limit = groups.len(); for (i, slot) in groups.iter_mut().enumerate() { // Try to read a trailing embedded IPv4 address. There must be // at least two groups left. if i < limit - 1 { let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr()); if let Some(v4_addr) = ipv4 { let [one, two, three, four] = v4_addr.octets(); groups[i] = u16::from_be_bytes([one, two]); groups[i + 1] = u16::from_be_bytes([three, four]); return (i + 2, true); } } let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true)); match group { Some(g) => *slot = g, None => return (i, false), } } (groups.len(), false) } self.read_atomically(|p| { // Read the front part of the address; either the whole thing, or up // to the first :: let mut head = [0; 8]; let (head_size, head_ipv4) = read_groups(p, &mut head); if head_size == 8 { return Some(head.into()); } // IPv4 part is not allowed before `::` if head_ipv4 { return None; } // Read `::` if previous code parsed less than 8 groups. // `::` indicates one or more groups of 16 bits of zeros. p.read_given_char(':')?; p.read_given_char(':')?; // Read the back part of the address. The :: must contain at least one // set of zeroes, so our max length is 7. let mut tail = [0; 7]; let limit = 8 - (head_size + 1); let (tail_size, _) = read_groups(p, &mut tail[..limit]); // Concat the head and tail of the IP address head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]); Some(head.into()) }) } /// Read an IP Address, either IPv4 or IPv6. fn read_ip_addr(&mut self) -> Option<IpAddr> { self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6)) } /// Read a `:` followed by a port in base 10. fn read_port(&mut self) -> Option<u16> { self.read_atomically(|p| { p.read_given_char(':')?; p.read_number(10, None, true) }) } /// Read a `%` followed by a scope ID in base 10. fn read_scope_id(&mut self) -> Option<u32> { self.read_atomically(|p| { p.read_given_char('%')?; p.read_number(10, None, true) }) } /// Read an IPv4 address with a port. fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> { self.read_atomically(|p| { let ip = p.read_ipv4_addr()?; let port = p.read_port()?; Some(SocketAddrV4::new(ip, port)) }) } /// Read an IPv6 address with a port. fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> { self.read_atomically(|p| { p.read_given_char('[')?; let ip = p.read_ipv6_addr()?; let scope_id = p.read_scope_id().unwrap_or(0); p.read_given_char(']')?; let port = p.read_port()?; Some(SocketAddrV6::new(ip, port, 0, scope_id)) }) } /// Read an IP address with a port fn read_socket_addr(&mut self) -> Option<SocketAddr> { self.read_socket_addr_v4() .map(SocketAddr::V4) .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6)) } } impl IpAddr { /// Parse an IP address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); /// /// assert_eq!(IpAddr::parse_ascii(b"127.0.0.1"), Ok(localhost_v4)); /// assert_eq!(IpAddr::parse_ascii(b"::1"), Ok(localhost_v6)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_ip_addr(), AddrKind::Ip) } } impl FromStr for IpAddr { type Err = AddrParseError; fn from_str(s: &str) -> Result<IpAddr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl Ipv4Addr { /// Parse an IPv4 address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::Ipv4Addr; /// /// let localhost = Ipv4Addr::new(127, 0, 0, 1); /// /// assert_eq!(Ipv4Addr::parse_ascii(b"127.0.0.1"), Ok(localhost)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { // don't try to parse if too long if b.len() > 15 { Err(AddrParseError(AddrKind::Ipv4)) } else { Parser::new(b).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4) } } } impl FromStr for Ipv4Addr { type Err = AddrParseError; fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl Ipv6Addr { /// Parse an IPv6 address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::Ipv6Addr; /// /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); /// /// assert_eq!(Ipv6Addr::parse_ascii(b"::1"), Ok(localhost)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6) } } impl FromStr for Ipv6Addr { type Err = AddrParseError; fn
(s: &str) -> Result<Ipv6Addr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddrV4 { /// Parse an IPv4 socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// /// assert_eq!(SocketAddrV4::parse_ascii(b"127.0.0.1:8080"), Ok(socket)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr_v4(), AddrKind::SocketV4) } } impl FromStr for SocketAddrV4 { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddrV6 { /// Parse an IPv6 socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// /// assert_eq!(SocketAddrV6::parse_ascii(b"[2001:db8::1]:8080"), Ok(socket)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr_v6(), AddrKind::SocketV6) } } impl FromStr for SocketAddrV6 { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddr { /// Parse a socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; /// /// let socket_v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); /// let socket_v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080); /// /// assert_eq!(SocketAddr::parse_ascii(b"127.0.0.1:8080"), Ok(socket_v4)); /// assert_eq!(SocketAddr::parse_ascii(b"[::1]:8080"), Ok(socket_v6)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr(), AddrKind::Socket) } } impl FromStr for SocketAddr { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } #[derive(Debug, Clone, PartialEq, Eq)] enum AddrKind { Ip, Ipv4, Ipv6, Socket, SocketV4, SocketV6, } /// An error which can be returned when parsing an IP address or a socket address. /// /// This error is used as the error type for the [`FromStr`] implementation for /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and /// [`SocketAddrV6`]. /// /// # Potential causes /// /// `AddrParseError` may be thrown because the provided string does not parse as the given type, /// often because it includes information only handled by a different address type. /// /// ```should_panic /// use std::net::IpAddr; /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port"); /// ``` /// /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead. /// /// ``` /// use std::net::SocketAddr; /// /// // No problem, the `panic!` message has disappeared. /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic"); /// ``` #[derive(Debug, Clone, PartialEq, Eq)] pub struct AddrParseError(AddrKind); impl fmt::Display for AddrParseError { #[allow(deprecated, deprecated_in_future)] fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str(self.description()) } } impl Error for AddrParseError { #[allow(deprecated)] fn description(&self) -> &str { match self.0 { AddrKind::Ip => "invalid IP address syntax", AddrKind::Ipv4 => "invalid IPv4 address syntax", AddrKind::Ipv6 => "invalid IPv6 address syntax", AddrKind::Socket => "invalid socket address syntax", AddrKind::SocketV4 => "invalid IPv4 socket address syntax", AddrKind::SocketV6 => "invalid IPv6 socket address syntax", } } }
from_str
identifier_name
parser.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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.. //! A private parser implementation of IPv4, IPv6, and socket addresses. //! //! This module is "publicly exported" through the `FromStr` implementations //! below. use crate::error::Error; use crate::fmt; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::str::FromStr; trait ReadNumberHelper: crate::marker::Sized { const ZERO: Self; fn checked_mul(&self, other: u32) -> Option<Self>; fn checked_add(&self, other: u32) -> Option<Self>; } macro_rules! impl_helper { ($($t:ty)*) => ($(impl ReadNumberHelper for $t { const ZERO: Self = 0; #[inline] fn checked_mul(&self, other: u32) -> Option<Self> { Self::checked_mul(*self, other.try_into().ok()?) } #[inline] fn checked_add(&self, other: u32) -> Option<Self> { Self::checked_add(*self, other.try_into().ok()?) } })*) } impl_helper! { u8 u16 u32 } struct Parser<'a> { // Parsing as ASCII, so can use byte array. state: &'a [u8], } impl<'a> Parser<'a> { fn new(input: &'a [u8]) -> Parser<'a> { Parser { state: input } } /// Run a parser, and restore the pre-parse state if it fails. fn read_atomically<T, F>(&mut self, inner: F) -> Option<T> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { let state = self.state; let result = inner(self); if result.is_none() { self.state = state; } result } /// Run a parser, but fail if the entire input wasn't consumed. /// Doesn't run atomically. fn parse_with<T, F>(&mut self, inner: F, kind: AddrKind) -> Result<T, AddrParseError> where F: FnOnce(&mut Parser<'_>) -> Option<T>, { let result = inner(self); if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind)) } /// Peek the next character from the input fn peek_char(&self) -> Option<char> { self.state.first().map(|&b| char::from(b)) } /// Read the next character from the input fn read_char(&mut self) -> Option<char> { self.state.split_first().map(|(&b, tail)| { self.state = tail; char::from(b) }) } #[must_use] /// Read the next character from the input if it matches the target. fn read_given_char(&mut self, target: char) -> Option<()> { self.read_atomically(|p| { p.read_char().and_then(|c| if c == target { Some(()) } else { None }) }) } /// Helper for reading separators in an indexed loop. Reads the separator /// character iff index > 0, then runs the parser. When used in a loop, /// the separator character will only be read on index > 0 (see /// read_ipv4_addr for an example) fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T> where F: FnOnce(&mut Parser<'_>) -> Option<T>,
// Read a number off the front of the input in the given radix, stopping // at the first non-digit character or eof. Fails if the number has more // digits than max_digits or if there is no number. #[allow(clippy::if_same_then_else)] fn read_number<T: ReadNumberHelper>( &mut self, radix: u32, max_digits: Option<usize>, allow_zero_prefix: bool, ) -> Option<T> { self.read_atomically(move |p| { let mut result = T::ZERO; let mut digit_count = 0; let has_leading_zero = p.peek_char() == Some('0'); while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) { result = result.checked_mul(radix)?; result = result.checked_add(digit)?; digit_count += 1; if let Some(max_digits) = max_digits { if digit_count > max_digits { return None; } } } if digit_count == 0 { None } else if!allow_zero_prefix && has_leading_zero && digit_count > 1 { None } else { Some(result) } }) } /// Read an IPv4 address. fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> { self.read_atomically(|p| { let mut groups = [0; 4]; for (i, slot) in groups.iter_mut().enumerate() { *slot = p.read_separator('.', i, |p| { // Disallow octal number in IP string. // https://tools.ietf.org/html/rfc6943#section-3.1.1 p.read_number(10, Some(3), false) })?; } Some(groups.into()) }) } /// Read an IPv6 Address. fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> { /// Read a chunk of an IPv6 address into `groups`. Returns the number /// of groups read, along with a bool indicating if an embedded /// trailing IPv4 address was read. Specifically, read a series of /// colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional /// trailing embedded IPv4 address. fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) { let limit = groups.len(); for (i, slot) in groups.iter_mut().enumerate() { // Try to read a trailing embedded IPv4 address. There must be // at least two groups left. if i < limit - 1 { let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr()); if let Some(v4_addr) = ipv4 { let [one, two, three, four] = v4_addr.octets(); groups[i] = u16::from_be_bytes([one, two]); groups[i + 1] = u16::from_be_bytes([three, four]); return (i + 2, true); } } let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true)); match group { Some(g) => *slot = g, None => return (i, false), } } (groups.len(), false) } self.read_atomically(|p| { // Read the front part of the address; either the whole thing, or up // to the first :: let mut head = [0; 8]; let (head_size, head_ipv4) = read_groups(p, &mut head); if head_size == 8 { return Some(head.into()); } // IPv4 part is not allowed before `::` if head_ipv4 { return None; } // Read `::` if previous code parsed less than 8 groups. // `::` indicates one or more groups of 16 bits of zeros. p.read_given_char(':')?; p.read_given_char(':')?; // Read the back part of the address. The :: must contain at least one // set of zeroes, so our max length is 7. let mut tail = [0; 7]; let limit = 8 - (head_size + 1); let (tail_size, _) = read_groups(p, &mut tail[..limit]); // Concat the head and tail of the IP address head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]); Some(head.into()) }) } /// Read an IP Address, either IPv4 or IPv6. fn read_ip_addr(&mut self) -> Option<IpAddr> { self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6)) } /// Read a `:` followed by a port in base 10. fn read_port(&mut self) -> Option<u16> { self.read_atomically(|p| { p.read_given_char(':')?; p.read_number(10, None, true) }) } /// Read a `%` followed by a scope ID in base 10. fn read_scope_id(&mut self) -> Option<u32> { self.read_atomically(|p| { p.read_given_char('%')?; p.read_number(10, None, true) }) } /// Read an IPv4 address with a port. fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> { self.read_atomically(|p| { let ip = p.read_ipv4_addr()?; let port = p.read_port()?; Some(SocketAddrV4::new(ip, port)) }) } /// Read an IPv6 address with a port. fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> { self.read_atomically(|p| { p.read_given_char('[')?; let ip = p.read_ipv6_addr()?; let scope_id = p.read_scope_id().unwrap_or(0); p.read_given_char(']')?; let port = p.read_port()?; Some(SocketAddrV6::new(ip, port, 0, scope_id)) }) } /// Read an IP address with a port fn read_socket_addr(&mut self) -> Option<SocketAddr> { self.read_socket_addr_v4() .map(SocketAddr::V4) .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6)) } } impl IpAddr { /// Parse an IP address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); /// /// assert_eq!(IpAddr::parse_ascii(b"127.0.0.1"), Ok(localhost_v4)); /// assert_eq!(IpAddr::parse_ascii(b"::1"), Ok(localhost_v6)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_ip_addr(), AddrKind::Ip) } } impl FromStr for IpAddr { type Err = AddrParseError; fn from_str(s: &str) -> Result<IpAddr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl Ipv4Addr { /// Parse an IPv4 address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::Ipv4Addr; /// /// let localhost = Ipv4Addr::new(127, 0, 0, 1); /// /// assert_eq!(Ipv4Addr::parse_ascii(b"127.0.0.1"), Ok(localhost)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { // don't try to parse if too long if b.len() > 15 { Err(AddrParseError(AddrKind::Ipv4)) } else { Parser::new(b).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4) } } } impl FromStr for Ipv4Addr { type Err = AddrParseError; fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl Ipv6Addr { /// Parse an IPv6 address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::Ipv6Addr; /// /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); /// /// assert_eq!(Ipv6Addr::parse_ascii(b"::1"), Ok(localhost)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6) } } impl FromStr for Ipv6Addr { type Err = AddrParseError; fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddrV4 { /// Parse an IPv4 socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// /// assert_eq!(SocketAddrV4::parse_ascii(b"127.0.0.1:8080"), Ok(socket)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr_v4(), AddrKind::SocketV4) } } impl FromStr for SocketAddrV4 { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddrV6 { /// Parse an IPv6 socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// /// assert_eq!(SocketAddrV6::parse_ascii(b"[2001:db8::1]:8080"), Ok(socket)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr_v6(), AddrKind::SocketV6) } } impl FromStr for SocketAddrV6 { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddr { /// Parse a socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; /// /// let socket_v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); /// let socket_v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080); /// /// assert_eq!(SocketAddr::parse_ascii(b"127.0.0.1:8080"), Ok(socket_v4)); /// assert_eq!(SocketAddr::parse_ascii(b"[::1]:8080"), Ok(socket_v6)); /// ``` pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> { Parser::new(b).parse_with(|p| p.read_socket_addr(), AddrKind::Socket) } } impl FromStr for SocketAddr { type Err = AddrParseError; fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } #[derive(Debug, Clone, PartialEq, Eq)] enum AddrKind { Ip, Ipv4, Ipv6, Socket, SocketV4, SocketV6, } /// An error which can be returned when parsing an IP address or a socket address. /// /// This error is used as the error type for the [`FromStr`] implementation for /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and /// [`SocketAddrV6`]. /// /// # Potential causes /// /// `AddrParseError` may be thrown because the provided string does not parse as the given type, /// often because it includes information only handled by a different address type. /// /// ```should_panic /// use std::net::IpAddr; /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port"); /// ``` /// /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead. /// /// ``` /// use std::net::SocketAddr; /// /// // No problem, the `panic!` message has disappeared. /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic"); /// ``` #[derive(Debug, Clone, PartialEq, Eq)] pub struct AddrParseError(AddrKind); impl fmt::Display for AddrParseError { #[allow(deprecated, deprecated_in_future)] fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str(self.description()) } } impl Error for AddrParseError { #[allow(deprecated)] fn description(&self) -> &str { match self.0 { AddrKind::Ip => "invalid IP address syntax", AddrKind::Ipv4 => "invalid IPv4 address syntax", AddrKind::Ipv6 => "invalid IPv6 address syntax", AddrKind::Socket => "invalid socket address syntax", AddrKind::SocketV4 => "invalid IPv4 socket address syntax", AddrKind::SocketV6 => "invalid IPv6 socket address syntax", } } }
{ self.read_atomically(move |p| { if index > 0 { p.read_given_char(sep)?; } inner(p) }) }
identifier_body
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use tiny_skia_path::NoStdFloat; pub const POINT_COUNT: usize = 4; const PI: f64 = 3.141592653589793; pub struct Cubic64Pair { pub points: [Point64; 7], } pub struct Cubic64 { pub points: [Point64; POINT_COUNT], } impl Cubic64 { pub fn new(points: [Point64; POINT_COUNT]) -> Self { Cubic64 { points } } pub fn as_f64_slice(&self) -> [f64; POINT_COUNT * 2] { [ self.points[0].x, self.points[0].y, self.points[1].x, self.points[1].y, self.points[2].x, self.points[2].y, self.points[3].x, self.points[3].y, ] } pub fn point_at_t(&self, t: f64) -> Point64 { if t == 0.0 { return self.points[0]; } if t == 1.0 { return self.points[3]; } let one_t = 1.0 - t; let one_t2 = one_t * one_t; let a = one_t2 * one_t; let b = 3.0 * one_t2 * t; let t2 = t * t; let c = 3.0 * one_t * t2; let d = t2 * t; Point64::from_xy( a * self.points[0].x + b * self.points[1].x + c * self.points[2].x + d * self.points[3].x, a * self.points[0].y + b * self.points[1].y + c * self.points[2].y + d * self.points[3].y, ) } pub fn search_roots( &self, mut extrema: usize, axis_intercept: f64, x_axis: SearchAxis, extreme_ts: &mut [f64; 6], valid_roots: &mut [f64], ) -> usize { extrema += self.find_inflections(&mut extreme_ts[extrema..]); extreme_ts[extrema] = 0.0; extrema += 1; extreme_ts[extrema] = 1.0; debug_assert!(extrema < 6); extreme_ts[0..extrema].sort_by(cmp_f64); let mut valid_count = 0; let mut index = 0; while index < extrema { let min = extreme_ts[index]; index += 1; let max = extreme_ts[index]; if min == max { continue; } let new_t = self.binary_search(min, max, axis_intercept, x_axis); if new_t >= 0.0 { if valid_count >= 3 { return 0; } valid_roots[valid_count] = new_t; valid_count += 1; } } valid_count } fn find_inflections(&self, t_values: &mut [f64]) -> usize { let ax = self.points[1].x - self.points[0].x; let ay = self.points[1].y - self.points[0].y; let bx = self.points[2].x - 2.0 * self.points[1].x + self.points[0].x; let by = self.points[2].y - 2.0 * self.points[1].y + self.points[0].y; let cx = self.points[3].x + 3.0 * (self.points[1].x - self.points[2].x) - self.points[0].x; let cy = self.points[3].y + 3.0 * (self.points[1].y - self.points[2].y) - self.points[0].y; quad64::roots_valid_t( bx * cy - by * cx, ax * cy - ay * cx, ax * by - ay * bx, t_values, ) } // give up when changing t no longer moves point // also, copy point rather than recompute it when it does change fn binary_search(&self, min: f64, max: f64, axis_intercept: f64, x_axis: SearchAxis) -> f64 { let mut t = (min + max) / 2.0; let mut step = (t - min) / 2.0; let mut cubic_at_t = self.point_at_t(t); let mut calc_pos = cubic_at_t.axis_coord(x_axis); let mut calc_dist = calc_pos - axis_intercept; loop { let prior_t = min.max(t - step); let less_pt = self.point_at_t(prior_t); if less_pt.x.approximately_equal_half(cubic_at_t.x) && less_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let less_dist = less_pt.axis_coord(x_axis) - axis_intercept; let last_step = step; step /= 2.0; let ok = if calc_dist > 0.0 { calc_dist > less_dist } else { calc_dist < less_dist }; if ok { t = prior_t; } else
continue; } t = next_t; } let test_at_t = self.point_at_t(t); cubic_at_t = test_at_t; calc_pos = cubic_at_t.axis_coord(x_axis); calc_dist = calc_pos - axis_intercept; if calc_pos.approximately_equal(axis_intercept) { break; } } t } pub fn chop_at(&self, t: f64) -> Cubic64Pair { let mut dst = [Point64::zero(); 7]; if t == 0.5 { dst[0] = self.points[0]; dst[1].x = (self.points[0].x + self.points[1].x) / 2.0; dst[1].y = (self.points[0].y + self.points[1].y) / 2.0; dst[2].x = (self.points[0].x + 2.0 * self.points[1].x + self.points[2].x) / 4.0; dst[2].y = (self.points[0].y + 2.0 * self.points[1].y + self.points[2].y) / 4.0; dst[3].x = (self.points[0].x + 3.0 * (self.points[1].x + self.points[2].x) + self.points[3].x) / 8.0; dst[3].y = (self.points[0].y + 3.0 * (self.points[1].y + self.points[2].y) + self.points[3].y) / 8.0; dst[4].x = (self.points[1].x + 2.0 * self.points[2].x + self.points[3].x) / 4.0; dst[4].y = (self.points[1].y + 2.0 * self.points[2].y + self.points[3].y) / 4.0; dst[5].x = (self.points[2].x + self.points[3].x) / 2.0; dst[5].y = (self.points[2].y + self.points[3].y) / 2.0; dst[6] = self.points[3]; Cubic64Pair { points: dst } } else { interp_cubic_coords_x(&self.points, t, &mut dst); interp_cubic_coords_y(&self.points, t, &mut dst); Cubic64Pair { points: dst } } } } pub fn coefficients(src: &[f64]) -> (f64, f64, f64, f64) { let mut a = src[6]; // d let mut b = src[4] * 3.0; // 3*c let mut c = src[2] * 3.0; // 3*b let d = src[0]; // a a -= d - c + b; // A = -a + 3*b - 3*c + d b += 3.0 * d - 2.0 * c; // B = 3*a - 6*b + 3*c c -= 3.0 * d; // C = -3*a + 3*b (a, b, c, d) } // from SkGeometry.cpp (and Numeric Solutions, 5.6) pub fn roots_valid_t(a: f64, b: f64, c: f64, d: f64, t: &mut [f64; 3]) -> usize { let mut s = [0.0; 3]; let real_roots = roots_real(a, b, c, d, &mut s); let mut found_roots = quad64::push_valid_ts(&s, real_roots, t); 'outer: for index in 0..real_roots { let t_value = s[index]; if!t_value.approximately_one_or_less() && t_value.between(1.0, 1.00005) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(1.0) { continue 'outer; } } debug_assert!(found_roots < 3); t[found_roots] = 1.0; found_roots += 1; } else if!t_value.approximately_zero_or_more() && t_value.between(-0.00005, 0.0) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(0.0) { continue 'outer; } } debug_assert!(found_roots < 3); t[found_roots] = 0.0; found_roots += 1; } } found_roots } fn roots_real(a: f64, b: f64, c: f64, d: f64, s: &mut [f64; 3]) -> usize { if a.approximately_zero() && a.approximately_zero_when_compared_to(b) && a.approximately_zero_when_compared_to(c) && a.approximately_zero_when_compared_to(d) { // we're just a quadratic return quad64::roots_real(b, c, d, s); } if d.approximately_zero_when_compared_to(a) && d.approximately_zero_when_compared_to(b) && d.approximately_zero_when_compared_to(c) { // 0 is one root let mut num = quad64::roots_real(a, b, c, s); for i in 0..num { if s[i].approximately_zero() { return num; } } s[num] = 0.0; num += 1; return num; } if (a + b + c + d).approximately_zero() { // 1 is one root let mut num = quad64::roots_real(a, a + b, -d, s); for i in 0..num { if s[i].almost_dequal_ulps(1.0) { return num; } } s[num] = 1.0; num += 1; return num; } let (a, b, c) = { let inv_a = 1.0 / a; let a = b * inv_a; let b = c * inv_a; let c = d * inv_a; (a, b, c) }; let a2 = a * a; let q = (a2 - b * 3.0) / 9.0; let r = (2.0 * a2 * a - 9.0 * a * b + 27.0 * c) / 54.0; let r2 = r * r; let q3 = q * q * q; let r2_minus_q3 = r2 - q3; let adiv3 = a / 3.0; let mut offset = 0; if r2_minus_q3 < 0.0 { // we have 3 real roots // the divide/root can, due to finite precisions, be slightly outside of -1...1 let theta = (r / q3.sqrt()).bound(-1.0, 1.0).acos(); let neg2_root_q = -2.0 * q.sqrt(); let mut rr = neg2_root_q * (theta / 3.0).cos() - adiv3; s[offset] = rr; offset += 1; rr = neg2_root_q * ((theta + 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) { s[offset] = rr; offset += 1; } rr = neg2_root_q * ((theta - 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) && (offset == 1 ||!s[1].almost_dequal_ulps(rr)) { s[offset] = rr; offset += 1; } } else { // we have 1 real root let sqrt_r2_minus_q3 = r2_minus_q3.sqrt(); let mut a = r.abs() + sqrt_r2_minus_q3; a = super::cube_root(a); if r > 0.0 { a = -a; } if a!= 0.0 { a += q / a; } let mut r2 = a - adiv3; s[offset] = r2; offset += 1; if r2.almost_dequal_ulps(q3) { r2 = -a / 2.0 - adiv3; if!s[0].almost_dequal_ulps(r2) { s[offset] = r2; offset += 1; } } } offset } // Cubic64'(t) = At^2 + Bt + C, where // A = 3(-a + 3(b - c) + d) // B = 6(a - 2b + c) // C = 3(b - a) // Solve for t, keeping only those that fit between 0 < t < 1 pub fn find_extrema(src: &[f64], t_values: &mut [f64]) -> usize { // we divide A,B,C by 3 to simplify let a = src[0]; let b = src[2]; let c = src[4]; let d = src[6]; let a2 = d - a + 3.0 * (b - c); let b2 = 2.0 * (a - b - b + c); let c2 = b - a; quad64::roots_valid_t(a2, b2, c2, t_values) } // Skia doesn't seems to care about NaN/inf during sorting, so we don't too. fn cmp_f64(a: &f64, b: &f64) -> core::cmp::Ordering { if a < b { core::cmp::Ordering::Less } else if a > b { core::cmp::Ordering::Greater } else { core::cmp::Ordering::Equal } } // classic one t subdivision fn interp_cubic_coords_x(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].x, src[1].x, t); let bc = interp(src[1].x, src[2].x, t); let cd = interp(src[2].x, src[3].x, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].x = src[0].x; dst[1].x = ab; dst[2].x = abc; dst[3].x = abcd; dst[4].x = bcd; dst[5].x = cd; dst[6].x = src[3].x; } fn interp_cubic_coords_y(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].y, src[1].y, t); let bc = interp(src[1].y, src[2].y, t); let cd = interp(src[2].y, src[3].y, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].y = src[0].y; dst[1].y = ab; dst[2].y = abc; dst[3].y = abcd; dst[4].y = bcd; dst[5].y = cd; dst[6].y = src[3].y; }
{ let next_t = t + last_step; if next_t > max { return -1.0; } let more_pt = self.point_at_t(next_t); if more_pt.x.approximately_equal_half(cubic_at_t.x) && more_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let more_dist = more_pt.axis_coord(x_axis) - axis_intercept; let ok = if calc_dist > 0.0 { calc_dist <= more_dist } else { calc_dist >= more_dist }; if ok {
conditional_block
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use tiny_skia_path::NoStdFloat; pub const POINT_COUNT: usize = 4; const PI: f64 = 3.141592653589793; pub struct Cubic64Pair { pub points: [Point64; 7], } pub struct Cubic64 { pub points: [Point64; POINT_COUNT], } impl Cubic64 { pub fn new(points: [Point64; POINT_COUNT]) -> Self { Cubic64 { points } } pub fn as_f64_slice(&self) -> [f64; POINT_COUNT * 2] { [ self.points[0].x, self.points[0].y, self.points[1].x, self.points[1].y, self.points[2].x, self.points[2].y, self.points[3].x, self.points[3].y, ] } pub fn point_at_t(&self, t: f64) -> Point64 { if t == 0.0 { return self.points[0]; } if t == 1.0 { return self.points[3]; } let one_t = 1.0 - t; let one_t2 = one_t * one_t; let a = one_t2 * one_t; let b = 3.0 * one_t2 * t; let t2 = t * t; let c = 3.0 * one_t * t2; let d = t2 * t; Point64::from_xy( a * self.points[0].x + b * self.points[1].x + c * self.points[2].x + d * self.points[3].x, a * self.points[0].y + b * self.points[1].y + c * self.points[2].y + d * self.points[3].y, ) } pub fn search_roots( &self, mut extrema: usize, axis_intercept: f64, x_axis: SearchAxis, extreme_ts: &mut [f64; 6], valid_roots: &mut [f64], ) -> usize { extrema += self.find_inflections(&mut extreme_ts[extrema..]); extreme_ts[extrema] = 0.0; extrema += 1; extreme_ts[extrema] = 1.0; debug_assert!(extrema < 6); extreme_ts[0..extrema].sort_by(cmp_f64); let mut valid_count = 0; let mut index = 0; while index < extrema { let min = extreme_ts[index]; index += 1; let max = extreme_ts[index]; if min == max { continue; } let new_t = self.binary_search(min, max, axis_intercept, x_axis); if new_t >= 0.0 { if valid_count >= 3 { return 0; } valid_roots[valid_count] = new_t; valid_count += 1; } } valid_count } fn find_inflections(&self, t_values: &mut [f64]) -> usize { let ax = self.points[1].x - self.points[0].x; let ay = self.points[1].y - self.points[0].y; let bx = self.points[2].x - 2.0 * self.points[1].x + self.points[0].x; let by = self.points[2].y - 2.0 * self.points[1].y + self.points[0].y; let cx = self.points[3].x + 3.0 * (self.points[1].x - self.points[2].x) - self.points[0].x; let cy = self.points[3].y + 3.0 * (self.points[1].y - self.points[2].y) - self.points[0].y; quad64::roots_valid_t( bx * cy - by * cx, ax * cy - ay * cx, ax * by - ay * bx, t_values, ) } // give up when changing t no longer moves point // also, copy point rather than recompute it when it does change fn binary_search(&self, min: f64, max: f64, axis_intercept: f64, x_axis: SearchAxis) -> f64 { let mut t = (min + max) / 2.0; let mut step = (t - min) / 2.0; let mut cubic_at_t = self.point_at_t(t); let mut calc_pos = cubic_at_t.axis_coord(x_axis); let mut calc_dist = calc_pos - axis_intercept; loop { let prior_t = min.max(t - step); let less_pt = self.point_at_t(prior_t); if less_pt.x.approximately_equal_half(cubic_at_t.x) && less_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let less_dist = less_pt.axis_coord(x_axis) - axis_intercept; let last_step = step; step /= 2.0; let ok = if calc_dist > 0.0 { calc_dist > less_dist } else { calc_dist < less_dist }; if ok { t = prior_t; } else { let next_t = t + last_step; if next_t > max { return -1.0; } let more_pt = self.point_at_t(next_t); if more_pt.x.approximately_equal_half(cubic_at_t.x) && more_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let more_dist = more_pt.axis_coord(x_axis) - axis_intercept; let ok = if calc_dist > 0.0 { calc_dist <= more_dist } else { calc_dist >= more_dist }; if ok { continue; } t = next_t; } let test_at_t = self.point_at_t(t); cubic_at_t = test_at_t; calc_pos = cubic_at_t.axis_coord(x_axis); calc_dist = calc_pos - axis_intercept; if calc_pos.approximately_equal(axis_intercept) { break; } } t } pub fn chop_at(&self, t: f64) -> Cubic64Pair { let mut dst = [Point64::zero(); 7]; if t == 0.5 { dst[0] = self.points[0]; dst[1].x = (self.points[0].x + self.points[1].x) / 2.0; dst[1].y = (self.points[0].y + self.points[1].y) / 2.0; dst[2].x = (self.points[0].x + 2.0 * self.points[1].x + self.points[2].x) / 4.0; dst[2].y = (self.points[0].y + 2.0 * self.points[1].y + self.points[2].y) / 4.0; dst[3].x = (self.points[0].x + 3.0 * (self.points[1].x + self.points[2].x) + self.points[3].x) / 8.0; dst[3].y = (self.points[0].y + 3.0 * (self.points[1].y + self.points[2].y) + self.points[3].y) / 8.0; dst[4].x = (self.points[1].x + 2.0 * self.points[2].x + self.points[3].x) / 4.0; dst[4].y = (self.points[1].y + 2.0 * self.points[2].y + self.points[3].y) / 4.0; dst[5].x = (self.points[2].x + self.points[3].x) / 2.0; dst[5].y = (self.points[2].y + self.points[3].y) / 2.0; dst[6] = self.points[3]; Cubic64Pair { points: dst } } else { interp_cubic_coords_x(&self.points, t, &mut dst); interp_cubic_coords_y(&self.points, t, &mut dst); Cubic64Pair { points: dst } } } } pub fn coefficients(src: &[f64]) -> (f64, f64, f64, f64) { let mut a = src[6]; // d let mut b = src[4] * 3.0; // 3*c let mut c = src[2] * 3.0; // 3*b let d = src[0]; // a a -= d - c + b; // A = -a + 3*b - 3*c + d b += 3.0 * d - 2.0 * c; // B = 3*a - 6*b + 3*c c -= 3.0 * d; // C = -3*a + 3*b (a, b, c, d) } // from SkGeometry.cpp (and Numeric Solutions, 5.6) pub fn roots_valid_t(a: f64, b: f64, c: f64, d: f64, t: &mut [f64; 3]) -> usize { let mut s = [0.0; 3]; let real_roots = roots_real(a, b, c, d, &mut s); let mut found_roots = quad64::push_valid_ts(&s, real_roots, t); 'outer: for index in 0..real_roots { let t_value = s[index]; if!t_value.approximately_one_or_less() && t_value.between(1.0, 1.00005) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(1.0) { continue 'outer; } } debug_assert!(found_roots < 3); t[found_roots] = 1.0; found_roots += 1; } else if!t_value.approximately_zero_or_more() && t_value.between(-0.00005, 0.0) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(0.0) { continue 'outer; } } debug_assert!(found_roots < 3); t[found_roots] = 0.0; found_roots += 1; } } found_roots } fn roots_real(a: f64, b: f64, c: f64, d: f64, s: &mut [f64; 3]) -> usize { if a.approximately_zero() && a.approximately_zero_when_compared_to(b) && a.approximately_zero_when_compared_to(c) && a.approximately_zero_when_compared_to(d) { // we're just a quadratic return quad64::roots_real(b, c, d, s); } if d.approximately_zero_when_compared_to(a) && d.approximately_zero_when_compared_to(b) && d.approximately_zero_when_compared_to(c) { // 0 is one root let mut num = quad64::roots_real(a, b, c, s); for i in 0..num { if s[i].approximately_zero() { return num; } } s[num] = 0.0; num += 1;
} if (a + b + c + d).approximately_zero() { // 1 is one root let mut num = quad64::roots_real(a, a + b, -d, s); for i in 0..num { if s[i].almost_dequal_ulps(1.0) { return num; } } s[num] = 1.0; num += 1; return num; } let (a, b, c) = { let inv_a = 1.0 / a; let a = b * inv_a; let b = c * inv_a; let c = d * inv_a; (a, b, c) }; let a2 = a * a; let q = (a2 - b * 3.0) / 9.0; let r = (2.0 * a2 * a - 9.0 * a * b + 27.0 * c) / 54.0; let r2 = r * r; let q3 = q * q * q; let r2_minus_q3 = r2 - q3; let adiv3 = a / 3.0; let mut offset = 0; if r2_minus_q3 < 0.0 { // we have 3 real roots // the divide/root can, due to finite precisions, be slightly outside of -1...1 let theta = (r / q3.sqrt()).bound(-1.0, 1.0).acos(); let neg2_root_q = -2.0 * q.sqrt(); let mut rr = neg2_root_q * (theta / 3.0).cos() - adiv3; s[offset] = rr; offset += 1; rr = neg2_root_q * ((theta + 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) { s[offset] = rr; offset += 1; } rr = neg2_root_q * ((theta - 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) && (offset == 1 ||!s[1].almost_dequal_ulps(rr)) { s[offset] = rr; offset += 1; } } else { // we have 1 real root let sqrt_r2_minus_q3 = r2_minus_q3.sqrt(); let mut a = r.abs() + sqrt_r2_minus_q3; a = super::cube_root(a); if r > 0.0 { a = -a; } if a!= 0.0 { a += q / a; } let mut r2 = a - adiv3; s[offset] = r2; offset += 1; if r2.almost_dequal_ulps(q3) { r2 = -a / 2.0 - adiv3; if!s[0].almost_dequal_ulps(r2) { s[offset] = r2; offset += 1; } } } offset } // Cubic64'(t) = At^2 + Bt + C, where // A = 3(-a + 3(b - c) + d) // B = 6(a - 2b + c) // C = 3(b - a) // Solve for t, keeping only those that fit between 0 < t < 1 pub fn find_extrema(src: &[f64], t_values: &mut [f64]) -> usize { // we divide A,B,C by 3 to simplify let a = src[0]; let b = src[2]; let c = src[4]; let d = src[6]; let a2 = d - a + 3.0 * (b - c); let b2 = 2.0 * (a - b - b + c); let c2 = b - a; quad64::roots_valid_t(a2, b2, c2, t_values) } // Skia doesn't seems to care about NaN/inf during sorting, so we don't too. fn cmp_f64(a: &f64, b: &f64) -> core::cmp::Ordering { if a < b { core::cmp::Ordering::Less } else if a > b { core::cmp::Ordering::Greater } else { core::cmp::Ordering::Equal } } // classic one t subdivision fn interp_cubic_coords_x(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].x, src[1].x, t); let bc = interp(src[1].x, src[2].x, t); let cd = interp(src[2].x, src[3].x, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].x = src[0].x; dst[1].x = ab; dst[2].x = abc; dst[3].x = abcd; dst[4].x = bcd; dst[5].x = cd; dst[6].x = src[3].x; } fn interp_cubic_coords_y(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].y, src[1].y, t); let bc = interp(src[1].y, src[2].y, t); let cd = interp(src[2].y, src[3].y, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].y = src[0].y; dst[1].y = ab; dst[2].y = abc; dst[3].y = abcd; dst[4].y = bcd; dst[5].y = cd; dst[6].y = src[3].y; }
return num;
random_line_split
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use tiny_skia_path::NoStdFloat; pub const POINT_COUNT: usize = 4; const PI: f64 = 3.141592653589793; pub struct Cubic64Pair { pub points: [Point64; 7], } pub struct Cubic64 { pub points: [Point64; POINT_COUNT], } impl Cubic64 { pub fn new(points: [Point64; POINT_COUNT]) -> Self { Cubic64 { points } } pub fn as_f64_slice(&self) -> [f64; POINT_COUNT * 2] { [ self.points[0].x, self.points[0].y, self.points[1].x, self.points[1].y, self.points[2].x, self.points[2].y, self.points[3].x, self.points[3].y, ] } pub fn point_at_t(&self, t: f64) -> Point64 { if t == 0.0 { return self.points[0]; } if t == 1.0 { return self.points[3]; } let one_t = 1.0 - t; let one_t2 = one_t * one_t; let a = one_t2 * one_t; let b = 3.0 * one_t2 * t; let t2 = t * t; let c = 3.0 * one_t * t2; let d = t2 * t; Point64::from_xy( a * self.points[0].x + b * self.points[1].x + c * self.points[2].x + d * self.points[3].x, a * self.points[0].y + b * self.points[1].y + c * self.points[2].y + d * self.points[3].y, ) } pub fn search_roots( &self, mut extrema: usize, axis_intercept: f64, x_axis: SearchAxis, extreme_ts: &mut [f64; 6], valid_roots: &mut [f64], ) -> usize { extrema += self.find_inflections(&mut extreme_ts[extrema..]); extreme_ts[extrema] = 0.0; extrema += 1; extreme_ts[extrema] = 1.0; debug_assert!(extrema < 6); extreme_ts[0..extrema].sort_by(cmp_f64); let mut valid_count = 0; let mut index = 0; while index < extrema { let min = extreme_ts[index]; index += 1; let max = extreme_ts[index]; if min == max { continue; } let new_t = self.binary_search(min, max, axis_intercept, x_axis); if new_t >= 0.0 { if valid_count >= 3 { return 0; } valid_roots[valid_count] = new_t; valid_count += 1; } } valid_count } fn find_inflections(&self, t_values: &mut [f64]) -> usize { let ax = self.points[1].x - self.points[0].x; let ay = self.points[1].y - self.points[0].y; let bx = self.points[2].x - 2.0 * self.points[1].x + self.points[0].x; let by = self.points[2].y - 2.0 * self.points[1].y + self.points[0].y; let cx = self.points[3].x + 3.0 * (self.points[1].x - self.points[2].x) - self.points[0].x; let cy = self.points[3].y + 3.0 * (self.points[1].y - self.points[2].y) - self.points[0].y; quad64::roots_valid_t( bx * cy - by * cx, ax * cy - ay * cx, ax * by - ay * bx, t_values, ) } // give up when changing t no longer moves point // also, copy point rather than recompute it when it does change fn binary_search(&self, min: f64, max: f64, axis_intercept: f64, x_axis: SearchAxis) -> f64 { let mut t = (min + max) / 2.0; let mut step = (t - min) / 2.0; let mut cubic_at_t = self.point_at_t(t); let mut calc_pos = cubic_at_t.axis_coord(x_axis); let mut calc_dist = calc_pos - axis_intercept; loop { let prior_t = min.max(t - step); let less_pt = self.point_at_t(prior_t); if less_pt.x.approximately_equal_half(cubic_at_t.x) && less_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let less_dist = less_pt.axis_coord(x_axis) - axis_intercept; let last_step = step; step /= 2.0; let ok = if calc_dist > 0.0 { calc_dist > less_dist } else { calc_dist < less_dist }; if ok { t = prior_t; } else { let next_t = t + last_step; if next_t > max { return -1.0; } let more_pt = self.point_at_t(next_t); if more_pt.x.approximately_equal_half(cubic_at_t.x) && more_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let more_dist = more_pt.axis_coord(x_axis) - axis_intercept; let ok = if calc_dist > 0.0 { calc_dist <= more_dist } else { calc_dist >= more_dist }; if ok { continue; } t = next_t; } let test_at_t = self.point_at_t(t); cubic_at_t = test_at_t; calc_pos = cubic_at_t.axis_coord(x_axis); calc_dist = calc_pos - axis_intercept; if calc_pos.approximately_equal(axis_intercept) { break; } } t } pub fn chop_at(&self, t: f64) -> Cubic64Pair { let mut dst = [Point64::zero(); 7]; if t == 0.5 { dst[0] = self.points[0]; dst[1].x = (self.points[0].x + self.points[1].x) / 2.0; dst[1].y = (self.points[0].y + self.points[1].y) / 2.0; dst[2].x = (self.points[0].x + 2.0 * self.points[1].x + self.points[2].x) / 4.0; dst[2].y = (self.points[0].y + 2.0 * self.points[1].y + self.points[2].y) / 4.0; dst[3].x = (self.points[0].x + 3.0 * (self.points[1].x + self.points[2].x) + self.points[3].x) / 8.0; dst[3].y = (self.points[0].y + 3.0 * (self.points[1].y + self.points[2].y) + self.points[3].y) / 8.0; dst[4].x = (self.points[1].x + 2.0 * self.points[2].x + self.points[3].x) / 4.0; dst[4].y = (self.points[1].y + 2.0 * self.points[2].y + self.points[3].y) / 4.0; dst[5].x = (self.points[2].x + self.points[3].x) / 2.0; dst[5].y = (self.points[2].y + self.points[3].y) / 2.0; dst[6] = self.points[3]; Cubic64Pair { points: dst } } else { interp_cubic_coords_x(&self.points, t, &mut dst); interp_cubic_coords_y(&self.points, t, &mut dst); Cubic64Pair { points: dst } } } } pub fn
(src: &[f64]) -> (f64, f64, f64, f64) { let mut a = src[6]; // d let mut b = src[4] * 3.0; // 3*c let mut c = src[2] * 3.0; // 3*b let d = src[0]; // a a -= d - c + b; // A = -a + 3*b - 3*c + d b += 3.0 * d - 2.0 * c; // B = 3*a - 6*b + 3*c c -= 3.0 * d; // C = -3*a + 3*b (a, b, c, d) } // from SkGeometry.cpp (and Numeric Solutions, 5.6) pub fn roots_valid_t(a: f64, b: f64, c: f64, d: f64, t: &mut [f64; 3]) -> usize { let mut s = [0.0; 3]; let real_roots = roots_real(a, b, c, d, &mut s); let mut found_roots = quad64::push_valid_ts(&s, real_roots, t); 'outer: for index in 0..real_roots { let t_value = s[index]; if!t_value.approximately_one_or_less() && t_value.between(1.0, 1.00005) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(1.0) { continue 'outer; } } debug_assert!(found_roots < 3); t[found_roots] = 1.0; found_roots += 1; } else if!t_value.approximately_zero_or_more() && t_value.between(-0.00005, 0.0) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(0.0) { continue 'outer; } } debug_assert!(found_roots < 3); t[found_roots] = 0.0; found_roots += 1; } } found_roots } fn roots_real(a: f64, b: f64, c: f64, d: f64, s: &mut [f64; 3]) -> usize { if a.approximately_zero() && a.approximately_zero_when_compared_to(b) && a.approximately_zero_when_compared_to(c) && a.approximately_zero_when_compared_to(d) { // we're just a quadratic return quad64::roots_real(b, c, d, s); } if d.approximately_zero_when_compared_to(a) && d.approximately_zero_when_compared_to(b) && d.approximately_zero_when_compared_to(c) { // 0 is one root let mut num = quad64::roots_real(a, b, c, s); for i in 0..num { if s[i].approximately_zero() { return num; } } s[num] = 0.0; num += 1; return num; } if (a + b + c + d).approximately_zero() { // 1 is one root let mut num = quad64::roots_real(a, a + b, -d, s); for i in 0..num { if s[i].almost_dequal_ulps(1.0) { return num; } } s[num] = 1.0; num += 1; return num; } let (a, b, c) = { let inv_a = 1.0 / a; let a = b * inv_a; let b = c * inv_a; let c = d * inv_a; (a, b, c) }; let a2 = a * a; let q = (a2 - b * 3.0) / 9.0; let r = (2.0 * a2 * a - 9.0 * a * b + 27.0 * c) / 54.0; let r2 = r * r; let q3 = q * q * q; let r2_minus_q3 = r2 - q3; let adiv3 = a / 3.0; let mut offset = 0; if r2_minus_q3 < 0.0 { // we have 3 real roots // the divide/root can, due to finite precisions, be slightly outside of -1...1 let theta = (r / q3.sqrt()).bound(-1.0, 1.0).acos(); let neg2_root_q = -2.0 * q.sqrt(); let mut rr = neg2_root_q * (theta / 3.0).cos() - adiv3; s[offset] = rr; offset += 1; rr = neg2_root_q * ((theta + 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) { s[offset] = rr; offset += 1; } rr = neg2_root_q * ((theta - 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) && (offset == 1 ||!s[1].almost_dequal_ulps(rr)) { s[offset] = rr; offset += 1; } } else { // we have 1 real root let sqrt_r2_minus_q3 = r2_minus_q3.sqrt(); let mut a = r.abs() + sqrt_r2_minus_q3; a = super::cube_root(a); if r > 0.0 { a = -a; } if a!= 0.0 { a += q / a; } let mut r2 = a - adiv3; s[offset] = r2; offset += 1; if r2.almost_dequal_ulps(q3) { r2 = -a / 2.0 - adiv3; if!s[0].almost_dequal_ulps(r2) { s[offset] = r2; offset += 1; } } } offset } // Cubic64'(t) = At^2 + Bt + C, where // A = 3(-a + 3(b - c) + d) // B = 6(a - 2b + c) // C = 3(b - a) // Solve for t, keeping only those that fit between 0 < t < 1 pub fn find_extrema(src: &[f64], t_values: &mut [f64]) -> usize { // we divide A,B,C by 3 to simplify let a = src[0]; let b = src[2]; let c = src[4]; let d = src[6]; let a2 = d - a + 3.0 * (b - c); let b2 = 2.0 * (a - b - b + c); let c2 = b - a; quad64::roots_valid_t(a2, b2, c2, t_values) } // Skia doesn't seems to care about NaN/inf during sorting, so we don't too. fn cmp_f64(a: &f64, b: &f64) -> core::cmp::Ordering { if a < b { core::cmp::Ordering::Less } else if a > b { core::cmp::Ordering::Greater } else { core::cmp::Ordering::Equal } } // classic one t subdivision fn interp_cubic_coords_x(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].x, src[1].x, t); let bc = interp(src[1].x, src[2].x, t); let cd = interp(src[2].x, src[3].x, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].x = src[0].x; dst[1].x = ab; dst[2].x = abc; dst[3].x = abcd; dst[4].x = bcd; dst[5].x = cd; dst[6].x = src[3].x; } fn interp_cubic_coords_y(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].y, src[1].y, t); let bc = interp(src[1].y, src[2].y, t); let cd = interp(src[2].y, src[3].y, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].y = src[0].y; dst[1].y = ab; dst[2].y = abc; dst[3].y = abcd; dst[4].y = bcd; dst[5].y = cd; dst[6].y = src[3].y; }
coefficients
identifier_name
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use tiny_skia_path::NoStdFloat; pub const POINT_COUNT: usize = 4; const PI: f64 = 3.141592653589793; pub struct Cubic64Pair { pub points: [Point64; 7], } pub struct Cubic64 { pub points: [Point64; POINT_COUNT], } impl Cubic64 { pub fn new(points: [Point64; POINT_COUNT]) -> Self { Cubic64 { points } } pub fn as_f64_slice(&self) -> [f64; POINT_COUNT * 2] { [ self.points[0].x, self.points[0].y, self.points[1].x, self.points[1].y, self.points[2].x, self.points[2].y, self.points[3].x, self.points[3].y, ] } pub fn point_at_t(&self, t: f64) -> Point64 { if t == 0.0 { return self.points[0]; } if t == 1.0 { return self.points[3]; } let one_t = 1.0 - t; let one_t2 = one_t * one_t; let a = one_t2 * one_t; let b = 3.0 * one_t2 * t; let t2 = t * t; let c = 3.0 * one_t * t2; let d = t2 * t; Point64::from_xy( a * self.points[0].x + b * self.points[1].x + c * self.points[2].x + d * self.points[3].x, a * self.points[0].y + b * self.points[1].y + c * self.points[2].y + d * self.points[3].y, ) } pub fn search_roots( &self, mut extrema: usize, axis_intercept: f64, x_axis: SearchAxis, extreme_ts: &mut [f64; 6], valid_roots: &mut [f64], ) -> usize { extrema += self.find_inflections(&mut extreme_ts[extrema..]); extreme_ts[extrema] = 0.0; extrema += 1; extreme_ts[extrema] = 1.0; debug_assert!(extrema < 6); extreme_ts[0..extrema].sort_by(cmp_f64); let mut valid_count = 0; let mut index = 0; while index < extrema { let min = extreme_ts[index]; index += 1; let max = extreme_ts[index]; if min == max { continue; } let new_t = self.binary_search(min, max, axis_intercept, x_axis); if new_t >= 0.0 { if valid_count >= 3 { return 0; } valid_roots[valid_count] = new_t; valid_count += 1; } } valid_count } fn find_inflections(&self, t_values: &mut [f64]) -> usize { let ax = self.points[1].x - self.points[0].x; let ay = self.points[1].y - self.points[0].y; let bx = self.points[2].x - 2.0 * self.points[1].x + self.points[0].x; let by = self.points[2].y - 2.0 * self.points[1].y + self.points[0].y; let cx = self.points[3].x + 3.0 * (self.points[1].x - self.points[2].x) - self.points[0].x; let cy = self.points[3].y + 3.0 * (self.points[1].y - self.points[2].y) - self.points[0].y; quad64::roots_valid_t( bx * cy - by * cx, ax * cy - ay * cx, ax * by - ay * bx, t_values, ) } // give up when changing t no longer moves point // also, copy point rather than recompute it when it does change fn binary_search(&self, min: f64, max: f64, axis_intercept: f64, x_axis: SearchAxis) -> f64 { let mut t = (min + max) / 2.0; let mut step = (t - min) / 2.0; let mut cubic_at_t = self.point_at_t(t); let mut calc_pos = cubic_at_t.axis_coord(x_axis); let mut calc_dist = calc_pos - axis_intercept; loop { let prior_t = min.max(t - step); let less_pt = self.point_at_t(prior_t); if less_pt.x.approximately_equal_half(cubic_at_t.x) && less_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let less_dist = less_pt.axis_coord(x_axis) - axis_intercept; let last_step = step; step /= 2.0; let ok = if calc_dist > 0.0 { calc_dist > less_dist } else { calc_dist < less_dist }; if ok { t = prior_t; } else { let next_t = t + last_step; if next_t > max { return -1.0; } let more_pt = self.point_at_t(next_t); if more_pt.x.approximately_equal_half(cubic_at_t.x) && more_pt.y.approximately_equal_half(cubic_at_t.y) { return -1.0; // binary search found no point at this axis intercept } let more_dist = more_pt.axis_coord(x_axis) - axis_intercept; let ok = if calc_dist > 0.0 { calc_dist <= more_dist } else { calc_dist >= more_dist }; if ok { continue; } t = next_t; } let test_at_t = self.point_at_t(t); cubic_at_t = test_at_t; calc_pos = cubic_at_t.axis_coord(x_axis); calc_dist = calc_pos - axis_intercept; if calc_pos.approximately_equal(axis_intercept) { break; } } t } pub fn chop_at(&self, t: f64) -> Cubic64Pair { let mut dst = [Point64::zero(); 7]; if t == 0.5 { dst[0] = self.points[0]; dst[1].x = (self.points[0].x + self.points[1].x) / 2.0; dst[1].y = (self.points[0].y + self.points[1].y) / 2.0; dst[2].x = (self.points[0].x + 2.0 * self.points[1].x + self.points[2].x) / 4.0; dst[2].y = (self.points[0].y + 2.0 * self.points[1].y + self.points[2].y) / 4.0; dst[3].x = (self.points[0].x + 3.0 * (self.points[1].x + self.points[2].x) + self.points[3].x) / 8.0; dst[3].y = (self.points[0].y + 3.0 * (self.points[1].y + self.points[2].y) + self.points[3].y) / 8.0; dst[4].x = (self.points[1].x + 2.0 * self.points[2].x + self.points[3].x) / 4.0; dst[4].y = (self.points[1].y + 2.0 * self.points[2].y + self.points[3].y) / 4.0; dst[5].x = (self.points[2].x + self.points[3].x) / 2.0; dst[5].y = (self.points[2].y + self.points[3].y) / 2.0; dst[6] = self.points[3]; Cubic64Pair { points: dst } } else { interp_cubic_coords_x(&self.points, t, &mut dst); interp_cubic_coords_y(&self.points, t, &mut dst); Cubic64Pair { points: dst } } } } pub fn coefficients(src: &[f64]) -> (f64, f64, f64, f64) { let mut a = src[6]; // d let mut b = src[4] * 3.0; // 3*c let mut c = src[2] * 3.0; // 3*b let d = src[0]; // a a -= d - c + b; // A = -a + 3*b - 3*c + d b += 3.0 * d - 2.0 * c; // B = 3*a - 6*b + 3*c c -= 3.0 * d; // C = -3*a + 3*b (a, b, c, d) } // from SkGeometry.cpp (and Numeric Solutions, 5.6) pub fn roots_valid_t(a: f64, b: f64, c: f64, d: f64, t: &mut [f64; 3]) -> usize
} } debug_assert!(found_roots < 3); t[found_roots] = 0.0; found_roots += 1; } } found_roots } fn roots_real(a: f64, b: f64, c: f64, d: f64, s: &mut [f64; 3]) -> usize { if a.approximately_zero() && a.approximately_zero_when_compared_to(b) && a.approximately_zero_when_compared_to(c) && a.approximately_zero_when_compared_to(d) { // we're just a quadratic return quad64::roots_real(b, c, d, s); } if d.approximately_zero_when_compared_to(a) && d.approximately_zero_when_compared_to(b) && d.approximately_zero_when_compared_to(c) { // 0 is one root let mut num = quad64::roots_real(a, b, c, s); for i in 0..num { if s[i].approximately_zero() { return num; } } s[num] = 0.0; num += 1; return num; } if (a + b + c + d).approximately_zero() { // 1 is one root let mut num = quad64::roots_real(a, a + b, -d, s); for i in 0..num { if s[i].almost_dequal_ulps(1.0) { return num; } } s[num] = 1.0; num += 1; return num; } let (a, b, c) = { let inv_a = 1.0 / a; let a = b * inv_a; let b = c * inv_a; let c = d * inv_a; (a, b, c) }; let a2 = a * a; let q = (a2 - b * 3.0) / 9.0; let r = (2.0 * a2 * a - 9.0 * a * b + 27.0 * c) / 54.0; let r2 = r * r; let q3 = q * q * q; let r2_minus_q3 = r2 - q3; let adiv3 = a / 3.0; let mut offset = 0; if r2_minus_q3 < 0.0 { // we have 3 real roots // the divide/root can, due to finite precisions, be slightly outside of -1...1 let theta = (r / q3.sqrt()).bound(-1.0, 1.0).acos(); let neg2_root_q = -2.0 * q.sqrt(); let mut rr = neg2_root_q * (theta / 3.0).cos() - adiv3; s[offset] = rr; offset += 1; rr = neg2_root_q * ((theta + 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) { s[offset] = rr; offset += 1; } rr = neg2_root_q * ((theta - 2.0 * PI) / 3.0).cos() - adiv3; if!s[0].almost_dequal_ulps(rr) && (offset == 1 ||!s[1].almost_dequal_ulps(rr)) { s[offset] = rr; offset += 1; } } else { // we have 1 real root let sqrt_r2_minus_q3 = r2_minus_q3.sqrt(); let mut a = r.abs() + sqrt_r2_minus_q3; a = super::cube_root(a); if r > 0.0 { a = -a; } if a!= 0.0 { a += q / a; } let mut r2 = a - adiv3; s[offset] = r2; offset += 1; if r2.almost_dequal_ulps(q3) { r2 = -a / 2.0 - adiv3; if!s[0].almost_dequal_ulps(r2) { s[offset] = r2; offset += 1; } } } offset } // Cubic64'(t) = At^2 + Bt + C, where // A = 3(-a + 3(b - c) + d) // B = 6(a - 2b + c) // C = 3(b - a) // Solve for t, keeping only those that fit between 0 < t < 1 pub fn find_extrema(src: &[f64], t_values: &mut [f64]) -> usize { // we divide A,B,C by 3 to simplify let a = src[0]; let b = src[2]; let c = src[4]; let d = src[6]; let a2 = d - a + 3.0 * (b - c); let b2 = 2.0 * (a - b - b + c); let c2 = b - a; quad64::roots_valid_t(a2, b2, c2, t_values) } // Skia doesn't seems to care about NaN/inf during sorting, so we don't too. fn cmp_f64(a: &f64, b: &f64) -> core::cmp::Ordering { if a < b { core::cmp::Ordering::Less } else if a > b { core::cmp::Ordering::Greater } else { core::cmp::Ordering::Equal } } // classic one t subdivision fn interp_cubic_coords_x(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].x, src[1].x, t); let bc = interp(src[1].x, src[2].x, t); let cd = interp(src[2].x, src[3].x, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].x = src[0].x; dst[1].x = ab; dst[2].x = abc; dst[3].x = abcd; dst[4].x = bcd; dst[5].x = cd; dst[6].x = src[3].x; } fn interp_cubic_coords_y(src: &[Point64; 4], t: f64, dst: &mut [Point64; 7]) { use super::interp; let ab = interp(src[0].y, src[1].y, t); let bc = interp(src[1].y, src[2].y, t); let cd = interp(src[2].y, src[3].y, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].y = src[0].y; dst[1].y = ab; dst[2].y = abc; dst[3].y = abcd; dst[4].y = bcd; dst[5].y = cd; dst[6].y = src[3].y; }
{ let mut s = [0.0; 3]; let real_roots = roots_real(a, b, c, d, &mut s); let mut found_roots = quad64::push_valid_ts(&s, real_roots, t); 'outer: for index in 0..real_roots { let t_value = s[index]; if !t_value.approximately_one_or_less() && t_value.between(1.0, 1.00005) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(1.0) { continue 'outer; } } debug_assert!(found_roots < 3); t[found_roots] = 1.0; found_roots += 1; } else if !t_value.approximately_zero_or_more() && t_value.between(-0.00005, 0.0) { for idx2 in 0..found_roots { if t[idx2].approximately_equal(0.0) { continue 'outer;
identifier_body
serde_snapshot.rs
use { crate::{ accounts::Accounts, accounts_db::{AccountStorageEntry, AccountsDB, AppendVecId, BankHashInfo}, accounts_index::Ancestors, append_vec::AppendVec, bank::{Bank, BankFieldsToDeserialize, BankRc, Builtins}, blockhash_queue::BlockhashQueue, epoch_stakes::EpochStakes, message_processor::MessageProcessor, rent_collector::RentCollector, stakes::Stakes, }, bincode, bincode::{config::Options, Error}, fs_extra::dir::CopyOptions, log::{info, warn}, rand::{thread_rng, Rng}, serde::{de::DeserializeOwned, Deserialize, Serialize}, solana_sdk::{ clock::{Epoch, Slot, UnixTimestamp}, epoch_schedule::EpochSchedule, fee_calculator::{FeeCalculator, FeeRateGovernor}, genesis_config::ClusterType, genesis_config::GenesisConfig, hard_forks::HardForks, hash::Hash, inflation::Inflation, pubkey::Pubkey, }, std::{ collections::{HashMap, HashSet}, io::{BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, result::Result, sync::{atomic::Ordering, Arc, RwLock}, time::Instant, }, }; #[cfg(RUSTC_WITH_SPECIALIZATION)] use solana_frozen_abi::abi_example::IgnoreAsHelper; mod common; mod future; mod tests; mod utils; use future::Context as TypeContextFuture; #[allow(unused_imports)] use utils::{serialize_iter_as_map, serialize_iter_as_seq, serialize_iter_as_tuple}; // a number of test cases in accounts_db use this #[cfg(test)] pub(crate) use self::tests::reconstruct_accounts_db_via_serialization; pub(crate) use crate::accounts_db::{SnapshotStorage, SnapshotStorages}; #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum SerdeStyle { NEWER, } const MAX_STREAM_SIZE: u64 = 32 * 1024 * 1024 * 1024; #[derive(Clone, Debug, Default, Deserialize, Serialize, AbiExample)] struct AccountsDbFields<T>(HashMap<Slot, Vec<T>>, u64, Slot, BankHashInfo); trait TypeContext<'a> { type SerializableAccountStorageEntry: Serialize + DeserializeOwned + From<&'a AccountStorageEntry> + Into<AccountStorageEntry>; fn serialize_bank_and_storage<S: serde::ser::Serializer>( serializer: S, serializable_bank: &SerializableBankAndStorage<'a, Self>, ) -> std::result::Result<S::Ok, S::Error> where Self: std::marker::Sized; fn serialize_accounts_db_fields<S: serde::ser::Serializer>( serializer: S, serializable_db: &SerializableAccountsDB<'a, Self>, ) -> std::result::Result<S::Ok, S::Error> where Self: std::marker::Sized; fn deserialize_bank_fields<R>( stream: &mut BufReader<R>, ) -> Result< ( BankFieldsToDeserialize, AccountsDbFields<Self::SerializableAccountStorageEntry>, ), Error, > where R: Read; fn deserialize_accounts_db_fields<R>( stream: &mut BufReader<R>, ) -> Result<AccountsDbFields<Self::SerializableAccountStorageEntry>, Error> where R: Read; } fn deserialize_from<R, T>(reader: R) -> bincode::Result<T> where R: Read, T: DeserializeOwned, { bincode::options() .with_limit(MAX_STREAM_SIZE) .with_fixint_encoding() .allow_trailing_bytes() .deserialize_from::<R, T>(reader) } pub(crate) fn bank_from_stream<R, P>( serde_style: SerdeStyle, stream: &mut BufReader<R>, append_vecs_path: P, account_paths: &[PathBuf], genesis_config: &GenesisConfig, frozen_account_pubkeys: &[Pubkey], debug_keys: Option<Arc<HashSet<Pubkey>>>, additional_builtins: Option<&Builtins>, ) -> std::result::Result<Bank, Error> where R: Read, P: AsRef<Path>, { macro_rules! INTO { ($x:ident) => {{ let (bank_fields, accounts_db_fields) = $x::deserialize_bank_fields(stream)?; let bank = reconstruct_bank_from_fields( bank_fields, accounts_db_fields, genesis_config, frozen_account_pubkeys, account_paths, append_vecs_path, debug_keys, additional_builtins, )?; Ok(bank) }}; } match serde_style { SerdeStyle::NEWER => INTO!(TypeContextFuture), } .map_err(|err| { warn!("bankrc_from_stream error: {:?}", err); err }) } pub(crate) fn bank_to_stream<W>( serde_style: SerdeStyle, stream: &mut BufWriter<W>, bank: &Bank, snapshot_storages: &[SnapshotStorage], ) -> Result<(), Error> where W: Write, { macro_rules! INTO { ($x:ident) => { bincode::serialize_into( stream, &SerializableBankAndStorage::<$x> { bank, snapshot_storages, phantom: std::marker::PhantomData::default(), }, ) }; } match serde_style { SerdeStyle::NEWER => INTO!(TypeContextFuture), } .map_err(|err| { warn!("bankrc_to_stream error: {:?}", err); err }) } struct SerializableBankAndStorage<'a, C> { bank: &'a Bank, snapshot_storages: &'a [SnapshotStorage], phantom: std::marker::PhantomData<C>, } impl<'a, C: TypeContext<'a>> Serialize for SerializableBankAndStorage<'a, C> { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_bank_and_storage(serializer, self) } } struct SerializableAccountsDB<'a, C> { accounts_db: &'a AccountsDB, slot: Slot, account_storage_entries: &'a [SnapshotStorage], phantom: std::marker::PhantomData<C>, } impl<'a, C: TypeContext<'a>> Serialize for SerializableAccountsDB<'a, C> { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_accounts_db_fields(serializer, self) } } #[cfg(RUSTC_WITH_SPECIALIZATION)] impl<'a, C> IgnoreAsHelper for SerializableAccountsDB<'a, C> {} fn reconstruct_bank_from_fields<E, P>( bank_fields: BankFieldsToDeserialize, accounts_db_fields: AccountsDbFields<E>,
frozen_account_pubkeys: &[Pubkey], account_paths: &[PathBuf], append_vecs_path: P, debug_keys: Option<Arc<HashSet<Pubkey>>>, additional_builtins: Option<&Builtins>, ) -> Result<Bank, Error> where E: Into<AccountStorageEntry>, P: AsRef<Path>, { let mut accounts_db = reconstruct_accountsdb_from_fields( accounts_db_fields, account_paths, append_vecs_path, &genesis_config.cluster_type, )?; accounts_db.freeze_accounts(&bank_fields.ancestors, frozen_account_pubkeys); let bank_rc = BankRc::new(Accounts::new_empty(accounts_db), bank_fields.slot); let bank = Bank::new_from_fields( bank_rc, genesis_config, bank_fields, debug_keys, additional_builtins, ); Ok(bank) } fn reconstruct_accountsdb_from_fields<E, P>( accounts_db_fields: AccountsDbFields<E>, account_paths: &[PathBuf], stream_append_vecs_path: P, cluster_type: &ClusterType, ) -> Result<AccountsDB, Error> where E: Into<AccountStorageEntry>, P: AsRef<Path>, { let mut accounts_db = AccountsDB::new(account_paths.to_vec(), cluster_type); let AccountsDbFields(storage, version, slot, bank_hash_info) = accounts_db_fields; // convert to two level map of slot -> id -> account storage entry let storage = { let mut map = HashMap::new(); for (slot, entries) in storage.into_iter() { let sub_map = map.entry(slot).or_insert_with(HashMap::new); for entry in entries.into_iter() { let entry: AccountStorageEntry = entry.into(); entry.slot.store(slot, Ordering::Relaxed); sub_map.insert(entry.append_vec_id(), Arc::new(entry)); } } map }; let mut last_log_update = Instant::now(); let mut remaining_slots_to_process = storage.len(); // Remap the deserialized AppendVec paths to point to correct local paths let mut storage = storage .into_iter() .map(|(slot, mut slot_storage)| { let now = Instant::now(); if now.duration_since(last_log_update).as_secs() >= 10 { info!("{} slots remaining...", remaining_slots_to_process); last_log_update = now; } remaining_slots_to_process -= 1; let mut new_slot_storage = HashMap::new(); for (id, storage_entry) in slot_storage.drain() { let path_index = thread_rng().gen_range(0, accounts_db.paths.len()); let local_dir = &accounts_db.paths[path_index]; std::fs::create_dir_all(local_dir).expect("Create directory failed"); // Move the corresponding AppendVec from the snapshot into the directory pointed // at by `local_dir` let append_vec_relative_path = AppendVec::new_relative_path(slot, storage_entry.append_vec_id()); let append_vec_abs_path = stream_append_vecs_path .as_ref() .join(&append_vec_relative_path); let target = local_dir.join(append_vec_abs_path.file_name().unwrap()); std::fs::rename(append_vec_abs_path.clone(), target).or_else(|_| { let mut copy_options = CopyOptions::new(); copy_options.overwrite = true; fs_extra::move_items(&vec![&append_vec_abs_path], &local_dir, &copy_options) .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)) .and(Ok(())) })?; // Notify the AppendVec of the new file location let local_path = local_dir.join(append_vec_relative_path); let mut u_storage_entry = Arc::try_unwrap(storage_entry).unwrap(); u_storage_entry.set_file(local_path)?; new_slot_storage.insert(id, Arc::new(u_storage_entry)); } Ok((slot, new_slot_storage)) }) .collect::<Result<HashMap<Slot, _>, Error>>()?; // discard any slots with no storage entries // this can happen if a non-root slot was serialized // but non-root stores should not be included in the snapshot storage.retain(|_slot, stores|!stores.is_empty()); accounts_db .bank_hashes .write() .unwrap() .insert(slot, bank_hash_info); // Process deserialized data, set necessary fields in self let max_id: usize = *storage .values() .flat_map(HashMap::keys) .max() .expect("At least one storage entry must exist from deserializing stream"); { accounts_db.storage.0.extend( storage.into_iter().map(|(slot, slot_storage_entry)| { (slot, Arc::new(RwLock::new(slot_storage_entry))) }), ); } accounts_db.next_id.store(max_id + 1, Ordering::Relaxed); accounts_db .write_version .fetch_add(version, Ordering::Relaxed); accounts_db.generate_index(); Ok(accounts_db) }
genesis_config: &GenesisConfig,
random_line_split
serde_snapshot.rs
use { crate::{ accounts::Accounts, accounts_db::{AccountStorageEntry, AccountsDB, AppendVecId, BankHashInfo}, accounts_index::Ancestors, append_vec::AppendVec, bank::{Bank, BankFieldsToDeserialize, BankRc, Builtins}, blockhash_queue::BlockhashQueue, epoch_stakes::EpochStakes, message_processor::MessageProcessor, rent_collector::RentCollector, stakes::Stakes, }, bincode, bincode::{config::Options, Error}, fs_extra::dir::CopyOptions, log::{info, warn}, rand::{thread_rng, Rng}, serde::{de::DeserializeOwned, Deserialize, Serialize}, solana_sdk::{ clock::{Epoch, Slot, UnixTimestamp}, epoch_schedule::EpochSchedule, fee_calculator::{FeeCalculator, FeeRateGovernor}, genesis_config::ClusterType, genesis_config::GenesisConfig, hard_forks::HardForks, hash::Hash, inflation::Inflation, pubkey::Pubkey, }, std::{ collections::{HashMap, HashSet}, io::{BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, result::Result, sync::{atomic::Ordering, Arc, RwLock}, time::Instant, }, }; #[cfg(RUSTC_WITH_SPECIALIZATION)] use solana_frozen_abi::abi_example::IgnoreAsHelper; mod common; mod future; mod tests; mod utils; use future::Context as TypeContextFuture; #[allow(unused_imports)] use utils::{serialize_iter_as_map, serialize_iter_as_seq, serialize_iter_as_tuple}; // a number of test cases in accounts_db use this #[cfg(test)] pub(crate) use self::tests::reconstruct_accounts_db_via_serialization; pub(crate) use crate::accounts_db::{SnapshotStorage, SnapshotStorages}; #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum SerdeStyle { NEWER, } const MAX_STREAM_SIZE: u64 = 32 * 1024 * 1024 * 1024; #[derive(Clone, Debug, Default, Deserialize, Serialize, AbiExample)] struct AccountsDbFields<T>(HashMap<Slot, Vec<T>>, u64, Slot, BankHashInfo); trait TypeContext<'a> { type SerializableAccountStorageEntry: Serialize + DeserializeOwned + From<&'a AccountStorageEntry> + Into<AccountStorageEntry>; fn serialize_bank_and_storage<S: serde::ser::Serializer>( serializer: S, serializable_bank: &SerializableBankAndStorage<'a, Self>, ) -> std::result::Result<S::Ok, S::Error> where Self: std::marker::Sized; fn serialize_accounts_db_fields<S: serde::ser::Serializer>( serializer: S, serializable_db: &SerializableAccountsDB<'a, Self>, ) -> std::result::Result<S::Ok, S::Error> where Self: std::marker::Sized; fn deserialize_bank_fields<R>( stream: &mut BufReader<R>, ) -> Result< ( BankFieldsToDeserialize, AccountsDbFields<Self::SerializableAccountStorageEntry>, ), Error, > where R: Read; fn deserialize_accounts_db_fields<R>( stream: &mut BufReader<R>, ) -> Result<AccountsDbFields<Self::SerializableAccountStorageEntry>, Error> where R: Read; } fn deserialize_from<R, T>(reader: R) -> bincode::Result<T> where R: Read, T: DeserializeOwned, { bincode::options() .with_limit(MAX_STREAM_SIZE) .with_fixint_encoding() .allow_trailing_bytes() .deserialize_from::<R, T>(reader) } pub(crate) fn bank_from_stream<R, P>( serde_style: SerdeStyle, stream: &mut BufReader<R>, append_vecs_path: P, account_paths: &[PathBuf], genesis_config: &GenesisConfig, frozen_account_pubkeys: &[Pubkey], debug_keys: Option<Arc<HashSet<Pubkey>>>, additional_builtins: Option<&Builtins>, ) -> std::result::Result<Bank, Error> where R: Read, P: AsRef<Path>, { macro_rules! INTO { ($x:ident) => {{ let (bank_fields, accounts_db_fields) = $x::deserialize_bank_fields(stream)?; let bank = reconstruct_bank_from_fields( bank_fields, accounts_db_fields, genesis_config, frozen_account_pubkeys, account_paths, append_vecs_path, debug_keys, additional_builtins, )?; Ok(bank) }}; } match serde_style { SerdeStyle::NEWER => INTO!(TypeContextFuture), } .map_err(|err| { warn!("bankrc_from_stream error: {:?}", err); err }) } pub(crate) fn bank_to_stream<W>( serde_style: SerdeStyle, stream: &mut BufWriter<W>, bank: &Bank, snapshot_storages: &[SnapshotStorage], ) -> Result<(), Error> where W: Write, { macro_rules! INTO { ($x:ident) => { bincode::serialize_into( stream, &SerializableBankAndStorage::<$x> { bank, snapshot_storages, phantom: std::marker::PhantomData::default(), }, ) }; } match serde_style { SerdeStyle::NEWER => INTO!(TypeContextFuture), } .map_err(|err| { warn!("bankrc_to_stream error: {:?}", err); err }) } struct SerializableBankAndStorage<'a, C> { bank: &'a Bank, snapshot_storages: &'a [SnapshotStorage], phantom: std::marker::PhantomData<C>, } impl<'a, C: TypeContext<'a>> Serialize for SerializableBankAndStorage<'a, C> { fn
<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_bank_and_storage(serializer, self) } } struct SerializableAccountsDB<'a, C> { accounts_db: &'a AccountsDB, slot: Slot, account_storage_entries: &'a [SnapshotStorage], phantom: std::marker::PhantomData<C>, } impl<'a, C: TypeContext<'a>> Serialize for SerializableAccountsDB<'a, C> { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_accounts_db_fields(serializer, self) } } #[cfg(RUSTC_WITH_SPECIALIZATION)] impl<'a, C> IgnoreAsHelper for SerializableAccountsDB<'a, C> {} fn reconstruct_bank_from_fields<E, P>( bank_fields: BankFieldsToDeserialize, accounts_db_fields: AccountsDbFields<E>, genesis_config: &GenesisConfig, frozen_account_pubkeys: &[Pubkey], account_paths: &[PathBuf], append_vecs_path: P, debug_keys: Option<Arc<HashSet<Pubkey>>>, additional_builtins: Option<&Builtins>, ) -> Result<Bank, Error> where E: Into<AccountStorageEntry>, P: AsRef<Path>, { let mut accounts_db = reconstruct_accountsdb_from_fields( accounts_db_fields, account_paths, append_vecs_path, &genesis_config.cluster_type, )?; accounts_db.freeze_accounts(&bank_fields.ancestors, frozen_account_pubkeys); let bank_rc = BankRc::new(Accounts::new_empty(accounts_db), bank_fields.slot); let bank = Bank::new_from_fields( bank_rc, genesis_config, bank_fields, debug_keys, additional_builtins, ); Ok(bank) } fn reconstruct_accountsdb_from_fields<E, P>( accounts_db_fields: AccountsDbFields<E>, account_paths: &[PathBuf], stream_append_vecs_path: P, cluster_type: &ClusterType, ) -> Result<AccountsDB, Error> where E: Into<AccountStorageEntry>, P: AsRef<Path>, { let mut accounts_db = AccountsDB::new(account_paths.to_vec(), cluster_type); let AccountsDbFields(storage, version, slot, bank_hash_info) = accounts_db_fields; // convert to two level map of slot -> id -> account storage entry let storage = { let mut map = HashMap::new(); for (slot, entries) in storage.into_iter() { let sub_map = map.entry(slot).or_insert_with(HashMap::new); for entry in entries.into_iter() { let entry: AccountStorageEntry = entry.into(); entry.slot.store(slot, Ordering::Relaxed); sub_map.insert(entry.append_vec_id(), Arc::new(entry)); } } map }; let mut last_log_update = Instant::now(); let mut remaining_slots_to_process = storage.len(); // Remap the deserialized AppendVec paths to point to correct local paths let mut storage = storage .into_iter() .map(|(slot, mut slot_storage)| { let now = Instant::now(); if now.duration_since(last_log_update).as_secs() >= 10 { info!("{} slots remaining...", remaining_slots_to_process); last_log_update = now; } remaining_slots_to_process -= 1; let mut new_slot_storage = HashMap::new(); for (id, storage_entry) in slot_storage.drain() { let path_index = thread_rng().gen_range(0, accounts_db.paths.len()); let local_dir = &accounts_db.paths[path_index]; std::fs::create_dir_all(local_dir).expect("Create directory failed"); // Move the corresponding AppendVec from the snapshot into the directory pointed // at by `local_dir` let append_vec_relative_path = AppendVec::new_relative_path(slot, storage_entry.append_vec_id()); let append_vec_abs_path = stream_append_vecs_path .as_ref() .join(&append_vec_relative_path); let target = local_dir.join(append_vec_abs_path.file_name().unwrap()); std::fs::rename(append_vec_abs_path.clone(), target).or_else(|_| { let mut copy_options = CopyOptions::new(); copy_options.overwrite = true; fs_extra::move_items(&vec![&append_vec_abs_path], &local_dir, &copy_options) .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)) .and(Ok(())) })?; // Notify the AppendVec of the new file location let local_path = local_dir.join(append_vec_relative_path); let mut u_storage_entry = Arc::try_unwrap(storage_entry).unwrap(); u_storage_entry.set_file(local_path)?; new_slot_storage.insert(id, Arc::new(u_storage_entry)); } Ok((slot, new_slot_storage)) }) .collect::<Result<HashMap<Slot, _>, Error>>()?; // discard any slots with no storage entries // this can happen if a non-root slot was serialized // but non-root stores should not be included in the snapshot storage.retain(|_slot, stores|!stores.is_empty()); accounts_db .bank_hashes .write() .unwrap() .insert(slot, bank_hash_info); // Process deserialized data, set necessary fields in self let max_id: usize = *storage .values() .flat_map(HashMap::keys) .max() .expect("At least one storage entry must exist from deserializing stream"); { accounts_db.storage.0.extend( storage.into_iter().map(|(slot, slot_storage_entry)| { (slot, Arc::new(RwLock::new(slot_storage_entry))) }), ); } accounts_db.next_id.store(max_id + 1, Ordering::Relaxed); accounts_db .write_version .fetch_add(version, Ordering::Relaxed); accounts_db.generate_index(); Ok(accounts_db) }
serialize
identifier_name
serde_snapshot.rs
use { crate::{ accounts::Accounts, accounts_db::{AccountStorageEntry, AccountsDB, AppendVecId, BankHashInfo}, accounts_index::Ancestors, append_vec::AppendVec, bank::{Bank, BankFieldsToDeserialize, BankRc, Builtins}, blockhash_queue::BlockhashQueue, epoch_stakes::EpochStakes, message_processor::MessageProcessor, rent_collector::RentCollector, stakes::Stakes, }, bincode, bincode::{config::Options, Error}, fs_extra::dir::CopyOptions, log::{info, warn}, rand::{thread_rng, Rng}, serde::{de::DeserializeOwned, Deserialize, Serialize}, solana_sdk::{ clock::{Epoch, Slot, UnixTimestamp}, epoch_schedule::EpochSchedule, fee_calculator::{FeeCalculator, FeeRateGovernor}, genesis_config::ClusterType, genesis_config::GenesisConfig, hard_forks::HardForks, hash::Hash, inflation::Inflation, pubkey::Pubkey, }, std::{ collections::{HashMap, HashSet}, io::{BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, result::Result, sync::{atomic::Ordering, Arc, RwLock}, time::Instant, }, }; #[cfg(RUSTC_WITH_SPECIALIZATION)] use solana_frozen_abi::abi_example::IgnoreAsHelper; mod common; mod future; mod tests; mod utils; use future::Context as TypeContextFuture; #[allow(unused_imports)] use utils::{serialize_iter_as_map, serialize_iter_as_seq, serialize_iter_as_tuple}; // a number of test cases in accounts_db use this #[cfg(test)] pub(crate) use self::tests::reconstruct_accounts_db_via_serialization; pub(crate) use crate::accounts_db::{SnapshotStorage, SnapshotStorages}; #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum SerdeStyle { NEWER, } const MAX_STREAM_SIZE: u64 = 32 * 1024 * 1024 * 1024; #[derive(Clone, Debug, Default, Deserialize, Serialize, AbiExample)] struct AccountsDbFields<T>(HashMap<Slot, Vec<T>>, u64, Slot, BankHashInfo); trait TypeContext<'a> { type SerializableAccountStorageEntry: Serialize + DeserializeOwned + From<&'a AccountStorageEntry> + Into<AccountStorageEntry>; fn serialize_bank_and_storage<S: serde::ser::Serializer>( serializer: S, serializable_bank: &SerializableBankAndStorage<'a, Self>, ) -> std::result::Result<S::Ok, S::Error> where Self: std::marker::Sized; fn serialize_accounts_db_fields<S: serde::ser::Serializer>( serializer: S, serializable_db: &SerializableAccountsDB<'a, Self>, ) -> std::result::Result<S::Ok, S::Error> where Self: std::marker::Sized; fn deserialize_bank_fields<R>( stream: &mut BufReader<R>, ) -> Result< ( BankFieldsToDeserialize, AccountsDbFields<Self::SerializableAccountStorageEntry>, ), Error, > where R: Read; fn deserialize_accounts_db_fields<R>( stream: &mut BufReader<R>, ) -> Result<AccountsDbFields<Self::SerializableAccountStorageEntry>, Error> where R: Read; } fn deserialize_from<R, T>(reader: R) -> bincode::Result<T> where R: Read, T: DeserializeOwned, { bincode::options() .with_limit(MAX_STREAM_SIZE) .with_fixint_encoding() .allow_trailing_bytes() .deserialize_from::<R, T>(reader) } pub(crate) fn bank_from_stream<R, P>( serde_style: SerdeStyle, stream: &mut BufReader<R>, append_vecs_path: P, account_paths: &[PathBuf], genesis_config: &GenesisConfig, frozen_account_pubkeys: &[Pubkey], debug_keys: Option<Arc<HashSet<Pubkey>>>, additional_builtins: Option<&Builtins>, ) -> std::result::Result<Bank, Error> where R: Read, P: AsRef<Path>, { macro_rules! INTO { ($x:ident) => {{ let (bank_fields, accounts_db_fields) = $x::deserialize_bank_fields(stream)?; let bank = reconstruct_bank_from_fields( bank_fields, accounts_db_fields, genesis_config, frozen_account_pubkeys, account_paths, append_vecs_path, debug_keys, additional_builtins, )?; Ok(bank) }}; } match serde_style { SerdeStyle::NEWER => INTO!(TypeContextFuture), } .map_err(|err| { warn!("bankrc_from_stream error: {:?}", err); err }) } pub(crate) fn bank_to_stream<W>( serde_style: SerdeStyle, stream: &mut BufWriter<W>, bank: &Bank, snapshot_storages: &[SnapshotStorage], ) -> Result<(), Error> where W: Write, { macro_rules! INTO { ($x:ident) => { bincode::serialize_into( stream, &SerializableBankAndStorage::<$x> { bank, snapshot_storages, phantom: std::marker::PhantomData::default(), }, ) }; } match serde_style { SerdeStyle::NEWER => INTO!(TypeContextFuture), } .map_err(|err| { warn!("bankrc_to_stream error: {:?}", err); err }) } struct SerializableBankAndStorage<'a, C> { bank: &'a Bank, snapshot_storages: &'a [SnapshotStorage], phantom: std::marker::PhantomData<C>, } impl<'a, C: TypeContext<'a>> Serialize for SerializableBankAndStorage<'a, C> { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_bank_and_storage(serializer, self) } } struct SerializableAccountsDB<'a, C> { accounts_db: &'a AccountsDB, slot: Slot, account_storage_entries: &'a [SnapshotStorage], phantom: std::marker::PhantomData<C>, } impl<'a, C: TypeContext<'a>> Serialize for SerializableAccountsDB<'a, C> { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_accounts_db_fields(serializer, self) } } #[cfg(RUSTC_WITH_SPECIALIZATION)] impl<'a, C> IgnoreAsHelper for SerializableAccountsDB<'a, C> {} fn reconstruct_bank_from_fields<E, P>( bank_fields: BankFieldsToDeserialize, accounts_db_fields: AccountsDbFields<E>, genesis_config: &GenesisConfig, frozen_account_pubkeys: &[Pubkey], account_paths: &[PathBuf], append_vecs_path: P, debug_keys: Option<Arc<HashSet<Pubkey>>>, additional_builtins: Option<&Builtins>, ) -> Result<Bank, Error> where E: Into<AccountStorageEntry>, P: AsRef<Path>, { let mut accounts_db = reconstruct_accountsdb_from_fields( accounts_db_fields, account_paths, append_vecs_path, &genesis_config.cluster_type, )?; accounts_db.freeze_accounts(&bank_fields.ancestors, frozen_account_pubkeys); let bank_rc = BankRc::new(Accounts::new_empty(accounts_db), bank_fields.slot); let bank = Bank::new_from_fields( bank_rc, genesis_config, bank_fields, debug_keys, additional_builtins, ); Ok(bank) } fn reconstruct_accountsdb_from_fields<E, P>( accounts_db_fields: AccountsDbFields<E>, account_paths: &[PathBuf], stream_append_vecs_path: P, cluster_type: &ClusterType, ) -> Result<AccountsDB, Error> where E: Into<AccountStorageEntry>, P: AsRef<Path>,
let mut remaining_slots_to_process = storage.len(); // Remap the deserialized AppendVec paths to point to correct local paths let mut storage = storage .into_iter() .map(|(slot, mut slot_storage)| { let now = Instant::now(); if now.duration_since(last_log_update).as_secs() >= 10 { info!("{} slots remaining...", remaining_slots_to_process); last_log_update = now; } remaining_slots_to_process -= 1; let mut new_slot_storage = HashMap::new(); for (id, storage_entry) in slot_storage.drain() { let path_index = thread_rng().gen_range(0, accounts_db.paths.len()); let local_dir = &accounts_db.paths[path_index]; std::fs::create_dir_all(local_dir).expect("Create directory failed"); // Move the corresponding AppendVec from the snapshot into the directory pointed // at by `local_dir` let append_vec_relative_path = AppendVec::new_relative_path(slot, storage_entry.append_vec_id()); let append_vec_abs_path = stream_append_vecs_path .as_ref() .join(&append_vec_relative_path); let target = local_dir.join(append_vec_abs_path.file_name().unwrap()); std::fs::rename(append_vec_abs_path.clone(), target).or_else(|_| { let mut copy_options = CopyOptions::new(); copy_options.overwrite = true; fs_extra::move_items(&vec![&append_vec_abs_path], &local_dir, &copy_options) .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)) .and(Ok(())) })?; // Notify the AppendVec of the new file location let local_path = local_dir.join(append_vec_relative_path); let mut u_storage_entry = Arc::try_unwrap(storage_entry).unwrap(); u_storage_entry.set_file(local_path)?; new_slot_storage.insert(id, Arc::new(u_storage_entry)); } Ok((slot, new_slot_storage)) }) .collect::<Result<HashMap<Slot, _>, Error>>()?; // discard any slots with no storage entries // this can happen if a non-root slot was serialized // but non-root stores should not be included in the snapshot storage.retain(|_slot, stores|!stores.is_empty()); accounts_db .bank_hashes .write() .unwrap() .insert(slot, bank_hash_info); // Process deserialized data, set necessary fields in self let max_id: usize = *storage .values() .flat_map(HashMap::keys) .max() .expect("At least one storage entry must exist from deserializing stream"); { accounts_db.storage.0.extend( storage.into_iter().map(|(slot, slot_storage_entry)| { (slot, Arc::new(RwLock::new(slot_storage_entry))) }), ); } accounts_db.next_id.store(max_id + 1, Ordering::Relaxed); accounts_db .write_version .fetch_add(version, Ordering::Relaxed); accounts_db.generate_index(); Ok(accounts_db) }
{ let mut accounts_db = AccountsDB::new(account_paths.to_vec(), cluster_type); let AccountsDbFields(storage, version, slot, bank_hash_info) = accounts_db_fields; // convert to two level map of slot -> id -> account storage entry let storage = { let mut map = HashMap::new(); for (slot, entries) in storage.into_iter() { let sub_map = map.entry(slot).or_insert_with(HashMap::new); for entry in entries.into_iter() { let entry: AccountStorageEntry = entry.into(); entry.slot.store(slot, Ordering::Relaxed); sub_map.insert(entry.append_vec_id(), Arc::new(entry)); } } map }; let mut last_log_update = Instant::now();
identifier_body
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concrete bits in fundamental elements. They are implementation details, and are not exported in the prelude. !*/
use core::{ cmp::Eq, fmt::{ Binary, Debug, Display, LowerHex, UpperHex, }, mem::size_of, ops::{ BitAnd, BitAndAssign, BitOrAssign, Not, Shl, ShlAssign, Shr, ShrAssign, }, }; #[cfg(feature = "atomic")] use core::sync::atomic::{ self, Ordering::Relaxed, }; #[cfg(not(feature = "atomic"))] use core::cell::Cell; /** Generalizes over the fundamental types for use in `bitvec` data structures. This trait must only be implemented on unsigned integer primitives with full alignment. It cannot be implemented on `u128` on any architecture, or on `u64` on 32-bit systems. The `Sealed` supertrait ensures that this can only be implemented locally, and will never be implemented by downstream crates on new types. **/ pub trait BitStore: // Forbid external implementation Sealed + Binary // Element-wise binary manipulation + BitAnd<Self, Output=Self> + BitAndAssign<Self> + BitOrAssign<Self> // Permit indexing into a generic array + Copy + Debug + Default + Display // Permit testing a value against 1 in `get()`. + Eq // Rust treats numeric literals in code as vaguely typed and does not make // them concrete until long after trait expansion, so this enables building // a concrete Self value from a numeric literal. + From<u8> // Permit extending into a `u64`. + Into<u64> + LowerHex + Not<Output=Self> + Send + Shl<u8, Output=Self> + ShlAssign<u8> + Shr<u8, Output=Self> + ShrAssign<u8> // Allow direct access to a concrete implementor type. + Sized + Sync + UpperHex { /// The width, in bits, of this type. const BITS: u8 = size_of::<Self>() as u8 * 8; /// The number of bits required to index a bit inside the type. This is /// always log<sub>2</sub> of the type’s bit width. const INDX: u8 = Self::BITS.trailing_zeros() as u8; /// The bitmask to turn an arbitrary number into a bit index. Bit indices /// are always stored in the lowest bits of an index value. const MASK: u8 = Self::BITS - 1; /// Name of the implementing type. This is only necessary until the compiler /// stabilizes `type_name()`. const TYPENAME: &'static str; /// Shared-mutability wrapper type used to safely mutate aliased data. /// /// Within `&/mut BitSlice` contexts, the `Nucleus` type **must** be used to /// ensure correctly-synchronized access to memory elements that may have /// aliased mutable access. When a codepath knows that it has full ownership /// of a memory element of `Self`, and no other codepath may observe, much /// less modify, it, then that codepath may skip the `Nucleus` type and use /// plain accessors. type Nucleus: BitAccess<Self>; /// Sets a specific bit in an element to a given value. /// /// # Safety /// /// This method cannot be called from within a `&mut BitSlice` context; it /// may only be called by construction of an `&mut Self` reference from a /// `Self` element directly. /// /// # Parameters /// /// - `&mut self` /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be set according to `value`. /// - `value`: A Boolean value, which sets the bit on `true` and clears it /// on `false`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. #[inline(always)] fn set<C>(&mut self, place: BitIdx<Self>, value: bool) where C: Cursor { let mask = *C::mask(place); if value { *self |= mask; } else { *self &=!mask; } } /// Gets a specific bit in an element. /// /// # Safety /// /// This method cannot be called from within a `&BitSlice` context; it may /// only be called by construction of an `&Self` reference from a `Self` /// element directly. /// /// # Parameters /// /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<Self>) -> bool where C: Cursor { *self & *C::mask(place)!= Self::from(0) } /// Counts how many bits in `self` are set to `1`. /// /// This zero-extends `self` to `u64`, and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `1`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_ones(&0u8), 0); /// assert_eq!(BitStore::count_ones(&128u8), 1); /// assert_eq!(BitStore::count_ones(&192u8), 2); /// assert_eq!(BitStore::count_ones(&224u8), 3); /// assert_eq!(BitStore::count_ones(&240u8), 4); /// assert_eq!(BitStore::count_ones(&248u8), 5); /// assert_eq!(BitStore::count_ones(&252u8), 6); /// assert_eq!(BitStore::count_ones(&254u8), 7); /// assert_eq!(BitStore::count_ones(&255u8), 8); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_ones(&self) -> usize { u64::count_ones((*self).into()) as usize } /// Counts how many bits in `self` are set to `0`. /// /// This inverts `self`, so all `0` bits are `1` and all `1` bits are `0`, /// then zero-extends `self` to `u64` and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `0`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_zeros(&0u8), 8); /// assert_eq!(BitStore::count_zeros(&1u8), 7); /// assert_eq!(BitStore::count_zeros(&3u8), 6); /// assert_eq!(BitStore::count_zeros(&7u8), 5); /// assert_eq!(BitStore::count_zeros(&15u8), 4); /// assert_eq!(BitStore::count_zeros(&31u8), 3); /// assert_eq!(BitStore::count_zeros(&63u8), 2); /// assert_eq!(BitStore::count_zeros(&127u8), 1); /// assert_eq!(BitStore::count_zeros(&255u8), 0); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_zeros(&self) -> usize { // invert (0 becomes 1, 1 becomes 0), zero-extend, count ones u64::count_ones((!*self).into()) as usize } /// Extends a single bit to fill the entire element. /// /// # Parameters /// /// - `bit`: The bit to extend. /// /// # Returns /// /// An element with all bits set to the input. #[inline] fn bits(bit: bool) -> Self { if bit { !Self::from(0) } else { Self::from(0) } } } /** Marker trait to seal `BitStore` against downstream implementation. This trait is public in the module, so that other modules in the crate can use it, but so long as it is not exported by the crate root and this module is private, this trait effectively forbids downstream implementation of the `BitStore` trait. **/ #[doc(hidden)] pub trait Sealed {} macro_rules! store { ( $( $t:ty, $a:ty $( ; )? );* ) => { $( impl Sealed for $t {} impl BitStore for $t { const TYPENAME: &'static str = stringify!($t); #[cfg(feature = "atomic")] type Nucleus = $a; #[cfg(not(feature = "atomic"))] type Nucleus = Cell<Self>; } )* }; } store![ u8, atomic::AtomicU8; u16, atomic::AtomicU16; u32, atomic::AtomicU32; ]; #[cfg(target_pointer_width = "64")] store![u64, atomic::AtomicU64]; /// Type alias to the CPU word element, `u32`. #[cfg(target_pointer_width = "32")] pub type Word = u32; /// Type alias to the CPU word element, `u64`. #[cfg(target_pointer_width = "64")] pub type Word = u64; /** Common interface for atomic and cellular shared-mutability wrappers. `&/mut BitSlice` contexts must use the `BitStore::Nucleus` type for all reference production, and must route through this trait in order to access the underlying memory. In multi-threaded contexts, this trait enforces that all access is synchronized through atomic accesses; in single-threaded contexts, this trait solely permits modification of an aliased element. It is implemented on the atomic type wrappers when the `atomic` feature is set, and implemented on the `Cell` type wrapper when the feature is missing. Coupled with the `Send` implementation on `BitSlice` **/ pub trait BitAccess<T>: Sized where T: BitStore { /// Sets a specific bit in an element low. /// /// `BitAccess::set` calls this when its `value` is `false`; it /// unconditionally writes a `0` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn clear_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Sets a specific bit in an element high. /// /// `BitAccess::set` calls this when its `value` is `true`; it /// unconditionally writes a `1` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn set_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Inverts a specific bit in an element. /// /// This is the driver of `BitStore::invert_bit`, and has the same API and /// documented behavior. fn invert_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Gets a specific bit in an element. /// /// # Parameters /// /// - `&self`: A shared reference to a maybe-mutable element. This uses the /// trait `load` function to ensure correct reads from memory. /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<T>) -> bool where C: Cursor { self.load() & *C::mask(place)!= T::from(0) } /// Sets a specific bit in an element to a given value. /// /// This is the driver of `BitStore::set`, and has the same API and /// documented behavior. #[inline(always)] fn set<C>(&self, place: BitIdx<T>, value: bool) where C: Cursor { if value { self.set_bit::<C>(place); } else { self.clear_bit::<C>(place); } } /// Removes the shared-mutability wrapper, producing a read reference to the /// inner type. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// A read reference to the wrapped type. /// /// # Safety /// /// As this removes mutability, it is strictly safe. #[inline(always)] fn base(&self) -> &T { unsafe { &*(self as *const Self as *const T) } } /// Transforms a reference of `&[T::Nucleus]` into `&mut [T]`. /// /// # Safety /// /// This function is undefined when the `this` slice referent has aliasing /// pointers. It must only ever be called when the slice referent is /// guaranteed to have no aliases, but mutability has been removed from the /// type system at an earlier point in the call stack. /// /// # Parameters /// /// - `this`: A slice reference to some shared-mutability reference type. /// /// # Returns /// /// A mutable reference to the wrapped interior type of the `this` referent. #[inline(always)] unsafe fn base_slice_mut(this: &[Self]) -> &mut [T] { &mut *(this as *const [Self] as *const [T] as *mut [T]) } /// Performs a synchronized load on an unsynchronized reference. /// /// Atomic implementors must ensure that the load is well synchronized, and /// cell implementors can just read. Each implementor must be strictly gated /// on the `atomic` feature flag. fn load(&self) -> T; } /* FIXME(myrrlyn): When the `radium` crate publishes generic traits, erase the implementations currently in use and enable the generic implementation below: impl<T, R> BitAccess<T> for R where T: BitStore, R: RadiumBits<T> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } } */ #[cfg(feature = "atomic")] fn _atom() { impl BitAccess<u8> for atomic::AtomicU8 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u8 { self.load(Relaxed) } } impl BitAccess<u16> for atomic::AtomicU16 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u16 { self.load(Relaxed) } } impl BitAccess<u32> for atomic::AtomicU32 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u32 { self.load(Relaxed) } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for atomic::AtomicU64 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u64 { self.load(Relaxed) } } } #[cfg(not(feature = "atomic"))] fn _cell() { impl BitAccess<u8> for Cell<u8> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u8 { self.get() } } impl BitAccess<u16> for Cell<u16> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u16 { self.get() } } impl BitAccess<u32> for Cell<u32> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u32 { self.get() } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for Cell<u64> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u64 { self.get() } } }
use crate::{ cursor::Cursor, indices::BitIdx, };
random_line_split
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concrete bits in fundamental elements. They are implementation details, and are not exported in the prelude. !*/ use crate::{ cursor::Cursor, indices::BitIdx, }; use core::{ cmp::Eq, fmt::{ Binary, Debug, Display, LowerHex, UpperHex, }, mem::size_of, ops::{ BitAnd, BitAndAssign, BitOrAssign, Not, Shl, ShlAssign, Shr, ShrAssign, }, }; #[cfg(feature = "atomic")] use core::sync::atomic::{ self, Ordering::Relaxed, }; #[cfg(not(feature = "atomic"))] use core::cell::Cell; /** Generalizes over the fundamental types for use in `bitvec` data structures. This trait must only be implemented on unsigned integer primitives with full alignment. It cannot be implemented on `u128` on any architecture, or on `u64` on 32-bit systems. The `Sealed` supertrait ensures that this can only be implemented locally, and will never be implemented by downstream crates on new types. **/ pub trait BitStore: // Forbid external implementation Sealed + Binary // Element-wise binary manipulation + BitAnd<Self, Output=Self> + BitAndAssign<Self> + BitOrAssign<Self> // Permit indexing into a generic array + Copy + Debug + Default + Display // Permit testing a value against 1 in `get()`. + Eq // Rust treats numeric literals in code as vaguely typed and does not make // them concrete until long after trait expansion, so this enables building // a concrete Self value from a numeric literal. + From<u8> // Permit extending into a `u64`. + Into<u64> + LowerHex + Not<Output=Self> + Send + Shl<u8, Output=Self> + ShlAssign<u8> + Shr<u8, Output=Self> + ShrAssign<u8> // Allow direct access to a concrete implementor type. + Sized + Sync + UpperHex { /// The width, in bits, of this type. const BITS: u8 = size_of::<Self>() as u8 * 8; /// The number of bits required to index a bit inside the type. This is /// always log<sub>2</sub> of the type’s bit width. const INDX: u8 = Self::BITS.trailing_zeros() as u8; /// The bitmask to turn an arbitrary number into a bit index. Bit indices /// are always stored in the lowest bits of an index value. const MASK: u8 = Self::BITS - 1; /// Name of the implementing type. This is only necessary until the compiler /// stabilizes `type_name()`. const TYPENAME: &'static str; /// Shared-mutability wrapper type used to safely mutate aliased data. /// /// Within `&/mut BitSlice` contexts, the `Nucleus` type **must** be used to /// ensure correctly-synchronized access to memory elements that may have /// aliased mutable access. When a codepath knows that it has full ownership /// of a memory element of `Self`, and no other codepath may observe, much /// less modify, it, then that codepath may skip the `Nucleus` type and use /// plain accessors. type Nucleus: BitAccess<Self>; /// Sets a specific bit in an element to a given value. /// /// # Safety /// /// This method cannot be called from within a `&mut BitSlice` context; it /// may only be called by construction of an `&mut Self` reference from a /// `Self` element directly. /// /// # Parameters /// /// - `&mut self` /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be set according to `value`. /// - `value`: A Boolean value, which sets the bit on `true` and clears it /// on `false`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. #[inline(always)] fn set<C>(&mut self, place: BitIdx<Self>, value: bool) where C: Cursor { let mask = *C::mask(place); if value { *self |= mask; } else { *self &=!mask; } } /// Gets a specific bit in an element. /// /// # Safety /// /// This method cannot be called from within a `&BitSlice` context; it may /// only be called by construction of an `&Self` reference from a `Self` /// element directly. /// /// # Parameters /// /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<Self>) -> bool where C: Cursor { *self & *C::mask(place)!= Self::from(0) } /// Counts how many bits in `self` are set to `1`. /// /// This zero-extends `self` to `u64`, and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `1`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_ones(&0u8), 0); /// assert_eq!(BitStore::count_ones(&128u8), 1); /// assert_eq!(BitStore::count_ones(&192u8), 2); /// assert_eq!(BitStore::count_ones(&224u8), 3); /// assert_eq!(BitStore::count_ones(&240u8), 4); /// assert_eq!(BitStore::count_ones(&248u8), 5); /// assert_eq!(BitStore::count_ones(&252u8), 6); /// assert_eq!(BitStore::count_ones(&254u8), 7); /// assert_eq!(BitStore::count_ones(&255u8), 8); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_ones(&self) -> usize { u64::count_ones((*self).into()) as usize } /// Counts how many bits in `self` are set to `0`. /// /// This inverts `self`, so all `0` bits are `1` and all `1` bits are `0`, /// then zero-extends `self` to `u64` and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `0`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_zeros(&0u8), 8); /// assert_eq!(BitStore::count_zeros(&1u8), 7); /// assert_eq!(BitStore::count_zeros(&3u8), 6); /// assert_eq!(BitStore::count_zeros(&7u8), 5); /// assert_eq!(BitStore::count_zeros(&15u8), 4); /// assert_eq!(BitStore::count_zeros(&31u8), 3); /// assert_eq!(BitStore::count_zeros(&63u8), 2); /// assert_eq!(BitStore::count_zeros(&127u8), 1); /// assert_eq!(BitStore::count_zeros(&255u8), 0); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_zeros(&self) -> usize { // invert (0 becomes 1, 1 becomes 0), zero-extend, count ones u64::count_ones((!*self).into()) as usize } /// Extends a single bit to fill the entire element. /// /// # Parameters /// /// - `bit`: The bit to extend. /// /// # Returns /// /// An element with all bits set to the input. #[inline] fn bits(bit: bool) -> Self { if bit { !Self::from(0) } else { Self::from(0) } } } /** Marker trait to seal `BitStore` against downstream implementation. This trait is public in the module, so that other modules in the crate can use it, but so long as it is not exported by the crate root and this module is private, this trait effectively forbids downstream implementation of the `BitStore` trait. **/ #[doc(hidden)] pub trait Sealed {} macro_rules! store { ( $( $t:ty, $a:ty $( ; )? );* ) => { $( impl Sealed for $t {} impl BitStore for $t { const TYPENAME: &'static str = stringify!($t); #[cfg(feature = "atomic")] type Nucleus = $a; #[cfg(not(feature = "atomic"))] type Nucleus = Cell<Self>; } )* }; } store![ u8, atomic::AtomicU8; u16, atomic::AtomicU16; u32, atomic::AtomicU32; ]; #[cfg(target_pointer_width = "64")] store![u64, atomic::AtomicU64]; /// Type alias to the CPU word element, `u32`. #[cfg(target_pointer_width = "32")] pub type Word = u32; /// Type alias to the CPU word element, `u64`. #[cfg(target_pointer_width = "64")] pub type Word = u64; /** Common interface for atomic and cellular shared-mutability wrappers. `&/mut BitSlice` contexts must use the `BitStore::Nucleus` type for all reference production, and must route through this trait in order to access the underlying memory. In multi-threaded contexts, this trait enforces that all access is synchronized through atomic accesses; in single-threaded contexts, this trait solely permits modification of an aliased element. It is implemented on the atomic type wrappers when the `atomic` feature is set, and implemented on the `Cell` type wrapper when the feature is missing. Coupled with the `Send` implementation on `BitSlice` **/ pub trait BitAccess<T>: Sized where T: BitStore { /// Sets a specific bit in an element low. /// /// `BitAccess::set` calls this when its `value` is `false`; it /// unconditionally writes a `0` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn clear_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Sets a specific bit in an element high. /// /// `BitAccess::set` calls this when its `value` is `true`; it /// unconditionally writes a `1` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn set_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Inverts a specific bit in an element. /// /// This is the driver of `BitStore::invert_bit`, and has the same API and /// documented behavior. fn invert_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Gets a specific bit in an element. /// /// # Parameters /// /// - `&self`: A shared reference to a maybe-mutable element. This uses the /// trait `load` function to ensure correct reads from memory. /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<T>) -> bool where C: Cursor { self.load() & *C::mask(place)!= T::from(0) } /// Sets a specific bit in an element to a given value. /// /// This is the driver of `BitStore::set`, and has the same API and /// documented behavior. #[inline(always)] fn set<C>(&self, place: BitIdx<T>, value: bool) where C: Cursor { if value { self.set_bit::<C>(place); } else { self.clear_bit::<C>(place); } } /// Removes the shared-mutability wrapper, producing a read reference to the /// inner type. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// A read reference to the wrapped type. /// /// # Safety /// /// As this removes mutability, it is strictly safe. #[inline(always)] fn base(&self) -> &T { unsafe { &*(self as *const Self as *const T) } } /// Transforms a reference of `&[T::Nucleus]` into `&mut [T]`. /// /// # Safety /// /// This function is undefined when the `this` slice referent has aliasing /// pointers. It must only ever be called when the slice referent is /// guaranteed to have no aliases, but mutability has been removed from the /// type system at an earlier point in the call stack. /// /// # Parameters /// /// - `this`: A slice reference to some shared-mutability reference type. /// /// # Returns /// /// A mutable reference to the wrapped interior type of the `this` referent. #[inline(always)] unsafe fn base_slice_mut(this: &[Self]) -> &mut [T] { &mut *(this as *const [Self] as *const [T] as *mut [T]) } /// Performs a synchronized load on an unsynchronized reference. /// /// Atomic implementors must ensure that the load is well synchronized, and /// cell implementors can just read. Each implementor must be strictly gated /// on the `atomic` feature flag. fn load(&self) -> T; } /* FIXME(myrrlyn): When the `radium` crate publishes generic traits, erase the implementations currently in use and enable the generic implementation below: impl<T, R> BitAccess<T> for R where T: BitStore, R: RadiumBits<T> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } } */ #[cfg(feature = "atomic")] fn _atom() { impl BitAccess<u8> for atomic::AtomicU8 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u8 { self.load(Relaxed) } } impl BitAccess<u16> for atomic::AtomicU16 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor {
#[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u16 { self.load(Relaxed) } } impl BitAccess<u32> for atomic::AtomicU32 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u32 { self.load(Relaxed) } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for atomic::AtomicU64 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u64 { self.load(Relaxed) } } } #[cfg(not(feature = "atomic"))] fn _cell() { impl BitAccess<u8> for Cell<u8> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u8 { self.get() } } impl BitAccess<u16> for Cell<u16> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u16 { self.get() } } impl BitAccess<u32> for Cell<u32> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u32 { self.get() } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for Cell<u64> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u64 { self.get() } } }
self.fetch_and(!*C::mask(bit), Relaxed); }
identifier_body
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concrete bits in fundamental elements. They are implementation details, and are not exported in the prelude. !*/ use crate::{ cursor::Cursor, indices::BitIdx, }; use core::{ cmp::Eq, fmt::{ Binary, Debug, Display, LowerHex, UpperHex, }, mem::size_of, ops::{ BitAnd, BitAndAssign, BitOrAssign, Not, Shl, ShlAssign, Shr, ShrAssign, }, }; #[cfg(feature = "atomic")] use core::sync::atomic::{ self, Ordering::Relaxed, }; #[cfg(not(feature = "atomic"))] use core::cell::Cell; /** Generalizes over the fundamental types for use in `bitvec` data structures. This trait must only be implemented on unsigned integer primitives with full alignment. It cannot be implemented on `u128` on any architecture, or on `u64` on 32-bit systems. The `Sealed` supertrait ensures that this can only be implemented locally, and will never be implemented by downstream crates on new types. **/ pub trait BitStore: // Forbid external implementation Sealed + Binary // Element-wise binary manipulation + BitAnd<Self, Output=Self> + BitAndAssign<Self> + BitOrAssign<Self> // Permit indexing into a generic array + Copy + Debug + Default + Display // Permit testing a value against 1 in `get()`. + Eq // Rust treats numeric literals in code as vaguely typed and does not make // them concrete until long after trait expansion, so this enables building // a concrete Self value from a numeric literal. + From<u8> // Permit extending into a `u64`. + Into<u64> + LowerHex + Not<Output=Self> + Send + Shl<u8, Output=Self> + ShlAssign<u8> + Shr<u8, Output=Self> + ShrAssign<u8> // Allow direct access to a concrete implementor type. + Sized + Sync + UpperHex { /// The width, in bits, of this type. const BITS: u8 = size_of::<Self>() as u8 * 8; /// The number of bits required to index a bit inside the type. This is /// always log<sub>2</sub> of the type’s bit width. const INDX: u8 = Self::BITS.trailing_zeros() as u8; /// The bitmask to turn an arbitrary number into a bit index. Bit indices /// are always stored in the lowest bits of an index value. const MASK: u8 = Self::BITS - 1; /// Name of the implementing type. This is only necessary until the compiler /// stabilizes `type_name()`. const TYPENAME: &'static str; /// Shared-mutability wrapper type used to safely mutate aliased data. /// /// Within `&/mut BitSlice` contexts, the `Nucleus` type **must** be used to /// ensure correctly-synchronized access to memory elements that may have /// aliased mutable access. When a codepath knows that it has full ownership /// of a memory element of `Self`, and no other codepath may observe, much /// less modify, it, then that codepath may skip the `Nucleus` type and use /// plain accessors. type Nucleus: BitAccess<Self>; /// Sets a specific bit in an element to a given value. /// /// # Safety /// /// This method cannot be called from within a `&mut BitSlice` context; it /// may only be called by construction of an `&mut Self` reference from a /// `Self` element directly. /// /// # Parameters /// /// - `&mut self` /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be set according to `value`. /// - `value`: A Boolean value, which sets the bit on `true` and clears it /// on `false`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. #[inline(always)] fn set<C>(&mut self, place: BitIdx<Self>, value: bool) where C: Cursor { let mask = *C::mask(place); if value { *self |= mask; } else { *self &=!mask; } } /// Gets a specific bit in an element. /// /// # Safety /// /// This method cannot be called from within a `&BitSlice` context; it may /// only be called by construction of an `&Self` reference from a `Self` /// element directly. /// /// # Parameters /// /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<Self>) -> bool where C: Cursor { *self & *C::mask(place)!= Self::from(0) } /// Counts how many bits in `self` are set to `1`. /// /// This zero-extends `self` to `u64`, and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `1`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_ones(&0u8), 0); /// assert_eq!(BitStore::count_ones(&128u8), 1); /// assert_eq!(BitStore::count_ones(&192u8), 2); /// assert_eq!(BitStore::count_ones(&224u8), 3); /// assert_eq!(BitStore::count_ones(&240u8), 4); /// assert_eq!(BitStore::count_ones(&248u8), 5); /// assert_eq!(BitStore::count_ones(&252u8), 6); /// assert_eq!(BitStore::count_ones(&254u8), 7); /// assert_eq!(BitStore::count_ones(&255u8), 8); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_ones(&self) -> usize { u64::count_ones((*self).into()) as usize } /// Counts how many bits in `self` are set to `0`. /// /// This inverts `self`, so all `0` bits are `1` and all `1` bits are `0`, /// then zero-extends `self` to `u64` and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `0`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_zeros(&0u8), 8); /// assert_eq!(BitStore::count_zeros(&1u8), 7); /// assert_eq!(BitStore::count_zeros(&3u8), 6); /// assert_eq!(BitStore::count_zeros(&7u8), 5); /// assert_eq!(BitStore::count_zeros(&15u8), 4); /// assert_eq!(BitStore::count_zeros(&31u8), 3); /// assert_eq!(BitStore::count_zeros(&63u8), 2); /// assert_eq!(BitStore::count_zeros(&127u8), 1); /// assert_eq!(BitStore::count_zeros(&255u8), 0); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_zeros(&self) -> usize { // invert (0 becomes 1, 1 becomes 0), zero-extend, count ones u64::count_ones((!*self).into()) as usize } /// Extends a single bit to fill the entire element. /// /// # Parameters /// /// - `bit`: The bit to extend. /// /// # Returns /// /// An element with all bits set to the input. #[inline] fn bits(bit: bool) -> Self { if bit { !Self::from(0) } else { Self::from(0) } } } /** Marker trait to seal `BitStore` against downstream implementation. This trait is public in the module, so that other modules in the crate can use it, but so long as it is not exported by the crate root and this module is private, this trait effectively forbids downstream implementation of the `BitStore` trait. **/ #[doc(hidden)] pub trait Sealed {} macro_rules! store { ( $( $t:ty, $a:ty $( ; )? );* ) => { $( impl Sealed for $t {} impl BitStore for $t { const TYPENAME: &'static str = stringify!($t); #[cfg(feature = "atomic")] type Nucleus = $a; #[cfg(not(feature = "atomic"))] type Nucleus = Cell<Self>; } )* }; } store![ u8, atomic::AtomicU8; u16, atomic::AtomicU16; u32, atomic::AtomicU32; ]; #[cfg(target_pointer_width = "64")] store![u64, atomic::AtomicU64]; /// Type alias to the CPU word element, `u32`. #[cfg(target_pointer_width = "32")] pub type Word = u32; /// Type alias to the CPU word element, `u64`. #[cfg(target_pointer_width = "64")] pub type Word = u64; /** Common interface for atomic and cellular shared-mutability wrappers. `&/mut BitSlice` contexts must use the `BitStore::Nucleus` type for all reference production, and must route through this trait in order to access the underlying memory. In multi-threaded contexts, this trait enforces that all access is synchronized through atomic accesses; in single-threaded contexts, this trait solely permits modification of an aliased element. It is implemented on the atomic type wrappers when the `atomic` feature is set, and implemented on the `Cell` type wrapper when the feature is missing. Coupled with the `Send` implementation on `BitSlice` **/ pub trait BitAccess<T>: Sized where T: BitStore { /// Sets a specific bit in an element low. /// /// `BitAccess::set` calls this when its `value` is `false`; it /// unconditionally writes a `0` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn clear_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Sets a specific bit in an element high. /// /// `BitAccess::set` calls this when its `value` is `true`; it /// unconditionally writes a `1` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn set_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Inverts a specific bit in an element. /// /// This is the driver of `BitStore::invert_bit`, and has the same API and /// documented behavior. fn invert_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Gets a specific bit in an element. /// /// # Parameters /// /// - `&self`: A shared reference to a maybe-mutable element. This uses the /// trait `load` function to ensure correct reads from memory. /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<T>) -> bool where C: Cursor { self.load() & *C::mask(place)!= T::from(0) } /// Sets a specific bit in an element to a given value. /// /// This is the driver of `BitStore::set`, and has the same API and /// documented behavior. #[inline(always)] fn set<C>(&self, place: BitIdx<T>, value: bool) where C: Cursor { if value { self.set_bit::<C>(place); } else { self.clear_bit::<C>(place); } } /// Removes the shared-mutability wrapper, producing a read reference to the /// inner type. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// A read reference to the wrapped type. /// /// # Safety /// /// As this removes mutability, it is strictly safe. #[inline(always)] fn base(&self) -> &T { unsafe { &*(self as *const Self as *const T) } } /// Transforms a reference of `&[T::Nucleus]` into `&mut [T]`. /// /// # Safety /// /// This function is undefined when the `this` slice referent has aliasing /// pointers. It must only ever be called when the slice referent is /// guaranteed to have no aliases, but mutability has been removed from the /// type system at an earlier point in the call stack. /// /// # Parameters /// /// - `this`: A slice reference to some shared-mutability reference type. /// /// # Returns /// /// A mutable reference to the wrapped interior type of the `this` referent. #[inline(always)] unsafe fn base_slice_mut(this: &[Self]) -> &mut [T] { &mut *(this as *const [Self] as *const [T] as *mut [T]) } /// Performs a synchronized load on an unsynchronized reference. /// /// Atomic implementors must ensure that the load is well synchronized, and /// cell implementors can just read. Each implementor must be strictly gated /// on the `atomic` feature flag. fn load(&self) -> T; } /* FIXME(myrrlyn): When the `radium` crate publishes generic traits, erase the implementations currently in use and enable the generic implementation below: impl<T, R> BitAccess<T> for R where T: BitStore, R: RadiumBits<T> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } } */ #[cfg(feature = "atomic")] fn _atom() { impl BitAccess<u8> for atomic::AtomicU8 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u8 { self.load(Relaxed) } } impl BitAccess<u16> for atomic::AtomicU16 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u16 { self.load(Relaxed) } } impl BitAccess<u32> for atomic::AtomicU32 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u32 { self.load(Relaxed) } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for atomic::AtomicU64 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn lo
self) -> u64 { self.load(Relaxed) } } } #[cfg(not(feature = "atomic"))] fn _cell() { impl BitAccess<u8> for Cell<u8> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u8 { self.get() } } impl BitAccess<u16> for Cell<u16> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u16 { self.get() } } impl BitAccess<u32> for Cell<u32> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u32 { self.get() } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for Cell<u64> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u64 { self.get() } } }
ad(&
identifier_name
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concrete bits in fundamental elements. They are implementation details, and are not exported in the prelude. !*/ use crate::{ cursor::Cursor, indices::BitIdx, }; use core::{ cmp::Eq, fmt::{ Binary, Debug, Display, LowerHex, UpperHex, }, mem::size_of, ops::{ BitAnd, BitAndAssign, BitOrAssign, Not, Shl, ShlAssign, Shr, ShrAssign, }, }; #[cfg(feature = "atomic")] use core::sync::atomic::{ self, Ordering::Relaxed, }; #[cfg(not(feature = "atomic"))] use core::cell::Cell; /** Generalizes over the fundamental types for use in `bitvec` data structures. This trait must only be implemented on unsigned integer primitives with full alignment. It cannot be implemented on `u128` on any architecture, or on `u64` on 32-bit systems. The `Sealed` supertrait ensures that this can only be implemented locally, and will never be implemented by downstream crates on new types. **/ pub trait BitStore: // Forbid external implementation Sealed + Binary // Element-wise binary manipulation + BitAnd<Self, Output=Self> + BitAndAssign<Self> + BitOrAssign<Self> // Permit indexing into a generic array + Copy + Debug + Default + Display // Permit testing a value against 1 in `get()`. + Eq // Rust treats numeric literals in code as vaguely typed and does not make // them concrete until long after trait expansion, so this enables building // a concrete Self value from a numeric literal. + From<u8> // Permit extending into a `u64`. + Into<u64> + LowerHex + Not<Output=Self> + Send + Shl<u8, Output=Self> + ShlAssign<u8> + Shr<u8, Output=Self> + ShrAssign<u8> // Allow direct access to a concrete implementor type. + Sized + Sync + UpperHex { /// The width, in bits, of this type. const BITS: u8 = size_of::<Self>() as u8 * 8; /// The number of bits required to index a bit inside the type. This is /// always log<sub>2</sub> of the type’s bit width. const INDX: u8 = Self::BITS.trailing_zeros() as u8; /// The bitmask to turn an arbitrary number into a bit index. Bit indices /// are always stored in the lowest bits of an index value. const MASK: u8 = Self::BITS - 1; /// Name of the implementing type. This is only necessary until the compiler /// stabilizes `type_name()`. const TYPENAME: &'static str; /// Shared-mutability wrapper type used to safely mutate aliased data. /// /// Within `&/mut BitSlice` contexts, the `Nucleus` type **must** be used to /// ensure correctly-synchronized access to memory elements that may have /// aliased mutable access. When a codepath knows that it has full ownership /// of a memory element of `Self`, and no other codepath may observe, much /// less modify, it, then that codepath may skip the `Nucleus` type and use /// plain accessors. type Nucleus: BitAccess<Self>; /// Sets a specific bit in an element to a given value. /// /// # Safety /// /// This method cannot be called from within a `&mut BitSlice` context; it /// may only be called by construction of an `&mut Self` reference from a /// `Self` element directly. /// /// # Parameters /// /// - `&mut self` /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be set according to `value`. /// - `value`: A Boolean value, which sets the bit on `true` and clears it /// on `false`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. #[inline(always)] fn set<C>(&mut self, place: BitIdx<Self>, value: bool) where C: Cursor { let mask = *C::mask(place); if value {
else { *self &=!mask; } } /// Gets a specific bit in an element. /// /// # Safety /// /// This method cannot be called from within a `&BitSlice` context; it may /// only be called by construction of an `&Self` reference from a `Self` /// element directly. /// /// # Parameters /// /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<Self>) -> bool where C: Cursor { *self & *C::mask(place)!= Self::from(0) } /// Counts how many bits in `self` are set to `1`. /// /// This zero-extends `self` to `u64`, and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `1`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_ones(&0u8), 0); /// assert_eq!(BitStore::count_ones(&128u8), 1); /// assert_eq!(BitStore::count_ones(&192u8), 2); /// assert_eq!(BitStore::count_ones(&224u8), 3); /// assert_eq!(BitStore::count_ones(&240u8), 4); /// assert_eq!(BitStore::count_ones(&248u8), 5); /// assert_eq!(BitStore::count_ones(&252u8), 6); /// assert_eq!(BitStore::count_ones(&254u8), 7); /// assert_eq!(BitStore::count_ones(&255u8), 8); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_ones(&self) -> usize { u64::count_ones((*self).into()) as usize } /// Counts how many bits in `self` are set to `0`. /// /// This inverts `self`, so all `0` bits are `1` and all `1` bits are `0`, /// then zero-extends `self` to `u64` and uses the [`u64::count_ones`] /// inherent method. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// The number of bits in `self` set to `0`. This is a `usize` instead of a /// `u32` in order to ease arithmetic throughout the crate. /// /// # Examples /// /// ```rust /// use bitvec::prelude::BitStore; /// assert_eq!(BitStore::count_zeros(&0u8), 8); /// assert_eq!(BitStore::count_zeros(&1u8), 7); /// assert_eq!(BitStore::count_zeros(&3u8), 6); /// assert_eq!(BitStore::count_zeros(&7u8), 5); /// assert_eq!(BitStore::count_zeros(&15u8), 4); /// assert_eq!(BitStore::count_zeros(&31u8), 3); /// assert_eq!(BitStore::count_zeros(&63u8), 2); /// assert_eq!(BitStore::count_zeros(&127u8), 1); /// assert_eq!(BitStore::count_zeros(&255u8), 0); /// ``` /// /// [`u64::count_ones`]: https://doc.rust-lang.org/stable/std/primitive.u64.html#method.count_ones #[inline(always)] fn count_zeros(&self) -> usize { // invert (0 becomes 1, 1 becomes 0), zero-extend, count ones u64::count_ones((!*self).into()) as usize } /// Extends a single bit to fill the entire element. /// /// # Parameters /// /// - `bit`: The bit to extend. /// /// # Returns /// /// An element with all bits set to the input. #[inline] fn bits(bit: bool) -> Self { if bit { !Self::from(0) } else { Self::from(0) } } } /** Marker trait to seal `BitStore` against downstream implementation. This trait is public in the module, so that other modules in the crate can use it, but so long as it is not exported by the crate root and this module is private, this trait effectively forbids downstream implementation of the `BitStore` trait. **/ #[doc(hidden)] pub trait Sealed {} macro_rules! store { ( $( $t:ty, $a:ty $( ; )? );* ) => { $( impl Sealed for $t {} impl BitStore for $t { const TYPENAME: &'static str = stringify!($t); #[cfg(feature = "atomic")] type Nucleus = $a; #[cfg(not(feature = "atomic"))] type Nucleus = Cell<Self>; } )* }; } store![ u8, atomic::AtomicU8; u16, atomic::AtomicU16; u32, atomic::AtomicU32; ]; #[cfg(target_pointer_width = "64")] store![u64, atomic::AtomicU64]; /// Type alias to the CPU word element, `u32`. #[cfg(target_pointer_width = "32")] pub type Word = u32; /// Type alias to the CPU word element, `u64`. #[cfg(target_pointer_width = "64")] pub type Word = u64; /** Common interface for atomic and cellular shared-mutability wrappers. `&/mut BitSlice` contexts must use the `BitStore::Nucleus` type for all reference production, and must route through this trait in order to access the underlying memory. In multi-threaded contexts, this trait enforces that all access is synchronized through atomic accesses; in single-threaded contexts, this trait solely permits modification of an aliased element. It is implemented on the atomic type wrappers when the `atomic` feature is set, and implemented on the `Cell` type wrapper when the feature is missing. Coupled with the `Send` implementation on `BitSlice` **/ pub trait BitAccess<T>: Sized where T: BitStore { /// Sets a specific bit in an element low. /// /// `BitAccess::set` calls this when its `value` is `false`; it /// unconditionally writes a `0` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn clear_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Sets a specific bit in an element high. /// /// `BitAccess::set` calls this when its `value` is `true`; it /// unconditionally writes a `1` bit into the electrical position that /// `place` controls according to the `Cursor` parameter `C`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation which translates `place` into a usable /// bit-mask. /// /// # Parameters /// /// - `&self` /// - `place`: The semantic bit index in the `self` element. fn set_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Inverts a specific bit in an element. /// /// This is the driver of `BitStore::invert_bit`, and has the same API and /// documented behavior. fn invert_bit<C>(&self, place: BitIdx<T>) where C: Cursor; /// Gets a specific bit in an element. /// /// # Parameters /// /// - `&self`: A shared reference to a maybe-mutable element. This uses the /// trait `load` function to ensure correct reads from memory. /// - `place`: A bit index in the element, from `0` to `Self::MASK`. The bit /// under this index will be retrieved as a `bool`. /// /// # Returns /// /// The value of the bit under `place`, as a `bool`. /// /// # Type Parameters /// /// - `C`: A `Cursor` implementation to translate the index into a position. fn get<C>(&self, place: BitIdx<T>) -> bool where C: Cursor { self.load() & *C::mask(place)!= T::from(0) } /// Sets a specific bit in an element to a given value. /// /// This is the driver of `BitStore::set`, and has the same API and /// documented behavior. #[inline(always)] fn set<C>(&self, place: BitIdx<T>, value: bool) where C: Cursor { if value { self.set_bit::<C>(place); } else { self.clear_bit::<C>(place); } } /// Removes the shared-mutability wrapper, producing a read reference to the /// inner type. /// /// # Parameters /// /// - `&self` /// /// # Returns /// /// A read reference to the wrapped type. /// /// # Safety /// /// As this removes mutability, it is strictly safe. #[inline(always)] fn base(&self) -> &T { unsafe { &*(self as *const Self as *const T) } } /// Transforms a reference of `&[T::Nucleus]` into `&mut [T]`. /// /// # Safety /// /// This function is undefined when the `this` slice referent has aliasing /// pointers. It must only ever be called when the slice referent is /// guaranteed to have no aliases, but mutability has been removed from the /// type system at an earlier point in the call stack. /// /// # Parameters /// /// - `this`: A slice reference to some shared-mutability reference type. /// /// # Returns /// /// A mutable reference to the wrapped interior type of the `this` referent. #[inline(always)] unsafe fn base_slice_mut(this: &[Self]) -> &mut [T] { &mut *(this as *const [Self] as *const [T] as *mut [T]) } /// Performs a synchronized load on an unsynchronized reference. /// /// Atomic implementors must ensure that the load is well synchronized, and /// cell implementors can just read. Each implementor must be strictly gated /// on the `atomic` feature flag. fn load(&self) -> T; } /* FIXME(myrrlyn): When the `radium` crate publishes generic traits, erase the implementations currently in use and enable the generic implementation below: impl<T, R> BitAccess<T> for R where T: BitStore, R: RadiumBits<T> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<T>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } } */ #[cfg(feature = "atomic")] fn _atom() { impl BitAccess<u8> for atomic::AtomicU8 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u8 { self.load(Relaxed) } } impl BitAccess<u16> for atomic::AtomicU16 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u16 { self.load(Relaxed) } } impl BitAccess<u32> for atomic::AtomicU32 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u32 { self.load(Relaxed) } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for atomic::AtomicU64 { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_and(!*C::mask(bit), Relaxed); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u64 { self.load(Relaxed) } } } #[cfg(not(feature = "atomic"))] fn _cell() { impl BitAccess<u8> for Cell<u8> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u8 { self.get() } } impl BitAccess<u16> for Cell<u16> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u16 { self.get() } } impl BitAccess<u32> for Cell<u32> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u32>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u32 { self.get() } } #[cfg(target_pointer_width = "64")] impl BitAccess<u64> for Cell<u64> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() | *C::mask(bit)); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u64>) where C: Cursor { self.set(self.get() ^ *C::mask(bit)); } #[inline(always)] fn load(&self) -> u64 { self.get() } } }
*self |= mask; }
conditional_block
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::fmt; use std::hash::{Hash, Hasher}; use std::io; use std::io::Write; use std::net::{IpAddr, Shutdown, SocketAddr, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use std::thread; use std::time::{Duration, UNIX_EPOCH}; /// Time to wait for the initial TCP connection const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); /// Time to wait for handshake messages before failing to connect const HANDSHAKE_READ_TIMEOUT: Duration = Duration::from_secs(3); /// Event emitted when a connection is established with the peer #[derive(Clone, Debug)] pub struct PeerConnected { pub peer: Arc<Peer>, } /// Event emitted when the connection with the peer is terminated #[derive(Clone, Debug)] pub struct PeerDisconnected { pub peer: Arc<Peer>, } /// Event emitted when the peer receives a network message #[derive(Clone, Debug)] pub struct PeerMessage { pub peer: Arc<Peer>, pub message: Message, } /// Filters peers based on their version information before connecting pub trait PeerFilter: Send + Sync { fn connectable(&self, _: &Version) -> bool; } /// Filters out all peers except for Bitcoin SV full nodes #[derive(Clone, Default, Debug)] pub struct SVPeerFilter { pub min_start_height: i32, } impl SVPeerFilter { /// Creates a new SV filter that requires a minimum starting chain height pub fn new(min_start_height: i32) -> Arc<SVPeerFilter> { Arc::new(SVPeerFilter { min_start_height }) } } impl PeerFilter for SVPeerFilter { fn connectable(&self, version: &Version) -> bool { version.user_agent.contains("Bitcoin SV") && version.start_height >= self.min_start_height && version.services & (NODE_BITCOIN_CASH | NODE_NETWORK)!= 0 } } /// Node on the network to send and receive messages /// /// It will setup a connection, respond to pings, and store basic properties about the connection, /// but any real logic to process messages will be handled outside. Network messages received will /// be published to an observable on the peer's receiver thread. Messages may be sent via send() /// from any thread. Once shutdown, the Peer may no longer be used. pub struct Peer { /// Unique id for this connection pub id: ProcessUniqueId, /// IP address pub ip: IpAddr, /// Port pub port: u16, /// Network pub network: Network, pub(crate) connected_event: Single<PeerConnected>, pub(crate) disconnected_event: Single<PeerDisconnected>, pub(crate) messages: Subject<PeerMessage>, tcp_writer: Mutex<Option<TcpStream>>, connected: AtomicBool, time_delta: Mutex<i64>, minfee: Mutex<u64>, sendheaders: AtomicBool, sendcmpct: AtomicBool, version: Mutex<Option<Version>>, /// Weak reference to self so we can pass ourselves in emitted events. This is a /// bit ugly, but we hopefully can able to remove it once arbitrary self types goes in. weak_self: Mutex<Option<Weak<Peer>>>, } impl Peer { /// Creates a new peer and begins connecting pub fn connect( ip: IpAddr, port: u16, network: Network, version: Version, filter: Arc<dyn PeerFilter>, ) -> Arc<Peer> { let peer = Arc::new(Peer { id: ProcessUniqueId::new(), ip, port, network, connected_event: Single::new(), disconnected_event: Single::new(), messages: Subject::new(), tcp_writer: Mutex::new(None), connected: AtomicBool::new(false), time_delta: Mutex::new(0), minfee: Mutex::new(0), sendheaders: AtomicBool::new(false), sendcmpct: AtomicBool::new(false), version: Mutex::new(None), weak_self: Mutex::new(None), }); *peer.weak_self.lock().unwrap() = Some(Arc::downgrade(&peer)); Peer::connect_internal(&peer, version, filter); peer } /// Sends a message to the peer pub fn send(&self, message: &Message) -> Result<()> { if!self.connected.load(Ordering::Relaxed) { return Err(Error::IllegalState("Not connected".to_string())); } let mut io_error: Option<io::Error> = None; { let mut tcp_writer = self.tcp_writer.lock().unwrap(); let mut tcp_writer = match tcp_writer.as_mut() { Some(tcp_writer) => tcp_writer, None => return Err(Error::IllegalState("No tcp stream".to_string())), }; debug!("{:?} Write {:#?}", self, message); if let Err(e) = message.write(&mut tcp_writer, self.network.magic()) { io_error = Some(e); } else { if let Err(e) = tcp_writer.flush() { io_error = Some(e); } } } match io_error { Some(e) => { self.disconnect(); Err(Error::IOError(e)) } None => Ok(()), } } /// Disconects and disables the peer pub fn disconnect(&self) { self.connected.swap(false, Ordering::Relaxed); info!("{:?} Disconnecting", self); let mut tcp_stream = self.tcp_writer.lock().unwrap(); if let Some(tcp_stream) = tcp_stream.as_mut() { if let Err(e) = tcp_stream.shutdown(Shutdown::Both) { warn!("{:?} Problem shutting down tcp stream: {:?}", self, e); } } if let Some(peer) = self.strong_self() { self.disconnected_event.next(&PeerDisconnected { peer }); } } /// Returns a Single that emits a message when connected pub fn connected_event(&self) -> &impl Observable<PeerConnected> { &self.connected_event } /// Returns a Single that emits a message when connected pub fn disconnected_event(&self) -> &impl Observable<PeerDisconnected> { &self.disconnected_event } /// Returns an Observable that emits network messages pub fn messages(&self) -> &impl Observable<PeerMessage> { &self.messages } /// Returns whether the peer is connected pub fn connected(&self) -> bool { self.connected.load(Ordering::Relaxed) } /// Returns the time difference in seconds between our time and theirs, which is valid after connecting pub fn time_delta(&self) -> i64 { *self.time_delta.lock().unwrap() } /// Returns the minimum fee this peer accepts in sats/1000bytes pub fn minfee(&self) -> u64 { *self.minfee.lock().unwrap() } /// Returns whether this peer may announce new blocks with headers instead of inv pub fn sendheaders(&self) -> bool { self.sendheaders.load(Ordering::Relaxed) } /// Returns whether compact blocks are supported pub fn sendcmpct(&self) -> bool { self.sendcmpct.load(Ordering::Relaxed) } /// Gets the version message received during the handshake pub fn version(&self) -> Result<Version> { match &*self.version.lock().unwrap() { Some(ref version) => Ok(version.clone()), None => Err(Error::IllegalState("Not connected".to_string())), } } fn connect_internal(peer: &Arc<Peer>, version: Version, filter: Arc<dyn PeerFilter>) { info!("{:?} Connecting to {:?}:{}", peer, peer.ip, peer.port); let tpeer = peer.clone(); thread::spawn(move || { let mut tcp_reader = match tpeer.handshake(version, filter) { Ok(tcp_stream) => tcp_stream, Err(e) => { error!("Failed to complete handshake: {:?}", e); tpeer.disconnect(); return; } }; // The peer is considered connected and may be written to now info!("{:?} Connected to {:?}:{}", tpeer, tpeer.ip, tpeer.port); tpeer.connected.store(true, Ordering::Relaxed); tpeer.connected_event.next(&PeerConnected { peer: tpeer.clone(), }); let mut partial: Option<MessageHeader> = None; let magic = tpeer.network.magic(); // Message reads over TCP must be all-or-nothing. let mut tcp_reader = AtomicReader::new(&mut tcp_reader); loop { let message = match &partial { Some(header) => Message::read_partial(&mut tcp_reader, header), None => Message::read(&mut tcp_reader, magic), }; // Always check the connected flag right after the blocking read so we exit right away, // and also so that we don't mistake errors with the stream shutting down if!tpeer.connected.load(Ordering::Relaxed) { return; } match message { Ok(message) => { if let Message::Partial(header) = message { partial = Some(header); } else { debug!("{:?} Read {:#?}", tpeer, message); partial = None; if let Err(e) = tpeer.handle_message(&message) { error!("{:?} Error handling message: {:?}", tpeer, e); tpeer.disconnect(); return; } tpeer.messages.next(&PeerMessage { peer: tpeer.clone(), message, }); } } Err(e) => { // If timeout, try again later. Otherwise, shutdown if let Error::IOError(ref e) = e { // Depending on platform, either TimedOut or WouldBlock may be returned to indicate a non-error timeout if e.kind() == io::ErrorKind::TimedOut || e.kind() == io::ErrorKind::WouldBlock { continue; } } error!("{:?} Error reading message {:?}", tpeer, e); tpeer.disconnect(); return; } } } }); } fn handshake(self: &Peer, version: Version, filter: Arc<dyn PeerFilter>) -> Result<TcpStream>
}; if!filter.connectable(&their_version) { return Err(Error::IllegalState("Peer filtered out".to_string())); } let now = secs_since(UNIX_EPOCH) as i64; *self.time_delta.lock().unwrap() = now - their_version.timestamp; *self.version.lock().unwrap() = Some(their_version); // Read their verack let their_verack = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, their_verack); match their_verack { Message::Verack => {} _ => return Err(Error::BadData("Unexpected command".to_string())), }; // Write our verack debug!("{:?} Write {:#?}", self, Message::Verack); Message::Verack.write(&mut tcp_stream, magic)?; // Write a ping message because this seems to help with connection weirdness // https://bitcoin.stackexchange.com/questions/49487/getaddr-not-returning-connected-node-addresses let ping = Message::Ping(Ping { nonce: secs_since(UNIX_EPOCH) as u64, }); debug!("{:?} Write {:#?}", self, ping); ping.write(&mut tcp_stream, magic)?; // After handshake, clone TCP stream and save the write version *self.tcp_writer.lock().unwrap() = Some(tcp_stream.try_clone()?); // We don't need a timeout for the read. The peer will shutdown just fine. // The read timeout doesn't work reliably across platforms anyway. tcp_stream.set_read_timeout(None)?; Ok(tcp_stream) } fn handle_message(&self, message: &Message) -> Result<()> { // A subset of messages are handled directly by the peer match message { Message::FeeFilter(feefilter) => { *self.minfee.lock().unwrap() = feefilter.minfee; } Message::Ping(ping) => { let pong = Message::Pong(ping.clone()); self.send(&pong)?; } Message::SendHeaders => { self.sendheaders.store(true, Ordering::Relaxed); } Message::SendCmpct(sendcmpct) => { let enable = sendcmpct.use_cmpctblock(); self.sendcmpct.store(enable, Ordering::Relaxed); } _ => {} } Ok(()) } fn strong_self(&self) -> Option<Arc<Peer>> { match &*self.weak_self.lock().unwrap() { Some(ref weak_peer) => weak_peer.upgrade(), None => None, } } } impl PartialEq for Peer { fn eq(&self, other: &Peer) -> bool { self.id == other.id } } impl Eq for Peer {} impl Hash for Peer { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state) } } impl fmt::Debug for Peer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&format!("[Peer {}]", self.id)) } } impl Drop for Peer { fn drop(&mut self) { self.disconnect(); } }
{ // Connect over TCP let tcp_addr = SocketAddr::new(self.ip, self.port); let mut tcp_stream = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)?; tcp_stream.set_nodelay(true)?; // Disable buffering tcp_stream.set_read_timeout(Some(HANDSHAKE_READ_TIMEOUT))?; tcp_stream.set_nonblocking(false)?; // Write our version let our_version = Message::Version(version); debug!("{:?} Write {:#?}", self, our_version); let magic = self.network.magic(); our_version.write(&mut tcp_stream, magic)?; // Read their version let msg = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, msg); let their_version = match msg { Message::Version(version) => version, _ => return Err(Error::BadData("Unexpected command".to_string())),
identifier_body
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::fmt; use std::hash::{Hash, Hasher}; use std::io; use std::io::Write; use std::net::{IpAddr, Shutdown, SocketAddr, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use std::thread; use std::time::{Duration, UNIX_EPOCH}; /// Time to wait for the initial TCP connection const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); /// Time to wait for handshake messages before failing to connect const HANDSHAKE_READ_TIMEOUT: Duration = Duration::from_secs(3); /// Event emitted when a connection is established with the peer #[derive(Clone, Debug)] pub struct PeerConnected { pub peer: Arc<Peer>, } /// Event emitted when the connection with the peer is terminated #[derive(Clone, Debug)] pub struct PeerDisconnected { pub peer: Arc<Peer>, } /// Event emitted when the peer receives a network message #[derive(Clone, Debug)] pub struct PeerMessage { pub peer: Arc<Peer>, pub message: Message, } /// Filters peers based on their version information before connecting pub trait PeerFilter: Send + Sync { fn connectable(&self, _: &Version) -> bool; } /// Filters out all peers except for Bitcoin SV full nodes #[derive(Clone, Default, Debug)] pub struct SVPeerFilter { pub min_start_height: i32, } impl SVPeerFilter { /// Creates a new SV filter that requires a minimum starting chain height pub fn new(min_start_height: i32) -> Arc<SVPeerFilter> { Arc::new(SVPeerFilter { min_start_height }) } } impl PeerFilter for SVPeerFilter { fn connectable(&self, version: &Version) -> bool { version.user_agent.contains("Bitcoin SV") && version.start_height >= self.min_start_height && version.services & (NODE_BITCOIN_CASH | NODE_NETWORK)!= 0 } } /// Node on the network to send and receive messages /// /// It will setup a connection, respond to pings, and store basic properties about the connection, /// but any real logic to process messages will be handled outside. Network messages received will /// be published to an observable on the peer's receiver thread. Messages may be sent via send() /// from any thread. Once shutdown, the Peer may no longer be used. pub struct Peer { /// Unique id for this connection pub id: ProcessUniqueId, /// IP address pub ip: IpAddr, /// Port pub port: u16, /// Network pub network: Network, pub(crate) connected_event: Single<PeerConnected>, pub(crate) disconnected_event: Single<PeerDisconnected>, pub(crate) messages: Subject<PeerMessage>, tcp_writer: Mutex<Option<TcpStream>>, connected: AtomicBool, time_delta: Mutex<i64>, minfee: Mutex<u64>, sendheaders: AtomicBool, sendcmpct: AtomicBool, version: Mutex<Option<Version>>, /// Weak reference to self so we can pass ourselves in emitted events. This is a /// bit ugly, but we hopefully can able to remove it once arbitrary self types goes in. weak_self: Mutex<Option<Weak<Peer>>>, } impl Peer { /// Creates a new peer and begins connecting pub fn connect( ip: IpAddr, port: u16, network: Network, version: Version, filter: Arc<dyn PeerFilter>, ) -> Arc<Peer> { let peer = Arc::new(Peer { id: ProcessUniqueId::new(), ip, port, network, connected_event: Single::new(), disconnected_event: Single::new(), messages: Subject::new(), tcp_writer: Mutex::new(None), connected: AtomicBool::new(false), time_delta: Mutex::new(0), minfee: Mutex::new(0), sendheaders: AtomicBool::new(false), sendcmpct: AtomicBool::new(false), version: Mutex::new(None), weak_self: Mutex::new(None), }); *peer.weak_self.lock().unwrap() = Some(Arc::downgrade(&peer)); Peer::connect_internal(&peer, version, filter); peer } /// Sends a message to the peer pub fn send(&self, message: &Message) -> Result<()> { if!self.connected.load(Ordering::Relaxed) { return Err(Error::IllegalState("Not connected".to_string())); } let mut io_error: Option<io::Error> = None; { let mut tcp_writer = self.tcp_writer.lock().unwrap(); let mut tcp_writer = match tcp_writer.as_mut() { Some(tcp_writer) => tcp_writer, None => return Err(Error::IllegalState("No tcp stream".to_string())), }; debug!("{:?} Write {:#?}", self, message); if let Err(e) = message.write(&mut tcp_writer, self.network.magic()) { io_error = Some(e); } else { if let Err(e) = tcp_writer.flush() { io_error = Some(e); } } } match io_error { Some(e) => { self.disconnect(); Err(Error::IOError(e)) } None => Ok(()), } } /// Disconects and disables the peer pub fn disconnect(&self) { self.connected.swap(false, Ordering::Relaxed); info!("{:?} Disconnecting", self); let mut tcp_stream = self.tcp_writer.lock().unwrap(); if let Some(tcp_stream) = tcp_stream.as_mut() { if let Err(e) = tcp_stream.shutdown(Shutdown::Both) { warn!("{:?} Problem shutting down tcp stream: {:?}", self, e); } } if let Some(peer) = self.strong_self() { self.disconnected_event.next(&PeerDisconnected { peer }); } } /// Returns a Single that emits a message when connected pub fn connected_event(&self) -> &impl Observable<PeerConnected> { &self.connected_event } /// Returns a Single that emits a message when connected pub fn disconnected_event(&self) -> &impl Observable<PeerDisconnected> { &self.disconnected_event } /// Returns an Observable that emits network messages pub fn messages(&self) -> &impl Observable<PeerMessage> { &self.messages } /// Returns whether the peer is connected pub fn connected(&self) -> bool { self.connected.load(Ordering::Relaxed) } /// Returns the time difference in seconds between our time and theirs, which is valid after connecting pub fn time_delta(&self) -> i64 { *self.time_delta.lock().unwrap() } /// Returns the minimum fee this peer accepts in sats/1000bytes pub fn minfee(&self) -> u64 { *self.minfee.lock().unwrap() } /// Returns whether this peer may announce new blocks with headers instead of inv pub fn sendheaders(&self) -> bool { self.sendheaders.load(Ordering::Relaxed) } /// Returns whether compact blocks are supported pub fn sendcmpct(&self) -> bool { self.sendcmpct.load(Ordering::Relaxed) } /// Gets the version message received during the handshake pub fn version(&self) -> Result<Version> { match &*self.version.lock().unwrap() { Some(ref version) => Ok(version.clone()), None => Err(Error::IllegalState("Not connected".to_string())), } } fn connect_internal(peer: &Arc<Peer>, version: Version, filter: Arc<dyn PeerFilter>) { info!("{:?} Connecting to {:?}:{}", peer, peer.ip, peer.port); let tpeer = peer.clone(); thread::spawn(move || { let mut tcp_reader = match tpeer.handshake(version, filter) { Ok(tcp_stream) => tcp_stream, Err(e) => { error!("Failed to complete handshake: {:?}", e); tpeer.disconnect(); return; } }; // The peer is considered connected and may be written to now info!("{:?} Connected to {:?}:{}", tpeer, tpeer.ip, tpeer.port); tpeer.connected.store(true, Ordering::Relaxed); tpeer.connected_event.next(&PeerConnected { peer: tpeer.clone(), }); let mut partial: Option<MessageHeader> = None; let magic = tpeer.network.magic(); // Message reads over TCP must be all-or-nothing. let mut tcp_reader = AtomicReader::new(&mut tcp_reader); loop { let message = match &partial { Some(header) => Message::read_partial(&mut tcp_reader, header),
// Always check the connected flag right after the blocking read so we exit right away, // and also so that we don't mistake errors with the stream shutting down if!tpeer.connected.load(Ordering::Relaxed) { return; } match message { Ok(message) => { if let Message::Partial(header) = message { partial = Some(header); } else { debug!("{:?} Read {:#?}", tpeer, message); partial = None; if let Err(e) = tpeer.handle_message(&message) { error!("{:?} Error handling message: {:?}", tpeer, e); tpeer.disconnect(); return; } tpeer.messages.next(&PeerMessage { peer: tpeer.clone(), message, }); } } Err(e) => { // If timeout, try again later. Otherwise, shutdown if let Error::IOError(ref e) = e { // Depending on platform, either TimedOut or WouldBlock may be returned to indicate a non-error timeout if e.kind() == io::ErrorKind::TimedOut || e.kind() == io::ErrorKind::WouldBlock { continue; } } error!("{:?} Error reading message {:?}", tpeer, e); tpeer.disconnect(); return; } } } }); } fn handshake(self: &Peer, version: Version, filter: Arc<dyn PeerFilter>) -> Result<TcpStream> { // Connect over TCP let tcp_addr = SocketAddr::new(self.ip, self.port); let mut tcp_stream = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)?; tcp_stream.set_nodelay(true)?; // Disable buffering tcp_stream.set_read_timeout(Some(HANDSHAKE_READ_TIMEOUT))?; tcp_stream.set_nonblocking(false)?; // Write our version let our_version = Message::Version(version); debug!("{:?} Write {:#?}", self, our_version); let magic = self.network.magic(); our_version.write(&mut tcp_stream, magic)?; // Read their version let msg = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, msg); let their_version = match msg { Message::Version(version) => version, _ => return Err(Error::BadData("Unexpected command".to_string())), }; if!filter.connectable(&their_version) { return Err(Error::IllegalState("Peer filtered out".to_string())); } let now = secs_since(UNIX_EPOCH) as i64; *self.time_delta.lock().unwrap() = now - their_version.timestamp; *self.version.lock().unwrap() = Some(their_version); // Read their verack let their_verack = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, their_verack); match their_verack { Message::Verack => {} _ => return Err(Error::BadData("Unexpected command".to_string())), }; // Write our verack debug!("{:?} Write {:#?}", self, Message::Verack); Message::Verack.write(&mut tcp_stream, magic)?; // Write a ping message because this seems to help with connection weirdness // https://bitcoin.stackexchange.com/questions/49487/getaddr-not-returning-connected-node-addresses let ping = Message::Ping(Ping { nonce: secs_since(UNIX_EPOCH) as u64, }); debug!("{:?} Write {:#?}", self, ping); ping.write(&mut tcp_stream, magic)?; // After handshake, clone TCP stream and save the write version *self.tcp_writer.lock().unwrap() = Some(tcp_stream.try_clone()?); // We don't need a timeout for the read. The peer will shutdown just fine. // The read timeout doesn't work reliably across platforms anyway. tcp_stream.set_read_timeout(None)?; Ok(tcp_stream) } fn handle_message(&self, message: &Message) -> Result<()> { // A subset of messages are handled directly by the peer match message { Message::FeeFilter(feefilter) => { *self.minfee.lock().unwrap() = feefilter.minfee; } Message::Ping(ping) => { let pong = Message::Pong(ping.clone()); self.send(&pong)?; } Message::SendHeaders => { self.sendheaders.store(true, Ordering::Relaxed); } Message::SendCmpct(sendcmpct) => { let enable = sendcmpct.use_cmpctblock(); self.sendcmpct.store(enable, Ordering::Relaxed); } _ => {} } Ok(()) } fn strong_self(&self) -> Option<Arc<Peer>> { match &*self.weak_self.lock().unwrap() { Some(ref weak_peer) => weak_peer.upgrade(), None => None, } } } impl PartialEq for Peer { fn eq(&self, other: &Peer) -> bool { self.id == other.id } } impl Eq for Peer {} impl Hash for Peer { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state) } } impl fmt::Debug for Peer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&format!("[Peer {}]", self.id)) } } impl Drop for Peer { fn drop(&mut self) { self.disconnect(); } }
None => Message::read(&mut tcp_reader, magic), };
random_line_split
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::fmt; use std::hash::{Hash, Hasher}; use std::io; use std::io::Write; use std::net::{IpAddr, Shutdown, SocketAddr, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use std::thread; use std::time::{Duration, UNIX_EPOCH}; /// Time to wait for the initial TCP connection const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); /// Time to wait for handshake messages before failing to connect const HANDSHAKE_READ_TIMEOUT: Duration = Duration::from_secs(3); /// Event emitted when a connection is established with the peer #[derive(Clone, Debug)] pub struct PeerConnected { pub peer: Arc<Peer>, } /// Event emitted when the connection with the peer is terminated #[derive(Clone, Debug)] pub struct PeerDisconnected { pub peer: Arc<Peer>, } /// Event emitted when the peer receives a network message #[derive(Clone, Debug)] pub struct PeerMessage { pub peer: Arc<Peer>, pub message: Message, } /// Filters peers based on their version information before connecting pub trait PeerFilter: Send + Sync { fn connectable(&self, _: &Version) -> bool; } /// Filters out all peers except for Bitcoin SV full nodes #[derive(Clone, Default, Debug)] pub struct SVPeerFilter { pub min_start_height: i32, } impl SVPeerFilter { /// Creates a new SV filter that requires a minimum starting chain height pub fn new(min_start_height: i32) -> Arc<SVPeerFilter> { Arc::new(SVPeerFilter { min_start_height }) } } impl PeerFilter for SVPeerFilter { fn connectable(&self, version: &Version) -> bool { version.user_agent.contains("Bitcoin SV") && version.start_height >= self.min_start_height && version.services & (NODE_BITCOIN_CASH | NODE_NETWORK)!= 0 } } /// Node on the network to send and receive messages /// /// It will setup a connection, respond to pings, and store basic properties about the connection, /// but any real logic to process messages will be handled outside. Network messages received will /// be published to an observable on the peer's receiver thread. Messages may be sent via send() /// from any thread. Once shutdown, the Peer may no longer be used. pub struct Peer { /// Unique id for this connection pub id: ProcessUniqueId, /// IP address pub ip: IpAddr, /// Port pub port: u16, /// Network pub network: Network, pub(crate) connected_event: Single<PeerConnected>, pub(crate) disconnected_event: Single<PeerDisconnected>, pub(crate) messages: Subject<PeerMessage>, tcp_writer: Mutex<Option<TcpStream>>, connected: AtomicBool, time_delta: Mutex<i64>, minfee: Mutex<u64>, sendheaders: AtomicBool, sendcmpct: AtomicBool, version: Mutex<Option<Version>>, /// Weak reference to self so we can pass ourselves in emitted events. This is a /// bit ugly, but we hopefully can able to remove it once arbitrary self types goes in. weak_self: Mutex<Option<Weak<Peer>>>, } impl Peer { /// Creates a new peer and begins connecting pub fn connect( ip: IpAddr, port: u16, network: Network, version: Version, filter: Arc<dyn PeerFilter>, ) -> Arc<Peer> { let peer = Arc::new(Peer { id: ProcessUniqueId::new(), ip, port, network, connected_event: Single::new(), disconnected_event: Single::new(), messages: Subject::new(), tcp_writer: Mutex::new(None), connected: AtomicBool::new(false), time_delta: Mutex::new(0), minfee: Mutex::new(0), sendheaders: AtomicBool::new(false), sendcmpct: AtomicBool::new(false), version: Mutex::new(None), weak_self: Mutex::new(None), }); *peer.weak_self.lock().unwrap() = Some(Arc::downgrade(&peer)); Peer::connect_internal(&peer, version, filter); peer } /// Sends a message to the peer pub fn send(&self, message: &Message) -> Result<()> { if!self.connected.load(Ordering::Relaxed) { return Err(Error::IllegalState("Not connected".to_string())); } let mut io_error: Option<io::Error> = None; { let mut tcp_writer = self.tcp_writer.lock().unwrap(); let mut tcp_writer = match tcp_writer.as_mut() { Some(tcp_writer) => tcp_writer, None => return Err(Error::IllegalState("No tcp stream".to_string())), }; debug!("{:?} Write {:#?}", self, message); if let Err(e) = message.write(&mut tcp_writer, self.network.magic()) { io_error = Some(e); } else { if let Err(e) = tcp_writer.flush() { io_error = Some(e); } } } match io_error { Some(e) => { self.disconnect(); Err(Error::IOError(e)) } None => Ok(()), } } /// Disconects and disables the peer pub fn disconnect(&self) { self.connected.swap(false, Ordering::Relaxed); info!("{:?} Disconnecting", self); let mut tcp_stream = self.tcp_writer.lock().unwrap(); if let Some(tcp_stream) = tcp_stream.as_mut() { if let Err(e) = tcp_stream.shutdown(Shutdown::Both) { warn!("{:?} Problem shutting down tcp stream: {:?}", self, e); } } if let Some(peer) = self.strong_self() { self.disconnected_event.next(&PeerDisconnected { peer }); } } /// Returns a Single that emits a message when connected pub fn connected_event(&self) -> &impl Observable<PeerConnected> { &self.connected_event } /// Returns a Single that emits a message when connected pub fn disconnected_event(&self) -> &impl Observable<PeerDisconnected> { &self.disconnected_event } /// Returns an Observable that emits network messages pub fn messages(&self) -> &impl Observable<PeerMessage> { &self.messages } /// Returns whether the peer is connected pub fn connected(&self) -> bool { self.connected.load(Ordering::Relaxed) } /// Returns the time difference in seconds between our time and theirs, which is valid after connecting pub fn time_delta(&self) -> i64 { *self.time_delta.lock().unwrap() } /// Returns the minimum fee this peer accepts in sats/1000bytes pub fn minfee(&self) -> u64 { *self.minfee.lock().unwrap() } /// Returns whether this peer may announce new blocks with headers instead of inv pub fn sendheaders(&self) -> bool { self.sendheaders.load(Ordering::Relaxed) } /// Returns whether compact blocks are supported pub fn sendcmpct(&self) -> bool { self.sendcmpct.load(Ordering::Relaxed) } /// Gets the version message received during the handshake pub fn
(&self) -> Result<Version> { match &*self.version.lock().unwrap() { Some(ref version) => Ok(version.clone()), None => Err(Error::IllegalState("Not connected".to_string())), } } fn connect_internal(peer: &Arc<Peer>, version: Version, filter: Arc<dyn PeerFilter>) { info!("{:?} Connecting to {:?}:{}", peer, peer.ip, peer.port); let tpeer = peer.clone(); thread::spawn(move || { let mut tcp_reader = match tpeer.handshake(version, filter) { Ok(tcp_stream) => tcp_stream, Err(e) => { error!("Failed to complete handshake: {:?}", e); tpeer.disconnect(); return; } }; // The peer is considered connected and may be written to now info!("{:?} Connected to {:?}:{}", tpeer, tpeer.ip, tpeer.port); tpeer.connected.store(true, Ordering::Relaxed); tpeer.connected_event.next(&PeerConnected { peer: tpeer.clone(), }); let mut partial: Option<MessageHeader> = None; let magic = tpeer.network.magic(); // Message reads over TCP must be all-or-nothing. let mut tcp_reader = AtomicReader::new(&mut tcp_reader); loop { let message = match &partial { Some(header) => Message::read_partial(&mut tcp_reader, header), None => Message::read(&mut tcp_reader, magic), }; // Always check the connected flag right after the blocking read so we exit right away, // and also so that we don't mistake errors with the stream shutting down if!tpeer.connected.load(Ordering::Relaxed) { return; } match message { Ok(message) => { if let Message::Partial(header) = message { partial = Some(header); } else { debug!("{:?} Read {:#?}", tpeer, message); partial = None; if let Err(e) = tpeer.handle_message(&message) { error!("{:?} Error handling message: {:?}", tpeer, e); tpeer.disconnect(); return; } tpeer.messages.next(&PeerMessage { peer: tpeer.clone(), message, }); } } Err(e) => { // If timeout, try again later. Otherwise, shutdown if let Error::IOError(ref e) = e { // Depending on platform, either TimedOut or WouldBlock may be returned to indicate a non-error timeout if e.kind() == io::ErrorKind::TimedOut || e.kind() == io::ErrorKind::WouldBlock { continue; } } error!("{:?} Error reading message {:?}", tpeer, e); tpeer.disconnect(); return; } } } }); } fn handshake(self: &Peer, version: Version, filter: Arc<dyn PeerFilter>) -> Result<TcpStream> { // Connect over TCP let tcp_addr = SocketAddr::new(self.ip, self.port); let mut tcp_stream = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)?; tcp_stream.set_nodelay(true)?; // Disable buffering tcp_stream.set_read_timeout(Some(HANDSHAKE_READ_TIMEOUT))?; tcp_stream.set_nonblocking(false)?; // Write our version let our_version = Message::Version(version); debug!("{:?} Write {:#?}", self, our_version); let magic = self.network.magic(); our_version.write(&mut tcp_stream, magic)?; // Read their version let msg = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, msg); let their_version = match msg { Message::Version(version) => version, _ => return Err(Error::BadData("Unexpected command".to_string())), }; if!filter.connectable(&their_version) { return Err(Error::IllegalState("Peer filtered out".to_string())); } let now = secs_since(UNIX_EPOCH) as i64; *self.time_delta.lock().unwrap() = now - their_version.timestamp; *self.version.lock().unwrap() = Some(their_version); // Read their verack let their_verack = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, their_verack); match their_verack { Message::Verack => {} _ => return Err(Error::BadData("Unexpected command".to_string())), }; // Write our verack debug!("{:?} Write {:#?}", self, Message::Verack); Message::Verack.write(&mut tcp_stream, magic)?; // Write a ping message because this seems to help with connection weirdness // https://bitcoin.stackexchange.com/questions/49487/getaddr-not-returning-connected-node-addresses let ping = Message::Ping(Ping { nonce: secs_since(UNIX_EPOCH) as u64, }); debug!("{:?} Write {:#?}", self, ping); ping.write(&mut tcp_stream, magic)?; // After handshake, clone TCP stream and save the write version *self.tcp_writer.lock().unwrap() = Some(tcp_stream.try_clone()?); // We don't need a timeout for the read. The peer will shutdown just fine. // The read timeout doesn't work reliably across platforms anyway. tcp_stream.set_read_timeout(None)?; Ok(tcp_stream) } fn handle_message(&self, message: &Message) -> Result<()> { // A subset of messages are handled directly by the peer match message { Message::FeeFilter(feefilter) => { *self.minfee.lock().unwrap() = feefilter.minfee; } Message::Ping(ping) => { let pong = Message::Pong(ping.clone()); self.send(&pong)?; } Message::SendHeaders => { self.sendheaders.store(true, Ordering::Relaxed); } Message::SendCmpct(sendcmpct) => { let enable = sendcmpct.use_cmpctblock(); self.sendcmpct.store(enable, Ordering::Relaxed); } _ => {} } Ok(()) } fn strong_self(&self) -> Option<Arc<Peer>> { match &*self.weak_self.lock().unwrap() { Some(ref weak_peer) => weak_peer.upgrade(), None => None, } } } impl PartialEq for Peer { fn eq(&self, other: &Peer) -> bool { self.id == other.id } } impl Eq for Peer {} impl Hash for Peer { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state) } } impl fmt::Debug for Peer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&format!("[Peer {}]", self.id)) } } impl Drop for Peer { fn drop(&mut self) { self.disconnect(); } }
version
identifier_name
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::fmt; use std::hash::{Hash, Hasher}; use std::io; use std::io::Write; use std::net::{IpAddr, Shutdown, SocketAddr, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use std::thread; use std::time::{Duration, UNIX_EPOCH}; /// Time to wait for the initial TCP connection const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); /// Time to wait for handshake messages before failing to connect const HANDSHAKE_READ_TIMEOUT: Duration = Duration::from_secs(3); /// Event emitted when a connection is established with the peer #[derive(Clone, Debug)] pub struct PeerConnected { pub peer: Arc<Peer>, } /// Event emitted when the connection with the peer is terminated #[derive(Clone, Debug)] pub struct PeerDisconnected { pub peer: Arc<Peer>, } /// Event emitted when the peer receives a network message #[derive(Clone, Debug)] pub struct PeerMessage { pub peer: Arc<Peer>, pub message: Message, } /// Filters peers based on their version information before connecting pub trait PeerFilter: Send + Sync { fn connectable(&self, _: &Version) -> bool; } /// Filters out all peers except for Bitcoin SV full nodes #[derive(Clone, Default, Debug)] pub struct SVPeerFilter { pub min_start_height: i32, } impl SVPeerFilter { /// Creates a new SV filter that requires a minimum starting chain height pub fn new(min_start_height: i32) -> Arc<SVPeerFilter> { Arc::new(SVPeerFilter { min_start_height }) } } impl PeerFilter for SVPeerFilter { fn connectable(&self, version: &Version) -> bool { version.user_agent.contains("Bitcoin SV") && version.start_height >= self.min_start_height && version.services & (NODE_BITCOIN_CASH | NODE_NETWORK)!= 0 } } /// Node on the network to send and receive messages /// /// It will setup a connection, respond to pings, and store basic properties about the connection, /// but any real logic to process messages will be handled outside. Network messages received will /// be published to an observable on the peer's receiver thread. Messages may be sent via send() /// from any thread. Once shutdown, the Peer may no longer be used. pub struct Peer { /// Unique id for this connection pub id: ProcessUniqueId, /// IP address pub ip: IpAddr, /// Port pub port: u16, /// Network pub network: Network, pub(crate) connected_event: Single<PeerConnected>, pub(crate) disconnected_event: Single<PeerDisconnected>, pub(crate) messages: Subject<PeerMessage>, tcp_writer: Mutex<Option<TcpStream>>, connected: AtomicBool, time_delta: Mutex<i64>, minfee: Mutex<u64>, sendheaders: AtomicBool, sendcmpct: AtomicBool, version: Mutex<Option<Version>>, /// Weak reference to self so we can pass ourselves in emitted events. This is a /// bit ugly, but we hopefully can able to remove it once arbitrary self types goes in. weak_self: Mutex<Option<Weak<Peer>>>, } impl Peer { /// Creates a new peer and begins connecting pub fn connect( ip: IpAddr, port: u16, network: Network, version: Version, filter: Arc<dyn PeerFilter>, ) -> Arc<Peer> { let peer = Arc::new(Peer { id: ProcessUniqueId::new(), ip, port, network, connected_event: Single::new(), disconnected_event: Single::new(), messages: Subject::new(), tcp_writer: Mutex::new(None), connected: AtomicBool::new(false), time_delta: Mutex::new(0), minfee: Mutex::new(0), sendheaders: AtomicBool::new(false), sendcmpct: AtomicBool::new(false), version: Mutex::new(None), weak_self: Mutex::new(None), }); *peer.weak_self.lock().unwrap() = Some(Arc::downgrade(&peer)); Peer::connect_internal(&peer, version, filter); peer } /// Sends a message to the peer pub fn send(&self, message: &Message) -> Result<()> { if!self.connected.load(Ordering::Relaxed) { return Err(Error::IllegalState("Not connected".to_string())); } let mut io_error: Option<io::Error> = None; { let mut tcp_writer = self.tcp_writer.lock().unwrap(); let mut tcp_writer = match tcp_writer.as_mut() { Some(tcp_writer) => tcp_writer, None => return Err(Error::IllegalState("No tcp stream".to_string())), }; debug!("{:?} Write {:#?}", self, message); if let Err(e) = message.write(&mut tcp_writer, self.network.magic()) { io_error = Some(e); } else { if let Err(e) = tcp_writer.flush() { io_error = Some(e); } } } match io_error { Some(e) => { self.disconnect(); Err(Error::IOError(e)) } None => Ok(()), } } /// Disconects and disables the peer pub fn disconnect(&self) { self.connected.swap(false, Ordering::Relaxed); info!("{:?} Disconnecting", self); let mut tcp_stream = self.tcp_writer.lock().unwrap(); if let Some(tcp_stream) = tcp_stream.as_mut() { if let Err(e) = tcp_stream.shutdown(Shutdown::Both) { warn!("{:?} Problem shutting down tcp stream: {:?}", self, e); } } if let Some(peer) = self.strong_self() { self.disconnected_event.next(&PeerDisconnected { peer }); } } /// Returns a Single that emits a message when connected pub fn connected_event(&self) -> &impl Observable<PeerConnected> { &self.connected_event } /// Returns a Single that emits a message when connected pub fn disconnected_event(&self) -> &impl Observable<PeerDisconnected> { &self.disconnected_event } /// Returns an Observable that emits network messages pub fn messages(&self) -> &impl Observable<PeerMessage> { &self.messages } /// Returns whether the peer is connected pub fn connected(&self) -> bool { self.connected.load(Ordering::Relaxed) } /// Returns the time difference in seconds between our time and theirs, which is valid after connecting pub fn time_delta(&self) -> i64 { *self.time_delta.lock().unwrap() } /// Returns the minimum fee this peer accepts in sats/1000bytes pub fn minfee(&self) -> u64 { *self.minfee.lock().unwrap() } /// Returns whether this peer may announce new blocks with headers instead of inv pub fn sendheaders(&self) -> bool { self.sendheaders.load(Ordering::Relaxed) } /// Returns whether compact blocks are supported pub fn sendcmpct(&self) -> bool { self.sendcmpct.load(Ordering::Relaxed) } /// Gets the version message received during the handshake pub fn version(&self) -> Result<Version> { match &*self.version.lock().unwrap() { Some(ref version) => Ok(version.clone()), None => Err(Error::IllegalState("Not connected".to_string())), } } fn connect_internal(peer: &Arc<Peer>, version: Version, filter: Arc<dyn PeerFilter>) { info!("{:?} Connecting to {:?}:{}", peer, peer.ip, peer.port); let tpeer = peer.clone(); thread::spawn(move || { let mut tcp_reader = match tpeer.handshake(version, filter) { Ok(tcp_stream) => tcp_stream, Err(e) => { error!("Failed to complete handshake: {:?}", e); tpeer.disconnect(); return; } }; // The peer is considered connected and may be written to now info!("{:?} Connected to {:?}:{}", tpeer, tpeer.ip, tpeer.port); tpeer.connected.store(true, Ordering::Relaxed); tpeer.connected_event.next(&PeerConnected { peer: tpeer.clone(), }); let mut partial: Option<MessageHeader> = None; let magic = tpeer.network.magic(); // Message reads over TCP must be all-or-nothing. let mut tcp_reader = AtomicReader::new(&mut tcp_reader); loop { let message = match &partial { Some(header) => Message::read_partial(&mut tcp_reader, header), None => Message::read(&mut tcp_reader, magic), }; // Always check the connected flag right after the blocking read so we exit right away, // and also so that we don't mistake errors with the stream shutting down if!tpeer.connected.load(Ordering::Relaxed) { return; } match message { Ok(message) => { if let Message::Partial(header) = message { partial = Some(header); } else { debug!("{:?} Read {:#?}", tpeer, message); partial = None; if let Err(e) = tpeer.handle_message(&message) { error!("{:?} Error handling message: {:?}", tpeer, e); tpeer.disconnect(); return; } tpeer.messages.next(&PeerMessage { peer: tpeer.clone(), message, }); } } Err(e) => { // If timeout, try again later. Otherwise, shutdown if let Error::IOError(ref e) = e { // Depending on platform, either TimedOut or WouldBlock may be returned to indicate a non-error timeout if e.kind() == io::ErrorKind::TimedOut || e.kind() == io::ErrorKind::WouldBlock { continue; } } error!("{:?} Error reading message {:?}", tpeer, e); tpeer.disconnect(); return; } } } }); } fn handshake(self: &Peer, version: Version, filter: Arc<dyn PeerFilter>) -> Result<TcpStream> { // Connect over TCP let tcp_addr = SocketAddr::new(self.ip, self.port); let mut tcp_stream = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)?; tcp_stream.set_nodelay(true)?; // Disable buffering tcp_stream.set_read_timeout(Some(HANDSHAKE_READ_TIMEOUT))?; tcp_stream.set_nonblocking(false)?; // Write our version let our_version = Message::Version(version); debug!("{:?} Write {:#?}", self, our_version); let magic = self.network.magic(); our_version.write(&mut tcp_stream, magic)?; // Read their version let msg = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, msg); let their_version = match msg { Message::Version(version) => version, _ => return Err(Error::BadData("Unexpected command".to_string())), }; if!filter.connectable(&their_version) { return Err(Error::IllegalState("Peer filtered out".to_string())); } let now = secs_since(UNIX_EPOCH) as i64; *self.time_delta.lock().unwrap() = now - their_version.timestamp; *self.version.lock().unwrap() = Some(their_version); // Read their verack let their_verack = Message::read(&mut tcp_stream, magic)?; debug!("{:?} Read {:#?}", self, their_verack); match their_verack { Message::Verack =>
_ => return Err(Error::BadData("Unexpected command".to_string())), }; // Write our verack debug!("{:?} Write {:#?}", self, Message::Verack); Message::Verack.write(&mut tcp_stream, magic)?; // Write a ping message because this seems to help with connection weirdness // https://bitcoin.stackexchange.com/questions/49487/getaddr-not-returning-connected-node-addresses let ping = Message::Ping(Ping { nonce: secs_since(UNIX_EPOCH) as u64, }); debug!("{:?} Write {:#?}", self, ping); ping.write(&mut tcp_stream, magic)?; // After handshake, clone TCP stream and save the write version *self.tcp_writer.lock().unwrap() = Some(tcp_stream.try_clone()?); // We don't need a timeout for the read. The peer will shutdown just fine. // The read timeout doesn't work reliably across platforms anyway. tcp_stream.set_read_timeout(None)?; Ok(tcp_stream) } fn handle_message(&self, message: &Message) -> Result<()> { // A subset of messages are handled directly by the peer match message { Message::FeeFilter(feefilter) => { *self.minfee.lock().unwrap() = feefilter.minfee; } Message::Ping(ping) => { let pong = Message::Pong(ping.clone()); self.send(&pong)?; } Message::SendHeaders => { self.sendheaders.store(true, Ordering::Relaxed); } Message::SendCmpct(sendcmpct) => { let enable = sendcmpct.use_cmpctblock(); self.sendcmpct.store(enable, Ordering::Relaxed); } _ => {} } Ok(()) } fn strong_self(&self) -> Option<Arc<Peer>> { match &*self.weak_self.lock().unwrap() { Some(ref weak_peer) => weak_peer.upgrade(), None => None, } } } impl PartialEq for Peer { fn eq(&self, other: &Peer) -> bool { self.id == other.id } } impl Eq for Peer {} impl Hash for Peer { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state) } } impl fmt::Debug for Peer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&format!("[Peer {}]", self.id)) } } impl Drop for Peer { fn drop(&mut self) { self.disconnect(); } }
{}
conditional_block
mod.rs
/// /// ```no_run /// # #[macro_use] extern crate vulkano; /// # fn main() { /// use vulkano::{ /// instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// Version, VulkanLibrary, /// }; /// /// let library = VulkanLibrary::new().unwrap(); /// let _instance = Instance::new( /// library, /// InstanceCreateInfo::application_from_cargo_toml(), /// ).unwrap(); /// # } /// ``` /// /// # API versions /// /// Both an `Instance` and a [`Device`](crate::device::Device) have a highest version of the Vulkan /// API that they support. This places a limit on what Vulkan functions and features are available /// to use when used on a particular instance or device. It is possible for the instance and the /// device to support different versions. The supported version for an instance can be queried /// before creation with /// [`VulkanLibrary::api_version`](crate::VulkanLibrary::api_version), /// while for a device it can be retrieved with /// [`PhysicalDevice::api_version`](crate::device::physical::PhysicalDevice::api_version). /// /// When creating an `Instance`, you have to specify a maximum API version that you will use. /// This restricts the API version that is available for the instance and any devices created from /// it. For example, if both instance and device potentially support Vulkan 1.2, but you specify /// 1.1 as the maximum API version when creating the `Instance`, then you can only use Vulkan 1.1 /// functions, even though they could theoretically support a higher version. You can think of it /// as a promise never to use any functionality from a higher version. /// /// The maximum API version is not a _minimum_, so it is possible to set it to a higher version than /// what the instance or device inherently support. The final API version that you are able to use /// on an instance or device is the lower of the supported API version and the chosen maximum API /// version of the `Instance`. /// /// Due to a quirk in how the Vulkan 1.0 specification was written, if the instance only /// supports Vulkan 1.0, then it is not possible to specify a maximum API version higher than 1.0. /// Trying to create an `Instance` will return an `IncompatibleDriver` error. Consequently, it is /// not possible to use a higher device API version with an instance that only supports 1.0. /// /// # Extensions /// /// When creating an `Instance`, you must provide a list of extensions that must be enabled on the /// newly-created instance. Trying to enable an extension that is not supported by the system will /// result in an error. /// /// Contrary to OpenGL, it is not possible to use the features of an extension if it was not /// explicitly enabled. /// /// Extensions are especially important to take into account if you want to render images on the /// screen, as the only way to do so is to use the `VK_KHR_surface` extension. More information /// about this in the `swapchain` module. /// /// For example, here is how we create an instance with the `VK_KHR_surface` and /// `VK_KHR_android_surface` extensions enabled, which will allow us to render images to an /// Android screen. You can compile and run this code on any system, but it is highly unlikely to /// succeed on anything else than an Android-running device. /// /// ```no_run /// use vulkano::{ /// instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// Version, VulkanLibrary, /// }; /// /// let library = VulkanLibrary::new() /// .unwrap_or_else(|err| panic!("Couldn't load Vulkan library: {:?}", err)); /// /// let extensions = InstanceExtensions { /// khr_surface: true, /// khr_android_surface: true, /// .. InstanceExtensions::empty() /// }; /// /// let instance = Instance::new( /// library, /// InstanceCreateInfo { /// enabled_extensions: extensions, /// ..Default::default() /// }, /// ) ///.unwrap_or_else(|err| panic!("Couldn't create instance: {:?}", err)); /// ``` /// /// # Layers /// /// When creating an `Instance`, you have the possibility to pass a list of **layers** that will /// be activated on the newly-created instance. The list of available layers can be retrieved by /// calling the [`layer_properties`](crate::VulkanLibrary::layer_properties) method of /// `VulkanLibrary`. /// /// A layer is a component that will hook and potentially modify the Vulkan function calls. /// For example, activating a layer could add a frames-per-second counter on the screen, or it /// could send information to a debugger that will debug your application. /// /// > **Note**: From an application's point of view, layers "just exist". In practice, on Windows /// > and Linux, layers can be installed by third party installers or by package managers and can /// > also be activated by setting the value of the `VK_INSTANCE_LAYERS` environment variable /// > before starting the program. See the documentation of the official Vulkan loader for these /// > platforms. /// /// > **Note**: In practice, the most common use of layers right now is for debugging purposes. /// > To do so, you are encouraged to set the `VK_INSTANCE_LAYERS` environment variable on Windows /// > or Linux instead of modifying the source code of your program. For example: /// > `export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump` on Linux if you installed the Vulkan SDK /// > will print the list of raw Vulkan function calls. /// /// ## Examples /// /// ``` /// # use std::{sync::Arc, error::Error}; /// # use vulkano::{ /// # instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// # Version, VulkanLibrary, /// # }; /// # fn test() -> Result<Arc<Instance>, Box<dyn Error>> { /// let library = VulkanLibrary::new()?; /// /// // For the sake of the example, we activate all the layers that /// // contain the word "foo" in their description. /// let layers: Vec<_> = library.layer_properties()? /// .filter(|l| l.description().contains("foo")) /// .collect(); /// /// let instance = Instance::new( /// library, /// InstanceCreateInfo { /// enabled_layers: layers.iter().map(|l| l.name().to_owned()).collect(), /// ..Default::default() /// }, /// )?; /// # Ok(instance) /// # } /// ``` // TODO: mention that extensions must be supported by layers as well pub struct Instance { handle: ash::vk::Instance, fns: InstanceFunctions, id: NonZeroU64, api_version: Version, enabled_extensions: InstanceExtensions, enabled_layers: Vec<String>, library: Arc<VulkanLibrary>, max_api_version: Version, _user_callbacks: Vec<Box<UserCallback>>, } // TODO: fix the underlying cause instead impl UnwindSafe for Instance {} impl RefUnwindSafe for Instance {} impl Instance { /// Creates a new `Instance`. /// /// # Panics /// /// - Panics if any version numbers in `create_info` contain a field too large to be converted /// into a Vulkan version number. /// - Panics if `create_info.max_api_version` is not at least `V1_0`. pub fn new( library: Arc<VulkanLibrary>, create_info: InstanceCreateInfo, ) -> Result<Arc<Instance>, InstanceCreationError> { unsafe { Self::with_debug_utils_messengers(library, create_info, []) } } /// Creates a new `Instance` with debug messengers to use during the creation and destruction /// of the instance. /// /// The debug messengers are not used at any other time, /// [`DebugUtilsMessenger`](crate::instance::debug::DebugUtilsMessenger) should be used for /// that. /// /// If `debug_utils_messengers` is not empty, the `ext_debug_utils` extension must be set in /// `enabled_extensions`. /// /// # Panics /// /// - Panics if the `message_severity` or `message_type` members of any element of /// `debug_utils_messengers` are empty. /// /// # Safety /// /// - The `user_callback` of each element of `debug_utils_messengers` must not make any calls /// to the Vulkan API. pub unsafe fn with_debug_utils_messengers( library: Arc<VulkanLibrary>, create_info: InstanceCreateInfo, debug_utils_messengers: impl IntoIterator<Item = DebugUtilsMessengerCreateInfo>, ) -> Result<Arc<Instance>, InstanceCreationError> { let InstanceCreateInfo { application_name, application_version, mut enabled_extensions, enabled_layers, engine_name, engine_version, max_api_version, enumerate_portability, enabled_validation_features, disabled_validation_features, _ne: _, } = create_info; let (api_version, max_api_version) = { let api_version = library.api_version(); let max_api_version = if let Some(max_api_version) = max_api_version { max_api_version } else if api_version < Version::V1_1 { api_version } else { Version::HEADER_VERSION }; (std::cmp::min(max_api_version, api_version), max_api_version) }; // VUID-VkApplicationInfo-apiVersion-04010 assert!(max_api_version >= Version::V1_0); let supported_extensions = library.supported_extensions_with_layers(enabled_layers.iter().map(String::as_str))?; let mut flags = ash::vk::InstanceCreateFlags::empty(); if enumerate_portability && supported_extensions.khr_portability_enumeration { enabled_extensions.khr_portability_enumeration = true; flags |= ash::vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR; } // Check if the extensions are correct enabled_extensions.check_requirements(&supported_extensions, api_version)?; // FIXME: check whether each layer is supported let enabled_layers_cstr: Vec<CString> = enabled_layers .iter() .map(|name| CString::new(name.clone()).unwrap()) .collect(); let enabled_layers_ptrs = enabled_layers_cstr .iter() .map(|layer| layer.as_ptr()) .collect::<SmallVec<[_; 2]>>(); let enabled_extensions_cstr: Vec<CString> = (&enabled_extensions).into(); let enabled_extensions_ptrs = enabled_extensions_cstr .iter() .map(|extension| extension.as_ptr()) .collect::<SmallVec<[_; 2]>>(); let application_name_cstr = application_name.map(|name| CString::new(name).unwrap()); let engine_name_cstr = engine_name.map(|name| CString::new(name).unwrap()); let application_info = ash::vk::ApplicationInfo { p_application_name: application_name_cstr .as_ref() .map(|s| s.as_ptr()) .unwrap_or(ptr::null()), application_version: application_version .try_into() .expect("Version out of range"), p_engine_name: engine_name_cstr .as_ref() .map(|s| s.as_ptr()) .unwrap_or(ptr::null()), engine_version: engine_version.try_into().expect("Version out of range"), api_version: max_api_version.try_into().expect("Version out of range"), ..Default::default() }; let enable_validation_features_vk: SmallVec<[_; 5]> = enabled_validation_features .iter() .copied() .map(Into::into) .collect(); let disable_validation_features_vk: SmallVec<[_; 8]> = disabled_validation_features .iter() .copied() .map(Into::into) .collect(); let mut create_info_vk = ash::vk::InstanceCreateInfo { flags, p_application_info: &application_info, enabled_layer_count: enabled_layers_ptrs.len() as u32, pp_enabled_layer_names: enabled_layers_ptrs.as_ptr(), enabled_extension_count: enabled_extensions_ptrs.len() as u32, pp_enabled_extension_names: enabled_extensions_ptrs.as_ptr(), ..Default::default() }; let mut validation_features_vk = None; if!enabled_validation_features.is_empty() ||!disabled_validation_features.is_empty() { if!enabled_extensions.ext_validation_features { return Err(InstanceCreationError::RequirementNotMet { required_for: "`create_info.enabled_validation_features` or \ `create_info.disabled_validation_features` are not empty", requires_one_of: RequiresOneOf { instance_extensions: &["ext_validation_features"], ..Default::default() }, }); } // VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02967 assert!( !enabled_validation_features .contains(&ValidationFeatureEnable::GpuAssistedReserveBindingSlot) || enabled_validation_features.contains(&ValidationFeatureEnable::GpuAssisted) ); // VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02968 assert!( !(enabled_validation_features.contains(&ValidationFeatureEnable::DebugPrintf) && enabled_validation_features.contains(&ValidationFeatureEnable::GpuAssisted)) ); let next = validation_features_vk.insert(ash::vk::ValidationFeaturesEXT { enabled_validation_feature_count: enable_validation_features_vk.len() as u32, p_enabled_validation_features: enable_validation_features_vk.as_ptr(), disabled_validation_feature_count: disable_validation_features_vk.len() as u32, p_disabled_validation_features: disable_validation_features_vk.as_ptr(), ..Default::default() }); next.p_next = create_info_vk.p_next; create_info_vk.p_next = next as *const _ as *const _; } // Handle debug messengers let debug_utils_messengers = debug_utils_messengers.into_iter(); let mut debug_utils_messenger_create_infos = Vec::with_capacity(debug_utils_messengers.size_hint().0); let mut user_callbacks = Vec::with_capacity(debug_utils_messengers.size_hint().0); for create_info in debug_utils_messengers { let DebugUtilsMessengerCreateInfo { message_type, message_severity, user_callback, _ne: _, } = create_info; // VUID-VkInstanceCreateInfo-pNext-04926 if!enabled_extensions.ext_debug_utils { return Err(InstanceCreationError::RequirementNotMet { required_for: "`create_info.debug_utils_messengers` is not empty", requires_one_of: RequiresOneOf { instance_extensions: &["ext_debug_utils"], ..Default::default() }, }); } // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageSeverity-parameter // TODO: message_severity.validate_instance()?; // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageSeverity-requiredbitmask assert!(!message_severity.is_empty()); // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageType-parameter // TODO: message_type.validate_instance()?; // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageType-requiredbitmask assert!(!message_type.is_empty()); // VUID-PFN_vkDebugUtilsMessengerCallbackEXT-None-04769 // Can't be checked, creation is unsafe. let user_callback = Box::new(user_callback); let create_info = ash::vk::DebugUtilsMessengerCreateInfoEXT { flags: ash::vk::DebugUtilsMessengerCreateFlagsEXT::empty(), message_severity: message_severity.into(), message_type: message_type.into(), pfn_user_callback: Some(trampoline), p_user_data: &*user_callback as &Arc<_> as *const Arc<_> as *const c_void as *mut _, ..Default::default() }; debug_utils_messenger_create_infos.push(create_info); user_callbacks.push(user_callback); } for i in 1..debug_utils_messenger_create_infos.len() { debug_utils_messenger_create_infos[i - 1].p_next = &debug_utils_messenger_create_infos[i] as *const _ as *const _; } if let Some(info) = debug_utils_messenger_create_infos.first() { create_info_vk.p_next = info as *const _ as *const _; } // Creating the Vulkan instance. let handle = { let mut output = MaybeUninit::uninit(); let fns = library.fns(); (fns.v1_0.create_instance)(&create_info_vk, ptr::null(), output.as_mut_ptr()) .result() .map_err(VulkanError::from)?; output.assume_init() }; // Loading the function pointers of the newly-created instance. let fns = { InstanceFunctions::load(|name| { library .get_instance_proc_addr(handle, name.as_ptr()) .map_or(ptr::null(), |func| func as _) }) }; Ok(Arc::new(Instance { handle, fns, id: Self::next_id(), api_version, enabled_extensions, enabled_layers, library, max_api_version, _user_callbacks: user_callbacks, })) }
pub fn library(&self) -> &Arc<VulkanLibrary> { &self.library } /// Returns the Vulkan version supported by the instance. /// /// This is the lower of the /// [driver's supported version](crate::VulkanLibrary::api_version) and /// [`max_api_version`](Instance::max_api_version). #[inline] pub fn api_version(&self) -> Version { self.api_version } /// Returns the maximum Vulkan version that was specified when creating the instance. #[inline] pub fn max_api_version(&self) -> Version { self.max_api_version } /// Returns pointers to the raw Vulkan functions of the instance. #[inline] pub fn fns(&self) -> &InstanceFunctions { &self.fns } /// Returns the extensions that have been enabled on the instance. #[inline] pub fn enabled_extensions(&self) -> &InstanceExtensions { &self.enabled_extensions } /// Returns the layers that have been enabled on the instance. #[inline] pub fn enabled_layers(&self) -> &[String] { &self.enabled_layers } /// Returns an iterator that enumerates the physical devices available. /// /// # Examples /// /// ```no_run /// # use vulkano::{ /// # instance::{Instance, InstanceExtensions}, /// # Version, VulkanLibrary, /// # }; /// /// # let library = VulkanLibrary::new().unwrap(); /// # let instance = Instance::new(library, Default::default()).unwrap(); /// for physical_device in instance.enumerate_physical_devices().unwrap() { /// println!("Available device: {}", physical_device.properties().device_name); /// } /// ``` pub fn enumerate_physical_devices( self: &Arc<Self>, ) -> Result<impl ExactSizeIterator<Item = Arc<PhysicalDevice>>, VulkanError> { let fns = self.fns(); unsafe { let handles = loop { let mut count = 0; (fns.v1_0.enumerate_physical_devices)(self.handle, &mut count, ptr::null_mut()) .result() .map_err(VulkanError::from)?; let mut handles = Vec::with_capacity(count as usize); let result = (fns.v1_0.enumerate_physical_devices)( self.handle, &mut count, handles.as_mut_ptr(), ); match result { ash::vk::Result::SUCCESS => { handles.set_len(count as usize); break handles; } ash::vk::Result::INCOMPLETE => (), err => return Err(VulkanError::from(err)), } }; let physical_devices: SmallVec<[_; 4]> = handles .into_iter() .map(|handle| PhysicalDevice::from_handle(self.clone(), handle)) .collect::<Result<_, _>>()?; Ok(physical_devices.into_iter()) } } } impl Drop for Instance { #[inline] fn drop(&mut self) { let fns = self.fns();
/// Returns the Vulkan library used to create this instance. #[inline]
random_line_split
mod.rs
}; (std::cmp::min(max_api_version, api_version), max_api_version) }; // VUID-VkApplicationInfo-apiVersion-04010 assert!(max_api_version >= Version::V1_0); let supported_extensions = library.supported_extensions_with_layers(enabled_layers.iter().map(String::as_str))?; let mut flags = ash::vk::InstanceCreateFlags::empty(); if enumerate_portability && supported_extensions.khr_portability_enumeration { enabled_extensions.khr_portability_enumeration = true; flags |= ash::vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR; } // Check if the extensions are correct enabled_extensions.check_requirements(&supported_extensions, api_version)?; // FIXME: check whether each layer is supported let enabled_layers_cstr: Vec<CString> = enabled_layers .iter() .map(|name| CString::new(name.clone()).unwrap()) .collect(); let enabled_layers_ptrs = enabled_layers_cstr .iter() .map(|layer| layer.as_ptr()) .collect::<SmallVec<[_; 2]>>(); let enabled_extensions_cstr: Vec<CString> = (&enabled_extensions).into(); let enabled_extensions_ptrs = enabled_extensions_cstr .iter() .map(|extension| extension.as_ptr()) .collect::<SmallVec<[_; 2]>>(); let application_name_cstr = application_name.map(|name| CString::new(name).unwrap()); let engine_name_cstr = engine_name.map(|name| CString::new(name).unwrap()); let application_info = ash::vk::ApplicationInfo { p_application_name: application_name_cstr .as_ref() .map(|s| s.as_ptr()) .unwrap_or(ptr::null()), application_version: application_version .try_into() .expect("Version out of range"), p_engine_name: engine_name_cstr .as_ref() .map(|s| s.as_ptr()) .unwrap_or(ptr::null()), engine_version: engine_version.try_into().expect("Version out of range"), api_version: max_api_version.try_into().expect("Version out of range"), ..Default::default() }; let enable_validation_features_vk: SmallVec<[_; 5]> = enabled_validation_features .iter() .copied() .map(Into::into) .collect(); let disable_validation_features_vk: SmallVec<[_; 8]> = disabled_validation_features .iter() .copied() .map(Into::into) .collect(); let mut create_info_vk = ash::vk::InstanceCreateInfo { flags, p_application_info: &application_info, enabled_layer_count: enabled_layers_ptrs.len() as u32, pp_enabled_layer_names: enabled_layers_ptrs.as_ptr(), enabled_extension_count: enabled_extensions_ptrs.len() as u32, pp_enabled_extension_names: enabled_extensions_ptrs.as_ptr(), ..Default::default() }; let mut validation_features_vk = None; if!enabled_validation_features.is_empty() ||!disabled_validation_features.is_empty() { if!enabled_extensions.ext_validation_features { return Err(InstanceCreationError::RequirementNotMet { required_for: "`create_info.enabled_validation_features` or \ `create_info.disabled_validation_features` are not empty", requires_one_of: RequiresOneOf { instance_extensions: &["ext_validation_features"], ..Default::default() }, }); } // VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02967 assert!( !enabled_validation_features .contains(&ValidationFeatureEnable::GpuAssistedReserveBindingSlot) || enabled_validation_features.contains(&ValidationFeatureEnable::GpuAssisted) ); // VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02968 assert!( !(enabled_validation_features.contains(&ValidationFeatureEnable::DebugPrintf) && enabled_validation_features.contains(&ValidationFeatureEnable::GpuAssisted)) ); let next = validation_features_vk.insert(ash::vk::ValidationFeaturesEXT { enabled_validation_feature_count: enable_validation_features_vk.len() as u32, p_enabled_validation_features: enable_validation_features_vk.as_ptr(), disabled_validation_feature_count: disable_validation_features_vk.len() as u32, p_disabled_validation_features: disable_validation_features_vk.as_ptr(), ..Default::default() }); next.p_next = create_info_vk.p_next; create_info_vk.p_next = next as *const _ as *const _; } // Handle debug messengers let debug_utils_messengers = debug_utils_messengers.into_iter(); let mut debug_utils_messenger_create_infos = Vec::with_capacity(debug_utils_messengers.size_hint().0); let mut user_callbacks = Vec::with_capacity(debug_utils_messengers.size_hint().0); for create_info in debug_utils_messengers { let DebugUtilsMessengerCreateInfo { message_type, message_severity, user_callback, _ne: _, } = create_info; // VUID-VkInstanceCreateInfo-pNext-04926 if!enabled_extensions.ext_debug_utils { return Err(InstanceCreationError::RequirementNotMet { required_for: "`create_info.debug_utils_messengers` is not empty", requires_one_of: RequiresOneOf { instance_extensions: &["ext_debug_utils"], ..Default::default() }, }); } // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageSeverity-parameter // TODO: message_severity.validate_instance()?; // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageSeverity-requiredbitmask assert!(!message_severity.is_empty()); // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageType-parameter // TODO: message_type.validate_instance()?; // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageType-requiredbitmask assert!(!message_type.is_empty()); // VUID-PFN_vkDebugUtilsMessengerCallbackEXT-None-04769 // Can't be checked, creation is unsafe. let user_callback = Box::new(user_callback); let create_info = ash::vk::DebugUtilsMessengerCreateInfoEXT { flags: ash::vk::DebugUtilsMessengerCreateFlagsEXT::empty(), message_severity: message_severity.into(), message_type: message_type.into(), pfn_user_callback: Some(trampoline), p_user_data: &*user_callback as &Arc<_> as *const Arc<_> as *const c_void as *mut _, ..Default::default() }; debug_utils_messenger_create_infos.push(create_info); user_callbacks.push(user_callback); } for i in 1..debug_utils_messenger_create_infos.len() { debug_utils_messenger_create_infos[i - 1].p_next = &debug_utils_messenger_create_infos[i] as *const _ as *const _; } if let Some(info) = debug_utils_messenger_create_infos.first() { create_info_vk.p_next = info as *const _ as *const _; } // Creating the Vulkan instance. let handle = { let mut output = MaybeUninit::uninit(); let fns = library.fns(); (fns.v1_0.create_instance)(&create_info_vk, ptr::null(), output.as_mut_ptr()) .result() .map_err(VulkanError::from)?; output.assume_init() }; // Loading the function pointers of the newly-created instance. let fns = { InstanceFunctions::load(|name| { library .get_instance_proc_addr(handle, name.as_ptr()) .map_or(ptr::null(), |func| func as _) }) }; Ok(Arc::new(Instance { handle, fns, id: Self::next_id(), api_version, enabled_extensions, enabled_layers, library, max_api_version, _user_callbacks: user_callbacks, })) } /// Returns the Vulkan library used to create this instance. #[inline] pub fn library(&self) -> &Arc<VulkanLibrary> { &self.library } /// Returns the Vulkan version supported by the instance. /// /// This is the lower of the /// [driver's supported version](crate::VulkanLibrary::api_version) and /// [`max_api_version`](Instance::max_api_version). #[inline] pub fn api_version(&self) -> Version { self.api_version } /// Returns the maximum Vulkan version that was specified when creating the instance. #[inline] pub fn max_api_version(&self) -> Version { self.max_api_version } /// Returns pointers to the raw Vulkan functions of the instance. #[inline] pub fn fns(&self) -> &InstanceFunctions { &self.fns } /// Returns the extensions that have been enabled on the instance. #[inline] pub fn enabled_extensions(&self) -> &InstanceExtensions { &self.enabled_extensions } /// Returns the layers that have been enabled on the instance. #[inline] pub fn enabled_layers(&self) -> &[String] { &self.enabled_layers } /// Returns an iterator that enumerates the physical devices available. /// /// # Examples /// /// ```no_run /// # use vulkano::{ /// # instance::{Instance, InstanceExtensions}, /// # Version, VulkanLibrary, /// # }; /// /// # let library = VulkanLibrary::new().unwrap(); /// # let instance = Instance::new(library, Default::default()).unwrap(); /// for physical_device in instance.enumerate_physical_devices().unwrap() { /// println!("Available device: {}", physical_device.properties().device_name); /// } /// ``` pub fn enumerate_physical_devices( self: &Arc<Self>, ) -> Result<impl ExactSizeIterator<Item = Arc<PhysicalDevice>>, VulkanError> { let fns = self.fns(); unsafe { let handles = loop { let mut count = 0; (fns.v1_0.enumerate_physical_devices)(self.handle, &mut count, ptr::null_mut()) .result() .map_err(VulkanError::from)?; let mut handles = Vec::with_capacity(count as usize); let result = (fns.v1_0.enumerate_physical_devices)( self.handle, &mut count, handles.as_mut_ptr(), ); match result { ash::vk::Result::SUCCESS => { handles.set_len(count as usize); break handles; } ash::vk::Result::INCOMPLETE => (), err => return Err(VulkanError::from(err)), } }; let physical_devices: SmallVec<[_; 4]> = handles .into_iter() .map(|handle| PhysicalDevice::from_handle(self.clone(), handle)) .collect::<Result<_, _>>()?; Ok(physical_devices.into_iter()) } } } impl Drop for Instance { #[inline] fn drop(&mut self) { let fns = self.fns(); unsafe { (fns.v1_0.destroy_instance)(self.handle, ptr::null()); } } } unsafe impl VulkanObject for Instance { type Handle = ash::vk::Instance; #[inline] fn handle(&self) -> Self::Handle { self.handle } } crate::impl_id_counter!(Instance); impl Debug for Instance { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { let Self { handle, fns, id: _, api_version, enabled_extensions, enabled_layers, library: function_pointers, max_api_version, _user_callbacks: _, } = self; f.debug_struct("Instance") .field("handle", handle) .field("fns", fns) .field("api_version", api_version) .field("enabled_extensions", enabled_extensions) .field("enabled_layers", enabled_layers) .field("function_pointers", function_pointers) .field("max_api_version", max_api_version) .finish_non_exhaustive() } } /// Parameters to create a new `Instance`. #[derive(Debug)] pub struct InstanceCreateInfo { /// A string of your choice stating the name of your application. /// /// The default value is `None`. pub application_name: Option<String>, /// A version number of your choice specifying the version of your application. /// /// The default value is zero. pub application_version: Version, /// The extensions to enable on the instance. /// /// The default value is [`InstanceExtensions::empty()`]. pub enabled_extensions: InstanceExtensions, /// The layers to enable on the instance. /// /// The default value is empty. pub enabled_layers: Vec<String>, /// A string of your choice stating the name of the engine used to power the application. pub engine_name: Option<String>, /// A version number of your choice specifying the version of the engine used to power the /// application. /// /// The default value is zero. pub engine_version: Version, /// The highest Vulkan API version that the application will use with the instance. /// /// Usually, you will want to leave this at the default. /// /// The default value is [`Version::HEADER_VERSION`], but if the /// supported instance version is 1.0, then it will be 1.0. pub max_api_version: Option<Version>, /// Include [portability subset](crate::instance#portability-subset-devices-and-the-enumerate_portability-flag) /// devices when enumerating physical devices. /// /// If you enable this flag, you must ensure that your program is prepared to handle the /// non-conformant aspects of these devices. /// /// If this flag is not enabled, and there are no fully-conformant devices on the system, then /// [`Instance::new`] will return an `IncompatibleDriver` error. /// /// The default value is `false`. /// /// # Notes /// /// If this flag is enabled, and the /// [`khr_portability_enumeration`](crate::instance::InstanceExtensions::khr_portability_enumeration) /// extension is supported, it will be enabled automatically when creating the instance. /// If the extension is not supported, this flag will be ignored. pub enumerate_portability: bool, /// Features of the validation layer to enable. /// /// If not empty, the /// [`ext_validation_features`](crate::instance::InstanceExtensions::ext_validation_features) /// extension must be enabled on the instance. pub enabled_validation_features: Vec<ValidationFeatureEnable>, /// Features of the validation layer to disable. /// /// If not empty, the /// [`ext_validation_features`](crate::instance::InstanceExtensions::ext_validation_features) /// extension must be enabled on the instance. pub disabled_validation_features: Vec<ValidationFeatureDisable>, pub _ne: crate::NonExhaustive, } impl Default for InstanceCreateInfo { #[inline] fn default() -> Self { Self { application_name: None, application_version: Version::major_minor(0, 0), enabled_extensions: InstanceExtensions::empty(), enabled_layers: Vec::new(), engine_name: None, engine_version: Version::major_minor(0, 0), max_api_version: None, enumerate_portability: false, enabled_validation_features: Vec::new(), disabled_validation_features: Vec::new(), _ne: crate::NonExhaustive(()), } } } impl InstanceCreateInfo { /// Returns an `InstanceCreateInfo` with the `application_name` and `application_version` set /// from information in your crate's Cargo.toml file. /// /// # Panics /// /// - Panics if the required environment variables are missing, which happens if the project /// wasn't built by Cargo. #[inline] pub fn application_from_cargo_toml() -> Self { Self { application_name: Some(env!("CARGO_PKG_NAME").to_owned()), application_version: Version { major: env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap(), minor: env!("CARGO_PKG_VERSION_MINOR").parse().unwrap(), patch: env!("CARGO_PKG_VERSION_PATCH").parse().unwrap(), }, ..Default::default() } } } /// Error that can happen when creating an instance. #[derive(Clone, Debug)] pub enum InstanceCreationError { /// Not enough memory. OomError(OomError), /// Failed to initialize for an implementation-specific reason. InitializationFailed, /// One of the requested layers is missing. LayerNotPresent, /// One of the requested extensions is not supported by the implementation. ExtensionNotPresent, /// The version requested is not supported by the implementation. IncompatibleDriver, /// A restriction for an extension was not met. ExtensionRestrictionNotMet(ExtensionRestrictionError), RequirementNotMet { required_for: &'static str, requires_one_of: RequiresOneOf, }, } impl Error for InstanceCreationError { fn source(&self) -> Option<&(dyn Error +'static)> { match self { Self::OomError(err) => Some(err), _ => None, } } } impl Display for InstanceCreationError { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { match self { Self::OomError(_) => write!(f, "not enough memory available"), Self::InitializationFailed => write!(f, "initialization failed"), Self::LayerNotPresent => write!(f, "layer not present"), Self::ExtensionNotPresent => write!(f, "extension not present"), Self::IncompatibleDriver => write!(f, "incompatible driver"), Self::ExtensionRestrictionNotMet(err) => Display::fmt(err, f), Self::RequirementNotMet { required_for, requires_one_of, } => write!( f, "a requirement was not met for: {}; requires one of: {}", required_for, requires_one_of, ), } } } impl From<OomError> for InstanceCreationError { fn
from
identifier_name
mod.rs
/// ```no_run /// # #[macro_use] extern crate vulkano; /// # fn main() { /// use vulkano::{ /// instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// Version, VulkanLibrary, /// }; /// /// let library = VulkanLibrary::new().unwrap(); /// let _instance = Instance::new( /// library, /// InstanceCreateInfo::application_from_cargo_toml(), /// ).unwrap(); /// # } /// ``` /// /// # API versions /// /// Both an `Instance` and a [`Device`](crate::device::Device) have a highest version of the Vulkan /// API that they support. This places a limit on what Vulkan functions and features are available /// to use when used on a particular instance or device. It is possible for the instance and the /// device to support different versions. The supported version for an instance can be queried /// before creation with /// [`VulkanLibrary::api_version`](crate::VulkanLibrary::api_version), /// while for a device it can be retrieved with /// [`PhysicalDevice::api_version`](crate::device::physical::PhysicalDevice::api_version). /// /// When creating an `Instance`, you have to specify a maximum API version that you will use. /// This restricts the API version that is available for the instance and any devices created from /// it. For example, if both instance and device potentially support Vulkan 1.2, but you specify /// 1.1 as the maximum API version when creating the `Instance`, then you can only use Vulkan 1.1 /// functions, even though they could theoretically support a higher version. You can think of it /// as a promise never to use any functionality from a higher version. /// /// The maximum API version is not a _minimum_, so it is possible to set it to a higher version than /// what the instance or device inherently support. The final API version that you are able to use /// on an instance or device is the lower of the supported API version and the chosen maximum API /// version of the `Instance`. /// /// Due to a quirk in how the Vulkan 1.0 specification was written, if the instance only /// supports Vulkan 1.0, then it is not possible to specify a maximum API version higher than 1.0. /// Trying to create an `Instance` will return an `IncompatibleDriver` error. Consequently, it is /// not possible to use a higher device API version with an instance that only supports 1.0. /// /// # Extensions /// /// When creating an `Instance`, you must provide a list of extensions that must be enabled on the /// newly-created instance. Trying to enable an extension that is not supported by the system will /// result in an error. /// /// Contrary to OpenGL, it is not possible to use the features of an extension if it was not /// explicitly enabled. /// /// Extensions are especially important to take into account if you want to render images on the /// screen, as the only way to do so is to use the `VK_KHR_surface` extension. More information /// about this in the `swapchain` module. /// /// For example, here is how we create an instance with the `VK_KHR_surface` and /// `VK_KHR_android_surface` extensions enabled, which will allow us to render images to an /// Android screen. You can compile and run this code on any system, but it is highly unlikely to /// succeed on anything else than an Android-running device. /// /// ```no_run /// use vulkano::{ /// instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// Version, VulkanLibrary, /// }; /// /// let library = VulkanLibrary::new() /// .unwrap_or_else(|err| panic!("Couldn't load Vulkan library: {:?}", err)); /// /// let extensions = InstanceExtensions { /// khr_surface: true, /// khr_android_surface: true, /// .. InstanceExtensions::empty() /// }; /// /// let instance = Instance::new( /// library, /// InstanceCreateInfo { /// enabled_extensions: extensions, /// ..Default::default() /// }, /// ) ///.unwrap_or_else(|err| panic!("Couldn't create instance: {:?}", err)); /// ``` /// /// # Layers /// /// When creating an `Instance`, you have the possibility to pass a list of **layers** that will /// be activated on the newly-created instance. The list of available layers can be retrieved by /// calling the [`layer_properties`](crate::VulkanLibrary::layer_properties) method of /// `VulkanLibrary`. /// /// A layer is a component that will hook and potentially modify the Vulkan function calls. /// For example, activating a layer could add a frames-per-second counter on the screen, or it /// could send information to a debugger that will debug your application. /// /// > **Note**: From an application's point of view, layers "just exist". In practice, on Windows /// > and Linux, layers can be installed by third party installers or by package managers and can /// > also be activated by setting the value of the `VK_INSTANCE_LAYERS` environment variable /// > before starting the program. See the documentation of the official Vulkan loader for these /// > platforms. /// /// > **Note**: In practice, the most common use of layers right now is for debugging purposes. /// > To do so, you are encouraged to set the `VK_INSTANCE_LAYERS` environment variable on Windows /// > or Linux instead of modifying the source code of your program. For example: /// > `export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump` on Linux if you installed the Vulkan SDK /// > will print the list of raw Vulkan function calls. /// /// ## Examples /// /// ``` /// # use std::{sync::Arc, error::Error}; /// # use vulkano::{ /// # instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// # Version, VulkanLibrary, /// # }; /// # fn test() -> Result<Arc<Instance>, Box<dyn Error>> { /// let library = VulkanLibrary::new()?; /// /// // For the sake of the example, we activate all the layers that /// // contain the word "foo" in their description. /// let layers: Vec<_> = library.layer_properties()? /// .filter(|l| l.description().contains("foo")) /// .collect(); /// /// let instance = Instance::new( /// library, /// InstanceCreateInfo { /// enabled_layers: layers.iter().map(|l| l.name().to_owned()).collect(), /// ..Default::default() /// }, /// )?; /// # Ok(instance) /// # } /// ``` // TODO: mention that extensions must be supported by layers as well pub struct Instance { handle: ash::vk::Instance, fns: InstanceFunctions, id: NonZeroU64, api_version: Version, enabled_extensions: InstanceExtensions, enabled_layers: Vec<String>, library: Arc<VulkanLibrary>, max_api_version: Version, _user_callbacks: Vec<Box<UserCallback>>, } // TODO: fix the underlying cause instead impl UnwindSafe for Instance {} impl RefUnwindSafe for Instance {} impl Instance { /// Creates a new `Instance`. /// /// # Panics /// /// - Panics if any version numbers in `create_info` contain a field too large to be converted /// into a Vulkan version number. /// - Panics if `create_info.max_api_version` is not at least `V1_0`. pub fn new( library: Arc<VulkanLibrary>, create_info: InstanceCreateInfo, ) -> Result<Arc<Instance>, InstanceCreationError> { unsafe { Self::with_debug_utils_messengers(library, create_info, []) } } /// Creates a new `Instance` with debug messengers to use during the creation and destruction /// of the instance. /// /// The debug messengers are not used at any other time, /// [`DebugUtilsMessenger`](crate::instance::debug::DebugUtilsMessenger) should be used for /// that. /// /// If `debug_utils_messengers` is not empty, the `ext_debug_utils` extension must be set in /// `enabled_extensions`. /// /// # Panics /// /// - Panics if the `message_severity` or `message_type` members of any element of /// `debug_utils_messengers` are empty. /// /// # Safety /// /// - The `user_callback` of each element of `debug_utils_messengers` must not make any calls /// to the Vulkan API. pub unsafe fn with_debug_utils_messengers( library: Arc<VulkanLibrary>, create_info: InstanceCreateInfo, debug_utils_messengers: impl IntoIterator<Item = DebugUtilsMessengerCreateInfo>, ) -> Result<Arc<Instance>, InstanceCreationError> { let InstanceCreateInfo { application_name, application_version, mut enabled_extensions, enabled_layers, engine_name, engine_version, max_api_version, enumerate_portability, enabled_validation_features, disabled_validation_features, _ne: _, } = create_info; let (api_version, max_api_version) = { let api_version = library.api_version(); let max_api_version = if let Some(max_api_version) = max_api_version { max_api_version } else if api_version < Version::V1_1 { api_version } else { Version::HEADER_VERSION }; (std::cmp::min(max_api_version, api_version), max_api_version) }; // VUID-VkApplicationInfo-apiVersion-04010 assert!(max_api_version >= Version::V1_0); let supported_extensions = library.supported_extensions_with_layers(enabled_layers.iter().map(String::as_str))?; let mut flags = ash::vk::InstanceCreateFlags::empty(); if enumerate_portability && supported_extensions.khr_portability_enumeration { enabled_extensions.khr_portability_enumeration = true; flags |= ash::vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR; } // Check if the extensions are correct enabled_extensions.check_requirements(&supported_extensions, api_version)?; // FIXME: check whether each layer is supported let enabled_layers_cstr: Vec<CString> = enabled_layers .iter() .map(|name| CString::new(name.clone()).unwrap()) .collect(); let enabled_layers_ptrs = enabled_layers_cstr .iter() .map(|layer| layer.as_ptr()) .collect::<SmallVec<[_; 2]>>(); let enabled_extensions_cstr: Vec<CString> = (&enabled_extensions).into(); let enabled_extensions_ptrs = enabled_extensions_cstr .iter() .map(|extension| extension.as_ptr()) .collect::<SmallVec<[_; 2]>>(); let application_name_cstr = application_name.map(|name| CString::new(name).unwrap()); let engine_name_cstr = engine_name.map(|name| CString::new(name).unwrap()); let application_info = ash::vk::ApplicationInfo { p_application_name: application_name_cstr .as_ref() .map(|s| s.as_ptr()) .unwrap_or(ptr::null()), application_version: application_version .try_into() .expect("Version out of range"), p_engine_name: engine_name_cstr .as_ref() .map(|s| s.as_ptr()) .unwrap_or(ptr::null()), engine_version: engine_version.try_into().expect("Version out of range"), api_version: max_api_version.try_into().expect("Version out of range"), ..Default::default() }; let enable_validation_features_vk: SmallVec<[_; 5]> = enabled_validation_features .iter() .copied() .map(Into::into) .collect(); let disable_validation_features_vk: SmallVec<[_; 8]> = disabled_validation_features .iter() .copied() .map(Into::into) .collect(); let mut create_info_vk = ash::vk::InstanceCreateInfo { flags, p_application_info: &application_info, enabled_layer_count: enabled_layers_ptrs.len() as u32, pp_enabled_layer_names: enabled_layers_ptrs.as_ptr(), enabled_extension_count: enabled_extensions_ptrs.len() as u32, pp_enabled_extension_names: enabled_extensions_ptrs.as_ptr(), ..Default::default() }; let mut validation_features_vk = None; if!enabled_validation_features.is_empty() ||!disabled_validation_features.is_empty() { if!enabled_extensions.ext_validation_features { return Err(InstanceCreationError::RequirementNotMet { required_for: "`create_info.enabled_validation_features` or \ `create_info.disabled_validation_features` are not empty", requires_one_of: RequiresOneOf { instance_extensions: &["ext_validation_features"], ..Default::default() }, }); } // VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02967 assert!( !enabled_validation_features .contains(&ValidationFeatureEnable::GpuAssistedReserveBindingSlot) || enabled_validation_features.contains(&ValidationFeatureEnable::GpuAssisted) ); // VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02968 assert!( !(enabled_validation_features.contains(&ValidationFeatureEnable::DebugPrintf) && enabled_validation_features.contains(&ValidationFeatureEnable::GpuAssisted)) ); let next = validation_features_vk.insert(ash::vk::ValidationFeaturesEXT { enabled_validation_feature_count: enable_validation_features_vk.len() as u32, p_enabled_validation_features: enable_validation_features_vk.as_ptr(), disabled_validation_feature_count: disable_validation_features_vk.len() as u32, p_disabled_validation_features: disable_validation_features_vk.as_ptr(), ..Default::default() }); next.p_next = create_info_vk.p_next; create_info_vk.p_next = next as *const _ as *const _; } // Handle debug messengers let debug_utils_messengers = debug_utils_messengers.into_iter(); let mut debug_utils_messenger_create_infos = Vec::with_capacity(debug_utils_messengers.size_hint().0); let mut user_callbacks = Vec::with_capacity(debug_utils_messengers.size_hint().0); for create_info in debug_utils_messengers { let DebugUtilsMessengerCreateInfo { message_type, message_severity, user_callback, _ne: _, } = create_info; // VUID-VkInstanceCreateInfo-pNext-04926 if!enabled_extensions.ext_debug_utils { return Err(InstanceCreationError::RequirementNotMet { required_for: "`create_info.debug_utils_messengers` is not empty", requires_one_of: RequiresOneOf { instance_extensions: &["ext_debug_utils"], ..Default::default() }, }); } // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageSeverity-parameter // TODO: message_severity.validate_instance()?; // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageSeverity-requiredbitmask assert!(!message_severity.is_empty()); // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageType-parameter // TODO: message_type.validate_instance()?; // VUID-VkDebugUtilsMessengerCreateInfoEXT-messageType-requiredbitmask assert!(!message_type.is_empty()); // VUID-PFN_vkDebugUtilsMessengerCallbackEXT-None-04769 // Can't be checked, creation is unsafe. let user_callback = Box::new(user_callback); let create_info = ash::vk::DebugUtilsMessengerCreateInfoEXT { flags: ash::vk::DebugUtilsMessengerCreateFlagsEXT::empty(), message_severity: message_severity.into(), message_type: message_type.into(), pfn_user_callback: Some(trampoline), p_user_data: &*user_callback as &Arc<_> as *const Arc<_> as *const c_void as *mut _, ..Default::default() }; debug_utils_messenger_create_infos.push(create_info); user_callbacks.push(user_callback); } for i in 1..debug_utils_messenger_create_infos.len() { debug_utils_messenger_create_infos[i - 1].p_next = &debug_utils_messenger_create_infos[i] as *const _ as *const _; } if let Some(info) = debug_utils_messenger_create_infos.first() { create_info_vk.p_next = info as *const _ as *const _; } // Creating the Vulkan instance. let handle = { let mut output = MaybeUninit::uninit(); let fns = library.fns(); (fns.v1_0.create_instance)(&create_info_vk, ptr::null(), output.as_mut_ptr()) .result() .map_err(VulkanError::from)?; output.assume_init() }; // Loading the function pointers of the newly-created instance. let fns = { InstanceFunctions::load(|name| { library .get_instance_proc_addr(handle, name.as_ptr()) .map_or(ptr::null(), |func| func as _) }) }; Ok(Arc::new(Instance { handle, fns, id: Self::next_id(), api_version, enabled_extensions, enabled_layers, library, max_api_version, _user_callbacks: user_callbacks, })) } /// Returns the Vulkan library used to create this instance. #[inline] pub fn library(&self) -> &Arc<VulkanLibrary> { &self.library } /// Returns the Vulkan version supported by the instance. /// /// This is the lower of the /// [driver's supported version](crate::VulkanLibrary::api_version) and /// [`max_api_version`](Instance::max_api_version). #[inline] pub fn api_version(&self) -> Version { self.api_version } /// Returns the maximum Vulkan version that was specified when creating the instance. #[inline] pub fn max_api_version(&self) -> Version { self.max_api_version } /// Returns pointers to the raw Vulkan functions of the instance. #[inline] pub fn fns(&self) -> &InstanceFunctions { &self.fns } /// Returns the extensions that have been enabled on the instance. #[inline] pub fn enabled_extensions(&self) -> &InstanceExtensions { &self.enabled_extensions } /// Returns the layers that have been enabled on the instance. #[inline] pub fn enabled_layers(&self) -> &[String]
/// Returns an iterator that enumerates the physical devices available. /// /// # Examples /// /// ```no_run /// # use vulkano::{ /// # instance::{Instance, InstanceExtensions}, /// # Version, VulkanLibrary, /// # }; /// /// # let library = VulkanLibrary::new().unwrap(); /// # let instance = Instance::new(library, Default::default()).unwrap(); /// for physical_device in instance.enumerate_physical_devices().unwrap() { /// println!("Available device: {}", physical_device.properties().device_name); /// } /// ``` pub fn enumerate_physical_devices( self: &Arc<Self>, ) -> Result<impl ExactSizeIterator<Item = Arc<PhysicalDevice>>, VulkanError> { let fns = self.fns(); unsafe { let handles = loop { let mut count = 0; (fns.v1_0.enumerate_physical_devices)(self.handle, &mut count, ptr::null_mut()) .result() .map_err(VulkanError::from)?; let mut handles = Vec::with_capacity(count as usize); let result = (fns.v1_0.enumerate_physical_devices)( self.handle, &mut count, handles.as_mut_ptr(), ); match result { ash::vk::Result::SUCCESS => { handles.set_len(count as usize); break handles; } ash::vk::Result::INCOMPLETE => (), err => return Err(VulkanError::from(err)), } }; let physical_devices: SmallVec<[_; 4]> = handles .into_iter() .map(|handle| PhysicalDevice::from_handle(self.clone(), handle)) .collect::<Result<_, _>>()?; Ok(physical_devices.into_iter()) } } } impl Drop for Instance { #[inline] fn drop(&mut self) { let fns = self.fns();
{ &self.enabled_layers }
identifier_body
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney, cli::{Config, ThresholdType}, fisher::FisherTest, reference::RefPos, alleles::{AllDesc, LargeDeletion}, stat_funcs::pnormc, }; const FLT_FS: u32 = 1; const FLT_QUAL_BIAS: u32 = 2; const FLT_BLACKLIST: u32 = 4; const FLT_Q30: u32 = 8; const FLT_LOW_FREQ: u32 = 16; const FLT_HOMO_POLY: u32 = 32; const FLT_STR: [(&str, &str); 6] = [ ("strand_bias", "Alleles unevenely distributed across strands", ), ("qual_bias", "Minor allele has lower quality values"), ("blacklist", "Position on black list"), ("q30", "Quality < 30"), ("low_freq", "Low heteroplasmy frequency"), ("homopolymer", "Indel starting in homopolymer region"), ]; pub(crate) struct VcfCalc<'a, 'b, 'c> { pub(crate) ftest: &'a FisherTest, pub(crate) seq_len: usize, pub(crate) ref_seq: &'b [RefPos], pub(crate) homopolymer_limit: u8, pub(crate) all_desc: Vec<AllDesc>, // AllDesc for'standard' 5 alleles (A, C, G, T, Del) pub(crate) cfg: &'c Config, } pub(crate) struct Allele { pub(crate) res: AlleleRes, pub(crate) ix: usize, } pub(crate) struct VcfRes { pub(crate) alleles: Vec<Allele>, pub(crate) adesc: Option<Vec<AllDesc>>, pub(crate) x: usize, pub(crate) phred: u8, } // Additional allele specific results #[derive(Default, Copy, Clone)] struct ExtraRes { flt: u32, avg_qual: f64, fisher_strand: f64, wilcox: f64, } impl<'a, 'b, 'c> VcfCalc<'a, 'b, 'c> { pub fn get_allele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> VcfRes { // Should only be used for single base variants where we expect 5 'alleles' // for A, C, G, T and Del assert_eq!(cts.len(), 5); let indel_flags = [false, false, false, false, true]; let ref_ix = (self.ref_seq[x].base()) as usize; self.est_allele_freqs(x, ref_ix, cts, qcts, &indel_flags) } pub fn get_mallele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { self.est_allele_freqs(x,0, cts, qcts, indel_flags) } pub fn est_allele_freqs(&self, x: usize, ref_ix: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { let n_alls = cts.len(); assert_eq!(n_alls, qcts.len()); let qual_model = self.cfg.qual_table(); // Fold across strands let jcts: Vec<usize> = cts.iter().map(|x| x[0] + x[1]).collect(); // Sort possible alleles by reverse numeric order on counts except that the reference base is always first let alleles: Vec<usize> = { let mut ix: Vec<usize> = (0..n_alls).filter(|x| *x!= ref_ix).collect(); ix.sort_unstable_by(|a, b| jcts[*b].cmp(&jcts[*a])); // Remove alleles where alleles not seen on both strands (apart from reference) let mut ix1 = Vec::with_capacity(n_alls); ix1.push(ref_ix); // Reference allele; for &k in ix.iter() { if cts[k][0] > 0 && cts[k][1] > 0 && cts[k][0] + cts[k][1] > 2 { ix1.push(k) } } ix1 }; let mut mr = freq_mle(&alleles, qcts, qual_model); if log_enabled!(Trace) { trace!("mle freq. estimates"); for &k in alleles.iter() { trace!("{}\t{}\t{}", k, mr.alleles[k].freq, indel_flags[k]); } } // Remove non-reference alleles where the frequencies were estimated below the thresholds let snv_lim = self.cfg.snv_threshold(ThresholdType::Hard); let indel_lim = self.cfg.indel_threshold(ThresholdType::Hard); for ar in mr.alleles.iter_mut() { ar.flag = false } let alleles: Vec<_> = alleles.iter().enumerate() .filter(|(i, &k)| *i == 0 || mr.alleles[k].freq >= match indel_flags[k] { true => indel_lim, false => snv_lim, }) .map(|(_, &k)| k).collect(); for &i in alleles.iter() { mr.alleles[i].flag =true; } // Adjust the frequencies to account for any alleles that have been filtered let tot = alleles.iter().fold(0.0, |s, &x| s + mr.alleles[x].freq); // Rescale if necessary if tot < 1.0 { assert!(tot > 0.0); for ar in mr.alleles.iter_mut() { if ar.flag { ar.freq /= tot } else { ar.freq = 0.0; } } } let ModelRes{alleles: all, phred} = mr; let (all, phred) = (all, phred); let alleles: Vec<_> = alleles.iter().filter(|&&k| all[k].flag) .map(|&k| Allele{ix: k, res: all[k]}).collect(); VcfRes{alleles, adesc: None, x, phred} } // Generate VCF output line for large deletions pub fn del_output(&self, del: &LargeDeletion) -> String { let mut f = String::new(); let cts = del.counts; let fq = del.fq(); let sd = (fq * (1.0 - fq) / (del.n() as f64)).sqrt(); let z = fq / sd; let phred = if z > 10.0 { MAX_PHRED } else { (pnormc(z).log10()*-10.0).round().min(MAX_PHRED as f64) as u8 }; let flt = if phred >= 30 { 0 } else { FLT_Q30 }; // ALT, QUAL, FILTER let _ = write!(f, "<DEL>\t{}\t{}", phred, Filter(flt)); // INFO let _ = write!(f, "\tSVTYPE=DEL;END={};SVLEN={};CIPOS={},{};CILEN={},{}", del.end() + 1, del.length, del.pos_ci(0), del.pos_ci(1), del.len_ci(0), del.len_ci(1)); // FORMAT let _ = write!(f, "\tGT:ADF:ADR:HPL\t0/1:{},{}:{},{}:{:.5}", cts[0][0], cts[1][0], cts[0][1], cts[1][1], fq); f } // Generate Optional String with VCF output line pub fn output(&self, vr: &mut VcfRes, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> Option<String> { let x = vr.x; let raw_depth = cts.iter().fold(0, |t, x| t + x[0] + x[1]); let thresh = 0.05 / (self.seq_len as f64); // Sort alleles by frequency (keeping reference alleles at position 0) vr.alleles[1..].sort_unstable_by(|a1, a2| a2.res.freq.partial_cmp(&a1.res.freq).unwrap()); // Find index of major allele let (major_idx, mj_idx) = vr.alleles.iter().enumerate().max_by(|(_, ar1), (_, ar2)| ar1.res.freq.partial_cmp(&ar2.res.freq).unwrap()) .map(|(i, ar)| (ar.ix, i)).unwrap();
// Filter cutoffs let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter().map(|ar| { // Average quality let (n, s) = qcts[ar.ix].iter().enumerate().fold((0, 0), |(n, s), (q, &ct)| { (n + ct, s + ct * q) }); let avg_qual = if n > 0 { s as f64 / n as f64 } else { 0.0 }; let mut flt = 0; // Fisher strand test let fisher_strand = if ar.ix!= major_idx { let k = ar.ix; let k1 = major_idx; let all_cts = [cts[k][0], cts[k1][0], cts[k][1], cts[k1][1]]; let fs = self.ftest.fisher(&all_cts); if ar.res.freq < 0.75 && fs <= thresh { flt |= FLT_FS } fs } else { 1.0 }; // Wilcoxon-Mann-Whitney test for quality bias between the major (most frequent) // allele and all minor alleles let wilcox = if ar.ix!= major_idx { mann_whitney(qcts, major_idx, ar.ix).unwrap_or(1.0) } else { 1.0 }; // Set allele freq. flags let (lim, pos_adjust) = if desc[ar.ix].len()!= desc[ref_ix].len() { // This is an indel (size difference from reference) let hp_size = (self.ref_seq[x].hpoly() & 0xf).max(self.ref_seq[x + 1].hpoly() & 0xf) + 1; if hp_size >= self.homopolymer_limit { flt |= FLT_HOMO_POLY } (indel_soft_lim, 0) } else { // In a complex variant, a SNV could start a few bases after the location of the variant let x = if ar.ix == ref_ix { 0 } else { // Find position of first base that differs between this allele and the reference desc[ref_ix].iter().zip(desc[ar.ix].iter()).enumerate() .find(|(_, (c1, c2))| *c1!= *c2).map(|(ix, _)| ix as u32).unwrap() }; (snv_soft_lim, x) }; if ar.res.freq < lim { flt |= FLT_LOW_FREQ } // LR flags if ar.res.lr_test < 30 { flt |= FLT_Q30 } // Blacklist if self.cfg.blacklist(x + 1 + pos_adjust as usize) { flt |= FLT_BLACKLIST } ExtraRes{ flt, avg_qual, fisher_strand, wilcox} }).collect(); // Set wilcox allele flags let mjr_qual = all_res[mj_idx].avg_qual; for res in all_res.iter_mut() { if res.wilcox <= thresh && mjr_qual - res.avg_qual > 2.0 { res.flt |= FLT_QUAL_BIAS } } // Genotype call let f0 = vr.alleles[0].res.freq >= 1.0e-5; let gt = match vr.alleles.len() { 1 => String::from("0"), n => if f0 { let mut s = String::from("0"); for i in 1..n { s = format!("{}/{}", s, i); } s } else { let mut s = String::from("1"); for i in 2..n { s = format!("{}/{}", s, i); } s }, }; // Collect global flags let mut flt = if vr.phred < 30 { FLT_Q30 } else { 0 }; // If no non-reference allele has no flags set, then set global flags // to union of all allele flags if all_res[1..].iter().all(|ar| ar.flt!= 0) { for ar in all_res[1..].iter() { flt |= ar.flt } } if vr.alleles.len() > 1 { let mut f = String::new(); write!(f, "{}\t{}", desc[ref_ix], desc[vr.alleles[1].ix]).ok()?; for s in vr.alleles[2..].iter().map(|a| &desc[a.ix]) { write!(f, ",{}", s).ok()?; } write!(f, "\t{}\t{}", vr.phred, Filter(flt)).ok()?; // INFO field write!(f, "\tDP={}", raw_depth).ok()?; for ar in vr.alleles[1..].iter() { if desc[ar.ix].len()!= desc[ref_ix].len() { write!(f, ";INDEL").ok()?; break } } // FORMAT field write!(f, "\tGT:ADF:ADR:HPL:FQSE:AQ:AFLT:QAVG:FSB:QBS").ok()?; // GT field write!(f, "\t{}:{}", gt, cts[vr.alleles[0].ix][0]).ok()?; // ADF for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][0]).ok()?; } // ADR write!(f, ":{}", cts[vr.alleles[0].ix][1]).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][1]).ok()?; } // HPL write!(f, ":{:.5}", vr.alleles[1].res.freq).ok()?; for all in vr.alleles[2..].iter() { write!(f, ",{:.5}", all.res.freq).ok()?; } // FQSE write!(f, ":{:.5}", vr.alleles[0].res.se).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{:.5}", all.res.se).ok()?; } // AQ write!(f, ":{}", vr.alleles[0].res.lr_test).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", all.res.lr_test).ok()?; } // AFLT write!(f, ":{}", Filter(all_res[0].flt)).ok()?; for ar in &all_res[1..] { write!(f, ",{}", Filter(ar.flt)).ok()?; } // QAVG write!(f, ":{:.2}", all_res[0].avg_qual).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2}", ar.avg_qual).ok()?; } // FS write!(f, ":{:.2e}", all_res[0].fisher_strand).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.fisher_strand).ok()?; } // QSB write!(f, ":{:.2e}", all_res[0].wilcox).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.wilcox).ok()?; } Some(f) } else { None } } } #[derive(Default, Copy, Clone)] struct Filter(u32); impl fmt::Display for Filter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.0 == 0 { write!(f, "PASS") } else { let mut first = true; let mut x = self.0; for (s, _) in FLT_STR.iter() { if (x & 1) == 1 { if!first { write!(f, ";{}", s)? } else { first = false; write!(f, "{}", s)? } } x >>= 1; if x == 0 { break; } } Ok(()) } } } pub fn write_vcf_header(sam_hdr: &SamHeader, cfg: &Config) -> io::Result<BufWriter<Writer>> { let vcf_output = format!("{}.vcf", cfg.output_prefix()); let reg = cfg.region(); let mut vcf_wrt = CompressIo::new() .path(vcf_output) .ctype(CompressType::Bgzip) .bufwriter()?; let sample = cfg.sample().unwrap_or("SAMPLE"); // Write VCF Headers writeln!(vcf_wrt, "##fileformat=VCFv4.2")?; writeln!(vcf_wrt, "##contig=<ID={},length={}>", sam_hdr.tid2name(reg.tid()), reg.ctg_size())?; writeln!(vcf_wrt, "##FILTER=<ID=PASS,Description=\"Site contains at least one allele that passes filters\">")?; for (s1, s2) in FLT_STR.iter() { writeln!(vcf_wrt, "##FILTER=<ID={},Description=\"{}\">", s1, s2)?; } writeln!(vcf_wrt, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADF,Number=R,Type=Integer,Description=\"Allelic depths on the forward strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADR,Number=R,Type=Integer,Description=\"Allelic depths on the reverse strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=HPL,Number=A,Type=Float,Description=\"Estimate of heteroplasmy frequency for alternate alleles\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FQSE,Number=R,Type=Float,Description=\"Standard errors of allele frequency estimates per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AQ,Number=R,Type=Float,Description=\"Phred scaled likelihood ratio for each allele (H0: allele freq is zero)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AFLT,Number=R,Type=String,Description=\"Filters per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FSB,Number=R,Type=Float,Description=\"Fisher test of allele strand bias per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QAVG,Number=R,Type=Float,Description=\"Average allele base quality scores\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QBS,Number=R,Type=Float,Description=\"Mann-Whitney-Wilcoxon test of minor allele base quality scores\">")?; writeln!(vcf_wrt, "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Raw read depth\">")?; writeln!(vcf_wrt, "##INFO=<ID=INDEL,Number=0,Type=Flag,Description=\"Indicates that the variant is an INDEL\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVLEN,Number=1,Type=Integer,Description=\"Difference in length between REF and ALT alleles\">")?; writeln!(vcf_wrt, "##INFO=<ID=CIPOS,Number=2,Type=Integer,Description=\"95% confidence interval around POS for structural variants\">")?; writeln!(vcf_wrt, "##INFO=<ID=CILEN,Number=2,Type=Integer,Description=\"95% confidence interval around SVLEN for structural variants\">")?; writeln!(vcf_wrt, "##ALT=<ID=DEL, Description=\"Deletion\">")?; writeln!(vcf_wrt, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{}", sample)?; Ok(vcf_wrt) }
// Reference allele let ref_ix = vr.alleles[0].ix;
random_line_split
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney, cli::{Config, ThresholdType}, fisher::FisherTest, reference::RefPos, alleles::{AllDesc, LargeDeletion}, stat_funcs::pnormc, }; const FLT_FS: u32 = 1; const FLT_QUAL_BIAS: u32 = 2; const FLT_BLACKLIST: u32 = 4; const FLT_Q30: u32 = 8; const FLT_LOW_FREQ: u32 = 16; const FLT_HOMO_POLY: u32 = 32; const FLT_STR: [(&str, &str); 6] = [ ("strand_bias", "Alleles unevenely distributed across strands", ), ("qual_bias", "Minor allele has lower quality values"), ("blacklist", "Position on black list"), ("q30", "Quality < 30"), ("low_freq", "Low heteroplasmy frequency"), ("homopolymer", "Indel starting in homopolymer region"), ]; pub(crate) struct VcfCalc<'a, 'b, 'c> { pub(crate) ftest: &'a FisherTest, pub(crate) seq_len: usize, pub(crate) ref_seq: &'b [RefPos], pub(crate) homopolymer_limit: u8, pub(crate) all_desc: Vec<AllDesc>, // AllDesc for'standard' 5 alleles (A, C, G, T, Del) pub(crate) cfg: &'c Config, } pub(crate) struct Allele { pub(crate) res: AlleleRes, pub(crate) ix: usize, } pub(crate) struct VcfRes { pub(crate) alleles: Vec<Allele>, pub(crate) adesc: Option<Vec<AllDesc>>, pub(crate) x: usize, pub(crate) phred: u8, } // Additional allele specific results #[derive(Default, Copy, Clone)] struct ExtraRes { flt: u32, avg_qual: f64, fisher_strand: f64, wilcox: f64, } impl<'a, 'b, 'c> VcfCalc<'a, 'b, 'c> { pub fn get_allele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> VcfRes { // Should only be used for single base variants where we expect 5 'alleles' // for A, C, G, T and Del assert_eq!(cts.len(), 5); let indel_flags = [false, false, false, false, true]; let ref_ix = (self.ref_seq[x].base()) as usize; self.est_allele_freqs(x, ref_ix, cts, qcts, &indel_flags) } pub fn get_mallele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { self.est_allele_freqs(x,0, cts, qcts, indel_flags) } pub fn est_allele_freqs(&self, x: usize, ref_ix: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { let n_alls = cts.len(); assert_eq!(n_alls, qcts.len()); let qual_model = self.cfg.qual_table(); // Fold across strands let jcts: Vec<usize> = cts.iter().map(|x| x[0] + x[1]).collect(); // Sort possible alleles by reverse numeric order on counts except that the reference base is always first let alleles: Vec<usize> = { let mut ix: Vec<usize> = (0..n_alls).filter(|x| *x!= ref_ix).collect(); ix.sort_unstable_by(|a, b| jcts[*b].cmp(&jcts[*a])); // Remove alleles where alleles not seen on both strands (apart from reference) let mut ix1 = Vec::with_capacity(n_alls); ix1.push(ref_ix); // Reference allele; for &k in ix.iter() { if cts[k][0] > 0 && cts[k][1] > 0 && cts[k][0] + cts[k][1] > 2 { ix1.push(k) } } ix1 }; let mut mr = freq_mle(&alleles, qcts, qual_model); if log_enabled!(Trace) { trace!("mle freq. estimates"); for &k in alleles.iter() { trace!("{}\t{}\t{}", k, mr.alleles[k].freq, indel_flags[k]); } } // Remove non-reference alleles where the frequencies were estimated below the thresholds let snv_lim = self.cfg.snv_threshold(ThresholdType::Hard); let indel_lim = self.cfg.indel_threshold(ThresholdType::Hard); for ar in mr.alleles.iter_mut() { ar.flag = false } let alleles: Vec<_> = alleles.iter().enumerate() .filter(|(i, &k)| *i == 0 || mr.alleles[k].freq >= match indel_flags[k] { true => indel_lim, false => snv_lim, }) .map(|(_, &k)| k).collect(); for &i in alleles.iter() { mr.alleles[i].flag =true; } // Adjust the frequencies to account for any alleles that have been filtered let tot = alleles.iter().fold(0.0, |s, &x| s + mr.alleles[x].freq); // Rescale if necessary if tot < 1.0 { assert!(tot > 0.0); for ar in mr.alleles.iter_mut() { if ar.flag { ar.freq /= tot } else { ar.freq = 0.0; } } } let ModelRes{alleles: all, phred} = mr; let (all, phred) = (all, phred); let alleles: Vec<_> = alleles.iter().filter(|&&k| all[k].flag) .map(|&k| Allele{ix: k, res: all[k]}).collect(); VcfRes{alleles, adesc: None, x, phred} } // Generate VCF output line for large deletions pub fn del_output(&self, del: &LargeDeletion) -> String { let mut f = String::new(); let cts = del.counts; let fq = del.fq(); let sd = (fq * (1.0 - fq) / (del.n() as f64)).sqrt(); let z = fq / sd; let phred = if z > 10.0 { MAX_PHRED } else { (pnormc(z).log10()*-10.0).round().min(MAX_PHRED as f64) as u8 }; let flt = if phred >= 30 { 0 } else { FLT_Q30 }; // ALT, QUAL, FILTER let _ = write!(f, "<DEL>\t{}\t{}", phred, Filter(flt)); // INFO let _ = write!(f, "\tSVTYPE=DEL;END={};SVLEN={};CIPOS={},{};CILEN={},{}", del.end() + 1, del.length, del.pos_ci(0), del.pos_ci(1), del.len_ci(0), del.len_ci(1)); // FORMAT let _ = write!(f, "\tGT:ADF:ADR:HPL\t0/1:{},{}:{},{}:{:.5}", cts[0][0], cts[1][0], cts[0][1], cts[1][1], fq); f } // Generate Optional String with VCF output line pub fn output(&self, vr: &mut VcfRes, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> Option<String>
let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter().map(|ar| { // Average quality let (n, s) = qcts[ar.ix].iter().enumerate().fold((0, 0), |(n, s), (q, &ct)| { (n + ct, s + ct * q) }); let avg_qual = if n > 0 { s as f64 / n as f64 } else { 0.0 }; let mut flt = 0; // Fisher strand test let fisher_strand = if ar.ix!= major_idx { let k = ar.ix; let k1 = major_idx; let all_cts = [cts[k][0], cts[k1][0], cts[k][1], cts[k1][1]]; let fs = self.ftest.fisher(&all_cts); if ar.res.freq < 0.75 && fs <= thresh { flt |= FLT_FS } fs } else { 1.0 }; // Wilcoxon-Mann-Whitney test for quality bias between the major (most frequent) // allele and all minor alleles let wilcox = if ar.ix!= major_idx { mann_whitney(qcts, major_idx, ar.ix).unwrap_or(1.0) } else { 1.0 }; // Set allele freq. flags let (lim, pos_adjust) = if desc[ar.ix].len()!= desc[ref_ix].len() { // This is an indel (size difference from reference) let hp_size = (self.ref_seq[x].hpoly() & 0xf).max(self.ref_seq[x + 1].hpoly() & 0xf) + 1; if hp_size >= self.homopolymer_limit { flt |= FLT_HOMO_POLY } (indel_soft_lim, 0) } else { // In a complex variant, a SNV could start a few bases after the location of the variant let x = if ar.ix == ref_ix { 0 } else { // Find position of first base that differs between this allele and the reference desc[ref_ix].iter().zip(desc[ar.ix].iter()).enumerate() .find(|(_, (c1, c2))| *c1!= *c2).map(|(ix, _)| ix as u32).unwrap() }; (snv_soft_lim, x) }; if ar.res.freq < lim { flt |= FLT_LOW_FREQ } // LR flags if ar.res.lr_test < 30 { flt |= FLT_Q30 } // Blacklist if self.cfg.blacklist(x + 1 + pos_adjust as usize) { flt |= FLT_BLACKLIST } ExtraRes{ flt, avg_qual, fisher_strand, wilcox} }).collect(); // Set wilcox allele flags let mjr_qual = all_res[mj_idx].avg_qual; for res in all_res.iter_mut() { if res.wilcox <= thresh && mjr_qual - res.avg_qual > 2.0 { res.flt |= FLT_QUAL_BIAS } } // Genotype call let f0 = vr.alleles[0].res.freq >= 1.0e-5; let gt = match vr.alleles.len() { 1 => String::from("0"), n => if f0 { let mut s = String::from("0"); for i in 1..n { s = format!("{}/{}", s, i); } s } else { let mut s = String::from("1"); for i in 2..n { s = format!("{}/{}", s, i); } s }, }; // Collect global flags let mut flt = if vr.phred < 30 { FLT_Q30 } else { 0 }; // If no non-reference allele has no flags set, then set global flags // to union of all allele flags if all_res[1..].iter().all(|ar| ar.flt!= 0) { for ar in all_res[1..].iter() { flt |= ar.flt } } if vr.alleles.len() > 1 { let mut f = String::new(); write!(f, "{}\t{}", desc[ref_ix], desc[vr.alleles[1].ix]).ok()?; for s in vr.alleles[2..].iter().map(|a| &desc[a.ix]) { write!(f, ",{}", s).ok()?; } write!(f, "\t{}\t{}", vr.phred, Filter(flt)).ok()?; // INFO field write!(f, "\tDP={}", raw_depth).ok()?; for ar in vr.alleles[1..].iter() { if desc[ar.ix].len()!= desc[ref_ix].len() { write!(f, ";INDEL").ok()?; break } } // FORMAT field write!(f, "\tGT:ADF:ADR:HPL:FQSE:AQ:AFLT:QAVG:FSB:QBS").ok()?; // GT field write!(f, "\t{}:{}", gt, cts[vr.alleles[0].ix][0]).ok()?; // ADF for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][0]).ok()?; } // ADR write!(f, ":{}", cts[vr.alleles[0].ix][1]).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][1]).ok()?; } // HPL write!(f, ":{:.5}", vr.alleles[1].res.freq).ok()?; for all in vr.alleles[2..].iter() { write!(f, ",{:.5}", all.res.freq).ok()?; } // FQSE write!(f, ":{:.5}", vr.alleles[0].res.se).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{:.5}", all.res.se).ok()?; } // AQ write!(f, ":{}", vr.alleles[0].res.lr_test).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", all.res.lr_test).ok()?; } // AFLT write!(f, ":{}", Filter(all_res[0].flt)).ok()?; for ar in &all_res[1..] { write!(f, ",{}", Filter(ar.flt)).ok()?; } // QAVG write!(f, ":{:.2}", all_res[0].avg_qual).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2}", ar.avg_qual).ok()?; } // FS write!(f, ":{:.2e}", all_res[0].fisher_strand).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.fisher_strand).ok()?; } // QSB write!(f, ":{:.2e}", all_res[0].wilcox).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.wilcox).ok()?; } Some(f) } else { None } } } #[derive(Default, Copy, Clone)] struct Filter(u32); impl fmt::Display for Filter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.0 == 0 { write!(f, "PASS") } else { let mut first = true; let mut x = self.0; for (s, _) in FLT_STR.iter() { if (x & 1) == 1 { if!first { write!(f, ";{}", s)? } else { first = false; write!(f, "{}", s)? } } x >>= 1; if x == 0 { break; } } Ok(()) } } } pub fn write_vcf_header(sam_hdr: &SamHeader, cfg: &Config) -> io::Result<BufWriter<Writer>> { let vcf_output = format!("{}.vcf", cfg.output_prefix()); let reg = cfg.region(); let mut vcf_wrt = CompressIo::new() .path(vcf_output) .ctype(CompressType::Bgzip) .bufwriter()?; let sample = cfg.sample().unwrap_or("SAMPLE"); // Write VCF Headers writeln!(vcf_wrt, "##fileformat=VCFv4.2")?; writeln!(vcf_wrt, "##contig=<ID={},length={}>", sam_hdr.tid2name(reg.tid()), reg.ctg_size())?; writeln!(vcf_wrt, "##FILTER=<ID=PASS,Description=\"Site contains at least one allele that passes filters\">")?; for (s1, s2) in FLT_STR.iter() { writeln!(vcf_wrt, "##FILTER=<ID={},Description=\"{}\">", s1, s2)?; } writeln!(vcf_wrt, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADF,Number=R,Type=Integer,Description=\"Allelic depths on the forward strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADR,Number=R,Type=Integer,Description=\"Allelic depths on the reverse strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=HPL,Number=A,Type=Float,Description=\"Estimate of heteroplasmy frequency for alternate alleles\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FQSE,Number=R,Type=Float,Description=\"Standard errors of allele frequency estimates per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AQ,Number=R,Type=Float,Description=\"Phred scaled likelihood ratio for each allele (H0: allele freq is zero)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AFLT,Number=R,Type=String,Description=\"Filters per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FSB,Number=R,Type=Float,Description=\"Fisher test of allele strand bias per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QAVG,Number=R,Type=Float,Description=\"Average allele base quality scores\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QBS,Number=R,Type=Float,Description=\"Mann-Whitney-Wilcoxon test of minor allele base quality scores\">")?; writeln!(vcf_wrt, "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Raw read depth\">")?; writeln!(vcf_wrt, "##INFO=<ID=INDEL,Number=0,Type=Flag,Description=\"Indicates that the variant is an INDEL\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVLEN,Number=1,Type=Integer,Description=\"Difference in length between REF and ALT alleles\">")?; writeln!(vcf_wrt, "##INFO=<ID=CIPOS,Number=2,Type=Integer,Description=\"95% confidence interval around POS for structural variants\">")?; writeln!(vcf_wrt, "##INFO=<ID=CILEN,Number=2,Type=Integer,Description=\"95% confidence interval around SVLEN for structural variants\">")?; writeln!(vcf_wrt, "##ALT=<ID=DEL, Description=\"Deletion\">")?; writeln!(vcf_wrt, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{}", sample)?; Ok(vcf_wrt) }
{ let x = vr.x; let raw_depth = cts.iter().fold(0, |t, x| t + x[0] + x[1]); let thresh = 0.05 / (self.seq_len as f64); // Sort alleles by frequency (keeping reference alleles at position 0) vr.alleles[1..].sort_unstable_by(|a1, a2| a2.res.freq.partial_cmp(&a1.res.freq).unwrap()); // Find index of major allele let (major_idx, mj_idx) = vr.alleles.iter().enumerate().max_by(|(_, ar1), (_, ar2)| ar1.res.freq.partial_cmp(&ar2.res.freq).unwrap()) .map(|(i, ar)| (ar.ix, i)).unwrap(); // Reference allele let ref_ix = vr.alleles[0].ix; // Filter cutoffs
identifier_body
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney, cli::{Config, ThresholdType}, fisher::FisherTest, reference::RefPos, alleles::{AllDesc, LargeDeletion}, stat_funcs::pnormc, }; const FLT_FS: u32 = 1; const FLT_QUAL_BIAS: u32 = 2; const FLT_BLACKLIST: u32 = 4; const FLT_Q30: u32 = 8; const FLT_LOW_FREQ: u32 = 16; const FLT_HOMO_POLY: u32 = 32; const FLT_STR: [(&str, &str); 6] = [ ("strand_bias", "Alleles unevenely distributed across strands", ), ("qual_bias", "Minor allele has lower quality values"), ("blacklist", "Position on black list"), ("q30", "Quality < 30"), ("low_freq", "Low heteroplasmy frequency"), ("homopolymer", "Indel starting in homopolymer region"), ]; pub(crate) struct VcfCalc<'a, 'b, 'c> { pub(crate) ftest: &'a FisherTest, pub(crate) seq_len: usize, pub(crate) ref_seq: &'b [RefPos], pub(crate) homopolymer_limit: u8, pub(crate) all_desc: Vec<AllDesc>, // AllDesc for'standard' 5 alleles (A, C, G, T, Del) pub(crate) cfg: &'c Config, } pub(crate) struct
{ pub(crate) res: AlleleRes, pub(crate) ix: usize, } pub(crate) struct VcfRes { pub(crate) alleles: Vec<Allele>, pub(crate) adesc: Option<Vec<AllDesc>>, pub(crate) x: usize, pub(crate) phred: u8, } // Additional allele specific results #[derive(Default, Copy, Clone)] struct ExtraRes { flt: u32, avg_qual: f64, fisher_strand: f64, wilcox: f64, } impl<'a, 'b, 'c> VcfCalc<'a, 'b, 'c> { pub fn get_allele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> VcfRes { // Should only be used for single base variants where we expect 5 'alleles' // for A, C, G, T and Del assert_eq!(cts.len(), 5); let indel_flags = [false, false, false, false, true]; let ref_ix = (self.ref_seq[x].base()) as usize; self.est_allele_freqs(x, ref_ix, cts, qcts, &indel_flags) } pub fn get_mallele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { self.est_allele_freqs(x,0, cts, qcts, indel_flags) } pub fn est_allele_freqs(&self, x: usize, ref_ix: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { let n_alls = cts.len(); assert_eq!(n_alls, qcts.len()); let qual_model = self.cfg.qual_table(); // Fold across strands let jcts: Vec<usize> = cts.iter().map(|x| x[0] + x[1]).collect(); // Sort possible alleles by reverse numeric order on counts except that the reference base is always first let alleles: Vec<usize> = { let mut ix: Vec<usize> = (0..n_alls).filter(|x| *x!= ref_ix).collect(); ix.sort_unstable_by(|a, b| jcts[*b].cmp(&jcts[*a])); // Remove alleles where alleles not seen on both strands (apart from reference) let mut ix1 = Vec::with_capacity(n_alls); ix1.push(ref_ix); // Reference allele; for &k in ix.iter() { if cts[k][0] > 0 && cts[k][1] > 0 && cts[k][0] + cts[k][1] > 2 { ix1.push(k) } } ix1 }; let mut mr = freq_mle(&alleles, qcts, qual_model); if log_enabled!(Trace) { trace!("mle freq. estimates"); for &k in alleles.iter() { trace!("{}\t{}\t{}", k, mr.alleles[k].freq, indel_flags[k]); } } // Remove non-reference alleles where the frequencies were estimated below the thresholds let snv_lim = self.cfg.snv_threshold(ThresholdType::Hard); let indel_lim = self.cfg.indel_threshold(ThresholdType::Hard); for ar in mr.alleles.iter_mut() { ar.flag = false } let alleles: Vec<_> = alleles.iter().enumerate() .filter(|(i, &k)| *i == 0 || mr.alleles[k].freq >= match indel_flags[k] { true => indel_lim, false => snv_lim, }) .map(|(_, &k)| k).collect(); for &i in alleles.iter() { mr.alleles[i].flag =true; } // Adjust the frequencies to account for any alleles that have been filtered let tot = alleles.iter().fold(0.0, |s, &x| s + mr.alleles[x].freq); // Rescale if necessary if tot < 1.0 { assert!(tot > 0.0); for ar in mr.alleles.iter_mut() { if ar.flag { ar.freq /= tot } else { ar.freq = 0.0; } } } let ModelRes{alleles: all, phred} = mr; let (all, phred) = (all, phred); let alleles: Vec<_> = alleles.iter().filter(|&&k| all[k].flag) .map(|&k| Allele{ix: k, res: all[k]}).collect(); VcfRes{alleles, adesc: None, x, phred} } // Generate VCF output line for large deletions pub fn del_output(&self, del: &LargeDeletion) -> String { let mut f = String::new(); let cts = del.counts; let fq = del.fq(); let sd = (fq * (1.0 - fq) / (del.n() as f64)).sqrt(); let z = fq / sd; let phred = if z > 10.0 { MAX_PHRED } else { (pnormc(z).log10()*-10.0).round().min(MAX_PHRED as f64) as u8 }; let flt = if phred >= 30 { 0 } else { FLT_Q30 }; // ALT, QUAL, FILTER let _ = write!(f, "<DEL>\t{}\t{}", phred, Filter(flt)); // INFO let _ = write!(f, "\tSVTYPE=DEL;END={};SVLEN={};CIPOS={},{};CILEN={},{}", del.end() + 1, del.length, del.pos_ci(0), del.pos_ci(1), del.len_ci(0), del.len_ci(1)); // FORMAT let _ = write!(f, "\tGT:ADF:ADR:HPL\t0/1:{},{}:{},{}:{:.5}", cts[0][0], cts[1][0], cts[0][1], cts[1][1], fq); f } // Generate Optional String with VCF output line pub fn output(&self, vr: &mut VcfRes, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> Option<String> { let x = vr.x; let raw_depth = cts.iter().fold(0, |t, x| t + x[0] + x[1]); let thresh = 0.05 / (self.seq_len as f64); // Sort alleles by frequency (keeping reference alleles at position 0) vr.alleles[1..].sort_unstable_by(|a1, a2| a2.res.freq.partial_cmp(&a1.res.freq).unwrap()); // Find index of major allele let (major_idx, mj_idx) = vr.alleles.iter().enumerate().max_by(|(_, ar1), (_, ar2)| ar1.res.freq.partial_cmp(&ar2.res.freq).unwrap()) .map(|(i, ar)| (ar.ix, i)).unwrap(); // Reference allele let ref_ix = vr.alleles[0].ix; // Filter cutoffs let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter().map(|ar| { // Average quality let (n, s) = qcts[ar.ix].iter().enumerate().fold((0, 0), |(n, s), (q, &ct)| { (n + ct, s + ct * q) }); let avg_qual = if n > 0 { s as f64 / n as f64 } else { 0.0 }; let mut flt = 0; // Fisher strand test let fisher_strand = if ar.ix!= major_idx { let k = ar.ix; let k1 = major_idx; let all_cts = [cts[k][0], cts[k1][0], cts[k][1], cts[k1][1]]; let fs = self.ftest.fisher(&all_cts); if ar.res.freq < 0.75 && fs <= thresh { flt |= FLT_FS } fs } else { 1.0 }; // Wilcoxon-Mann-Whitney test for quality bias between the major (most frequent) // allele and all minor alleles let wilcox = if ar.ix!= major_idx { mann_whitney(qcts, major_idx, ar.ix).unwrap_or(1.0) } else { 1.0 }; // Set allele freq. flags let (lim, pos_adjust) = if desc[ar.ix].len()!= desc[ref_ix].len() { // This is an indel (size difference from reference) let hp_size = (self.ref_seq[x].hpoly() & 0xf).max(self.ref_seq[x + 1].hpoly() & 0xf) + 1; if hp_size >= self.homopolymer_limit { flt |= FLT_HOMO_POLY } (indel_soft_lim, 0) } else { // In a complex variant, a SNV could start a few bases after the location of the variant let x = if ar.ix == ref_ix { 0 } else { // Find position of first base that differs between this allele and the reference desc[ref_ix].iter().zip(desc[ar.ix].iter()).enumerate() .find(|(_, (c1, c2))| *c1!= *c2).map(|(ix, _)| ix as u32).unwrap() }; (snv_soft_lim, x) }; if ar.res.freq < lim { flt |= FLT_LOW_FREQ } // LR flags if ar.res.lr_test < 30 { flt |= FLT_Q30 } // Blacklist if self.cfg.blacklist(x + 1 + pos_adjust as usize) { flt |= FLT_BLACKLIST } ExtraRes{ flt, avg_qual, fisher_strand, wilcox} }).collect(); // Set wilcox allele flags let mjr_qual = all_res[mj_idx].avg_qual; for res in all_res.iter_mut() { if res.wilcox <= thresh && mjr_qual - res.avg_qual > 2.0 { res.flt |= FLT_QUAL_BIAS } } // Genotype call let f0 = vr.alleles[0].res.freq >= 1.0e-5; let gt = match vr.alleles.len() { 1 => String::from("0"), n => if f0 { let mut s = String::from("0"); for i in 1..n { s = format!("{}/{}", s, i); } s } else { let mut s = String::from("1"); for i in 2..n { s = format!("{}/{}", s, i); } s }, }; // Collect global flags let mut flt = if vr.phred < 30 { FLT_Q30 } else { 0 }; // If no non-reference allele has no flags set, then set global flags // to union of all allele flags if all_res[1..].iter().all(|ar| ar.flt!= 0) { for ar in all_res[1..].iter() { flt |= ar.flt } } if vr.alleles.len() > 1 { let mut f = String::new(); write!(f, "{}\t{}", desc[ref_ix], desc[vr.alleles[1].ix]).ok()?; for s in vr.alleles[2..].iter().map(|a| &desc[a.ix]) { write!(f, ",{}", s).ok()?; } write!(f, "\t{}\t{}", vr.phred, Filter(flt)).ok()?; // INFO field write!(f, "\tDP={}", raw_depth).ok()?; for ar in vr.alleles[1..].iter() { if desc[ar.ix].len()!= desc[ref_ix].len() { write!(f, ";INDEL").ok()?; break } } // FORMAT field write!(f, "\tGT:ADF:ADR:HPL:FQSE:AQ:AFLT:QAVG:FSB:QBS").ok()?; // GT field write!(f, "\t{}:{}", gt, cts[vr.alleles[0].ix][0]).ok()?; // ADF for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][0]).ok()?; } // ADR write!(f, ":{}", cts[vr.alleles[0].ix][1]).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][1]).ok()?; } // HPL write!(f, ":{:.5}", vr.alleles[1].res.freq).ok()?; for all in vr.alleles[2..].iter() { write!(f, ",{:.5}", all.res.freq).ok()?; } // FQSE write!(f, ":{:.5}", vr.alleles[0].res.se).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{:.5}", all.res.se).ok()?; } // AQ write!(f, ":{}", vr.alleles[0].res.lr_test).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", all.res.lr_test).ok()?; } // AFLT write!(f, ":{}", Filter(all_res[0].flt)).ok()?; for ar in &all_res[1..] { write!(f, ",{}", Filter(ar.flt)).ok()?; } // QAVG write!(f, ":{:.2}", all_res[0].avg_qual).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2}", ar.avg_qual).ok()?; } // FS write!(f, ":{:.2e}", all_res[0].fisher_strand).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.fisher_strand).ok()?; } // QSB write!(f, ":{:.2e}", all_res[0].wilcox).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.wilcox).ok()?; } Some(f) } else { None } } } #[derive(Default, Copy, Clone)] struct Filter(u32); impl fmt::Display for Filter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.0 == 0 { write!(f, "PASS") } else { let mut first = true; let mut x = self.0; for (s, _) in FLT_STR.iter() { if (x & 1) == 1 { if!first { write!(f, ";{}", s)? } else { first = false; write!(f, "{}", s)? } } x >>= 1; if x == 0 { break; } } Ok(()) } } } pub fn write_vcf_header(sam_hdr: &SamHeader, cfg: &Config) -> io::Result<BufWriter<Writer>> { let vcf_output = format!("{}.vcf", cfg.output_prefix()); let reg = cfg.region(); let mut vcf_wrt = CompressIo::new() .path(vcf_output) .ctype(CompressType::Bgzip) .bufwriter()?; let sample = cfg.sample().unwrap_or("SAMPLE"); // Write VCF Headers writeln!(vcf_wrt, "##fileformat=VCFv4.2")?; writeln!(vcf_wrt, "##contig=<ID={},length={}>", sam_hdr.tid2name(reg.tid()), reg.ctg_size())?; writeln!(vcf_wrt, "##FILTER=<ID=PASS,Description=\"Site contains at least one allele that passes filters\">")?; for (s1, s2) in FLT_STR.iter() { writeln!(vcf_wrt, "##FILTER=<ID={},Description=\"{}\">", s1, s2)?; } writeln!(vcf_wrt, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADF,Number=R,Type=Integer,Description=\"Allelic depths on the forward strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADR,Number=R,Type=Integer,Description=\"Allelic depths on the reverse strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=HPL,Number=A,Type=Float,Description=\"Estimate of heteroplasmy frequency for alternate alleles\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FQSE,Number=R,Type=Float,Description=\"Standard errors of allele frequency estimates per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AQ,Number=R,Type=Float,Description=\"Phred scaled likelihood ratio for each allele (H0: allele freq is zero)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AFLT,Number=R,Type=String,Description=\"Filters per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FSB,Number=R,Type=Float,Description=\"Fisher test of allele strand bias per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QAVG,Number=R,Type=Float,Description=\"Average allele base quality scores\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QBS,Number=R,Type=Float,Description=\"Mann-Whitney-Wilcoxon test of minor allele base quality scores\">")?; writeln!(vcf_wrt, "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Raw read depth\">")?; writeln!(vcf_wrt, "##INFO=<ID=INDEL,Number=0,Type=Flag,Description=\"Indicates that the variant is an INDEL\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVLEN,Number=1,Type=Integer,Description=\"Difference in length between REF and ALT alleles\">")?; writeln!(vcf_wrt, "##INFO=<ID=CIPOS,Number=2,Type=Integer,Description=\"95% confidence interval around POS for structural variants\">")?; writeln!(vcf_wrt, "##INFO=<ID=CILEN,Number=2,Type=Integer,Description=\"95% confidence interval around SVLEN for structural variants\">")?; writeln!(vcf_wrt, "##ALT=<ID=DEL, Description=\"Deletion\">")?; writeln!(vcf_wrt, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{}", sample)?; Ok(vcf_wrt) }
Allele
identifier_name
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney, cli::{Config, ThresholdType}, fisher::FisherTest, reference::RefPos, alleles::{AllDesc, LargeDeletion}, stat_funcs::pnormc, }; const FLT_FS: u32 = 1; const FLT_QUAL_BIAS: u32 = 2; const FLT_BLACKLIST: u32 = 4; const FLT_Q30: u32 = 8; const FLT_LOW_FREQ: u32 = 16; const FLT_HOMO_POLY: u32 = 32; const FLT_STR: [(&str, &str); 6] = [ ("strand_bias", "Alleles unevenely distributed across strands", ), ("qual_bias", "Minor allele has lower quality values"), ("blacklist", "Position on black list"), ("q30", "Quality < 30"), ("low_freq", "Low heteroplasmy frequency"), ("homopolymer", "Indel starting in homopolymer region"), ]; pub(crate) struct VcfCalc<'a, 'b, 'c> { pub(crate) ftest: &'a FisherTest, pub(crate) seq_len: usize, pub(crate) ref_seq: &'b [RefPos], pub(crate) homopolymer_limit: u8, pub(crate) all_desc: Vec<AllDesc>, // AllDesc for'standard' 5 alleles (A, C, G, T, Del) pub(crate) cfg: &'c Config, } pub(crate) struct Allele { pub(crate) res: AlleleRes, pub(crate) ix: usize, } pub(crate) struct VcfRes { pub(crate) alleles: Vec<Allele>, pub(crate) adesc: Option<Vec<AllDesc>>, pub(crate) x: usize, pub(crate) phred: u8, } // Additional allele specific results #[derive(Default, Copy, Clone)] struct ExtraRes { flt: u32, avg_qual: f64, fisher_strand: f64, wilcox: f64, } impl<'a, 'b, 'c> VcfCalc<'a, 'b, 'c> { pub fn get_allele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> VcfRes { // Should only be used for single base variants where we expect 5 'alleles' // for A, C, G, T and Del assert_eq!(cts.len(), 5); let indel_flags = [false, false, false, false, true]; let ref_ix = (self.ref_seq[x].base()) as usize; self.est_allele_freqs(x, ref_ix, cts, qcts, &indel_flags) } pub fn get_mallele_freqs(&self, x: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { self.est_allele_freqs(x,0, cts, qcts, indel_flags) } pub fn est_allele_freqs(&self, x: usize, ref_ix: usize, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]], indel_flags: &[bool]) -> VcfRes { let n_alls = cts.len(); assert_eq!(n_alls, qcts.len()); let qual_model = self.cfg.qual_table(); // Fold across strands let jcts: Vec<usize> = cts.iter().map(|x| x[0] + x[1]).collect(); // Sort possible alleles by reverse numeric order on counts except that the reference base is always first let alleles: Vec<usize> = { let mut ix: Vec<usize> = (0..n_alls).filter(|x| *x!= ref_ix).collect(); ix.sort_unstable_by(|a, b| jcts[*b].cmp(&jcts[*a])); // Remove alleles where alleles not seen on both strands (apart from reference) let mut ix1 = Vec::with_capacity(n_alls); ix1.push(ref_ix); // Reference allele; for &k in ix.iter() { if cts[k][0] > 0 && cts[k][1] > 0 && cts[k][0] + cts[k][1] > 2 { ix1.push(k) } } ix1 }; let mut mr = freq_mle(&alleles, qcts, qual_model); if log_enabled!(Trace) { trace!("mle freq. estimates"); for &k in alleles.iter() { trace!("{}\t{}\t{}", k, mr.alleles[k].freq, indel_flags[k]); } } // Remove non-reference alleles where the frequencies were estimated below the thresholds let snv_lim = self.cfg.snv_threshold(ThresholdType::Hard); let indel_lim = self.cfg.indel_threshold(ThresholdType::Hard); for ar in mr.alleles.iter_mut() { ar.flag = false } let alleles: Vec<_> = alleles.iter().enumerate() .filter(|(i, &k)| *i == 0 || mr.alleles[k].freq >= match indel_flags[k] { true => indel_lim, false => snv_lim, }) .map(|(_, &k)| k).collect(); for &i in alleles.iter() { mr.alleles[i].flag =true; } // Adjust the frequencies to account for any alleles that have been filtered let tot = alleles.iter().fold(0.0, |s, &x| s + mr.alleles[x].freq); // Rescale if necessary if tot < 1.0 { assert!(tot > 0.0); for ar in mr.alleles.iter_mut() { if ar.flag { ar.freq /= tot } else { ar.freq = 0.0; } } } let ModelRes{alleles: all, phred} = mr; let (all, phred) = (all, phred); let alleles: Vec<_> = alleles.iter().filter(|&&k| all[k].flag) .map(|&k| Allele{ix: k, res: all[k]}).collect(); VcfRes{alleles, adesc: None, x, phred} } // Generate VCF output line for large deletions pub fn del_output(&self, del: &LargeDeletion) -> String { let mut f = String::new(); let cts = del.counts; let fq = del.fq(); let sd = (fq * (1.0 - fq) / (del.n() as f64)).sqrt(); let z = fq / sd; let phred = if z > 10.0 { MAX_PHRED } else { (pnormc(z).log10()*-10.0).round().min(MAX_PHRED as f64) as u8 }; let flt = if phred >= 30 { 0 } else { FLT_Q30 }; // ALT, QUAL, FILTER let _ = write!(f, "<DEL>\t{}\t{}", phred, Filter(flt)); // INFO let _ = write!(f, "\tSVTYPE=DEL;END={};SVLEN={};CIPOS={},{};CILEN={},{}", del.end() + 1, del.length, del.pos_ci(0), del.pos_ci(1), del.len_ci(0), del.len_ci(1)); // FORMAT let _ = write!(f, "\tGT:ADF:ADR:HPL\t0/1:{},{}:{},{}:{:.5}", cts[0][0], cts[1][0], cts[0][1], cts[1][1], fq); f } // Generate Optional String with VCF output line pub fn output(&self, vr: &mut VcfRes, cts: &[[usize; 2]], qcts: &[[usize; N_QUAL]]) -> Option<String> { let x = vr.x; let raw_depth = cts.iter().fold(0, |t, x| t + x[0] + x[1]); let thresh = 0.05 / (self.seq_len as f64); // Sort alleles by frequency (keeping reference alleles at position 0) vr.alleles[1..].sort_unstable_by(|a1, a2| a2.res.freq.partial_cmp(&a1.res.freq).unwrap()); // Find index of major allele let (major_idx, mj_idx) = vr.alleles.iter().enumerate().max_by(|(_, ar1), (_, ar2)| ar1.res.freq.partial_cmp(&ar2.res.freq).unwrap()) .map(|(i, ar)| (ar.ix, i)).unwrap(); // Reference allele let ref_ix = vr.alleles[0].ix; // Filter cutoffs let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter().map(|ar| { // Average quality let (n, s) = qcts[ar.ix].iter().enumerate().fold((0, 0), |(n, s), (q, &ct)| { (n + ct, s + ct * q) }); let avg_qual = if n > 0 { s as f64 / n as f64 } else { 0.0 }; let mut flt = 0; // Fisher strand test let fisher_strand = if ar.ix!= major_idx
else { 1.0 }; // Wilcoxon-Mann-Whitney test for quality bias between the major (most frequent) // allele and all minor alleles let wilcox = if ar.ix!= major_idx { mann_whitney(qcts, major_idx, ar.ix).unwrap_or(1.0) } else { 1.0 }; // Set allele freq. flags let (lim, pos_adjust) = if desc[ar.ix].len()!= desc[ref_ix].len() { // This is an indel (size difference from reference) let hp_size = (self.ref_seq[x].hpoly() & 0xf).max(self.ref_seq[x + 1].hpoly() & 0xf) + 1; if hp_size >= self.homopolymer_limit { flt |= FLT_HOMO_POLY } (indel_soft_lim, 0) } else { // In a complex variant, a SNV could start a few bases after the location of the variant let x = if ar.ix == ref_ix { 0 } else { // Find position of first base that differs between this allele and the reference desc[ref_ix].iter().zip(desc[ar.ix].iter()).enumerate() .find(|(_, (c1, c2))| *c1!= *c2).map(|(ix, _)| ix as u32).unwrap() }; (snv_soft_lim, x) }; if ar.res.freq < lim { flt |= FLT_LOW_FREQ } // LR flags if ar.res.lr_test < 30 { flt |= FLT_Q30 } // Blacklist if self.cfg.blacklist(x + 1 + pos_adjust as usize) { flt |= FLT_BLACKLIST } ExtraRes{ flt, avg_qual, fisher_strand, wilcox} }).collect(); // Set wilcox allele flags let mjr_qual = all_res[mj_idx].avg_qual; for res in all_res.iter_mut() { if res.wilcox <= thresh && mjr_qual - res.avg_qual > 2.0 { res.flt |= FLT_QUAL_BIAS } } // Genotype call let f0 = vr.alleles[0].res.freq >= 1.0e-5; let gt = match vr.alleles.len() { 1 => String::from("0"), n => if f0 { let mut s = String::from("0"); for i in 1..n { s = format!("{}/{}", s, i); } s } else { let mut s = String::from("1"); for i in 2..n { s = format!("{}/{}", s, i); } s }, }; // Collect global flags let mut flt = if vr.phred < 30 { FLT_Q30 } else { 0 }; // If no non-reference allele has no flags set, then set global flags // to union of all allele flags if all_res[1..].iter().all(|ar| ar.flt!= 0) { for ar in all_res[1..].iter() { flt |= ar.flt } } if vr.alleles.len() > 1 { let mut f = String::new(); write!(f, "{}\t{}", desc[ref_ix], desc[vr.alleles[1].ix]).ok()?; for s in vr.alleles[2..].iter().map(|a| &desc[a.ix]) { write!(f, ",{}", s).ok()?; } write!(f, "\t{}\t{}", vr.phred, Filter(flt)).ok()?; // INFO field write!(f, "\tDP={}", raw_depth).ok()?; for ar in vr.alleles[1..].iter() { if desc[ar.ix].len()!= desc[ref_ix].len() { write!(f, ";INDEL").ok()?; break } } // FORMAT field write!(f, "\tGT:ADF:ADR:HPL:FQSE:AQ:AFLT:QAVG:FSB:QBS").ok()?; // GT field write!(f, "\t{}:{}", gt, cts[vr.alleles[0].ix][0]).ok()?; // ADF for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][0]).ok()?; } // ADR write!(f, ":{}", cts[vr.alleles[0].ix][1]).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", cts[all.ix][1]).ok()?; } // HPL write!(f, ":{:.5}", vr.alleles[1].res.freq).ok()?; for all in vr.alleles[2..].iter() { write!(f, ",{:.5}", all.res.freq).ok()?; } // FQSE write!(f, ":{:.5}", vr.alleles[0].res.se).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{:.5}", all.res.se).ok()?; } // AQ write!(f, ":{}", vr.alleles[0].res.lr_test).ok()?; for all in vr.alleles[1..].iter() { write!(f, ",{}", all.res.lr_test).ok()?; } // AFLT write!(f, ":{}", Filter(all_res[0].flt)).ok()?; for ar in &all_res[1..] { write!(f, ",{}", Filter(ar.flt)).ok()?; } // QAVG write!(f, ":{:.2}", all_res[0].avg_qual).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2}", ar.avg_qual).ok()?; } // FS write!(f, ":{:.2e}", all_res[0].fisher_strand).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.fisher_strand).ok()?; } // QSB write!(f, ":{:.2e}", all_res[0].wilcox).ok()?; for ar in &all_res[1..] { write!(f, ",{:.2e}", ar.wilcox).ok()?; } Some(f) } else { None } } } #[derive(Default, Copy, Clone)] struct Filter(u32); impl fmt::Display for Filter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.0 == 0 { write!(f, "PASS") } else { let mut first = true; let mut x = self.0; for (s, _) in FLT_STR.iter() { if (x & 1) == 1 { if!first { write!(f, ";{}", s)? } else { first = false; write!(f, "{}", s)? } } x >>= 1; if x == 0 { break; } } Ok(()) } } } pub fn write_vcf_header(sam_hdr: &SamHeader, cfg: &Config) -> io::Result<BufWriter<Writer>> { let vcf_output = format!("{}.vcf", cfg.output_prefix()); let reg = cfg.region(); let mut vcf_wrt = CompressIo::new() .path(vcf_output) .ctype(CompressType::Bgzip) .bufwriter()?; let sample = cfg.sample().unwrap_or("SAMPLE"); // Write VCF Headers writeln!(vcf_wrt, "##fileformat=VCFv4.2")?; writeln!(vcf_wrt, "##contig=<ID={},length={}>", sam_hdr.tid2name(reg.tid()), reg.ctg_size())?; writeln!(vcf_wrt, "##FILTER=<ID=PASS,Description=\"Site contains at least one allele that passes filters\">")?; for (s1, s2) in FLT_STR.iter() { writeln!(vcf_wrt, "##FILTER=<ID={},Description=\"{}\">", s1, s2)?; } writeln!(vcf_wrt, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADF,Number=R,Type=Integer,Description=\"Allelic depths on the forward strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=ADR,Number=R,Type=Integer,Description=\"Allelic depths on the reverse strand (high-quality bases)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=HPL,Number=A,Type=Float,Description=\"Estimate of heteroplasmy frequency for alternate alleles\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FQSE,Number=R,Type=Float,Description=\"Standard errors of allele frequency estimates per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AQ,Number=R,Type=Float,Description=\"Phred scaled likelihood ratio for each allele (H0: allele freq is zero)\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=AFLT,Number=R,Type=String,Description=\"Filters per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=FSB,Number=R,Type=Float,Description=\"Fisher test of allele strand bias per allele\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QAVG,Number=R,Type=Float,Description=\"Average allele base quality scores\">")?; writeln!(vcf_wrt, "##FORMAT=<ID=QBS,Number=R,Type=Float,Description=\"Mann-Whitney-Wilcoxon test of minor allele base quality scores\">")?; writeln!(vcf_wrt, "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Raw read depth\">")?; writeln!(vcf_wrt, "##INFO=<ID=INDEL,Number=0,Type=Flag,Description=\"Indicates that the variant is an INDEL\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of structural variant\">")?; writeln!(vcf_wrt, "##INFO=<ID=SVLEN,Number=1,Type=Integer,Description=\"Difference in length between REF and ALT alleles\">")?; writeln!(vcf_wrt, "##INFO=<ID=CIPOS,Number=2,Type=Integer,Description=\"95% confidence interval around POS for structural variants\">")?; writeln!(vcf_wrt, "##INFO=<ID=CILEN,Number=2,Type=Integer,Description=\"95% confidence interval around SVLEN for structural variants\">")?; writeln!(vcf_wrt, "##ALT=<ID=DEL, Description=\"Deletion\">")?; writeln!(vcf_wrt, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{}", sample)?; Ok(vcf_wrt) }
{ let k = ar.ix; let k1 = major_idx; let all_cts = [cts[k][0], cts[k1][0], cts[k][1], cts[k1][1]]; let fs = self.ftest.fisher(&all_cts); if ar.res.freq < 0.75 && fs <= thresh { flt |= FLT_FS } fs }
conditional_block
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use crate::utils::tabs; // HACK: WordDiff should probably be a distinct top-level line state pub fn is_word_diff() -> bool { #[cfg(not(test))] { *CACHED_IS_WORD_DIFF } #[cfg(test)] { compute_is_word_diff() } } lazy_static! { static ref CACHED_IS_WORD_DIFF: bool = compute_is_word_diff(); } fn compute_is_word_diff() -> bool { match &*process::calling_process() { CallingProcess::GitDiff(cmd_line) | CallingProcess::GitShow(cmd_line, _) | CallingProcess::GitLog(cmd_line) | CallingProcess::GitReflog(cmd_line) => { cmd_line.long_options.contains("--word-diff") || cmd_line.long_options.contains("--word-diff-regex") || cmd_line.long_options.contains("--color-words") } _ => false, } } impl<'a> StateMachine<'a> { #[inline] fn test_hunk_line(&self) -> bool { matches!( self.state, State::HunkHeader(_, _, _, _) | State::HunkZero(_, _) | State::HunkMinus(_, _) | State::HunkPlus(_, _) ) } /// Handle a hunk line, i.e. a minus line, a plus line, or an unchanged line. // In the case of a minus or plus line, we store the line in a // buffer. When we exit the changed region we process the collected // minus and plus lines jointly, in order to paint detailed // highlighting according to inferred edit operations. In the case of // an unchanged line, we paint it immediately. pub fn handle_hunk_line(&mut self) -> std::io::Result<bool>
self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, raw_line)) => { if let HunkPlus(_, _) = self.state { // We have just entered a new subhunk; process the previous one // and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); } let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkMinus(diff_type, raw_line); self.painter.minus_lines.push((line, state.clone())); state } Some(HunkPlus(diff_type, raw_line)) => { let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkPlus(diff_type, raw_line); self.painter.plus_lines.push((line, state.clone())); state } Some(HunkZero(diff_type, raw_line)) => { // We are in a zero (unchanged) line, therefore we have just exited a subhunk (a // sequence of consecutive minus (removed) and/or plus (added) lines). Process that // subhunk and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); let n_parents = if is_word_diff() { 0 } else { diff_type.n_parents() }; let line = prepare(&self.line, n_parents, self.config); let state = State::HunkZero(diff_type, raw_line); self.painter.paint_zero_line(&line, state.clone()); state } _ => { // The first character here could be e.g. '\' from '\ No newline at end of file'. This // is not a hunk line, but the parser does not have a more accurate state corresponding // to this. self.painter.paint_buffered_minus_and_plus_lines(); self.painter .output_buffer .push_str(&tabs::expand(&self.raw_line, &self.config.tab_cfg)); self.painter.output_buffer.push('\n'); State::HunkZero(Unified, None) } }; self.painter.emit()?; Ok(true) } } // Return Some(prepared_raw_line) if delta should emit this line raw. fn maybe_raw_line( raw_line: &str, state_style_is_raw: bool, n_parents: usize, non_raw_styles: &[style::Style], config: &Config, ) -> Option<String> { let emit_raw_line = is_word_diff() || config.inspect_raw_lines == cli::InspectRawLines::True && style::line_has_style_other_than(raw_line, non_raw_styles) || state_style_is_raw; if emit_raw_line { Some(prepare_raw_line(raw_line, n_parents, config)) } else { None } } // Return the new state corresponding to `new_line`, given the previous state. A return value of // None means that `new_line` is not recognized as a hunk line. fn new_line_state( new_line: &str, new_raw_line: &str, prev_state: &State, config: &Config, ) -> Option<State> { use DiffType::*; use MergeParents::*; use State::*; if is_word_diff() { return Some(HunkZero( Unified, maybe_raw_line(new_raw_line, config.zero_style.is_raw, 0, &[], config), )); } // 1. Given the previous line state, compute the new line diff type. These are basically the // same, except that a string prefix is converted into an integer number of parents (prefix // length). let diff_type = match prev_state { HunkMinus(Unified, _) | HunkZero(Unified, _) | HunkPlus(Unified, _) | HunkHeader(Unified, _, _, _) => Unified, HunkHeader(Combined(Number(n), InMergeConflict::No), _, _, _) => { Combined(Number(*n), InMergeConflict::No) } // The prefixes are specific to the previous line, but the number of merge parents remains // equal to the prefix length. HunkHeader(Combined(Prefix(prefix), InMergeConflict::No), _, _, _) => { Combined(Number(prefix.len()), InMergeConflict::No) } HunkMinus(Combined(Prefix(prefix), in_merge_conflict), _) | HunkZero(Combined(Prefix(prefix), in_merge_conflict), _) | HunkPlus(Combined(Prefix(prefix), in_merge_conflict), _) => { Combined(Number(prefix.len()), in_merge_conflict.clone()) } HunkMinus(Combined(Number(n), in_merge_conflict), _) | HunkZero(Combined(Number(n), in_merge_conflict), _) | HunkPlus(Combined(Number(n), in_merge_conflict), _) => { Combined(Number(*n), in_merge_conflict.clone()) } _ => delta_unreachable(&format!( "Unexpected state in new_line_state: {prev_state:?}", )), }; // 2. Given the new diff state, and the new line, compute the new prefix. let (prefix_char, prefix, in_merge_conflict) = match diff_type.clone() { Unified => (new_line.chars().next(), None, None), Combined(Number(n_parents), in_merge_conflict) => { let prefix = &new_line[..min(n_parents, new_line.len())]; let prefix_char = match prefix.chars().find(|c| c == &'-' || c == &'+') { Some(c) => Some(c), None => match prefix.chars().find(|c| c!= &' ') { None => Some(' '), Some(_) => None, }, }; ( prefix_char, Some(prefix.to_string()), Some(in_merge_conflict), ) } _ => delta_unreachable(""), }; let maybe_minus_raw_line = || { maybe_raw_line( new_raw_line, config.minus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_MINUS_STYLE, config.git_minus_style], config, ) }; let maybe_zero_raw_line = || { maybe_raw_line( new_raw_line, config.zero_style.is_raw, diff_type.n_parents(), &[], config, ) }; let maybe_plus_raw_line = || { maybe_raw_line( new_raw_line, config.plus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_PLUS_STYLE, config.git_plus_style], config, ) }; // 3. Given the new prefix, compute the full new line state...except without its raw_line, which // is added later. TODO: that is not a sensible design. match (prefix_char, prefix, in_merge_conflict) { (Some('-'), None, None) => Some(HunkMinus(Unified, maybe_minus_raw_line())), (Some(' '), None, None) => Some(HunkZero(Unified, maybe_zero_raw_line())), (Some('+'), None, None) => Some(HunkPlus(Unified, maybe_plus_raw_line())), (Some('-'), Some(prefix), Some(in_merge_conflict)) => Some(HunkMinus( Combined(Prefix(prefix), in_merge_conflict), maybe_minus_raw_line(), )), (Some(' '), Some(prefix), Some(in_merge_conflict)) => Some(HunkZero( Combined(Prefix(prefix), in_merge_conflict), maybe_zero_raw_line(), )), (Some('+'), Some(prefix), Some(in_merge_conflict)) => Some(HunkPlus( Combined(Prefix(prefix), in_merge_conflict), maybe_plus_raw_line(), )), _ => None, } } #[cfg(test)] mod tests { use crate::tests::integration_test_utils::DeltaTest; mod word_diff { use super::*; #[test] fn test_word_diff() { DeltaTest::with_args(&[]) .with_calling_process("git diff --word-diff") .explain_ansi() .with_input(GIT_DIFF_WORD_DIFF) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)[-aaa-](green){+bbb+}(normal) ", ); } #[test] fn test_color_words() { DeltaTest::with_args(&[]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)aaa(green)bbb(normal) ", ); } #[test] #[ignore] // FIXME fn test_color_words_map_styles() { DeltaTest::with_args(&[ "--map-styles", "red => bold yellow #dddddd, green => bold blue #dddddd", ]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .inspect() .expect_after_skip( 11, r##" #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (bold yellow "#dddddd")aaa(bold blue "#dddddd")bbb(normal) "##, ); } #[test] fn test_hunk_line_style_raw() { DeltaTest::with_args(&["--minus-style", "raw", "--plus-style", "raw"]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (red)aaa(normal) (green)bbb(normal) ", ); } #[test] fn test_hunk_line_style_raw_map_styles() { DeltaTest::with_args(&[ "--minus-style", "raw", "--plus-style", "raw", "--map-styles", "red => bold blue, green => dim yellow", ]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (bold blue)aaa(normal) (dim yellow)bbb(normal) ", ); } const GIT_DIFF_WITH_COLOR: &str = r#"\ commit 3ef7fba7258fe473f1d8befff367bb793c786107 Author: Dan Davison <[email protected]> Date: Mon Dec 13 22:54:43 2021 -0500 753 Test file diff --git a/file b/file index 72943a1..f761ec1 100644 --- a/file +++ b/file @@ -1 +1 @@ -aaa +bbb "#; const GIT_DIFF_COLOR_WORDS: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ aaabbb "#; const GIT_DIFF_WORD_DIFF: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ [-aaa-]{+bbb+} "#; } }
{ use DiffType::*; use State::*; // A true hunk line should start with one of: '+', '-', ' '. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if !self.test_hunk_line() { return Ok(false); } // Don't let the line buffers become arbitrarily large -- if we // were to allow that, then for a large deleted/added file we // would process the entire file before painting anything. if self.painter.minus_lines.len() > self.config.line_buffer_size || self.painter.plus_lines.len() > self.config.line_buffer_size { self.painter.paint_buffered_minus_and_plus_lines(); } if let State::HunkHeader(_, parsed_hunk_header, line, raw_line) = &self.state.clone() { self.emit_hunk_header_line(parsed_hunk_header, line, raw_line)?; }
identifier_body
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use crate::utils::tabs; // HACK: WordDiff should probably be a distinct top-level line state pub fn is_word_diff() -> bool { #[cfg(not(test))] { *CACHED_IS_WORD_DIFF } #[cfg(test)] { compute_is_word_diff() } } lazy_static! { static ref CACHED_IS_WORD_DIFF: bool = compute_is_word_diff(); } fn compute_is_word_diff() -> bool { match &*process::calling_process() { CallingProcess::GitDiff(cmd_line) | CallingProcess::GitShow(cmd_line, _) | CallingProcess::GitLog(cmd_line) | CallingProcess::GitReflog(cmd_line) => { cmd_line.long_options.contains("--word-diff") || cmd_line.long_options.contains("--word-diff-regex") || cmd_line.long_options.contains("--color-words") } _ => false, } } impl<'a> StateMachine<'a> { #[inline] fn
(&self) -> bool { matches!( self.state, State::HunkHeader(_, _, _, _) | State::HunkZero(_, _) | State::HunkMinus(_, _) | State::HunkPlus(_, _) ) } /// Handle a hunk line, i.e. a minus line, a plus line, or an unchanged line. // In the case of a minus or plus line, we store the line in a // buffer. When we exit the changed region we process the collected // minus and plus lines jointly, in order to paint detailed // highlighting according to inferred edit operations. In the case of // an unchanged line, we paint it immediately. pub fn handle_hunk_line(&mut self) -> std::io::Result<bool> { use DiffType::*; use State::*; // A true hunk line should start with one of: '+', '-',''. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if!self.test_hunk_line() { return Ok(false); } // Don't let the line buffers become arbitrarily large -- if we // were to allow that, then for a large deleted/added file we // would process the entire file before painting anything. if self.painter.minus_lines.len() > self.config.line_buffer_size || self.painter.plus_lines.len() > self.config.line_buffer_size { self.painter.paint_buffered_minus_and_plus_lines(); } if let State::HunkHeader(_, parsed_hunk_header, line, raw_line) = &self.state.clone() { self.emit_hunk_header_line(parsed_hunk_header, line, raw_line)?; } self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, raw_line)) => { if let HunkPlus(_, _) = self.state { // We have just entered a new subhunk; process the previous one // and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); } let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkMinus(diff_type, raw_line); self.painter.minus_lines.push((line, state.clone())); state } Some(HunkPlus(diff_type, raw_line)) => { let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkPlus(diff_type, raw_line); self.painter.plus_lines.push((line, state.clone())); state } Some(HunkZero(diff_type, raw_line)) => { // We are in a zero (unchanged) line, therefore we have just exited a subhunk (a // sequence of consecutive minus (removed) and/or plus (added) lines). Process that // subhunk and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); let n_parents = if is_word_diff() { 0 } else { diff_type.n_parents() }; let line = prepare(&self.line, n_parents, self.config); let state = State::HunkZero(diff_type, raw_line); self.painter.paint_zero_line(&line, state.clone()); state } _ => { // The first character here could be e.g. '\' from '\ No newline at end of file'. This // is not a hunk line, but the parser does not have a more accurate state corresponding // to this. self.painter.paint_buffered_minus_and_plus_lines(); self.painter .output_buffer .push_str(&tabs::expand(&self.raw_line, &self.config.tab_cfg)); self.painter.output_buffer.push('\n'); State::HunkZero(Unified, None) } }; self.painter.emit()?; Ok(true) } } // Return Some(prepared_raw_line) if delta should emit this line raw. fn maybe_raw_line( raw_line: &str, state_style_is_raw: bool, n_parents: usize, non_raw_styles: &[style::Style], config: &Config, ) -> Option<String> { let emit_raw_line = is_word_diff() || config.inspect_raw_lines == cli::InspectRawLines::True && style::line_has_style_other_than(raw_line, non_raw_styles) || state_style_is_raw; if emit_raw_line { Some(prepare_raw_line(raw_line, n_parents, config)) } else { None } } // Return the new state corresponding to `new_line`, given the previous state. A return value of // None means that `new_line` is not recognized as a hunk line. fn new_line_state( new_line: &str, new_raw_line: &str, prev_state: &State, config: &Config, ) -> Option<State> { use DiffType::*; use MergeParents::*; use State::*; if is_word_diff() { return Some(HunkZero( Unified, maybe_raw_line(new_raw_line, config.zero_style.is_raw, 0, &[], config), )); } // 1. Given the previous line state, compute the new line diff type. These are basically the // same, except that a string prefix is converted into an integer number of parents (prefix // length). let diff_type = match prev_state { HunkMinus(Unified, _) | HunkZero(Unified, _) | HunkPlus(Unified, _) | HunkHeader(Unified, _, _, _) => Unified, HunkHeader(Combined(Number(n), InMergeConflict::No), _, _, _) => { Combined(Number(*n), InMergeConflict::No) } // The prefixes are specific to the previous line, but the number of merge parents remains // equal to the prefix length. HunkHeader(Combined(Prefix(prefix), InMergeConflict::No), _, _, _) => { Combined(Number(prefix.len()), InMergeConflict::No) } HunkMinus(Combined(Prefix(prefix), in_merge_conflict), _) | HunkZero(Combined(Prefix(prefix), in_merge_conflict), _) | HunkPlus(Combined(Prefix(prefix), in_merge_conflict), _) => { Combined(Number(prefix.len()), in_merge_conflict.clone()) } HunkMinus(Combined(Number(n), in_merge_conflict), _) | HunkZero(Combined(Number(n), in_merge_conflict), _) | HunkPlus(Combined(Number(n), in_merge_conflict), _) => { Combined(Number(*n), in_merge_conflict.clone()) } _ => delta_unreachable(&format!( "Unexpected state in new_line_state: {prev_state:?}", )), }; // 2. Given the new diff state, and the new line, compute the new prefix. let (prefix_char, prefix, in_merge_conflict) = match diff_type.clone() { Unified => (new_line.chars().next(), None, None), Combined(Number(n_parents), in_merge_conflict) => { let prefix = &new_line[..min(n_parents, new_line.len())]; let prefix_char = match prefix.chars().find(|c| c == &'-' || c == &'+') { Some(c) => Some(c), None => match prefix.chars().find(|c| c!= &' ') { None => Some(' '), Some(_) => None, }, }; ( prefix_char, Some(prefix.to_string()), Some(in_merge_conflict), ) } _ => delta_unreachable(""), }; let maybe_minus_raw_line = || { maybe_raw_line( new_raw_line, config.minus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_MINUS_STYLE, config.git_minus_style], config, ) }; let maybe_zero_raw_line = || { maybe_raw_line( new_raw_line, config.zero_style.is_raw, diff_type.n_parents(), &[], config, ) }; let maybe_plus_raw_line = || { maybe_raw_line( new_raw_line, config.plus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_PLUS_STYLE, config.git_plus_style], config, ) }; // 3. Given the new prefix, compute the full new line state...except without its raw_line, which // is added later. TODO: that is not a sensible design. match (prefix_char, prefix, in_merge_conflict) { (Some('-'), None, None) => Some(HunkMinus(Unified, maybe_minus_raw_line())), (Some(' '), None, None) => Some(HunkZero(Unified, maybe_zero_raw_line())), (Some('+'), None, None) => Some(HunkPlus(Unified, maybe_plus_raw_line())), (Some('-'), Some(prefix), Some(in_merge_conflict)) => Some(HunkMinus( Combined(Prefix(prefix), in_merge_conflict), maybe_minus_raw_line(), )), (Some(' '), Some(prefix), Some(in_merge_conflict)) => Some(HunkZero( Combined(Prefix(prefix), in_merge_conflict), maybe_zero_raw_line(), )), (Some('+'), Some(prefix), Some(in_merge_conflict)) => Some(HunkPlus( Combined(Prefix(prefix), in_merge_conflict), maybe_plus_raw_line(), )), _ => None, } } #[cfg(test)] mod tests { use crate::tests::integration_test_utils::DeltaTest; mod word_diff { use super::*; #[test] fn test_word_diff() { DeltaTest::with_args(&[]) .with_calling_process("git diff --word-diff") .explain_ansi() .with_input(GIT_DIFF_WORD_DIFF) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)[-aaa-](green){+bbb+}(normal) ", ); } #[test] fn test_color_words() { DeltaTest::with_args(&[]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)aaa(green)bbb(normal) ", ); } #[test] #[ignore] // FIXME fn test_color_words_map_styles() { DeltaTest::with_args(&[ "--map-styles", "red => bold yellow #dddddd, green => bold blue #dddddd", ]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .inspect() .expect_after_skip( 11, r##" #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (bold yellow "#dddddd")aaa(bold blue "#dddddd")bbb(normal) "##, ); } #[test] fn test_hunk_line_style_raw() { DeltaTest::with_args(&["--minus-style", "raw", "--plus-style", "raw"]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (red)aaa(normal) (green)bbb(normal) ", ); } #[test] fn test_hunk_line_style_raw_map_styles() { DeltaTest::with_args(&[ "--minus-style", "raw", "--plus-style", "raw", "--map-styles", "red => bold blue, green => dim yellow", ]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (bold blue)aaa(normal) (dim yellow)bbb(normal) ", ); } const GIT_DIFF_WITH_COLOR: &str = r#"\ commit 3ef7fba7258fe473f1d8befff367bb793c786107 Author: Dan Davison <[email protected]> Date: Mon Dec 13 22:54:43 2021 -0500 753 Test file diff --git a/file b/file index 72943a1..f761ec1 100644 --- a/file +++ b/file @@ -1 +1 @@ -aaa +bbb "#; const GIT_DIFF_COLOR_WORDS: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ aaabbb "#; const GIT_DIFF_WORD_DIFF: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ [-aaa-]{+bbb+} "#; } }
test_hunk_line
identifier_name
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use crate::utils::tabs; // HACK: WordDiff should probably be a distinct top-level line state pub fn is_word_diff() -> bool { #[cfg(not(test))] { *CACHED_IS_WORD_DIFF } #[cfg(test)] { compute_is_word_diff() } } lazy_static! { static ref CACHED_IS_WORD_DIFF: bool = compute_is_word_diff(); } fn compute_is_word_diff() -> bool { match &*process::calling_process() { CallingProcess::GitDiff(cmd_line) | CallingProcess::GitShow(cmd_line, _) | CallingProcess::GitLog(cmd_line) | CallingProcess::GitReflog(cmd_line) => { cmd_line.long_options.contains("--word-diff") || cmd_line.long_options.contains("--word-diff-regex") || cmd_line.long_options.contains("--color-words") } _ => false, } } impl<'a> StateMachine<'a> { #[inline] fn test_hunk_line(&self) -> bool { matches!( self.state, State::HunkHeader(_, _, _, _) | State::HunkZero(_, _) | State::HunkMinus(_, _) | State::HunkPlus(_, _) ) } /// Handle a hunk line, i.e. a minus line, a plus line, or an unchanged line. // In the case of a minus or plus line, we store the line in a // buffer. When we exit the changed region we process the collected // minus and plus lines jointly, in order to paint detailed // highlighting according to inferred edit operations. In the case of // an unchanged line, we paint it immediately. pub fn handle_hunk_line(&mut self) -> std::io::Result<bool> { use DiffType::*; use State::*; // A true hunk line should start with one of: '+', '-',''. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if!self.test_hunk_line() { return Ok(false); } // Don't let the line buffers become arbitrarily large -- if we // were to allow that, then for a large deleted/added file we // would process the entire file before painting anything. if self.painter.minus_lines.len() > self.config.line_buffer_size
if let State::HunkHeader(_, parsed_hunk_header, line, raw_line) = &self.state.clone() { self.emit_hunk_header_line(parsed_hunk_header, line, raw_line)?; } self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, raw_line)) => { if let HunkPlus(_, _) = self.state { // We have just entered a new subhunk; process the previous one // and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); } let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkMinus(diff_type, raw_line); self.painter.minus_lines.push((line, state.clone())); state } Some(HunkPlus(diff_type, raw_line)) => { let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkPlus(diff_type, raw_line); self.painter.plus_lines.push((line, state.clone())); state } Some(HunkZero(diff_type, raw_line)) => { // We are in a zero (unchanged) line, therefore we have just exited a subhunk (a // sequence of consecutive minus (removed) and/or plus (added) lines). Process that // subhunk and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); let n_parents = if is_word_diff() { 0 } else { diff_type.n_parents() }; let line = prepare(&self.line, n_parents, self.config); let state = State::HunkZero(diff_type, raw_line); self.painter.paint_zero_line(&line, state.clone()); state } _ => { // The first character here could be e.g. '\' from '\ No newline at end of file'. This // is not a hunk line, but the parser does not have a more accurate state corresponding // to this. self.painter.paint_buffered_minus_and_plus_lines(); self.painter .output_buffer .push_str(&tabs::expand(&self.raw_line, &self.config.tab_cfg)); self.painter.output_buffer.push('\n'); State::HunkZero(Unified, None) } }; self.painter.emit()?; Ok(true) } } // Return Some(prepared_raw_line) if delta should emit this line raw. fn maybe_raw_line( raw_line: &str, state_style_is_raw: bool, n_parents: usize, non_raw_styles: &[style::Style], config: &Config, ) -> Option<String> { let emit_raw_line = is_word_diff() || config.inspect_raw_lines == cli::InspectRawLines::True && style::line_has_style_other_than(raw_line, non_raw_styles) || state_style_is_raw; if emit_raw_line { Some(prepare_raw_line(raw_line, n_parents, config)) } else { None } } // Return the new state corresponding to `new_line`, given the previous state. A return value of // None means that `new_line` is not recognized as a hunk line. fn new_line_state( new_line: &str, new_raw_line: &str, prev_state: &State, config: &Config, ) -> Option<State> { use DiffType::*; use MergeParents::*; use State::*; if is_word_diff() { return Some(HunkZero( Unified, maybe_raw_line(new_raw_line, config.zero_style.is_raw, 0, &[], config), )); } // 1. Given the previous line state, compute the new line diff type. These are basically the // same, except that a string prefix is converted into an integer number of parents (prefix // length). let diff_type = match prev_state { HunkMinus(Unified, _) | HunkZero(Unified, _) | HunkPlus(Unified, _) | HunkHeader(Unified, _, _, _) => Unified, HunkHeader(Combined(Number(n), InMergeConflict::No), _, _, _) => { Combined(Number(*n), InMergeConflict::No) } // The prefixes are specific to the previous line, but the number of merge parents remains // equal to the prefix length. HunkHeader(Combined(Prefix(prefix), InMergeConflict::No), _, _, _) => { Combined(Number(prefix.len()), InMergeConflict::No) } HunkMinus(Combined(Prefix(prefix), in_merge_conflict), _) | HunkZero(Combined(Prefix(prefix), in_merge_conflict), _) | HunkPlus(Combined(Prefix(prefix), in_merge_conflict), _) => { Combined(Number(prefix.len()), in_merge_conflict.clone()) } HunkMinus(Combined(Number(n), in_merge_conflict), _) | HunkZero(Combined(Number(n), in_merge_conflict), _) | HunkPlus(Combined(Number(n), in_merge_conflict), _) => { Combined(Number(*n), in_merge_conflict.clone()) } _ => delta_unreachable(&format!( "Unexpected state in new_line_state: {prev_state:?}", )), }; // 2. Given the new diff state, and the new line, compute the new prefix. let (prefix_char, prefix, in_merge_conflict) = match diff_type.clone() { Unified => (new_line.chars().next(), None, None), Combined(Number(n_parents), in_merge_conflict) => { let prefix = &new_line[..min(n_parents, new_line.len())]; let prefix_char = match prefix.chars().find(|c| c == &'-' || c == &'+') { Some(c) => Some(c), None => match prefix.chars().find(|c| c!= &' ') { None => Some(' '), Some(_) => None, }, }; ( prefix_char, Some(prefix.to_string()), Some(in_merge_conflict), ) } _ => delta_unreachable(""), }; let maybe_minus_raw_line = || { maybe_raw_line( new_raw_line, config.minus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_MINUS_STYLE, config.git_minus_style], config, ) }; let maybe_zero_raw_line = || { maybe_raw_line( new_raw_line, config.zero_style.is_raw, diff_type.n_parents(), &[], config, ) }; let maybe_plus_raw_line = || { maybe_raw_line( new_raw_line, config.plus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_PLUS_STYLE, config.git_plus_style], config, ) }; // 3. Given the new prefix, compute the full new line state...except without its raw_line, which // is added later. TODO: that is not a sensible design. match (prefix_char, prefix, in_merge_conflict) { (Some('-'), None, None) => Some(HunkMinus(Unified, maybe_minus_raw_line())), (Some(' '), None, None) => Some(HunkZero(Unified, maybe_zero_raw_line())), (Some('+'), None, None) => Some(HunkPlus(Unified, maybe_plus_raw_line())), (Some('-'), Some(prefix), Some(in_merge_conflict)) => Some(HunkMinus( Combined(Prefix(prefix), in_merge_conflict), maybe_minus_raw_line(), )), (Some(' '), Some(prefix), Some(in_merge_conflict)) => Some(HunkZero( Combined(Prefix(prefix), in_merge_conflict), maybe_zero_raw_line(), )), (Some('+'), Some(prefix), Some(in_merge_conflict)) => Some(HunkPlus( Combined(Prefix(prefix), in_merge_conflict), maybe_plus_raw_line(), )), _ => None, } } #[cfg(test)] mod tests { use crate::tests::integration_test_utils::DeltaTest; mod word_diff { use super::*; #[test] fn test_word_diff() { DeltaTest::with_args(&[]) .with_calling_process("git diff --word-diff") .explain_ansi() .with_input(GIT_DIFF_WORD_DIFF) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)[-aaa-](green){+bbb+}(normal) ", ); } #[test] fn test_color_words() { DeltaTest::with_args(&[]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)aaa(green)bbb(normal) ", ); } #[test] #[ignore] // FIXME fn test_color_words_map_styles() { DeltaTest::with_args(&[ "--map-styles", "red => bold yellow #dddddd, green => bold blue #dddddd", ]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .inspect() .expect_after_skip( 11, r##" #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (bold yellow "#dddddd")aaa(bold blue "#dddddd")bbb(normal) "##, ); } #[test] fn test_hunk_line_style_raw() { DeltaTest::with_args(&["--minus-style", "raw", "--plus-style", "raw"]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (red)aaa(normal) (green)bbb(normal) ", ); } #[test] fn test_hunk_line_style_raw_map_styles() { DeltaTest::with_args(&[ "--minus-style", "raw", "--plus-style", "raw", "--map-styles", "red => bold blue, green => dim yellow", ]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (bold blue)aaa(normal) (dim yellow)bbb(normal) ", ); } const GIT_DIFF_WITH_COLOR: &str = r#"\ commit 3ef7fba7258fe473f1d8befff367bb793c786107 Author: Dan Davison <[email protected]> Date: Mon Dec 13 22:54:43 2021 -0500 753 Test file diff --git a/file b/file index 72943a1..f761ec1 100644 --- a/file +++ b/file @@ -1 +1 @@ -aaa +bbb "#; const GIT_DIFF_COLOR_WORDS: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ aaabbb "#; const GIT_DIFF_WORD_DIFF: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ [-aaa-]{+bbb+} "#; } }
|| self.painter.plus_lines.len() > self.config.line_buffer_size { self.painter.paint_buffered_minus_and_plus_lines(); }
random_line_split
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use crate::utils::tabs; // HACK: WordDiff should probably be a distinct top-level line state pub fn is_word_diff() -> bool { #[cfg(not(test))] { *CACHED_IS_WORD_DIFF } #[cfg(test)] { compute_is_word_diff() } } lazy_static! { static ref CACHED_IS_WORD_DIFF: bool = compute_is_word_diff(); } fn compute_is_word_diff() -> bool { match &*process::calling_process() { CallingProcess::GitDiff(cmd_line) | CallingProcess::GitShow(cmd_line, _) | CallingProcess::GitLog(cmd_line) | CallingProcess::GitReflog(cmd_line) => { cmd_line.long_options.contains("--word-diff") || cmd_line.long_options.contains("--word-diff-regex") || cmd_line.long_options.contains("--color-words") } _ => false, } } impl<'a> StateMachine<'a> { #[inline] fn test_hunk_line(&self) -> bool { matches!( self.state, State::HunkHeader(_, _, _, _) | State::HunkZero(_, _) | State::HunkMinus(_, _) | State::HunkPlus(_, _) ) } /// Handle a hunk line, i.e. a minus line, a plus line, or an unchanged line. // In the case of a minus or plus line, we store the line in a // buffer. When we exit the changed region we process the collected // minus and plus lines jointly, in order to paint detailed // highlighting according to inferred edit operations. In the case of // an unchanged line, we paint it immediately. pub fn handle_hunk_line(&mut self) -> std::io::Result<bool> { use DiffType::*; use State::*; // A true hunk line should start with one of: '+', '-',''. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if!self.test_hunk_line() { return Ok(false); } // Don't let the line buffers become arbitrarily large -- if we // were to allow that, then for a large deleted/added file we // would process the entire file before painting anything. if self.painter.minus_lines.len() > self.config.line_buffer_size || self.painter.plus_lines.len() > self.config.line_buffer_size { self.painter.paint_buffered_minus_and_plus_lines(); } if let State::HunkHeader(_, parsed_hunk_header, line, raw_line) = &self.state.clone() { self.emit_hunk_header_line(parsed_hunk_header, line, raw_line)?; } self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, raw_line)) => { if let HunkPlus(_, _) = self.state { // We have just entered a new subhunk; process the previous one // and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); } let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkMinus(diff_type, raw_line); self.painter.minus_lines.push((line, state.clone())); state } Some(HunkPlus(diff_type, raw_line)) => { let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkPlus(diff_type, raw_line); self.painter.plus_lines.push((line, state.clone())); state } Some(HunkZero(diff_type, raw_line)) => { // We are in a zero (unchanged) line, therefore we have just exited a subhunk (a // sequence of consecutive minus (removed) and/or plus (added) lines). Process that // subhunk and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); let n_parents = if is_word_diff() { 0 } else { diff_type.n_parents() }; let line = prepare(&self.line, n_parents, self.config); let state = State::HunkZero(diff_type, raw_line); self.painter.paint_zero_line(&line, state.clone()); state } _ => { // The first character here could be e.g. '\' from '\ No newline at end of file'. This // is not a hunk line, but the parser does not have a more accurate state corresponding // to this. self.painter.paint_buffered_minus_and_plus_lines(); self.painter .output_buffer .push_str(&tabs::expand(&self.raw_line, &self.config.tab_cfg)); self.painter.output_buffer.push('\n'); State::HunkZero(Unified, None) } }; self.painter.emit()?; Ok(true) } } // Return Some(prepared_raw_line) if delta should emit this line raw. fn maybe_raw_line( raw_line: &str, state_style_is_raw: bool, n_parents: usize, non_raw_styles: &[style::Style], config: &Config, ) -> Option<String> { let emit_raw_line = is_word_diff() || config.inspect_raw_lines == cli::InspectRawLines::True && style::line_has_style_other_than(raw_line, non_raw_styles) || state_style_is_raw; if emit_raw_line { Some(prepare_raw_line(raw_line, n_parents, config)) } else { None } } // Return the new state corresponding to `new_line`, given the previous state. A return value of // None means that `new_line` is not recognized as a hunk line. fn new_line_state( new_line: &str, new_raw_line: &str, prev_state: &State, config: &Config, ) -> Option<State> { use DiffType::*; use MergeParents::*; use State::*; if is_word_diff()
// 1. Given the previous line state, compute the new line diff type. These are basically the // same, except that a string prefix is converted into an integer number of parents (prefix // length). let diff_type = match prev_state { HunkMinus(Unified, _) | HunkZero(Unified, _) | HunkPlus(Unified, _) | HunkHeader(Unified, _, _, _) => Unified, HunkHeader(Combined(Number(n), InMergeConflict::No), _, _, _) => { Combined(Number(*n), InMergeConflict::No) } // The prefixes are specific to the previous line, but the number of merge parents remains // equal to the prefix length. HunkHeader(Combined(Prefix(prefix), InMergeConflict::No), _, _, _) => { Combined(Number(prefix.len()), InMergeConflict::No) } HunkMinus(Combined(Prefix(prefix), in_merge_conflict), _) | HunkZero(Combined(Prefix(prefix), in_merge_conflict), _) | HunkPlus(Combined(Prefix(prefix), in_merge_conflict), _) => { Combined(Number(prefix.len()), in_merge_conflict.clone()) } HunkMinus(Combined(Number(n), in_merge_conflict), _) | HunkZero(Combined(Number(n), in_merge_conflict), _) | HunkPlus(Combined(Number(n), in_merge_conflict), _) => { Combined(Number(*n), in_merge_conflict.clone()) } _ => delta_unreachable(&format!( "Unexpected state in new_line_state: {prev_state:?}", )), }; // 2. Given the new diff state, and the new line, compute the new prefix. let (prefix_char, prefix, in_merge_conflict) = match diff_type.clone() { Unified => (new_line.chars().next(), None, None), Combined(Number(n_parents), in_merge_conflict) => { let prefix = &new_line[..min(n_parents, new_line.len())]; let prefix_char = match prefix.chars().find(|c| c == &'-' || c == &'+') { Some(c) => Some(c), None => match prefix.chars().find(|c| c!= &' ') { None => Some(' '), Some(_) => None, }, }; ( prefix_char, Some(prefix.to_string()), Some(in_merge_conflict), ) } _ => delta_unreachable(""), }; let maybe_minus_raw_line = || { maybe_raw_line( new_raw_line, config.minus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_MINUS_STYLE, config.git_minus_style], config, ) }; let maybe_zero_raw_line = || { maybe_raw_line( new_raw_line, config.zero_style.is_raw, diff_type.n_parents(), &[], config, ) }; let maybe_plus_raw_line = || { maybe_raw_line( new_raw_line, config.plus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_PLUS_STYLE, config.git_plus_style], config, ) }; // 3. Given the new prefix, compute the full new line state...except without its raw_line, which // is added later. TODO: that is not a sensible design. match (prefix_char, prefix, in_merge_conflict) { (Some('-'), None, None) => Some(HunkMinus(Unified, maybe_minus_raw_line())), (Some(' '), None, None) => Some(HunkZero(Unified, maybe_zero_raw_line())), (Some('+'), None, None) => Some(HunkPlus(Unified, maybe_plus_raw_line())), (Some('-'), Some(prefix), Some(in_merge_conflict)) => Some(HunkMinus( Combined(Prefix(prefix), in_merge_conflict), maybe_minus_raw_line(), )), (Some(' '), Some(prefix), Some(in_merge_conflict)) => Some(HunkZero( Combined(Prefix(prefix), in_merge_conflict), maybe_zero_raw_line(), )), (Some('+'), Some(prefix), Some(in_merge_conflict)) => Some(HunkPlus( Combined(Prefix(prefix), in_merge_conflict), maybe_plus_raw_line(), )), _ => None, } } #[cfg(test)] mod tests { use crate::tests::integration_test_utils::DeltaTest; mod word_diff { use super::*; #[test] fn test_word_diff() { DeltaTest::with_args(&[]) .with_calling_process("git diff --word-diff") .explain_ansi() .with_input(GIT_DIFF_WORD_DIFF) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)[-aaa-](green){+bbb+}(normal) ", ); } #[test] fn test_color_words() { DeltaTest::with_args(&[]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)aaa(green)bbb(normal) ", ); } #[test] #[ignore] // FIXME fn test_color_words_map_styles() { DeltaTest::with_args(&[ "--map-styles", "red => bold yellow #dddddd, green => bold blue #dddddd", ]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .inspect() .expect_after_skip( 11, r##" #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (bold yellow "#dddddd")aaa(bold blue "#dddddd")bbb(normal) "##, ); } #[test] fn test_hunk_line_style_raw() { DeltaTest::with_args(&["--minus-style", "raw", "--plus-style", "raw"]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (red)aaa(normal) (green)bbb(normal) ", ); } #[test] fn test_hunk_line_style_raw_map_styles() { DeltaTest::with_args(&[ "--minus-style", "raw", "--plus-style", "raw", "--map-styles", "red => bold blue, green => dim yellow", ]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (bold blue)aaa(normal) (dim yellow)bbb(normal) ", ); } const GIT_DIFF_WITH_COLOR: &str = r#"\ commit 3ef7fba7258fe473f1d8befff367bb793c786107 Author: Dan Davison <[email protected]> Date: Mon Dec 13 22:54:43 2021 -0500 753 Test file diff --git a/file b/file index 72943a1..f761ec1 100644 --- a/file +++ b/file @@ -1 +1 @@ -aaa +bbb "#; const GIT_DIFF_COLOR_WORDS: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ aaabbb "#; const GIT_DIFF_WORD_DIFF: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <[email protected]> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ [-aaa-]{+bbb+} "#; } }
{ return Some(HunkZero( Unified, maybe_raw_line(new_raw_line, config.zero_style.is_raw, 0, &[], config), )); }
conditional_block
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, width: Option<usize>, thousands: bool, precision: Option<usize>, ty: Option<char>, buff: &'b mut String, pattern: &'a str, } fn is_alignment_token(c: char) -> bool { match c { '=' | '<' | '^' | '>' => true, _ => false, } } fn is_sign_element(c: char) -> bool { match c { '' | '-' | '+' => true, _ => false, } } fn is_type_element(c: char) -> bool { match c { 'b' | 'o' | 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' |'s' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for b in rest { match *b as char { '0'..='9' => {} _ => break, }; consumed += 1; } if consumed == 0 { (0, None) } else { let (intstr, _) = rest.split_at(consumed); let val = unsafe { // I think I can be reasonably sure that 0-9 chars are utf8 :) match str::from_utf8_unchecked(intstr).parse::<i64>() { Ok(v) => Some(v), Err(_) => None, } }; (consumed, val) } } #[derive(Debug)] /// The format struct as it is defined in the python source struct FmtPy { pub fill: char, pub align: char, pub alternate: bool, pub sign: char, pub width: i64, pub thousands: bool, pub precision: i64, pub ty: char, } fn parse_like_python(rest: &str) -> Result<FmtPy> { // The rest of this was pretty much strait up copied from python's format parser // All credit goes to python source file: formatter_unicode.c // let mut format = FmtPy { fill:'', align: '\0', alternate: false, sign: '\0', width: -1, thousands: false, precision: -1, ty: '\0', }; let mut chars = rest.chars(); let fake_fill = match chars.next() { Some(c) => c, None => return Ok(format), }; // from now on all format characters MUST be valid // ASCII characters (fill and identifier were the // only ones that weren't. // Therefore we can use bytes for the rest let rest = rest.as_bytes(); let mut align_specified = false; let mut fill_specified = false; let end: usize = rest.len(); let mut pos: usize = 0; // If the second char is an alignment token, // then fake_fill as fill if end - pos >= 1 + fake_fill.len_utf8() && is_alignment_token(rest[pos + fake_fill.len_utf8()] as char) { format.align = rest[pos + fake_fill.len_utf8()] as char; format.fill = fake_fill; fill_specified = true; align_specified = true; pos += 1 + fake_fill.len_utf8(); } else if end - pos >= 1 && is_alignment_token(fake_fill) { format.align = fake_fill; pos += fake_fill.len_utf8(); } // Parse the various sign options if end - pos >= 1 && is_sign_element(rest[pos] as char) { format.sign = rest[pos] as char; pos += 1; } // If the next character is #, we're in alternate mode. This only // applies to integers. if end - pos >= 1 && rest[pos] as char == '#' { format.alternate = true; pos += 1; } // The special case for 0-padding (backwards compat) if!fill_specified && end - pos >= 1 && rest[pos] == '0' as u8 { format.fill = '0'; if!align_specified { format.align = '='; } pos += 1; } // check to make sure that val is good let (consumed, val) = get_integer(rest, pos); pos += consumed; if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing width".to_string(), )) } Some(v) => { format.width = v; } } } // Comma signifies add thousands separators if end - pos > 0 && rest[pos] as char == ',' { format.thousands = true; pos += 1; } // Parse field precision if end - pos > 0 && rest[pos] as char == '.' { pos += 1; let (consumed, val) = get_integer(rest, pos); if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing precision".to_string(), )) } Some(v) => { format.precision = v; } } } else { // Not having a precision after a dot is an error. if consumed == 0 { return Err(FmtError::Invalid( "Format specifier missing precision".to_string(), )); } } pos += consumed; } // Finally, parse the type field. if end - pos > 1 { // More than one char remain, invalid format specifier. return Err(FmtError::Invalid("Invalid format specifier".to_string())); } if end - pos == 1 { format.ty = rest[pos] as char; if!is_type_element(format.ty) { let mut msg = String::new(); write!(msg, "Invalid type specifier: {:?}", format.ty).unwrap(); return Err(FmtError::TypeError(msg)); } // pos+=1; } // Do as much validating as we can, just by looking at the format // specifier. Do not take into account what type of formatting // we're doing (int, float, string). if format.thousands { match format.ty { 'd' | 'e' | 'f' | 'g' | 'E' | 'G' | '%' | 'F' | '\0' => {} /* These are allowed. See PEP 378.*/ _ => { let mut msg = String::new(); write!(msg, "Invalid comma type: {}", format.ty).unwrap(); return Err(FmtError::Invalid(msg)); } } } Ok(format) } impl<'a, 'b> Formatter<'a, 'b> { /// create Formatter from format string pub fn from_str(s: &'a str, buff: &'b mut String) -> Result<Formatter<'a, 'b>> { let mut found_colon = false; let mut chars = s.chars(); let mut c = match chars.next() { Some(':') | None => { return Err(FmtError::Invalid("must specify identifier".to_string())) } Some(c) => c, }; let mut consumed = 0; // find the identifier loop { consumed += c.len_utf8(); if c == ':' { found_colon = true; break; } c = match chars.next() { Some(c) => c, None => { break; } }; } let (identifier, rest) = s.split_at(consumed); let identifier = if found_colon { let (i, _) = identifier.split_at(identifier.len() - 1); // get rid of ':' i } else { identifier }; let format = parse_like_python(rest)?; Ok(Formatter { key: identifier, fill: format.fill, align: match format.align { '\0' => Alignment::Unspecified, '<' => Alignment::Left, '^' => Alignment::Center, '>' => Alignment::Right, '=' => Alignment::Equal, _ => unreachable!(), }, sign: match format.sign { '\0' => Sign::Unspecified, '+' => Sign::Plus, '-' => Sign::Minus, '' => Sign::Space, _ => unreachable!(), }, alternate: format.alternate, width: match format.width { -1 => None, _ => Some(format.width as usize), }, thousands: format.thousands, precision: match format.precision { -1 => None, _ => Some(format.precision as usize), }, ty: match format.ty { '\0' => None, _ => Some(format.ty), }, buff: buff, pattern: s, }) } /// call this to re-write the original format string verbatum /// back to the output pub fn skip(mut self) -> Result<()> { self.buff.push('{'); self.write_str(self.pattern).unwrap(); self.buff.push('}'); Ok(()) } /// fill getter pub fn fill(&self) -> char { self.fill } /// align getter pub fn align(&self) -> Alignment { self.align.clone() } // provide default for unspecified alignment pub fn set_default_align(&mut self, align: Alignment) { if self.align == Alignment::Unspecified { self.align = align } } /// width getter pub fn width(&self) -> Option<usize>
/// thousands getter pub fn thousands(&self) -> bool { self.thousands } /// precision getter pub fn precision(&self) -> Option<usize> { self.precision } /// set precision to None, used for formatting int, float, etc pub fn set_precision(&mut self, precision: Option<usize>) { self.precision = precision; } /// sign getter pub fn sign(&self) -> Sign { self.sign.clone() } /// sign plus getter /// here because it is in fmt::Formatter pub fn sign_plus(&self) -> bool { self.sign == Sign::Plus } /// sign minus getter /// here because it is in fmt::Formatter pub fn sign_minus(&self) -> bool { self.sign == Sign::Minus } /// alternate getter pub fn alternate(&self) -> bool { self.alternate } // sign_aware_zero_pad // Not supported /// type getter pub fn ty(&self) -> Option<char> { self.ty } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting integers pub fn is_int_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'b' | 'o' | 'x' | 'X' => true, _ => false, }, } } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting floats pub fn is_float_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'f' | 'e' | 'E' => true, _ => false, }, } } } impl<'a, 'b> fmt::Write for Formatter<'a, 'b> { fn write_str(&mut self, s: &str) -> fmt::Result { self.buff.write_str(s) } }
{ self.width }
identifier_body
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, width: Option<usize>, thousands: bool, precision: Option<usize>, ty: Option<char>, buff: &'b mut String, pattern: &'a str, } fn is_alignment_token(c: char) -> bool { match c { '=' | '<' | '^' | '>' => true, _ => false, } } fn is_sign_element(c: char) -> bool { match c { '' | '-' | '+' => true, _ => false, } } fn is_type_element(c: char) -> bool { match c { 'b' | 'o' | 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' |'s' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for b in rest { match *b as char { '0'..='9' => {} _ => break, }; consumed += 1; } if consumed == 0 { (0, None) } else { let (intstr, _) = rest.split_at(consumed); let val = unsafe { // I think I can be reasonably sure that 0-9 chars are utf8 :) match str::from_utf8_unchecked(intstr).parse::<i64>() { Ok(v) => Some(v), Err(_) => None, } }; (consumed, val) } } #[derive(Debug)] /// The format struct as it is defined in the python source struct FmtPy { pub fill: char, pub align: char, pub alternate: bool, pub sign: char, pub width: i64, pub thousands: bool, pub precision: i64, pub ty: char, } fn parse_like_python(rest: &str) -> Result<FmtPy> { // The rest of this was pretty much strait up copied from python's format parser // All credit goes to python source file: formatter_unicode.c // let mut format = FmtPy { fill:'', align: '\0', alternate: false, sign: '\0', width: -1, thousands: false, precision: -1, ty: '\0', }; let mut chars = rest.chars(); let fake_fill = match chars.next() { Some(c) => c, None => return Ok(format), }; // from now on all format characters MUST be valid // ASCII characters (fill and identifier were the // only ones that weren't. // Therefore we can use bytes for the rest let rest = rest.as_bytes(); let mut align_specified = false; let mut fill_specified = false; let end: usize = rest.len(); let mut pos: usize = 0; // If the second char is an alignment token, // then fake_fill as fill if end - pos >= 1 + fake_fill.len_utf8() && is_alignment_token(rest[pos + fake_fill.len_utf8()] as char) { format.align = rest[pos + fake_fill.len_utf8()] as char; format.fill = fake_fill; fill_specified = true; align_specified = true; pos += 1 + fake_fill.len_utf8(); } else if end - pos >= 1 && is_alignment_token(fake_fill) { format.align = fake_fill; pos += fake_fill.len_utf8(); } // Parse the various sign options if end - pos >= 1 && is_sign_element(rest[pos] as char) { format.sign = rest[pos] as char; pos += 1; }
if end - pos >= 1 && rest[pos] as char == '#' { format.alternate = true; pos += 1; } // The special case for 0-padding (backwards compat) if!fill_specified && end - pos >= 1 && rest[pos] == '0' as u8 { format.fill = '0'; if!align_specified { format.align = '='; } pos += 1; } // check to make sure that val is good let (consumed, val) = get_integer(rest, pos); pos += consumed; if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing width".to_string(), )) } Some(v) => { format.width = v; } } } // Comma signifies add thousands separators if end - pos > 0 && rest[pos] as char == ',' { format.thousands = true; pos += 1; } // Parse field precision if end - pos > 0 && rest[pos] as char == '.' { pos += 1; let (consumed, val) = get_integer(rest, pos); if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing precision".to_string(), )) } Some(v) => { format.precision = v; } } } else { // Not having a precision after a dot is an error. if consumed == 0 { return Err(FmtError::Invalid( "Format specifier missing precision".to_string(), )); } } pos += consumed; } // Finally, parse the type field. if end - pos > 1 { // More than one char remain, invalid format specifier. return Err(FmtError::Invalid("Invalid format specifier".to_string())); } if end - pos == 1 { format.ty = rest[pos] as char; if!is_type_element(format.ty) { let mut msg = String::new(); write!(msg, "Invalid type specifier: {:?}", format.ty).unwrap(); return Err(FmtError::TypeError(msg)); } // pos+=1; } // Do as much validating as we can, just by looking at the format // specifier. Do not take into account what type of formatting // we're doing (int, float, string). if format.thousands { match format.ty { 'd' | 'e' | 'f' | 'g' | 'E' | 'G' | '%' | 'F' | '\0' => {} /* These are allowed. See PEP 378.*/ _ => { let mut msg = String::new(); write!(msg, "Invalid comma type: {}", format.ty).unwrap(); return Err(FmtError::Invalid(msg)); } } } Ok(format) } impl<'a, 'b> Formatter<'a, 'b> { /// create Formatter from format string pub fn from_str(s: &'a str, buff: &'b mut String) -> Result<Formatter<'a, 'b>> { let mut found_colon = false; let mut chars = s.chars(); let mut c = match chars.next() { Some(':') | None => { return Err(FmtError::Invalid("must specify identifier".to_string())) } Some(c) => c, }; let mut consumed = 0; // find the identifier loop { consumed += c.len_utf8(); if c == ':' { found_colon = true; break; } c = match chars.next() { Some(c) => c, None => { break; } }; } let (identifier, rest) = s.split_at(consumed); let identifier = if found_colon { let (i, _) = identifier.split_at(identifier.len() - 1); // get rid of ':' i } else { identifier }; let format = parse_like_python(rest)?; Ok(Formatter { key: identifier, fill: format.fill, align: match format.align { '\0' => Alignment::Unspecified, '<' => Alignment::Left, '^' => Alignment::Center, '>' => Alignment::Right, '=' => Alignment::Equal, _ => unreachable!(), }, sign: match format.sign { '\0' => Sign::Unspecified, '+' => Sign::Plus, '-' => Sign::Minus, '' => Sign::Space, _ => unreachable!(), }, alternate: format.alternate, width: match format.width { -1 => None, _ => Some(format.width as usize), }, thousands: format.thousands, precision: match format.precision { -1 => None, _ => Some(format.precision as usize), }, ty: match format.ty { '\0' => None, _ => Some(format.ty), }, buff: buff, pattern: s, }) } /// call this to re-write the original format string verbatum /// back to the output pub fn skip(mut self) -> Result<()> { self.buff.push('{'); self.write_str(self.pattern).unwrap(); self.buff.push('}'); Ok(()) } /// fill getter pub fn fill(&self) -> char { self.fill } /// align getter pub fn align(&self) -> Alignment { self.align.clone() } // provide default for unspecified alignment pub fn set_default_align(&mut self, align: Alignment) { if self.align == Alignment::Unspecified { self.align = align } } /// width getter pub fn width(&self) -> Option<usize> { self.width } /// thousands getter pub fn thousands(&self) -> bool { self.thousands } /// precision getter pub fn precision(&self) -> Option<usize> { self.precision } /// set precision to None, used for formatting int, float, etc pub fn set_precision(&mut self, precision: Option<usize>) { self.precision = precision; } /// sign getter pub fn sign(&self) -> Sign { self.sign.clone() } /// sign plus getter /// here because it is in fmt::Formatter pub fn sign_plus(&self) -> bool { self.sign == Sign::Plus } /// sign minus getter /// here because it is in fmt::Formatter pub fn sign_minus(&self) -> bool { self.sign == Sign::Minus } /// alternate getter pub fn alternate(&self) -> bool { self.alternate } // sign_aware_zero_pad // Not supported /// type getter pub fn ty(&self) -> Option<char> { self.ty } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting integers pub fn is_int_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'b' | 'o' | 'x' | 'X' => true, _ => false, }, } } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting floats pub fn is_float_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'f' | 'e' | 'E' => true, _ => false, }, } } } impl<'a, 'b> fmt::Write for Formatter<'a, 'b> { fn write_str(&mut self, s: &str) -> fmt::Result { self.buff.write_str(s) } }
// If the next character is #, we're in alternate mode. This only // applies to integers.
random_line_split
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, width: Option<usize>, thousands: bool, precision: Option<usize>, ty: Option<char>, buff: &'b mut String, pattern: &'a str, } fn is_alignment_token(c: char) -> bool { match c { '=' | '<' | '^' | '>' => true, _ => false, } } fn is_sign_element(c: char) -> bool { match c { '' | '-' | '+' => true, _ => false, } } fn is_type_element(c: char) -> bool { match c { 'b' | 'o' | 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' |'s' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for b in rest { match *b as char { '0'..='9' => {} _ => break, }; consumed += 1; } if consumed == 0 { (0, None) } else { let (intstr, _) = rest.split_at(consumed); let val = unsafe { // I think I can be reasonably sure that 0-9 chars are utf8 :) match str::from_utf8_unchecked(intstr).parse::<i64>() { Ok(v) => Some(v), Err(_) => None, } }; (consumed, val) } } #[derive(Debug)] /// The format struct as it is defined in the python source struct FmtPy { pub fill: char, pub align: char, pub alternate: bool, pub sign: char, pub width: i64, pub thousands: bool, pub precision: i64, pub ty: char, } fn parse_like_python(rest: &str) -> Result<FmtPy> { // The rest of this was pretty much strait up copied from python's format parser // All credit goes to python source file: formatter_unicode.c // let mut format = FmtPy { fill:'', align: '\0', alternate: false, sign: '\0', width: -1, thousands: false, precision: -1, ty: '\0', }; let mut chars = rest.chars(); let fake_fill = match chars.next() { Some(c) => c, None => return Ok(format), }; // from now on all format characters MUST be valid // ASCII characters (fill and identifier were the // only ones that weren't. // Therefore we can use bytes for the rest let rest = rest.as_bytes(); let mut align_specified = false; let mut fill_specified = false; let end: usize = rest.len(); let mut pos: usize = 0; // If the second char is an alignment token, // then fake_fill as fill if end - pos >= 1 + fake_fill.len_utf8() && is_alignment_token(rest[pos + fake_fill.len_utf8()] as char) { format.align = rest[pos + fake_fill.len_utf8()] as char; format.fill = fake_fill; fill_specified = true; align_specified = true; pos += 1 + fake_fill.len_utf8(); } else if end - pos >= 1 && is_alignment_token(fake_fill) { format.align = fake_fill; pos += fake_fill.len_utf8(); } // Parse the various sign options if end - pos >= 1 && is_sign_element(rest[pos] as char) { format.sign = rest[pos] as char; pos += 1; } // If the next character is #, we're in alternate mode. This only // applies to integers. if end - pos >= 1 && rest[pos] as char == '#' { format.alternate = true; pos += 1; } // The special case for 0-padding (backwards compat) if!fill_specified && end - pos >= 1 && rest[pos] == '0' as u8 { format.fill = '0'; if!align_specified { format.align = '='; } pos += 1; } // check to make sure that val is good let (consumed, val) = get_integer(rest, pos); pos += consumed; if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing width".to_string(), )) } Some(v) => { format.width = v; } } } // Comma signifies add thousands separators if end - pos > 0 && rest[pos] as char == ',' { format.thousands = true; pos += 1; } // Parse field precision if end - pos > 0 && rest[pos] as char == '.' { pos += 1; let (consumed, val) = get_integer(rest, pos); if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing precision".to_string(), )) } Some(v) => { format.precision = v; } } } else { // Not having a precision after a dot is an error. if consumed == 0 { return Err(FmtError::Invalid( "Format specifier missing precision".to_string(), )); } } pos += consumed; } // Finally, parse the type field. if end - pos > 1 { // More than one char remain, invalid format specifier. return Err(FmtError::Invalid("Invalid format specifier".to_string())); } if end - pos == 1 { format.ty = rest[pos] as char; if!is_type_element(format.ty) { let mut msg = String::new(); write!(msg, "Invalid type specifier: {:?}", format.ty).unwrap(); return Err(FmtError::TypeError(msg)); } // pos+=1; } // Do as much validating as we can, just by looking at the format // specifier. Do not take into account what type of formatting // we're doing (int, float, string). if format.thousands { match format.ty { 'd' | 'e' | 'f' | 'g' | 'E' | 'G' | '%' | 'F' | '\0' => {} /* These are allowed. See PEP 378.*/ _ => { let mut msg = String::new(); write!(msg, "Invalid comma type: {}", format.ty).unwrap(); return Err(FmtError::Invalid(msg)); } } } Ok(format) } impl<'a, 'b> Formatter<'a, 'b> { /// create Formatter from format string pub fn from_str(s: &'a str, buff: &'b mut String) -> Result<Formatter<'a, 'b>> { let mut found_colon = false; let mut chars = s.chars(); let mut c = match chars.next() { Some(':') | None => { return Err(FmtError::Invalid("must specify identifier".to_string())) } Some(c) => c, }; let mut consumed = 0; // find the identifier loop { consumed += c.len_utf8(); if c == ':' { found_colon = true; break; } c = match chars.next() { Some(c) => c, None => { break; } }; } let (identifier, rest) = s.split_at(consumed); let identifier = if found_colon { let (i, _) = identifier.split_at(identifier.len() - 1); // get rid of ':' i } else { identifier }; let format = parse_like_python(rest)?; Ok(Formatter { key: identifier, fill: format.fill, align: match format.align { '\0' => Alignment::Unspecified, '<' => Alignment::Left, '^' => Alignment::Center, '>' => Alignment::Right, '=' => Alignment::Equal, _ => unreachable!(), }, sign: match format.sign { '\0' => Sign::Unspecified, '+' => Sign::Plus, '-' => Sign::Minus, '' => Sign::Space, _ => unreachable!(), }, alternate: format.alternate, width: match format.width { -1 => None, _ => Some(format.width as usize), }, thousands: format.thousands, precision: match format.precision { -1 => None, _ => Some(format.precision as usize), }, ty: match format.ty { '\0' => None, _ => Some(format.ty), }, buff: buff, pattern: s, }) } /// call this to re-write the original format string verbatum /// back to the output pub fn skip(mut self) -> Result<()> { self.buff.push('{'); self.write_str(self.pattern).unwrap(); self.buff.push('}'); Ok(()) } /// fill getter pub fn fill(&self) -> char { self.fill } /// align getter pub fn align(&self) -> Alignment { self.align.clone() } // provide default for unspecified alignment pub fn set_default_align(&mut self, align: Alignment) { if self.align == Alignment::Unspecified { self.align = align } } /// width getter pub fn width(&self) -> Option<usize> { self.width } /// thousands getter pub fn thousands(&self) -> bool { self.thousands } /// precision getter pub fn precision(&self) -> Option<usize> { self.precision } /// set precision to None, used for formatting int, float, etc pub fn set_precision(&mut self, precision: Option<usize>) { self.precision = precision; } /// sign getter pub fn sign(&self) -> Sign { self.sign.clone() } /// sign plus getter /// here because it is in fmt::Formatter pub fn sign_plus(&self) -> bool { self.sign == Sign::Plus } /// sign minus getter /// here because it is in fmt::Formatter pub fn sign_minus(&self) -> bool { self.sign == Sign::Minus } /// alternate getter pub fn
(&self) -> bool { self.alternate } // sign_aware_zero_pad // Not supported /// type getter pub fn ty(&self) -> Option<char> { self.ty } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting integers pub fn is_int_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'b' | 'o' | 'x' | 'X' => true, _ => false, }, } } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting floats pub fn is_float_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'f' | 'e' | 'E' => true, _ => false, }, } } } impl<'a, 'b> fmt::Write for Formatter<'a, 'b> { fn write_str(&mut self, s: &str) -> fmt::Result { self.buff.write_str(s) } }
alternate
identifier_name
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, width: Option<usize>, thousands: bool, precision: Option<usize>, ty: Option<char>, buff: &'b mut String, pattern: &'a str, } fn is_alignment_token(c: char) -> bool { match c { '=' | '<' | '^' | '>' => true, _ => false, } } fn is_sign_element(c: char) -> bool { match c { '' | '-' | '+' => true, _ => false, } } fn is_type_element(c: char) -> bool { match c { 'b' | 'o' | 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' |'s' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for b in rest { match *b as char { '0'..='9' => {} _ => break, }; consumed += 1; } if consumed == 0 { (0, None) } else { let (intstr, _) = rest.split_at(consumed); let val = unsafe { // I think I can be reasonably sure that 0-9 chars are utf8 :) match str::from_utf8_unchecked(intstr).parse::<i64>() { Ok(v) => Some(v), Err(_) => None, } }; (consumed, val) } } #[derive(Debug)] /// The format struct as it is defined in the python source struct FmtPy { pub fill: char, pub align: char, pub alternate: bool, pub sign: char, pub width: i64, pub thousands: bool, pub precision: i64, pub ty: char, } fn parse_like_python(rest: &str) -> Result<FmtPy> { // The rest of this was pretty much strait up copied from python's format parser // All credit goes to python source file: formatter_unicode.c // let mut format = FmtPy { fill:'', align: '\0', alternate: false, sign: '\0', width: -1, thousands: false, precision: -1, ty: '\0', }; let mut chars = rest.chars(); let fake_fill = match chars.next() { Some(c) => c, None => return Ok(format), }; // from now on all format characters MUST be valid // ASCII characters (fill and identifier were the // only ones that weren't. // Therefore we can use bytes for the rest let rest = rest.as_bytes(); let mut align_specified = false; let mut fill_specified = false; let end: usize = rest.len(); let mut pos: usize = 0; // If the second char is an alignment token, // then fake_fill as fill if end - pos >= 1 + fake_fill.len_utf8() && is_alignment_token(rest[pos + fake_fill.len_utf8()] as char) { format.align = rest[pos + fake_fill.len_utf8()] as char; format.fill = fake_fill; fill_specified = true; align_specified = true; pos += 1 + fake_fill.len_utf8(); } else if end - pos >= 1 && is_alignment_token(fake_fill) { format.align = fake_fill; pos += fake_fill.len_utf8(); } // Parse the various sign options if end - pos >= 1 && is_sign_element(rest[pos] as char) { format.sign = rest[pos] as char; pos += 1; } // If the next character is #, we're in alternate mode. This only // applies to integers. if end - pos >= 1 && rest[pos] as char == '#' { format.alternate = true; pos += 1; } // The special case for 0-padding (backwards compat) if!fill_specified && end - pos >= 1 && rest[pos] == '0' as u8 { format.fill = '0'; if!align_specified { format.align = '='; } pos += 1; } // check to make sure that val is good let (consumed, val) = get_integer(rest, pos); pos += consumed; if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing width".to_string(), )) } Some(v) => { format.width = v; } } } // Comma signifies add thousands separators if end - pos > 0 && rest[pos] as char == ',' { format.thousands = true; pos += 1; } // Parse field precision if end - pos > 0 && rest[pos] as char == '.' { pos += 1; let (consumed, val) = get_integer(rest, pos); if consumed!= 0 { match val { None => { return Err(FmtError::Invalid( "overflow error when parsing precision".to_string(), )) } Some(v) =>
} } else { // Not having a precision after a dot is an error. if consumed == 0 { return Err(FmtError::Invalid( "Format specifier missing precision".to_string(), )); } } pos += consumed; } // Finally, parse the type field. if end - pos > 1 { // More than one char remain, invalid format specifier. return Err(FmtError::Invalid("Invalid format specifier".to_string())); } if end - pos == 1 { format.ty = rest[pos] as char; if!is_type_element(format.ty) { let mut msg = String::new(); write!(msg, "Invalid type specifier: {:?}", format.ty).unwrap(); return Err(FmtError::TypeError(msg)); } // pos+=1; } // Do as much validating as we can, just by looking at the format // specifier. Do not take into account what type of formatting // we're doing (int, float, string). if format.thousands { match format.ty { 'd' | 'e' | 'f' | 'g' | 'E' | 'G' | '%' | 'F' | '\0' => {} /* These are allowed. See PEP 378.*/ _ => { let mut msg = String::new(); write!(msg, "Invalid comma type: {}", format.ty).unwrap(); return Err(FmtError::Invalid(msg)); } } } Ok(format) } impl<'a, 'b> Formatter<'a, 'b> { /// create Formatter from format string pub fn from_str(s: &'a str, buff: &'b mut String) -> Result<Formatter<'a, 'b>> { let mut found_colon = false; let mut chars = s.chars(); let mut c = match chars.next() { Some(':') | None => { return Err(FmtError::Invalid("must specify identifier".to_string())) } Some(c) => c, }; let mut consumed = 0; // find the identifier loop { consumed += c.len_utf8(); if c == ':' { found_colon = true; break; } c = match chars.next() { Some(c) => c, None => { break; } }; } let (identifier, rest) = s.split_at(consumed); let identifier = if found_colon { let (i, _) = identifier.split_at(identifier.len() - 1); // get rid of ':' i } else { identifier }; let format = parse_like_python(rest)?; Ok(Formatter { key: identifier, fill: format.fill, align: match format.align { '\0' => Alignment::Unspecified, '<' => Alignment::Left, '^' => Alignment::Center, '>' => Alignment::Right, '=' => Alignment::Equal, _ => unreachable!(), }, sign: match format.sign { '\0' => Sign::Unspecified, '+' => Sign::Plus, '-' => Sign::Minus, '' => Sign::Space, _ => unreachable!(), }, alternate: format.alternate, width: match format.width { -1 => None, _ => Some(format.width as usize), }, thousands: format.thousands, precision: match format.precision { -1 => None, _ => Some(format.precision as usize), }, ty: match format.ty { '\0' => None, _ => Some(format.ty), }, buff: buff, pattern: s, }) } /// call this to re-write the original format string verbatum /// back to the output pub fn skip(mut self) -> Result<()> { self.buff.push('{'); self.write_str(self.pattern).unwrap(); self.buff.push('}'); Ok(()) } /// fill getter pub fn fill(&self) -> char { self.fill } /// align getter pub fn align(&self) -> Alignment { self.align.clone() } // provide default for unspecified alignment pub fn set_default_align(&mut self, align: Alignment) { if self.align == Alignment::Unspecified { self.align = align } } /// width getter pub fn width(&self) -> Option<usize> { self.width } /// thousands getter pub fn thousands(&self) -> bool { self.thousands } /// precision getter pub fn precision(&self) -> Option<usize> { self.precision } /// set precision to None, used for formatting int, float, etc pub fn set_precision(&mut self, precision: Option<usize>) { self.precision = precision; } /// sign getter pub fn sign(&self) -> Sign { self.sign.clone() } /// sign plus getter /// here because it is in fmt::Formatter pub fn sign_plus(&self) -> bool { self.sign == Sign::Plus } /// sign minus getter /// here because it is in fmt::Formatter pub fn sign_minus(&self) -> bool { self.sign == Sign::Minus } /// alternate getter pub fn alternate(&self) -> bool { self.alternate } // sign_aware_zero_pad // Not supported /// type getter pub fn ty(&self) -> Option<char> { self.ty } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting integers pub fn is_int_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'b' | 'o' | 'x' | 'X' => true, _ => false, }, } } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid for formatting floats pub fn is_float_type(&self) -> bool { match self.ty { None => true, Some(c) => match c { 'f' | 'e' | 'E' => true, _ => false, }, } } } impl<'a, 'b> fmt::Write for Formatter<'a, 'b> { fn write_str(&mut self, s: &str) -> fmt::Result { self.buff.write_str(s) } }
{ format.precision = v; }
conditional_block
align.rs
AlignMode::Global | AlignMode::Blockwise(_) => InternalMode::Global, } } } trait Align { fn align(&self, algo: &AlignAlgorithm, mode: InternalMode, x: &[u8], y: &[u8]) -> Vec<Op>; } /// Determines whether to use the banded variant of the algorithm with given k-mer length /// and window size #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] pub enum Banded { Normal, Banded { kmer: usize, window: usize }, } /// Contains parameters to run the alignment algorithm with #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(default)] pub struct AlignAlgorithm { pub gap_open: i32, pub gap_extend: i32, pub mismatch_score: i32, pub match_score: i32, pub mode: AlignMode, pub band: Banded, } impl Default for AlignAlgorithm { fn default() -> Self { AlignAlgorithm { gap_open: -5, gap_extend: -1, mismatch_score: -1, match_score: 1, mode: AlignMode::Blockwise(DEFAULT_BLOCKSIZE), band: Banded::Normal, } } } impl AlignAlgorithm { /// This function starts the threads for the alignment, which send the data over the sender. /// It should then immediately return. pub fn start_align( &self, x: FileContent, y: FileContent, addr: (usize, usize), sender: Sender<AlignedMessage>, ) { let algo = *self; match self.mode { AlignMode::Local => { // we only need one thread std::thread::spawn(move || algo.align_whole(x, y, InternalMode::Local, sender)); } AlignMode::Global => { std::thread::spawn(move || algo.align_whole(x, y, InternalMode::Global, sender)); } AlignMode::Blockwise(blocksize) => { // for Blockwise, we need one thread for each direction from the cursor // Clone the data for the second thread here let x_cp = x.clone(); let y_cp = y.clone(); let sender_cp = sender.clone(); std::thread::spawn(move || algo.align_end(x, y, addr, blocksize, sender)); std::thread::spawn(move || { algo.align_front(x_cp, y_cp, addr, blocksize, sender_cp) }); } } } pub fn start_align_with_selection( &self, files: [FileContent; 2], selection: [Option<Range<usize>>; 2], addr: [usize; 2], sender: Sender<AlignedMessage>, ) { let (selected, right, end) = match selection.clone() { [None, None] | [Some(_), Some(_)] => { let [file0, file1] = files; // if both or none are selected, just do the normal process return self.start_align(file0, file1, (addr[0], addr[1]), sender); } [Some(x), None] | [None, Some(x)] => { if x.is_empty() { // selection is empty, does not really make sense to do glocal alignment let [file0, file1] = files; return self.start_align(file0, file1, (addr[0], addr[1]), sender); } let right = selection[1].is_some(); ( x.clone(), selection[1].is_some(), addr[right as usize]!= x.start, ) } }; let algo = *self; std::thread::spawn(move || { algo.align_with_selection(files, (selected, right), end, sender) }); } fn align(&self, x: &[u8], y: &[u8], mode: InternalMode) -> Vec<Op> { if x[..] == y[..] { return vec![Op::Match; x.len()]; } if self.band == Banded::Normal { RustBio.align(self, mode, x, y) } else { align_banded(self, mode, x, y) } } /// Aligns x to y as a whole fn align_whole( &self, x: FileContent, y: FileContent, mode: InternalMode, sender: Sender<AlignedMessage>, ) { let alignment = self.align(&x, &y, mode); let _ = sender.send(AlignedMessage::Append( AlignElement::from_array(&alignment, &x, &y, 0, 0).0, )); } fn align_with_selection( &self, files: [FileContent; 2], selection: (Range<usize>, bool), end: bool, sender: Sender<AlignedMessage>, ) { let (select, right) = selection; let full_pattern = &files[right as usize].clone(); let pattern = &files[right as usize].clone()[select.clone()]; let text = &files[(!right) as usize].clone()[..]; let alignment = self.align(pattern, text, InternalMode::Semiglobal); let (alignment, textaddr) = ops_pattern_subrange(&alignment); let (mut array, pattern_end, text_end) = AlignElement::from_array(alignment, full_pattern, text, select.start, textaddr); let (start_addr, end_addr) = if right { array.iter_mut().for_each(|x| *x = x.mirror()); ((textaddr, select.start), (text_end, pattern_end)) } else { ((select.start, textaddr), (pattern_end, text_end)) }; let (prepend, append) = if end { let ap = array.pop().into_iter().collect(); (array, ap) } else { (Vec::new(), array) }; if sender.send(AlignedMessage::Append(append)).is_err() { return; } if sender.send(AlignedMessage::Prepend(prepend)).is_err() { return; } let blocksize = if let AlignMode::Blockwise(s) = self.mode { s } else { usize::MAX }; let files2 = files.clone(); let sender2 = sender.clone(); let algo = *self; std::thread::spawn(move || { algo.align_end( files2[0].clone(), files2[1].clone(), end_addr, blocksize, sender2, ); }); self.align_front( files[0].clone(), files[1].clone(), start_addr, blocksize, sender, ); } /// Blockwise alignment in the ascending address direction pub fn align_end( &self, x: FileContent, y: FileContent, addr: (usize, usize), block_size: usize, sender: Sender<AlignedMessage>, ) { let (mut xaddr, mut yaddr) = addr; // we want to have the beginning of our two arrays aligned at the same place // since we start from a previous alignment or a cursor while xaddr < x.len() && yaddr < y.len() { // align at most block_size bytes from each sequence let end_aligned = self.align( &x[xaddr..(xaddr + block_size).min(x.len())], &y[yaddr..(yaddr + block_size).min(y.len())], self.mode.into(), ); // we only actually append at most half of the block size since we make sure gaps crossing // block boundaries are better detected let ops = &end_aligned[0..end_aligned.len().min(block_size / 2)]; // we will not progress like this, so might as well quit if ops.is_empty() { break; } let (end, new_xaddr, new_yaddr) = AlignElement::from_array(ops, &x, &y, xaddr, yaddr); if sender.send(AlignedMessage::Append(end)).is_err() { return; } xaddr = new_xaddr; yaddr = new_yaddr; } let clip = if x.len() == xaddr { Op::Yclip(y.len() - yaddr) } else if y.len() == yaddr { Op::Xclip(x.len() - xaddr) } else { return; }; let leftover = AlignElement::from_array(&[clip], &x, &y, xaddr, yaddr).0; let _ = sender.send(AlignedMessage::Append(leftover)); } /// Same as align_end, but in the other direction pub fn align_front( &self, x: FileContent, y: FileContent, addr: (usize, usize), block_size: usize, sender: Sender<AlignedMessage>, ) { let (mut xaddr, mut yaddr) = addr; while xaddr > 0 && yaddr > 0 { let lower_xaddr = xaddr.saturating_sub(block_size); let lower_yaddr = yaddr.saturating_sub(block_size); let aligned = self.align( &x[lower_xaddr..xaddr], &y[lower_yaddr..yaddr], self.mode.into(), ); // unlike in align_end, we create the Alignelement from the whole array and then cut it // in half. This is because the addresses returned from from_array are at the end, which // we already know, so we instead take the start addresses from the array itself let (end, _, _) = AlignElement::from_array(&aligned, &x, &y, lower_xaddr, lower_yaddr); let real_end = Vec::from(&end[end.len().saturating_sub(block_size / 2)..end.len()]); // if this is empty, we will not progress, so send the leftover out and quit after that if real_end.is_empty() { break; } let first = real_end.first().unwrap(); xaddr = first.xaddr; yaddr = first.yaddr; if sender.send(AlignedMessage::Prepend(real_end)).is_err() { return; } } let clip = if xaddr == 0 { Op::Yclip(yaddr) } else if yaddr == 0 { Op::Xclip(xaddr) } else { return; }; let leftover = AlignElement::from_array(&[clip], &x, &y, 0, 0).0; let _ = sender.send(AlignedMessage::Prepend(leftover)); } } /// Representation of the alignment that saves the original addresses of the bytes. /// This has some space overhead, but alignment is slow enough for that not to matter in most cases. #[derive(Clone, Copy, Debug)] pub struct AlignElement { pub xaddr: usize, pub xbyte: Option<u8>, pub yaddr: usize, pub ybyte: Option<u8>, } impl AlignElement { /// mirrors the values pub fn mirror(&self) -> AlignElement { AlignElement { xaddr: self.yaddr, xbyte: self.ybyte, yaddr: self.xaddr, ybyte: self.xbyte, } } /// Creates a vector out of `AlignElement`s from the operations outputted by rust-bio. /// Also outputs the addresses at the end of the array. fn from_array( r: &[Op], x: &[u8], y: &[u8], mut xaddr: usize, mut yaddr: usize, ) -> (Vec<AlignElement>, usize, usize) { let mut v = Vec::new(); for op in r { match op { Op::Match | Op::Subst => { v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: Some(y[yaddr]), }); xaddr += 1; yaddr += 1; } Op::Ins => { v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: None, }); xaddr += 1; } Op::Del => { v.push(AlignElement { xaddr, xbyte: None, yaddr, ybyte: Some(y[yaddr]), }); yaddr += 1; } Op::Xclip(size) => { v.extend((xaddr..xaddr + size).map(|s| AlignElement { xaddr: s, xbyte: Some(x[s]), yaddr, ybyte: None, })); xaddr += size } Op::Yclip(size) => { v.extend((yaddr..yaddr + size).map(|s| AlignElement { xaddr, xbyte: None, yaddr: s, ybyte: Some(y[s]),
yaddr += size } } } (v, xaddr, yaddr) } } fn ops_pattern_subrange(mut ops: &[Op]) -> (&[Op], usize) { let mut ret_addr = 0; if let [Op::Yclip(addr), rest @..] = ops { ops = rest; ret_addr += addr; } while let [Op::Del, rest @..] = ops { ops = rest; ret_addr += 1; } while let [rest @.., Op::Del | Op::Yclip(_)] = ops { ops = rest; } (ops, ret_addr) } pub enum FlatAlignProgressMessage { Incomplete(u16), Complete(isize), } pub struct FlatAlignmentContext { is_running: Arc<AtomicBool>, vecs: [FileContent; 2], update_progress: Box<dyn FnMut(FlatAlignProgressMessage) + Send +'static>, } impl FlatAlignmentContext { pub fn new( is_running: Arc<AtomicBool>, vecs: [FileContent; 2], update_progress: Box<dyn FnMut(FlatAlignProgressMessage) + Send +'static>, ) -> Self { Self { is_running, vecs, update_progress, } } // this finds the alignment between two arrays *without* removing elements such that // fewest bytes are different (for the compvec) pub fn align_flat(mut self) { // this algorithm works by, for each byte: // * making an indicator vector for both files indicating the addresses that have the given byte // * cross-correlating them, which results in the number of matches of that byte value for each relative offset // and then adding them all together to get the total number of matching bytes let mut progress = 0u16; let current_byte = Arc::new(AtomicU16::new(0)); let mut fft_planner = RealFftPlanner::new(); let total_len = self.vecs.iter().map(|x| x.len()).max().unwrap() * 2; // the cross correlation is done using the omnipresent fft algorithm let fft_forward = fft_planner.plan_fft_forward(total_len); let fft_inverse = fft_planner.plan_fft_inverse(total_len); let mut sum = fft_forward.make_output_vec(); // this is easily parallelizable for up to 256 threads, for which we span a thread pool let thread_num = available_parallelism().map(usize::from).unwrap_or(1); let (send, recv) = std::sync::mpsc::sync_channel::<Vec<Complex64>>(4.max(thread_num)); for _ in 0..thread_num { let vecs = [self.vecs[0].clone(), self.vecs[1].clone()]; let inbyte = current_byte.clone(); let outvecs = send.clone(); let fft = fft_forward.clone(); std::thread::spawn(move || correlation_thread(vecs, inbyte, outvecs, fft)); } for vec in recv.into_iter().take(256) { if!self.is_running.load(Ordering::Relaxed) { return; } // add the vectors together in the frequency domain for (a, b) in sum.iter_mut().zip(vec.into_iter()) { *a += b; } progress += 1; (self.update_progress)(FlatAlignProgressMessage::Incomplete(progress)); } // get the actual result in the time domain let mut result = fft_inverse.make_output_vec(); fft_inverse .process(&mut sum, &mut result) .expect("Wrong lengths"); drop(sum); // positive offset of the array with the highest value of overlap let offset = result .iter() .enumerate() .max_by(|a, b| { a.1.partial_cmp(b.1).unwrap_or_else(|| { if a.1.is_nan() { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }) }) .unwrap_or
}));
random_line_split
align.rs
{ Local, Global, Semiglobal, } impl From<AlignMode> for InternalMode { fn from(value: AlignMode) -> Self { match value { AlignMode::Local => InternalMode::Local, AlignMode::Global | AlignMode::Blockwise(_) => InternalMode::Global, } } } trait Align { fn align(&self, algo: &AlignAlgorithm, mode: InternalMode, x: &[u8], y: &[u8]) -> Vec<Op>; } /// Determines whether to use the banded variant of the algorithm with given k-mer length /// and window size #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] pub enum Banded { Normal, Banded { kmer: usize, window: usize }, } /// Contains parameters to run the alignment algorithm with #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(default)] pub struct AlignAlgorithm { pub gap_open: i32, pub gap_extend: i32, pub mismatch_score: i32, pub match_score: i32, pub mode: AlignMode, pub band: Banded, } impl Default for AlignAlgorithm { fn default() -> Self { AlignAlgorithm { gap_open: -5, gap_extend: -1, mismatch_score: -1, match_score: 1, mode: AlignMode::Blockwise(DEFAULT_BLOCKSIZE), band: Banded::Normal, } } } impl AlignAlgorithm { /// This function starts the threads for the alignment, which send the data over the sender. /// It should then immediately return. pub fn start_align( &self, x: FileContent, y: FileContent, addr: (usize, usize), sender: Sender<AlignedMessage>, ) { let algo = *self; match self.mode { AlignMode::Local => { // we only need one thread std::thread::spawn(move || algo.align_whole(x, y, InternalMode::Local, sender)); } AlignMode::Global => { std::thread::spawn(move || algo.align_whole(x, y, InternalMode::Global, sender)); } AlignMode::Blockwise(blocksize) => { // for Blockwise, we need one thread for each direction from the cursor // Clone the data for the second thread here let x_cp = x.clone(); let y_cp = y.clone(); let sender_cp = sender.clone(); std::thread::spawn(move || algo.align_end(x, y, addr, blocksize, sender)); std::thread::spawn(move || { algo.align_front(x_cp, y_cp, addr, blocksize, sender_cp) }); } } } pub fn start_align_with_selection( &self, files: [FileContent; 2], selection: [Option<Range<usize>>; 2], addr: [usize; 2], sender: Sender<AlignedMessage>, ) { let (selected, right, end) = match selection.clone() { [None, None] | [Some(_), Some(_)] => { let [file0, file1] = files; // if both or none are selected, just do the normal process return self.start_align(file0, file1, (addr[0], addr[1]), sender); } [Some(x), None] | [None, Some(x)] => { if x.is_empty() { // selection is empty, does not really make sense to do glocal alignment let [file0, file1] = files; return self.start_align(file0, file1, (addr[0], addr[1]), sender); } let right = selection[1].is_some(); ( x.clone(), selection[1].is_some(), addr[right as usize]!= x.start, ) } }; let algo = *self; std::thread::spawn(move || { algo.align_with_selection(files, (selected, right), end, sender) }); } fn align(&self, x: &[u8], y: &[u8], mode: InternalMode) -> Vec<Op> { if x[..] == y[..] { return vec![Op::Match; x.len()]; } if self.band == Banded::Normal { RustBio.align(self, mode, x, y) } else { align_banded(self, mode, x, y) } } /// Aligns x to y as a whole fn align_whole( &self, x: FileContent, y: FileContent, mode: InternalMode, sender: Sender<AlignedMessage>, ) { let alignment = self.align(&x, &y, mode); let _ = sender.send(AlignedMessage::Append( AlignElement::from_array(&alignment, &x, &y, 0, 0).0, )); } fn align_with_selection( &self, files: [FileContent; 2], selection: (Range<usize>, bool), end: bool, sender: Sender<AlignedMessage>, ) { let (select, right) = selection; let full_pattern = &files[right as usize].clone(); let pattern = &files[right as usize].clone()[select.clone()]; let text = &files[(!right) as usize].clone()[..]; let alignment = self.align(pattern, text, InternalMode::Semiglobal); let (alignment, textaddr) = ops_pattern_subrange(&alignment); let (mut array, pattern_end, text_end) = AlignElement::from_array(alignment, full_pattern, text, select.start, textaddr); let (start_addr, end_addr) = if right { array.iter_mut().for_each(|x| *x = x.mirror()); ((textaddr, select.start), (text_end, pattern_end)) } else { ((select.start, textaddr), (pattern_end, text_end)) }; let (prepend, append) = if end { let ap = array.pop().into_iter().collect(); (array, ap) } else { (Vec::new(), array) }; if sender.send(AlignedMessage::Append(append)).is_err() { return; } if sender.send(AlignedMessage::Prepend(prepend)).is_err() { return; } let blocksize = if let AlignMode::Blockwise(s) = self.mode { s } else { usize::MAX }; let files2 = files.clone(); let sender2 = sender.clone(); let algo = *self; std::thread::spawn(move || { algo.align_end( files2[0].clone(), files2[1].clone(), end_addr, blocksize, sender2, ); }); self.align_front( files[0].clone(), files[1].clone(), start_addr, blocksize, sender, ); } /// Blockwise alignment in the ascending address direction pub fn align_end( &self, x: FileContent, y: FileContent, addr: (usize, usize), block_size: usize, sender: Sender<AlignedMessage>, ) { let (mut xaddr, mut yaddr) = addr; // we want to have the beginning of our two arrays aligned at the same place // since we start from a previous alignment or a cursor while xaddr < x.len() && yaddr < y.len() { // align at most block_size bytes from each sequence let end_aligned = self.align( &x[xaddr..(xaddr + block_size).min(x.len())], &y[yaddr..(yaddr + block_size).min(y.len())], self.mode.into(), ); // we only actually append at most half of the block size since we make sure gaps crossing // block boundaries are better detected let ops = &end_aligned[0..end_aligned.len().min(block_size / 2)]; // we will not progress like this, so might as well quit if ops.is_empty() { break; } let (end, new_xaddr, new_yaddr) = AlignElement::from_array(ops, &x, &y, xaddr, yaddr); if sender.send(AlignedMessage::Append(end)).is_err() { return; } xaddr = new_xaddr; yaddr = new_yaddr; } let clip = if x.len() == xaddr { Op::Yclip(y.len() - yaddr) } else if y.len() == yaddr { Op::Xclip(x.len() - xaddr) } else { return; }; let leftover = AlignElement::from_array(&[clip], &x, &y, xaddr, yaddr).0; let _ = sender.send(AlignedMessage::Append(leftover)); } /// Same as align_end, but in the other direction pub fn align_front( &self, x: FileContent, y: FileContent, addr: (usize, usize), block_size: usize, sender: Sender<AlignedMessage>, ) { let (mut xaddr, mut yaddr) = addr; while xaddr > 0 && yaddr > 0 { let lower_xaddr = xaddr.saturating_sub(block_size); let lower_yaddr = yaddr.saturating_sub(block_size); let aligned = self.align( &x[lower_xaddr..xaddr], &y[lower_yaddr..yaddr], self.mode.into(), ); // unlike in align_end, we create the Alignelement from the whole array and then cut it // in half. This is because the addresses returned from from_array are at the end, which // we already know, so we instead take the start addresses from the array itself let (end, _, _) = AlignElement::from_array(&aligned, &x, &y, lower_xaddr, lower_yaddr); let real_end = Vec::from(&end[end.len().saturating_sub(block_size / 2)..end.len()]); // if this is empty, we will not progress, so send the leftover out and quit after that if real_end.is_empty() { break; } let first = real_end.first().unwrap(); xaddr = first.xaddr; yaddr = first.yaddr; if sender.send(AlignedMessage::Prepend(real_end)).is_err() { return; } } let clip = if xaddr == 0 { Op::Yclip(yaddr) } else if yaddr == 0 { Op::Xclip(xaddr) } else { return; }; let leftover = AlignElement::from_array(&[clip], &x, &y, 0, 0).0; let _ = sender.send(AlignedMessage::Prepend(leftover)); } } /// Representation of the alignment that saves the original addresses of the bytes. /// This has some space overhead, but alignment is slow enough for that not to matter in most cases. #[derive(Clone, Copy, Debug)] pub struct AlignElement { pub xaddr: usize, pub xbyte: Option<u8>, pub yaddr: usize, pub ybyte: Option<u8>, } impl AlignElement { /// mirrors the values pub fn mirror(&self) -> AlignElement { AlignElement { xaddr: self.yaddr, xbyte: self.ybyte, yaddr: self.xaddr, ybyte: self.xbyte, } } /// Creates a vector out of `AlignElement`s from the operations outputted by rust-bio. /// Also outputs the addresses at the end of the array. fn from_array( r: &[Op], x: &[u8], y: &[u8], mut xaddr: usize, mut yaddr: usize, ) -> (Vec<AlignElement>, usize, usize) { let mut v = Vec::new(); for op in r { match op { Op::Match | Op::Subst => { v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: Some(y[yaddr]), }); xaddr += 1; yaddr += 1; } Op::Ins => { v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: None, }); xaddr += 1; } Op::Del => { v.push(AlignElement { xaddr, xbyte: None, yaddr, ybyte: Some(y[yaddr]), }); yaddr += 1; } Op::Xclip(size) => { v.extend((xaddr..xaddr + size).map(|s| AlignElement { xaddr: s, xbyte: Some(x[s]), yaddr, ybyte: None, })); xaddr += size } Op::Yclip(size) => { v.extend((yaddr..yaddr + size).map(|s| AlignElement { xaddr, xbyte: None, yaddr: s, ybyte: Some(y[s]), })); yaddr += size } } } (v, xaddr, yaddr) } } fn ops_pattern_subrange(mut ops: &[Op]) -> (&[Op], usize) { let mut ret_addr = 0; if let [Op::Yclip(addr), rest @..] = ops { ops = rest; ret_addr += addr; } while let [Op::Del, rest @..] = ops { ops = rest; ret_addr += 1; } while let [rest @.., Op::Del | Op::Yclip(_)] = ops { ops = rest; } (ops, ret_addr) } pub enum FlatAlignProgressMessage { Incomplete(u16), Complete(isize), } pub struct FlatAlignmentContext { is_running: Arc<AtomicBool>, vecs: [FileContent; 2], update_progress: Box<dyn FnMut(FlatAlignProgressMessage) + Send +'static>, } impl FlatAlignmentContext { pub fn new( is_running: Arc<AtomicBool>, vecs: [FileContent; 2], update_progress: Box<dyn FnMut(FlatAlignProgressMessage) + Send +'static>, ) -> Self { Self { is_running, vecs, update_progress, } } // this finds the alignment between two arrays *without* removing elements such that // fewest bytes are different (for the compvec) pub fn align_flat(mut self) { // this algorithm works by, for each byte: // * making an indicator vector for both files indicating the addresses that have the given byte // * cross-correlating them, which results in the number of matches of that byte value for each relative offset // and then adding them all together to get the total number of matching bytes let mut progress = 0u16; let current_byte = Arc::new(AtomicU16::new(0)); let mut fft_planner = RealFftPlanner::new(); let total_len = self.vecs.iter().map(|x| x.len()).max().unwrap() * 2; // the cross correlation is done using the omnipresent fft algorithm let fft_forward = fft_planner.plan_fft_forward(total_len); let fft_inverse = fft_planner.plan_fft_inverse(total_len); let mut sum = fft_forward.make_output_vec(); // this is easily parallelizable for up to 256 threads, for which we span a thread pool let thread_num = available_parallelism().map(usize::from).unwrap_or(1); let (send, recv) = std::sync::mpsc::sync_channel::<Vec<Complex64>>(4.max(thread_num)); for _ in 0..thread_num { let vecs = [self.vecs[0].clone(), self.vecs[1].clone()]; let inbyte = current_byte.clone(); let outvecs = send.clone(); let fft = fft_forward.clone(); std::thread::spawn(move || correlation_thread(vecs, inbyte, outvecs, fft)); } for vec in recv.into_iter().take(256) { if!self.is_running.load(Ordering::Relaxed) { return; } // add the vectors together in the frequency domain for (a, b) in sum.iter_mut().zip(vec.into_iter()) { *a += b; } progress += 1; (self.update_progress)(FlatAlignProgressMessage::Incomplete(progress)); } // get the actual result in the time domain let mut result = fft_inverse.make_output_vec(); fft_inverse .process(&mut sum, &mut result) .expect("Wrong lengths"); drop(sum); // positive offset of the array with the highest value of overlap let offset = result .iter() .enumerate() .max_by(|a, b| { a.1.partial_cmp(b.1).unwrap_or_else(|| { if a.1.is_nan() { std::cmp::Ordering::Less } else {
InternalMode
identifier_name
align.rs
AlignMode::Global | AlignMode::Blockwise(_) => InternalMode::Global, } } } trait Align { fn align(&self, algo: &AlignAlgorithm, mode: InternalMode, x: &[u8], y: &[u8]) -> Vec<Op>; } /// Determines whether to use the banded variant of the algorithm with given k-mer length /// and window size #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] pub enum Banded { Normal, Banded { kmer: usize, window: usize }, } /// Contains parameters to run the alignment algorithm with #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(default)] pub struct AlignAlgorithm { pub gap_open: i32, pub gap_extend: i32, pub mismatch_score: i32, pub match_score: i32, pub mode: AlignMode, pub band: Banded, } impl Default for AlignAlgorithm { fn default() -> Self { AlignAlgorithm { gap_open: -5, gap_extend: -1, mismatch_score: -1, match_score: 1, mode: AlignMode::Blockwise(DEFAULT_BLOCKSIZE), band: Banded::Normal, } } } impl AlignAlgorithm { /// This function starts the threads for the alignment, which send the data over the sender. /// It should then immediately return. pub fn start_align( &self, x: FileContent, y: FileContent, addr: (usize, usize), sender: Sender<AlignedMessage>, ) { let algo = *self; match self.mode { AlignMode::Local => { // we only need one thread std::thread::spawn(move || algo.align_whole(x, y, InternalMode::Local, sender)); } AlignMode::Global => { std::thread::spawn(move || algo.align_whole(x, y, InternalMode::Global, sender)); } AlignMode::Blockwise(blocksize) => { // for Blockwise, we need one thread for each direction from the cursor // Clone the data for the second thread here let x_cp = x.clone(); let y_cp = y.clone(); let sender_cp = sender.clone(); std::thread::spawn(move || algo.align_end(x, y, addr, blocksize, sender)); std::thread::spawn(move || { algo.align_front(x_cp, y_cp, addr, blocksize, sender_cp) }); } } } pub fn start_align_with_selection( &self, files: [FileContent; 2], selection: [Option<Range<usize>>; 2], addr: [usize; 2], sender: Sender<AlignedMessage>, ) { let (selected, right, end) = match selection.clone() { [None, None] | [Some(_), Some(_)] => { let [file0, file1] = files; // if both or none are selected, just do the normal process return self.start_align(file0, file1, (addr[0], addr[1]), sender); } [Some(x), None] | [None, Some(x)] => { if x.is_empty() { // selection is empty, does not really make sense to do glocal alignment let [file0, file1] = files; return self.start_align(file0, file1, (addr[0], addr[1]), sender); } let right = selection[1].is_some(); ( x.clone(), selection[1].is_some(), addr[right as usize]!= x.start, ) } }; let algo = *self; std::thread::spawn(move || { algo.align_with_selection(files, (selected, right), end, sender) }); } fn align(&self, x: &[u8], y: &[u8], mode: InternalMode) -> Vec<Op> { if x[..] == y[..] { return vec![Op::Match; x.len()]; } if self.band == Banded::Normal { RustBio.align(self, mode, x, y) } else { align_banded(self, mode, x, y) } } /// Aligns x to y as a whole fn align_whole( &self, x: FileContent, y: FileContent, mode: InternalMode, sender: Sender<AlignedMessage>, ) { let alignment = self.align(&x, &y, mode); let _ = sender.send(AlignedMessage::Append( AlignElement::from_array(&alignment, &x, &y, 0, 0).0, )); } fn align_with_selection( &self, files: [FileContent; 2], selection: (Range<usize>, bool), end: bool, sender: Sender<AlignedMessage>, ) { let (select, right) = selection; let full_pattern = &files[right as usize].clone(); let pattern = &files[right as usize].clone()[select.clone()]; let text = &files[(!right) as usize].clone()[..]; let alignment = self.align(pattern, text, InternalMode::Semiglobal); let (alignment, textaddr) = ops_pattern_subrange(&alignment); let (mut array, pattern_end, text_end) = AlignElement::from_array(alignment, full_pattern, text, select.start, textaddr); let (start_addr, end_addr) = if right { array.iter_mut().for_each(|x| *x = x.mirror()); ((textaddr, select.start), (text_end, pattern_end)) } else { ((select.start, textaddr), (pattern_end, text_end)) }; let (prepend, append) = if end { let ap = array.pop().into_iter().collect(); (array, ap) } else { (Vec::new(), array) }; if sender.send(AlignedMessage::Append(append)).is_err() { return; } if sender.send(AlignedMessage::Prepend(prepend)).is_err() { return; } let blocksize = if let AlignMode::Blockwise(s) = self.mode { s } else { usize::MAX }; let files2 = files.clone(); let sender2 = sender.clone(); let algo = *self; std::thread::spawn(move || { algo.align_end( files2[0].clone(), files2[1].clone(), end_addr, blocksize, sender2, ); }); self.align_front( files[0].clone(), files[1].clone(), start_addr, blocksize, sender, ); } /// Blockwise alignment in the ascending address direction pub fn align_end( &self, x: FileContent, y: FileContent, addr: (usize, usize), block_size: usize, sender: Sender<AlignedMessage>, ) { let (mut xaddr, mut yaddr) = addr; // we want to have the beginning of our two arrays aligned at the same place // since we start from a previous alignment or a cursor while xaddr < x.len() && yaddr < y.len() { // align at most block_size bytes from each sequence let end_aligned = self.align( &x[xaddr..(xaddr + block_size).min(x.len())], &y[yaddr..(yaddr + block_size).min(y.len())], self.mode.into(), ); // we only actually append at most half of the block size since we make sure gaps crossing // block boundaries are better detected let ops = &end_aligned[0..end_aligned.len().min(block_size / 2)]; // we will not progress like this, so might as well quit if ops.is_empty() { break; } let (end, new_xaddr, new_yaddr) = AlignElement::from_array(ops, &x, &y, xaddr, yaddr); if sender.send(AlignedMessage::Append(end)).is_err() { return; } xaddr = new_xaddr; yaddr = new_yaddr; } let clip = if x.len() == xaddr { Op::Yclip(y.len() - yaddr) } else if y.len() == yaddr { Op::Xclip(x.len() - xaddr) } else { return; }; let leftover = AlignElement::from_array(&[clip], &x, &y, xaddr, yaddr).0; let _ = sender.send(AlignedMessage::Append(leftover)); } /// Same as align_end, but in the other direction pub fn align_front( &self, x: FileContent, y: FileContent, addr: (usize, usize), block_size: usize, sender: Sender<AlignedMessage>, ) { let (mut xaddr, mut yaddr) = addr; while xaddr > 0 && yaddr > 0 { let lower_xaddr = xaddr.saturating_sub(block_size); let lower_yaddr = yaddr.saturating_sub(block_size); let aligned = self.align( &x[lower_xaddr..xaddr], &y[lower_yaddr..yaddr], self.mode.into(), ); // unlike in align_end, we create the Alignelement from the whole array and then cut it // in half. This is because the addresses returned from from_array are at the end, which // we already know, so we instead take the start addresses from the array itself let (end, _, _) = AlignElement::from_array(&aligned, &x, &y, lower_xaddr, lower_yaddr); let real_end = Vec::from(&end[end.len().saturating_sub(block_size / 2)..end.len()]); // if this is empty, we will not progress, so send the leftover out and quit after that if real_end.is_empty() { break; } let first = real_end.first().unwrap(); xaddr = first.xaddr; yaddr = first.yaddr; if sender.send(AlignedMessage::Prepend(real_end)).is_err() { return; } } let clip = if xaddr == 0 { Op::Yclip(yaddr) } else if yaddr == 0 { Op::Xclip(xaddr) } else { return; }; let leftover = AlignElement::from_array(&[clip], &x, &y, 0, 0).0; let _ = sender.send(AlignedMessage::Prepend(leftover)); } } /// Representation of the alignment that saves the original addresses of the bytes. /// This has some space overhead, but alignment is slow enough for that not to matter in most cases. #[derive(Clone, Copy, Debug)] pub struct AlignElement { pub xaddr: usize, pub xbyte: Option<u8>, pub yaddr: usize, pub ybyte: Option<u8>, } impl AlignElement { /// mirrors the values pub fn mirror(&self) -> AlignElement { AlignElement { xaddr: self.yaddr, xbyte: self.ybyte, yaddr: self.xaddr, ybyte: self.xbyte, } } /// Creates a vector out of `AlignElement`s from the operations outputted by rust-bio. /// Also outputs the addresses at the end of the array. fn from_array( r: &[Op], x: &[u8], y: &[u8], mut xaddr: usize, mut yaddr: usize, ) -> (Vec<AlignElement>, usize, usize) { let mut v = Vec::new(); for op in r { match op { Op::Match | Op::Subst => { v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: Some(y[yaddr]), }); xaddr += 1; yaddr += 1; } Op::Ins =>
Op::Del => { v.push(AlignElement { xaddr, xbyte: None, yaddr, ybyte: Some(y[yaddr]), }); yaddr += 1; } Op::Xclip(size) => { v.extend((xaddr..xaddr + size).map(|s| AlignElement { xaddr: s, xbyte: Some(x[s]), yaddr, ybyte: None, })); xaddr += size } Op::Yclip(size) => { v.extend((yaddr..yaddr + size).map(|s| AlignElement { xaddr, xbyte: None, yaddr: s, ybyte: Some(y[s]), })); yaddr += size } } } (v, xaddr, yaddr) } } fn ops_pattern_subrange(mut ops: &[Op]) -> (&[Op], usize) { let mut ret_addr = 0; if let [Op::Yclip(addr), rest @..] = ops { ops = rest; ret_addr += addr; } while let [Op::Del, rest @..] = ops { ops = rest; ret_addr += 1; } while let [rest @.., Op::Del | Op::Yclip(_)] = ops { ops = rest; } (ops, ret_addr) } pub enum FlatAlignProgressMessage { Incomplete(u16), Complete(isize), } pub struct FlatAlignmentContext { is_running: Arc<AtomicBool>, vecs: [FileContent; 2], update_progress: Box<dyn FnMut(FlatAlignProgressMessage) + Send +'static>, } impl FlatAlignmentContext { pub fn new( is_running: Arc<AtomicBool>, vecs: [FileContent; 2], update_progress: Box<dyn FnMut(FlatAlignProgressMessage) + Send +'static>, ) -> Self { Self { is_running, vecs, update_progress, } } // this finds the alignment between two arrays *without* removing elements such that // fewest bytes are different (for the compvec) pub fn align_flat(mut self) { // this algorithm works by, for each byte: // * making an indicator vector for both files indicating the addresses that have the given byte // * cross-correlating them, which results in the number of matches of that byte value for each relative offset // and then adding them all together to get the total number of matching bytes let mut progress = 0u16; let current_byte = Arc::new(AtomicU16::new(0)); let mut fft_planner = RealFftPlanner::new(); let total_len = self.vecs.iter().map(|x| x.len()).max().unwrap() * 2; // the cross correlation is done using the omnipresent fft algorithm let fft_forward = fft_planner.plan_fft_forward(total_len); let fft_inverse = fft_planner.plan_fft_inverse(total_len); let mut sum = fft_forward.make_output_vec(); // this is easily parallelizable for up to 256 threads, for which we span a thread pool let thread_num = available_parallelism().map(usize::from).unwrap_or(1); let (send, recv) = std::sync::mpsc::sync_channel::<Vec<Complex64>>(4.max(thread_num)); for _ in 0..thread_num { let vecs = [self.vecs[0].clone(), self.vecs[1].clone()]; let inbyte = current_byte.clone(); let outvecs = send.clone(); let fft = fft_forward.clone(); std::thread::spawn(move || correlation_thread(vecs, inbyte, outvecs, fft)); } for vec in recv.into_iter().take(256) { if!self.is_running.load(Ordering::Relaxed) { return; } // add the vectors together in the frequency domain for (a, b) in sum.iter_mut().zip(vec.into_iter()) { *a += b; } progress += 1; (self.update_progress)(FlatAlignProgressMessage::Incomplete(progress)); } // get the actual result in the time domain let mut result = fft_inverse.make_output_vec(); fft_inverse .process(&mut sum, &mut result) .expect("Wrong lengths"); drop(sum); // positive offset of the array with the highest value of overlap let offset = result .iter() .enumerate() .max_by(|a, b| { a.1.partial_cmp(b.1).unwrap_or_else(|| { if a.1.is_nan() { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }) }) .unwrap_o
{ v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: None, }); xaddr += 1; }
conditional_block
efi.rs
use core::ffi::c_void; use core::fmt; const ERROR_BIT: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); #[derive(Clone, Copy)] #[repr(transparent)] pub struct EFI_HANDLE(*mut c_void); #[derive(PartialEq, Debug)] #[repr(usize)] pub enum EFI_STATUS { /// The operation completed successfully. SUCCESS = 0, /// The string contained characters that could not be rendered and were skipped. WARN_UNKNOWN_GLYPH = 1, /// The handle was closed, but the file was not deleted. WARN_DELETE_FAILURE = 2, /// The handle was closed, but the data to the file was not flushed properly. WARN_WRITE_FAILURE = 3, /// The resulting buffer was too small, and the data was truncated. WARN_BUFFER_TOO_SMALL = 4, /// The data has not been updated within the timeframe set by local policy. WARN_STALE_DATA = 5, /// The resulting buffer contains UEFI-compliant file system. WARN_FILE_SYSTEM = 6, /// The operation will be processed across a system reset. WARN_RESET_REQUIRED = 7, /// The image failed to load. LOAD_ERROR = ERROR_BIT | 1, /// A parameter was incorrect. INVALID_PARAMETER = ERROR_BIT | 2, /// The operation is not supported. UNSUPPORTED = ERROR_BIT | 3, /// The buffer was not the proper size for the request. BAD_BUFFER_SIZE = ERROR_BIT | 4, /// The buffer is not large enough to hold the requested data. /// The required buffer size is returned in the appropriate parameter. BUFFER_TOO_SMALL = ERROR_BIT | 5, /// There is no data pending upon return. NOT_READY = ERROR_BIT | 6, /// The physical device reported an error while attempting the operation. DEVICE_ERROR = ERROR_BIT | 7, /// The device cannot be written to. WRITE_PROTECTED = ERROR_BIT | 8, /// A resource has run out. OUT_OF_RESOURCES = ERROR_BIT | 9, /// An inconstency was detected on the file system. VOLUME_CORRUPTED = ERROR_BIT | 10, /// There is no more space on the file system. VOLUME_FULL = ERROR_BIT | 11, /// The device does not contain any medium to perform the operation. NO_MEDIA = ERROR_BIT | 12, /// The medium in the device has changed since the last access. MEDIA_CHANGED = ERROR_BIT | 13, /// The item was not found. NOT_FOUND = ERROR_BIT | 14, /// Access was denied. ACCESS_DENIED = ERROR_BIT | 15, /// The server was not found or did not respond to the request. NO_RESPONSE = ERROR_BIT | 16, /// A mapping to a device does not exist. NO_MAPPING = ERROR_BIT | 17, /// The timeout time expired. TIMEOUT = ERROR_BIT | 18, /// The protocol has not been started. NOT_STARTED = ERROR_BIT | 19, /// The protocol has already been started. ALREADY_STARTED = ERROR_BIT | 20, /// The operation was aborted. ABORTED = ERROR_BIT | 21, /// An ICMP error occurred during the network operation. ICMP_ERROR = ERROR_BIT | 22, /// A TFTP error occurred during the network operation. TFTP_ERROR = ERROR_BIT | 23, /// A protocol error occurred during the network operation. PROTOCOL_ERROR = ERROR_BIT | 24, /// The function encountered an internal version that was /// incompatible with a version requested by the caller. INCOMPATIBLE_VERSION = ERROR_BIT | 25, /// The function was not performed due to a security violation. SECURITY_VIOLATION = ERROR_BIT | 26, /// A CRC error was detected. CRC_ERROR = ERROR_BIT | 27, /// Beginning or end of media was reached END_OF_MEDIA = ERROR_BIT | 28, /// The end of the file was reached. END_OF_FILE = ERROR_BIT | 31, /// The language specified was invalid. INVALID_LANGUAGE = ERROR_BIT | 32, /// The security status of the data is unknown or compromised and /// the data must be updated or replaced to restore a valid security status. COMPROMISED_DATA = ERROR_BIT | 33, /// There is an address conflict address allocation IP_ADDRESS_CONFLICT = ERROR_BIT | 34, /// A HTTP error occurred during the network operation. HTTP_ERROR = ERROR_BIT | 35, } #[repr(C)] pub struct EFI_SYSTEM_TABLE { pub Hdr: EFI_TABLE_HEADER, pub FirmwareVendor: *const u16, pub FirmwareRevision: u32, pub ConsoleInHandle: EFI_HANDLE, pub ConIn: *mut EFI_SIMPLE_TEXT_INPUT_PROTOCOL, pub ConsoleOutHandle: EFI_HANDLE, pub ConOut: *mut EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, pub StandardErrorHandle: EFI_HANDLE, pub StdErr: *mut EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, pub RuntimeServices: *mut EFI_RUNTIME_SERVICES, pub BootServices: *mut EFI_BOOT_SERVICES, pub NumberOfTableEntries: usize, pub ConfigurationTable: *mut EFI_CONFIGURATION_TABLE, } #[repr(C)] pub struct EFI_RUNTIME_SERVICES { pub Hdr: EFI_TABLE_HEADER, pub GetTime: unsafe extern "C" fn(Time: *mut EFI_TIME, Capabilities: *mut EFI_TIME_CAPABILITIES) -> EFI_STATUS, dummy1: [usize;3], // Time Services dummy2: [usize;2], // Virtual Memory Services dummy3: [usize;3], // Variable Services dummy4: [usize;2], // Miscellaneous Services dummy5: [usize;2], // UEFI 2.0 Capsule Services dummy6: [usize;1], // Miscellaneous UEFI 2.0 Service } #[repr(C)] pub struct EFI_BOOT_SERVICES { pub Hdr: EFI_TABLE_HEADER, // Task Priority Services dummy1: [usize;2], // Memory Services pub AllocatePages: unsafe extern "C" fn(Type: EFI_ALLOCATE_TYPE, MemoryType: EFI_MEMORY_TYPE, Pages:usize, Memory: &mut u64) -> EFI_STATUS, dymmy2a: [usize;1], pub GetMemoryMap: unsafe extern "C" fn(MemoryMapSize: &mut usize, MemoryMap: *mut EFI_MEMORY_DESCRIPTOR, MapKey: &mut usize, DescriptorSize: &mut usize, DescriptorVersion: &mut u32) -> EFI_STATUS, dummy2b: [usize;2], // Event & Timer Services dummy3: [usize;6], // Protocol Handler Services dummy4a: [usize;3], pub HandleProtocol: unsafe extern "C" fn(Handle: EFI_HANDLE, Protocol: &EFI_GUID, Interface: &mut *mut c_void) -> EFI_STATUS, dummy4b: [usize;4], // Image Services dummy5: [usize;5], // Miscellaneous Services dummy6: [usize;2], pub SetWatchdogTimer: unsafe extern "C" fn (Timeout: usize, WatchdogCode: u64, DataSize: usize, WatchdogData: *const u16) -> EFI_STATUS, // DriverSupport Services dummy7: [usize;2], // Open and Close Protocol Services dummy8: [usize;3], // Library Services dummy9a: [usize;2], pub LocateProtocol: unsafe extern "C" fn (Protocol: &EFI_GUID, Registration: *mut c_void, Interface: &mut *mut c_void) -> EFI_STATUS, dummy9b: [usize;2], // 32-bit CRC Services dummy10: [usize;1], // Miscellaneous Services dummy11: [usize;3], } #[repr(C)] pub struct EFI_CONFIGURATION_TABLE { pub Hdr: EFI_TABLE_HEADER, // TBD } #[repr(C)] pub struct EFI_TABLE_HEADER { pub Signature: u64, pub Revision: u32, pub HeaderSize: u32, pub CRC32: u32, pub Reserved: u32, } #[repr(C)] pub struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL { pub Reset: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_INPUT_PROTOCOL, ExtendedVerification: bool) -> EFI_STATUS, pub ReadKeyStroke: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_INPUT_PROTOCOL, Key: &EFI_INPUT_KEY) -> EFI_STATUS, // TBD } #[repr(C)] pub struct EFI_INPUT_KEY { pub ScanCode: u16, pub UnicodeChar: u16, } #[repr(C)] pub struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL { pub Reset: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, ExtendedVerification: bool) -> EFI_STATUS, pub OutputString: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, String: *const u16) -> EFI_STATUS, // TBD } #[derive(PartialEq)] #[repr(usize)] pub enum EFI_ALLOCATE_TYPE { AllocateAnyPages, AllocateMaxAddress, AllocateAddress, MaxAllocateType, } #[derive(Debug, PartialEq, Copy, Clone)] #[repr(u32)] pub enum EFI_MEMORY_TYPE { EfiReservedMemoryType, EfiLoaderCode, EfiLoaderData, EfiBootServicesCode, EfiBootServicesData, EfiRuntimeServicesCode, EfiRuntimeServicesData, EfiConventionalMemory, EfiUnusableMemory, EfiACPIReclaimMemory, EfiACPIMemoryNVS, EfiMemoryMappedIO, EfiMemoryMappedIOPortSpace, EfiPalCode, EfiPersistentMemory, EfiMaxMemoryType, } impl fmt::Display for EFI_MEMORY_TYPE { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(C)] pub struct MemoryMapKey(usize); #[repr(C)] #[derive(Copy, Clone)] pub struct EFI_MEMORY_DESCRIPTOR { pub Type: EFI_MEMORY_TYPE, padding: u32, pub PhysicalStart: u64, pub VirtualStart: u64, pub NumberOfPages: u64, pub Attribute: u64, } impl fmt::Display for EFI_MEMORY_DESCRIPTOR { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {:x}-{:x}", self.Type, self.PhysicalStart, self.PhysicalStart+self.NumberOfPages*4096) } } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct EFI_TIME { pub Year: u16, pub Month: u8, pub Day: u8, pub Hour: u8, pub Minute: u8, pub Second: u8, pub Pad1: u8, pub Nanosecond: u32, pub TimeZone: u16, pub Daylight: u8, pub Pad2: u8, } #[repr(C)] pub struct EFI_TIME_CAPABILITIES { pub Resolution: u32, pub Accuracy: u32, pub SetsToZero: bool, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(C)] pub struct EFI_GUID { pub a: u32, pub b: u16, pub c: u16, pub d: [u8;8], } #[repr(C)] pub struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL { pub Revision: u64, pub OpenVolume: unsafe extern "C" fn(This: &mut EFI_SIMPLE_FILE_SYSTEM_PROTOCOL, Root: &mut *mut EFI_FILE_PROTOCOL) -> EFI_STATUS, } #[repr(C)] pub struct EFI_FILE_PROTOCOL { pub Revision: u64, pub Open: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL, NewHandle: &mut *mut EFI_FILE_PROTOCOL, FileName: *const u16, OpenMode: EFI_FILE_MODE, Attributes: EFI_FILE_ATTRIBUTE) -> EFI_STATUS, pub Close: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL) -> EFI_STATUS, pub Delete: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL) -> EFI_STATUS, pub Read: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL, BufferSize: &mut usize, Buffer: *mut u8) -> EFI_STATUS, // TBD } #[repr(C)] pub struct EFI_LOADED_IMAGE_PROTOCOL { pub Revision: u32, pub ParentHandle: EFI_HANDLE, pub SystemTable: *const EFI_SYSTEM_TABLE, pub DeviceHandle: EFI_HANDLE, pub FilePath: *const c_void, pub Reserved: *const c_void, pub LoadOptionsSize: u32, pub LoadOptions: *const c_void, pub ImageBase: usize, pub ImageSize: u64, pub ImageCodeType: EFI_MEMORY_TYPE, pub ImageDataType: EFI_MEMORY_TYPE, pub Unload: unsafe extern "C" fn(ImageHandle: EFI_HANDLE) -> EFI_STATUS, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u64)] pub enum EFI_FILE_MODE { EFI_FILE_MODE_READ = 1, EFI_FILE_MODE_WRITE = 2 | 1, EFI_FILE_MODE_CREATE = (1 << 63) | 2 | 1, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u64)] pub enum EFI_FILE_ATTRIBUTE { EFI_FILE_READ_ONLY = 1, EFI_FILE_HIDDEN = 1 << 1, EFI_FILE_SYSTEM = 1 << 2, EFI_FILE_RESERVED = 1 << 3, EFI_FILE_DIRECTORY = 1 << 4, EFI_FILE_ARCHIVE = 1 << 5, EFI_FILE_VALID_ATTR = 0x37, }
{ let string = match *self { EFI_MEMORY_TYPE::EfiReservedMemoryType => "ReservedMemory", EFI_MEMORY_TYPE::EfiLoaderCode => "LoaderCode", EFI_MEMORY_TYPE::EfiLoaderData => "LoaderData", EFI_MEMORY_TYPE::EfiBootServicesCode => "BootServicesCode", EFI_MEMORY_TYPE::EfiBootServicesData => "BootServicesData", EFI_MEMORY_TYPE::EfiRuntimeServicesCode => "RuntimeServicesCode", EFI_MEMORY_TYPE::EfiRuntimeServicesData => "RuntimeServicesData", EFI_MEMORY_TYPE::EfiConventionalMemory => "Conventional", EFI_MEMORY_TYPE::EfiUnusableMemory => "Unusable", EFI_MEMORY_TYPE::EfiACPIReclaimMemory => "ACPIReclaim", EFI_MEMORY_TYPE::EfiACPIMemoryNVS => "ACPIMemoryNVS ", EFI_MEMORY_TYPE::EfiMemoryMappedIO => "MemoryMappedIO", EFI_MEMORY_TYPE::EfiMemoryMappedIOPortSpace => "MemoryMappedIOPortSpace", EFI_MEMORY_TYPE::EfiPalCode => "PalCode", EFI_MEMORY_TYPE::EfiPersistentMemory => "PersistentMemory", _ => "", }; write!(f, "{:>20}", string)
identifier_body
efi.rs
use core::ffi::c_void; use core::fmt; const ERROR_BIT: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); #[derive(Clone, Copy)] #[repr(transparent)] pub struct EFI_HANDLE(*mut c_void); #[derive(PartialEq, Debug)] #[repr(usize)] pub enum EFI_STATUS { /// The operation completed successfully. SUCCESS = 0, /// The string contained characters that could not be rendered and were skipped. WARN_UNKNOWN_GLYPH = 1, /// The handle was closed, but the file was not deleted. WARN_DELETE_FAILURE = 2, /// The handle was closed, but the data to the file was not flushed properly. WARN_WRITE_FAILURE = 3, /// The resulting buffer was too small, and the data was truncated. WARN_BUFFER_TOO_SMALL = 4, /// The data has not been updated within the timeframe set by local policy. WARN_STALE_DATA = 5, /// The resulting buffer contains UEFI-compliant file system. WARN_FILE_SYSTEM = 6, /// The operation will be processed across a system reset. WARN_RESET_REQUIRED = 7, /// The image failed to load. LOAD_ERROR = ERROR_BIT | 1, /// A parameter was incorrect. INVALID_PARAMETER = ERROR_BIT | 2, /// The operation is not supported. UNSUPPORTED = ERROR_BIT | 3, /// The buffer was not the proper size for the request. BAD_BUFFER_SIZE = ERROR_BIT | 4, /// The buffer is not large enough to hold the requested data. /// The required buffer size is returned in the appropriate parameter. BUFFER_TOO_SMALL = ERROR_BIT | 5, /// There is no data pending upon return. NOT_READY = ERROR_BIT | 6, /// The physical device reported an error while attempting the operation. DEVICE_ERROR = ERROR_BIT | 7, /// The device cannot be written to. WRITE_PROTECTED = ERROR_BIT | 8, /// A resource has run out. OUT_OF_RESOURCES = ERROR_BIT | 9, /// An inconstency was detected on the file system. VOLUME_CORRUPTED = ERROR_BIT | 10, /// There is no more space on the file system. VOLUME_FULL = ERROR_BIT | 11, /// The device does not contain any medium to perform the operation. NO_MEDIA = ERROR_BIT | 12, /// The medium in the device has changed since the last access. MEDIA_CHANGED = ERROR_BIT | 13, /// The item was not found. NOT_FOUND = ERROR_BIT | 14, /// Access was denied. ACCESS_DENIED = ERROR_BIT | 15, /// The server was not found or did not respond to the request. NO_RESPONSE = ERROR_BIT | 16, /// A mapping to a device does not exist. NO_MAPPING = ERROR_BIT | 17, /// The timeout time expired. TIMEOUT = ERROR_BIT | 18, /// The protocol has not been started. NOT_STARTED = ERROR_BIT | 19, /// The protocol has already been started. ALREADY_STARTED = ERROR_BIT | 20, /// The operation was aborted. ABORTED = ERROR_BIT | 21, /// An ICMP error occurred during the network operation. ICMP_ERROR = ERROR_BIT | 22, /// A TFTP error occurred during the network operation. TFTP_ERROR = ERROR_BIT | 23, /// A protocol error occurred during the network operation. PROTOCOL_ERROR = ERROR_BIT | 24, /// The function encountered an internal version that was /// incompatible with a version requested by the caller. INCOMPATIBLE_VERSION = ERROR_BIT | 25, /// The function was not performed due to a security violation. SECURITY_VIOLATION = ERROR_BIT | 26, /// A CRC error was detected. CRC_ERROR = ERROR_BIT | 27, /// Beginning or end of media was reached END_OF_MEDIA = ERROR_BIT | 28, /// The end of the file was reached. END_OF_FILE = ERROR_BIT | 31, /// The language specified was invalid. INVALID_LANGUAGE = ERROR_BIT | 32, /// The security status of the data is unknown or compromised and /// the data must be updated or replaced to restore a valid security status. COMPROMISED_DATA = ERROR_BIT | 33, /// There is an address conflict address allocation IP_ADDRESS_CONFLICT = ERROR_BIT | 34, /// A HTTP error occurred during the network operation. HTTP_ERROR = ERROR_BIT | 35, } #[repr(C)] pub struct EFI_SYSTEM_TABLE { pub Hdr: EFI_TABLE_HEADER, pub FirmwareVendor: *const u16, pub FirmwareRevision: u32, pub ConsoleInHandle: EFI_HANDLE, pub ConIn: *mut EFI_SIMPLE_TEXT_INPUT_PROTOCOL, pub ConsoleOutHandle: EFI_HANDLE, pub ConOut: *mut EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, pub StandardErrorHandle: EFI_HANDLE, pub StdErr: *mut EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, pub RuntimeServices: *mut EFI_RUNTIME_SERVICES, pub BootServices: *mut EFI_BOOT_SERVICES, pub NumberOfTableEntries: usize, pub ConfigurationTable: *mut EFI_CONFIGURATION_TABLE, } #[repr(C)] pub struct EFI_RUNTIME_SERVICES { pub Hdr: EFI_TABLE_HEADER, pub GetTime: unsafe extern "C" fn(Time: *mut EFI_TIME, Capabilities: *mut EFI_TIME_CAPABILITIES) -> EFI_STATUS, dummy1: [usize;3], // Time Services dummy2: [usize;2], // Virtual Memory Services dummy3: [usize;3], // Variable Services dummy4: [usize;2], // Miscellaneous Services dummy5: [usize;2], // UEFI 2.0 Capsule Services dummy6: [usize;1], // Miscellaneous UEFI 2.0 Service } #[repr(C)] pub struct
{ pub Hdr: EFI_TABLE_HEADER, // Task Priority Services dummy1: [usize;2], // Memory Services pub AllocatePages: unsafe extern "C" fn(Type: EFI_ALLOCATE_TYPE, MemoryType: EFI_MEMORY_TYPE, Pages:usize, Memory: &mut u64) -> EFI_STATUS, dymmy2a: [usize;1], pub GetMemoryMap: unsafe extern "C" fn(MemoryMapSize: &mut usize, MemoryMap: *mut EFI_MEMORY_DESCRIPTOR, MapKey: &mut usize, DescriptorSize: &mut usize, DescriptorVersion: &mut u32) -> EFI_STATUS, dummy2b: [usize;2], // Event & Timer Services dummy3: [usize;6], // Protocol Handler Services dummy4a: [usize;3], pub HandleProtocol: unsafe extern "C" fn(Handle: EFI_HANDLE, Protocol: &EFI_GUID, Interface: &mut *mut c_void) -> EFI_STATUS, dummy4b: [usize;4], // Image Services dummy5: [usize;5], // Miscellaneous Services dummy6: [usize;2], pub SetWatchdogTimer: unsafe extern "C" fn (Timeout: usize, WatchdogCode: u64, DataSize: usize, WatchdogData: *const u16) -> EFI_STATUS, // DriverSupport Services dummy7: [usize;2], // Open and Close Protocol Services dummy8: [usize;3], // Library Services dummy9a: [usize;2], pub LocateProtocol: unsafe extern "C" fn (Protocol: &EFI_GUID, Registration: *mut c_void, Interface: &mut *mut c_void) -> EFI_STATUS, dummy9b: [usize;2], // 32-bit CRC Services dummy10: [usize;1], // Miscellaneous Services dummy11: [usize;3], } #[repr(C)] pub struct EFI_CONFIGURATION_TABLE { pub Hdr: EFI_TABLE_HEADER, // TBD } #[repr(C)] pub struct EFI_TABLE_HEADER { pub Signature: u64, pub Revision: u32, pub HeaderSize: u32, pub CRC32: u32, pub Reserved: u32, } #[repr(C)] pub struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL { pub Reset: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_INPUT_PROTOCOL, ExtendedVerification: bool) -> EFI_STATUS, pub ReadKeyStroke: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_INPUT_PROTOCOL, Key: &EFI_INPUT_KEY) -> EFI_STATUS, // TBD } #[repr(C)] pub struct EFI_INPUT_KEY { pub ScanCode: u16, pub UnicodeChar: u16, } #[repr(C)] pub struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL { pub Reset: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, ExtendedVerification: bool) -> EFI_STATUS, pub OutputString: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, String: *const u16) -> EFI_STATUS, // TBD } #[derive(PartialEq)] #[repr(usize)] pub enum EFI_ALLOCATE_TYPE { AllocateAnyPages, AllocateMaxAddress, AllocateAddress, MaxAllocateType, } #[derive(Debug, PartialEq, Copy, Clone)] #[repr(u32)] pub enum EFI_MEMORY_TYPE { EfiReservedMemoryType, EfiLoaderCode, EfiLoaderData, EfiBootServicesCode, EfiBootServicesData, EfiRuntimeServicesCode, EfiRuntimeServicesData, EfiConventionalMemory, EfiUnusableMemory, EfiACPIReclaimMemory, EfiACPIMemoryNVS, EfiMemoryMappedIO, EfiMemoryMappedIOPortSpace, EfiPalCode, EfiPersistentMemory, EfiMaxMemoryType, } impl fmt::Display for EFI_MEMORY_TYPE { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let string = match *self { EFI_MEMORY_TYPE::EfiReservedMemoryType => "ReservedMemory", EFI_MEMORY_TYPE::EfiLoaderCode => "LoaderCode", EFI_MEMORY_TYPE::EfiLoaderData => "LoaderData", EFI_MEMORY_TYPE::EfiBootServicesCode => "BootServicesCode", EFI_MEMORY_TYPE::EfiBootServicesData => "BootServicesData", EFI_MEMORY_TYPE::EfiRuntimeServicesCode => "RuntimeServicesCode", EFI_MEMORY_TYPE::EfiRuntimeServicesData => "RuntimeServicesData", EFI_MEMORY_TYPE::EfiConventionalMemory => "Conventional", EFI_MEMORY_TYPE::EfiUnusableMemory => "Unusable", EFI_MEMORY_TYPE::EfiACPIReclaimMemory => "ACPIReclaim", EFI_MEMORY_TYPE::EfiACPIMemoryNVS => "ACPIMemoryNVS ", EFI_MEMORY_TYPE::EfiMemoryMappedIO => "MemoryMappedIO", EFI_MEMORY_TYPE::EfiMemoryMappedIOPortSpace => "MemoryMappedIOPortSpace", EFI_MEMORY_TYPE::EfiPalCode => "PalCode", EFI_MEMORY_TYPE::EfiPersistentMemory => "PersistentMemory", _ => "", }; write!(f, "{:>20}", string) } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(C)] pub struct MemoryMapKey(usize); #[repr(C)] #[derive(Copy, Clone)] pub struct EFI_MEMORY_DESCRIPTOR { pub Type: EFI_MEMORY_TYPE, padding: u32, pub PhysicalStart: u64, pub VirtualStart: u64, pub NumberOfPages: u64, pub Attribute: u64, } impl fmt::Display for EFI_MEMORY_DESCRIPTOR { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {:x}-{:x}", self.Type, self.PhysicalStart, self.PhysicalStart+self.NumberOfPages*4096) } } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct EFI_TIME { pub Year: u16, pub Month: u8, pub Day: u8, pub Hour: u8, pub Minute: u8, pub Second: u8, pub Pad1: u8, pub Nanosecond: u32, pub TimeZone: u16, pub Daylight: u8, pub Pad2: u8, } #[repr(C)] pub struct EFI_TIME_CAPABILITIES { pub Resolution: u32, pub Accuracy: u32, pub SetsToZero: bool, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(C)] pub struct EFI_GUID { pub a: u32, pub b: u16, pub c: u16, pub d: [u8;8], } #[repr(C)] pub struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL { pub Revision: u64, pub OpenVolume: unsafe extern "C" fn(This: &mut EFI_SIMPLE_FILE_SYSTEM_PROTOCOL, Root: &mut *mut EFI_FILE_PROTOCOL) -> EFI_STATUS, } #[repr(C)] pub struct EFI_FILE_PROTOCOL { pub Revision: u64, pub Open: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL, NewHandle: &mut *mut EFI_FILE_PROTOCOL, FileName: *const u16, OpenMode: EFI_FILE_MODE, Attributes: EFI_FILE_ATTRIBUTE) -> EFI_STATUS, pub Close: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL) -> EFI_STATUS, pub Delete: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL) -> EFI_STATUS, pub Read: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL, BufferSize: &mut usize, Buffer: *mut u8) -> EFI_STATUS, // TBD } #[repr(C)] pub struct EFI_LOADED_IMAGE_PROTOCOL { pub Revision: u32, pub ParentHandle: EFI_HANDLE, pub SystemTable: *const EFI_SYSTEM_TABLE, pub DeviceHandle: EFI_HANDLE, pub FilePath: *const c_void, pub Reserved: *const c_void, pub LoadOptionsSize: u32, pub LoadOptions: *const c_void, pub ImageBase: usize, pub ImageSize: u64, pub ImageCodeType: EFI_MEMORY_TYPE, pub ImageDataType: EFI_MEMORY_TYPE, pub Unload: unsafe extern "C" fn(ImageHandle: EFI_HANDLE) -> EFI_STATUS, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u64)] pub enum EFI_FILE_MODE { EFI_FILE_MODE_READ = 1, EFI_FILE_MODE_WRITE = 2 | 1, EFI_FILE_MODE_CREATE = (1 << 63) | 2 | 1, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u64)] pub enum EFI_FILE_ATTRIBUTE { EFI_FILE_READ_ONLY = 1, EFI_FILE_HIDDEN = 1 << 1, EFI_FILE_SYSTEM = 1 << 2, EFI_FILE_RESERVED = 1 << 3, EFI_FILE_DIRECTORY = 1 << 4, EFI_FILE_ARCHIVE = 1 << 5, EFI_FILE_VALID_ATTR = 0x37, }
EFI_BOOT_SERVICES
identifier_name
efi.rs
use core::ffi::c_void; use core::fmt; const ERROR_BIT: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); #[derive(Clone, Copy)] #[repr(transparent)] pub struct EFI_HANDLE(*mut c_void); #[derive(PartialEq, Debug)] #[repr(usize)] pub enum EFI_STATUS { /// The operation completed successfully. SUCCESS = 0, /// The string contained characters that could not be rendered and were skipped. WARN_UNKNOWN_GLYPH = 1, /// The handle was closed, but the file was not deleted. WARN_DELETE_FAILURE = 2, /// The handle was closed, but the data to the file was not flushed properly. WARN_WRITE_FAILURE = 3, /// The resulting buffer was too small, and the data was truncated. WARN_BUFFER_TOO_SMALL = 4, /// The data has not been updated within the timeframe set by local policy. WARN_STALE_DATA = 5, /// The resulting buffer contains UEFI-compliant file system. WARN_FILE_SYSTEM = 6, /// The operation will be processed across a system reset. WARN_RESET_REQUIRED = 7, /// The image failed to load. LOAD_ERROR = ERROR_BIT | 1, /// A parameter was incorrect. INVALID_PARAMETER = ERROR_BIT | 2, /// The operation is not supported. UNSUPPORTED = ERROR_BIT | 3, /// The buffer was not the proper size for the request. BAD_BUFFER_SIZE = ERROR_BIT | 4, /// The buffer is not large enough to hold the requested data. /// The required buffer size is returned in the appropriate parameter. BUFFER_TOO_SMALL = ERROR_BIT | 5, /// There is no data pending upon return. NOT_READY = ERROR_BIT | 6, /// The physical device reported an error while attempting the operation. DEVICE_ERROR = ERROR_BIT | 7, /// The device cannot be written to. WRITE_PROTECTED = ERROR_BIT | 8, /// A resource has run out. OUT_OF_RESOURCES = ERROR_BIT | 9, /// An inconstency was detected on the file system. VOLUME_CORRUPTED = ERROR_BIT | 10, /// There is no more space on the file system. VOLUME_FULL = ERROR_BIT | 11, /// The device does not contain any medium to perform the operation. NO_MEDIA = ERROR_BIT | 12, /// The medium in the device has changed since the last access. MEDIA_CHANGED = ERROR_BIT | 13, /// The item was not found. NOT_FOUND = ERROR_BIT | 14, /// Access was denied. ACCESS_DENIED = ERROR_BIT | 15, /// The server was not found or did not respond to the request. NO_RESPONSE = ERROR_BIT | 16, /// A mapping to a device does not exist. NO_MAPPING = ERROR_BIT | 17, /// The timeout time expired. TIMEOUT = ERROR_BIT | 18, /// The protocol has not been started. NOT_STARTED = ERROR_BIT | 19, /// The protocol has already been started. ALREADY_STARTED = ERROR_BIT | 20, /// The operation was aborted. ABORTED = ERROR_BIT | 21, /// An ICMP error occurred during the network operation. ICMP_ERROR = ERROR_BIT | 22, /// A TFTP error occurred during the network operation. TFTP_ERROR = ERROR_BIT | 23, /// A protocol error occurred during the network operation. PROTOCOL_ERROR = ERROR_BIT | 24, /// The function encountered an internal version that was /// incompatible with a version requested by the caller. INCOMPATIBLE_VERSION = ERROR_BIT | 25, /// The function was not performed due to a security violation. SECURITY_VIOLATION = ERROR_BIT | 26, /// A CRC error was detected. CRC_ERROR = ERROR_BIT | 27, /// Beginning or end of media was reached END_OF_MEDIA = ERROR_BIT | 28, /// The end of the file was reached. END_OF_FILE = ERROR_BIT | 31, /// The language specified was invalid. INVALID_LANGUAGE = ERROR_BIT | 32, /// The security status of the data is unknown or compromised and /// the data must be updated or replaced to restore a valid security status. COMPROMISED_DATA = ERROR_BIT | 33, /// There is an address conflict address allocation IP_ADDRESS_CONFLICT = ERROR_BIT | 34, /// A HTTP error occurred during the network operation. HTTP_ERROR = ERROR_BIT | 35, } #[repr(C)] pub struct EFI_SYSTEM_TABLE { pub Hdr: EFI_TABLE_HEADER, pub FirmwareVendor: *const u16, pub FirmwareRevision: u32, pub ConsoleInHandle: EFI_HANDLE, pub ConIn: *mut EFI_SIMPLE_TEXT_INPUT_PROTOCOL, pub ConsoleOutHandle: EFI_HANDLE, pub ConOut: *mut EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, pub StandardErrorHandle: EFI_HANDLE, pub StdErr: *mut EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, pub RuntimeServices: *mut EFI_RUNTIME_SERVICES, pub BootServices: *mut EFI_BOOT_SERVICES, pub NumberOfTableEntries: usize, pub ConfigurationTable: *mut EFI_CONFIGURATION_TABLE, } #[repr(C)] pub struct EFI_RUNTIME_SERVICES { pub Hdr: EFI_TABLE_HEADER, pub GetTime: unsafe extern "C" fn(Time: *mut EFI_TIME, Capabilities: *mut EFI_TIME_CAPABILITIES) -> EFI_STATUS, dummy1: [usize;3], // Time Services dummy2: [usize;2], // Virtual Memory Services dummy3: [usize;3], // Variable Services dummy4: [usize;2], // Miscellaneous Services dummy5: [usize;2], // UEFI 2.0 Capsule Services dummy6: [usize;1], // Miscellaneous UEFI 2.0 Service } #[repr(C)] pub struct EFI_BOOT_SERVICES { pub Hdr: EFI_TABLE_HEADER, // Task Priority Services dummy1: [usize;2], // Memory Services pub AllocatePages: unsafe extern "C" fn(Type: EFI_ALLOCATE_TYPE, MemoryType: EFI_MEMORY_TYPE, Pages:usize, Memory: &mut u64) -> EFI_STATUS, dymmy2a: [usize;1], pub GetMemoryMap: unsafe extern "C" fn(MemoryMapSize: &mut usize, MemoryMap: *mut EFI_MEMORY_DESCRIPTOR, MapKey: &mut usize, DescriptorSize: &mut usize, DescriptorVersion: &mut u32) -> EFI_STATUS, dummy2b: [usize;2], // Event & Timer Services dummy3: [usize;6], // Protocol Handler Services dummy4a: [usize;3], pub HandleProtocol: unsafe extern "C" fn(Handle: EFI_HANDLE, Protocol: &EFI_GUID, Interface: &mut *mut c_void) -> EFI_STATUS, dummy4b: [usize;4], // Image Services dummy5: [usize;5], // Miscellaneous Services dummy6: [usize;2], pub SetWatchdogTimer: unsafe extern "C" fn (Timeout: usize, WatchdogCode: u64, DataSize: usize, WatchdogData: *const u16) -> EFI_STATUS, // DriverSupport Services
// Library Services dummy9a: [usize;2], pub LocateProtocol: unsafe extern "C" fn (Protocol: &EFI_GUID, Registration: *mut c_void, Interface: &mut *mut c_void) -> EFI_STATUS, dummy9b: [usize;2], // 32-bit CRC Services dummy10: [usize;1], // Miscellaneous Services dummy11: [usize;3], } #[repr(C)] pub struct EFI_CONFIGURATION_TABLE { pub Hdr: EFI_TABLE_HEADER, // TBD } #[repr(C)] pub struct EFI_TABLE_HEADER { pub Signature: u64, pub Revision: u32, pub HeaderSize: u32, pub CRC32: u32, pub Reserved: u32, } #[repr(C)] pub struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL { pub Reset: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_INPUT_PROTOCOL, ExtendedVerification: bool) -> EFI_STATUS, pub ReadKeyStroke: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_INPUT_PROTOCOL, Key: &EFI_INPUT_KEY) -> EFI_STATUS, // TBD } #[repr(C)] pub struct EFI_INPUT_KEY { pub ScanCode: u16, pub UnicodeChar: u16, } #[repr(C)] pub struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL { pub Reset: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, ExtendedVerification: bool) -> EFI_STATUS, pub OutputString: unsafe extern "C" fn(This: &EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL, String: *const u16) -> EFI_STATUS, // TBD } #[derive(PartialEq)] #[repr(usize)] pub enum EFI_ALLOCATE_TYPE { AllocateAnyPages, AllocateMaxAddress, AllocateAddress, MaxAllocateType, } #[derive(Debug, PartialEq, Copy, Clone)] #[repr(u32)] pub enum EFI_MEMORY_TYPE { EfiReservedMemoryType, EfiLoaderCode, EfiLoaderData, EfiBootServicesCode, EfiBootServicesData, EfiRuntimeServicesCode, EfiRuntimeServicesData, EfiConventionalMemory, EfiUnusableMemory, EfiACPIReclaimMemory, EfiACPIMemoryNVS, EfiMemoryMappedIO, EfiMemoryMappedIOPortSpace, EfiPalCode, EfiPersistentMemory, EfiMaxMemoryType, } impl fmt::Display for EFI_MEMORY_TYPE { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let string = match *self { EFI_MEMORY_TYPE::EfiReservedMemoryType => "ReservedMemory", EFI_MEMORY_TYPE::EfiLoaderCode => "LoaderCode", EFI_MEMORY_TYPE::EfiLoaderData => "LoaderData", EFI_MEMORY_TYPE::EfiBootServicesCode => "BootServicesCode", EFI_MEMORY_TYPE::EfiBootServicesData => "BootServicesData", EFI_MEMORY_TYPE::EfiRuntimeServicesCode => "RuntimeServicesCode", EFI_MEMORY_TYPE::EfiRuntimeServicesData => "RuntimeServicesData", EFI_MEMORY_TYPE::EfiConventionalMemory => "Conventional", EFI_MEMORY_TYPE::EfiUnusableMemory => "Unusable", EFI_MEMORY_TYPE::EfiACPIReclaimMemory => "ACPIReclaim", EFI_MEMORY_TYPE::EfiACPIMemoryNVS => "ACPIMemoryNVS ", EFI_MEMORY_TYPE::EfiMemoryMappedIO => "MemoryMappedIO", EFI_MEMORY_TYPE::EfiMemoryMappedIOPortSpace => "MemoryMappedIOPortSpace", EFI_MEMORY_TYPE::EfiPalCode => "PalCode", EFI_MEMORY_TYPE::EfiPersistentMemory => "PersistentMemory", _ => "", }; write!(f, "{:>20}", string) } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(C)] pub struct MemoryMapKey(usize); #[repr(C)] #[derive(Copy, Clone)] pub struct EFI_MEMORY_DESCRIPTOR { pub Type: EFI_MEMORY_TYPE, padding: u32, pub PhysicalStart: u64, pub VirtualStart: u64, pub NumberOfPages: u64, pub Attribute: u64, } impl fmt::Display for EFI_MEMORY_DESCRIPTOR { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {:x}-{:x}", self.Type, self.PhysicalStart, self.PhysicalStart+self.NumberOfPages*4096) } } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct EFI_TIME { pub Year: u16, pub Month: u8, pub Day: u8, pub Hour: u8, pub Minute: u8, pub Second: u8, pub Pad1: u8, pub Nanosecond: u32, pub TimeZone: u16, pub Daylight: u8, pub Pad2: u8, } #[repr(C)] pub struct EFI_TIME_CAPABILITIES { pub Resolution: u32, pub Accuracy: u32, pub SetsToZero: bool, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(C)] pub struct EFI_GUID { pub a: u32, pub b: u16, pub c: u16, pub d: [u8;8], } #[repr(C)] pub struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL { pub Revision: u64, pub OpenVolume: unsafe extern "C" fn(This: &mut EFI_SIMPLE_FILE_SYSTEM_PROTOCOL, Root: &mut *mut EFI_FILE_PROTOCOL) -> EFI_STATUS, } #[repr(C)] pub struct EFI_FILE_PROTOCOL { pub Revision: u64, pub Open: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL, NewHandle: &mut *mut EFI_FILE_PROTOCOL, FileName: *const u16, OpenMode: EFI_FILE_MODE, Attributes: EFI_FILE_ATTRIBUTE) -> EFI_STATUS, pub Close: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL) -> EFI_STATUS, pub Delete: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL) -> EFI_STATUS, pub Read: unsafe extern "C" fn(This: &EFI_FILE_PROTOCOL, BufferSize: &mut usize, Buffer: *mut u8) -> EFI_STATUS, // TBD } #[repr(C)] pub struct EFI_LOADED_IMAGE_PROTOCOL { pub Revision: u32, pub ParentHandle: EFI_HANDLE, pub SystemTable: *const EFI_SYSTEM_TABLE, pub DeviceHandle: EFI_HANDLE, pub FilePath: *const c_void, pub Reserved: *const c_void, pub LoadOptionsSize: u32, pub LoadOptions: *const c_void, pub ImageBase: usize, pub ImageSize: u64, pub ImageCodeType: EFI_MEMORY_TYPE, pub ImageDataType: EFI_MEMORY_TYPE, pub Unload: unsafe extern "C" fn(ImageHandle: EFI_HANDLE) -> EFI_STATUS, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u64)] pub enum EFI_FILE_MODE { EFI_FILE_MODE_READ = 1, EFI_FILE_MODE_WRITE = 2 | 1, EFI_FILE_MODE_CREATE = (1 << 63) | 2 | 1, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u64)] pub enum EFI_FILE_ATTRIBUTE { EFI_FILE_READ_ONLY = 1, EFI_FILE_HIDDEN = 1 << 1, EFI_FILE_SYSTEM = 1 << 2, EFI_FILE_RESERVED = 1 << 3, EFI_FILE_DIRECTORY = 1 << 4, EFI_FILE_ARCHIVE = 1 << 5, EFI_FILE_VALID_ATTR = 0x37, }
dummy7: [usize;2], // Open and Close Protocol Services dummy8: [usize;3],
random_line_split
prio_bitmap.rs
//! Provides `FixedPrioBitmap`, a bit array structure supporting //! logarithmic-time bit scan operations. use core::{convert::TryFrom, fmt}; use super::{ctz::trailing_zeros, BinInteger, Init}; /// The maximum bit count supported by [`FixedPrioBitmap`]. pub const FIXED_PRIO_BITMAP_MAX_LEN: usize = WORD_LEN * WORD_LEN * WORD_LEN; /// A bit array structure supporting logarithmic-time bit scan operations. /// /// All valid instantiations implement [`PrioBitmap`]. pub type FixedPrioBitmap<const LEN: usize> = If! { if (LEN <= WORD_LEN) { OneLevelPrioBitmap<LEN> } else if (LEN <= WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN - 1) / WORD_LEN}>, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else if (LEN <= WORD_LEN * WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)}>, {(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)} >, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else { TooManyLevels } }; /// Get an instantiation of `OneLevelPrioBitmapImpl` capable of storing `LEN` /// entries. #[doc(hidden)] pub type OneLevelPrioBitmap<const LEN: usize> = If! { if (LEN == 0) { () } else if (LEN <= 8 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u8, LEN> } else if (LEN <= 16 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u16, LEN> } else if (LEN <= 32 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u32, LEN> } else if (LEN <= 64 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u64, LEN> } else if (LEN <= 128 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u128, LEN> } else { TooManyLevels } }; /// Trait for [`FixedPrioBitmap`]. /// /// All methods panic when the given bit position is out of range. pub trait PrioBitmap: Init + Send + Sync + Clone + Copy + fmt::Debug +'static { /// Get the bit at the specified position. fn get(&self, i: usize) -> bool; /// Clear the bit at the specified position. fn clear(&mut self, i: usize); /// Set the bit at the specified position. fn set(&mut self, i: usize); /// Get the position of the first set bit. fn find_set(&self) -> Option<usize>; } impl PrioBitmap for () { fn get(&self, _: usize) -> bool { unreachable!() } fn clear(&mut self, _: usize) { unreachable!() } fn set(&mut self, _: usize) { unreachable!() } fn find_set(&self) -> Option<usize> { None } } /// Stores `LEN` (≤ `T::BITS`) entries. #[doc(hidden)] #[derive(Clone, Copy)] pub struct OneLevelPrioBitmapImpl<T, const LEN: usize> { bits: T, } impl<T: BinInteger, const LEN: usize> Init for OneLevelPrioBitmapImpl<T, LEN> { const INIT: Self = Self { bits: T::INIT }; } impl<T: BinInteger, const LEN: usize> fmt::Debug for OneLevelPrioBitmapImpl<T, LEN> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.bits.one_digits()).finish() } } impl<T: BinInteger, const LEN: usize> PrioBitmap for OneLevelPrioBitmapImpl<T, LEN> { fn get(&self, i: usize) -> bool { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.get_bit(i as u32) } fn clear(&mut self, i: usize) { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.clear_bit(i as u32); } fn set(&mut self, i: usize) { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.set_bit(i as u32); } fn find_set(&self) -> Option<usize> { if LEN <= usize::BITS as usize { // Use an optimized version of `trailing_zeros` let bits = self.bits.to_usize().unwrap(); let i = trailing_zeros::<LEN>(bits); if i == usize::BITS { None } else { Some(i as usize) } } else { let i = self.bits.trailing_zeros(); if i == T::BITS { None } else { Some(i as usize) } } } } /// Stores `WORD_LEN * LEN` entries. `T` must implement `PrioBitmap` and /// be able to store `LEN` entries. #[doc(hidden)] #[derive(Clone, Copy)] pub struct TwoLevelPrioBitmapImpl<T, const LEN: usize> { // Invariant: `first.get(i) == (second[i]!= 0)` first: T, second: [Word; LEN], } type Word = usize; const WORD_LEN: usize = core::mem::size_of::<Word>() * 8; impl<T: PrioBitmap, const LEN: usize> Init for TwoLevelPrioBitmapImpl<T, LEN> { const INIT: Self = Self { first: T::INIT, second: [0; LEN], }; } impl<T: PrioBitmap, const LEN: usize> fmt::Debug for TwoLevelPrioBitmapImpl<T, LEN> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list() .entries( self.second .iter() .enumerate() .map(|(group_i, group)| { group .one_digits() .map(move |subgroup_i| subgroup_i as usize + group_i * WORD_LEN) }) .flatten(), ) .finish() } } impl<T: PrioBitmap, const LEN: usize> PrioBitmap for TwoLevelPrioBitmapImpl<T, LEN> { fn get(&self, i: usize) -> bool { self.second[i / WORD_LEN].get_bit(u32::try_from(i % WORD_LEN).unwrap()) } fn clear(&mut self, i: usize) { let group = &mut self.second[i / WORD_LEN]; group.clear_bit(u32::try_from(i % WORD_LEN).unwrap()); if *group == 0 { self.first.clear(i / WORD_LEN); } } fn set(&mut self, i: usize) { let group = &mut self.second[i / WORD_LEN]; group.set_bit(u32::try_from(i % WORD_LEN).unwrap()); self.first.set(i / WORD_LEN); } fn find_set(&self) -> Option<usize> { self.first.find_set().map(|group_i| { let group = self.second[group_i]; let subgroup_i = group.trailing_zeros() as usize; debug_assert_ne!(subgroup_i, WORD_LEN); subgroup_i as usize + group_i * WORD_LEN }) } } /// Indicates the requested size is not supported. #[doc(hidden)] #[non_exhaustive] pub struct TooManyLevels {} #[cfg(test)] mod tests { use super::*; use quickcheck_macros::quickcheck; use std::collections::BTreeSet; struct BTreePrioBitmap(BTreeSet<usize>); impl BTreePrioBitmap { fn new() -> Self { Self(BTreeSet::new()) } fn enum_set_bits(&self) -> Vec<usize> { self.0.iter().cloned().collect() } fn clear(&mut self, i: usize) { self.0.remove(&i); } fn set(&mut self, i: usize) { self.0.insert(i); } fn find_set(&self) -> Option<usize> { self.0.iter().next().cloned() } } /// A modifying operation on `PrioBitmap`. #[derive(Debug)] enum Cmd { Insert(usize), Remove(usize), } /// Map random bytes to operations on `PrioBitmap`. fn interpret(bytecode: &[u8], bitmap_len: usize) -> impl Iterator<Item = Cmd> + '_ { let mut i = 0; let mut known_set_bits = Vec::new(); std::iter::from_fn(move || { if bitmap_len == 0 { None } else if let Some(instr) = bytecode.get(i..i + 5) { i += 5; let value = u32::from_le_bytes([instr[1], instr[2], instr[3], instr[4]]) as usize; if instr[0] % 2 == 0 || known_set_bits.is_empty() { let bit = value % bitmap_len; known_set_bits.push(bit); Some(Cmd::Insert(bit)) } else { let i = value % known_set_bits.len(); let bit = known_set_bits.swap_remove(i); Some(Cmd::Remove(bit)) } } else { None } }) } fn enum_set_bits(bitmap: &impl PrioBitmap, bitmap_len: usize) -> Vec<usize> { (0..bitmap_len).filter(|&i| bitmap.get(i)).collect() } fn test_inner<T: PrioBitmap>(bytecode: Vec<u8>, size: usize) { let mut subject = T::INIT; let mut reference = BTreePrioBitmap::new(); log::info!("size = {}", size); for cmd in interpret(&bytecode, size) { log::trace!(" {:?}", cmd); match cmd { Cmd::Insert(bit) => { subject.set(bit); reference.set(bit); } Cmd::Remove(bit) => { subject.clear(bit); reference.clear(bit); } } assert_eq!(subject.find_set(), reference.find_set()); } assert_eq!(subject.find_set(), reference.find_set()); assert_eq!(enum_set_bits(&subject, size), reference.enum_set_bits()); } macro_rules! gen_test { ($(#[$m:meta])* mod $name:ident, $size:literal) => { $(#[$m])* mod $name { use super::*; #[quickcheck] fn test(bytecode: Vec<u8>) { test_inner::<FixedPrioBitmap<$size>>(bytecode, $size); } } }; } gen_test!(mod size_0, 0); gen_test!(mod size_1, 1); gen_test!(mod size_10, 10); gen_test!(mod size_100, 100); gen_test!(mod size_1000, 1000);
); gen_test!( #[cfg(any(target_pointer_width = "64", target_pointer_width = "128"))] mod size_100000, 100000 ); }
gen_test!( #[cfg(any(target_pointer_width = "32", target_pointer_width = "64", target_pointer_width = "128"))] mod size_10000, 10000
random_line_split
prio_bitmap.rs
//! Provides `FixedPrioBitmap`, a bit array structure supporting //! logarithmic-time bit scan operations. use core::{convert::TryFrom, fmt}; use super::{ctz::trailing_zeros, BinInteger, Init}; /// The maximum bit count supported by [`FixedPrioBitmap`]. pub const FIXED_PRIO_BITMAP_MAX_LEN: usize = WORD_LEN * WORD_LEN * WORD_LEN; /// A bit array structure supporting logarithmic-time bit scan operations. /// /// All valid instantiations implement [`PrioBitmap`]. pub type FixedPrioBitmap<const LEN: usize> = If! { if (LEN <= WORD_LEN) { OneLevelPrioBitmap<LEN> } else if (LEN <= WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN - 1) / WORD_LEN}>, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else if (LEN <= WORD_LEN * WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)}>, {(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)} >, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else { TooManyLevels } }; /// Get an instantiation of `OneLevelPrioBitmapImpl` capable of storing `LEN` /// entries. #[doc(hidden)] pub type OneLevelPrioBitmap<const LEN: usize> = If! { if (LEN == 0) { () } else if (LEN <= 8 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u8, LEN> } else if (LEN <= 16 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u16, LEN> } else if (LEN <= 32 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u32, LEN> } else if (LEN <= 64 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u64, LEN> } else if (LEN <= 128 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u128, LEN> } else { TooManyLevels } }; /// Trait for [`FixedPrioBitmap`]. /// /// All methods panic when the given bit position is out of range. pub trait PrioBitmap: Init + Send + Sync + Clone + Copy + fmt::Debug +'static { /// Get the bit at the specified position. fn get(&self, i: usize) -> bool; /// Clear the bit at the specified position. fn clear(&mut self, i: usize); /// Set the bit at the specified position. fn set(&mut self, i: usize); /// Get the position of the first set bit. fn find_set(&self) -> Option<usize>; } impl PrioBitmap for () { fn get(&self, _: usize) -> bool { unreachable!() } fn clear(&mut self, _: usize) { unreachable!() } fn set(&mut self, _: usize) { unreachable!() } fn find_set(&self) -> Option<usize> { None } } /// Stores `LEN` (≤ `T::BITS`) entries. #[doc(hidden)] #[derive(Clone, Copy)] pub struct OneLevelPrioBitmapImpl<T, const LEN: usize> { bits: T, } impl<T: BinInteger, const LEN: usize> Init for OneLevelPrioBitmapImpl<T, LEN> { const INIT: Self = Self { bits: T::INIT }; } impl<T: BinInteger, const LEN: usize> fmt::Debug for OneLevelPrioBitmapImpl<T, LEN> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.bits.one_digits()).finish() } } impl<T: BinInteger, const LEN: usize> PrioBitmap for OneLevelPrioBitmapImpl<T, LEN> { fn get(&self, i: usize) -> bool { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.get_bit(i as u32) } fn clear(&mut self, i: usize) { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.clear_bit(i as u32); } fn set(&mut self, i: usize) { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.set_bit(i as u32); } fn find_set(&self) -> Option<usize> { if LEN <= usize::BITS as usize { // Use an optimized version of `trailing_zeros` let bits = self.bits.to_usize().unwrap(); let i = trailing_zeros::<LEN>(bits); if i == usize::BITS { None } else { Some(i as usize) } } else { let i = self.bits.trailing_zeros(); if i == T::BITS { None } else { Some(i as usize) } } } } /// Stores `WORD_LEN * LEN` entries. `T` must implement `PrioBitmap` and /// be able to store `LEN` entries. #[doc(hidden)] #[derive(Clone, Copy)] pub struct TwoLevelPrioBitmapImpl<T, const LEN: usize> { // Invariant: `first.get(i) == (second[i]!= 0)` first: T, second: [Word; LEN], } type Word = usize; const WORD_LEN: usize = core::mem::size_of::<Word>() * 8; impl<T: PrioBitmap, const LEN: usize> Init for TwoLevelPrioBitmapImpl<T, LEN> { const INIT: Self = Self { first: T::INIT, second: [0; LEN], }; } impl<T: PrioBitmap, const LEN: usize> fmt::Debug for TwoLevelPrioBitmapImpl<T, LEN> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list() .entries( self.second .iter() .enumerate() .map(|(group_i, group)| { group .one_digits() .map(move |subgroup_i| subgroup_i as usize + group_i * WORD_LEN) }) .flatten(), ) .finish() } } impl<T: PrioBitmap, const LEN: usize> PrioBitmap for TwoLevelPrioBitmapImpl<T, LEN> { fn get(&self, i: usize) -> bool { self.second[i / WORD_LEN].get_bit(u32::try_from(i % WORD_LEN).unwrap()) } fn clear(&mut self, i: usize) { let group = &mut self.second[i / WORD_LEN]; group.clear_bit(u32::try_from(i % WORD_LEN).unwrap()); if *group == 0 { self.first.clear(i / WORD_LEN); } } fn set(&mut self, i: usize) { let group = &mut self.second[i / WORD_LEN]; group.set_bit(u32::try_from(i % WORD_LEN).unwrap()); self.first.set(i / WORD_LEN); } fn find_set(&self) -> Option<usize> { self.first.find_set().map(|group_i| { let group = self.second[group_i]; let subgroup_i = group.trailing_zeros() as usize; debug_assert_ne!(subgroup_i, WORD_LEN); subgroup_i as usize + group_i * WORD_LEN }) } } /// Indicates the requested size is not supported. #[doc(hidden)] #[non_exhaustive] pub struct TooManyLevels {} #[cfg(test)] mod tests { use super::*; use quickcheck_macros::quickcheck; use std::collections::BTreeSet; struct BTreePrioBitmap(BTreeSet<usize>); impl BTreePrioBitmap { fn new() -> Self { Self(BTreeSet::new()) } fn enum_set_bits(&self) -> Vec<usize> { self.0.iter().cloned().collect() } fn clear(&mut self, i: usize) { self.0.remove(&i); } fn set(&mut self, i: usize) { self.0.insert(i); } fn find_set(&self) -> Option<usize> { self.0.iter().next().cloned() } } /// A modifying operation on `PrioBitmap`. #[derive(Debug)] enum Cmd { Insert(usize), Remove(usize), } /// Map random bytes to operations on `PrioBitmap`. fn interpret(bytecode: &[u8], bitmap_len: usize) -> impl Iterator<Item = Cmd> + '_ { let mut i = 0; let mut known_set_bits = Vec::new(); std::iter::from_fn(move || { if bitmap_len == 0 { None } else if let Some(instr) = bytecode.get(i..i + 5) { i += 5; let value = u32::from_le_bytes([instr[1], instr[2], instr[3], instr[4]]) as usize; if instr[0] % 2 == 0 || known_set_bits.is_empty() { let bit = value % bitmap_len; known_set_bits.push(bit); Some(Cmd::Insert(bit)) } else { let i = value % known_set_bits.len(); let bit = known_set_bits.swap_remove(i); Some(Cmd::Remove(bit)) } } else {
}) } fn enum_set_bits(bitmap: &impl PrioBitmap, bitmap_len: usize) -> Vec<usize> { (0..bitmap_len).filter(|&i| bitmap.get(i)).collect() } fn test_inner<T: PrioBitmap>(bytecode: Vec<u8>, size: usize) { let mut subject = T::INIT; let mut reference = BTreePrioBitmap::new(); log::info!("size = {}", size); for cmd in interpret(&bytecode, size) { log::trace!(" {:?}", cmd); match cmd { Cmd::Insert(bit) => { subject.set(bit); reference.set(bit); } Cmd::Remove(bit) => { subject.clear(bit); reference.clear(bit); } } assert_eq!(subject.find_set(), reference.find_set()); } assert_eq!(subject.find_set(), reference.find_set()); assert_eq!(enum_set_bits(&subject, size), reference.enum_set_bits()); } macro_rules! gen_test { ($(#[$m:meta])* mod $name:ident, $size:literal) => { $(#[$m])* mod $name { use super::*; #[quickcheck] fn test(bytecode: Vec<u8>) { test_inner::<FixedPrioBitmap<$size>>(bytecode, $size); } } }; } gen_test!(mod size_0, 0); gen_test!(mod size_1, 1); gen_test!(mod size_10, 10); gen_test!(mod size_100, 100); gen_test!(mod size_1000, 1000); gen_test!( #[cfg(any(target_pointer_width = "32", target_pointer_width = "64", target_pointer_width = "128"))] mod size_10000, 10000 ); gen_test!( #[cfg(any(target_pointer_width = "64", target_pointer_width = "128"))] mod size_100000, 100000 ); }
None }
conditional_block
prio_bitmap.rs
//! Provides `FixedPrioBitmap`, a bit array structure supporting //! logarithmic-time bit scan operations. use core::{convert::TryFrom, fmt}; use super::{ctz::trailing_zeros, BinInteger, Init}; /// The maximum bit count supported by [`FixedPrioBitmap`]. pub const FIXED_PRIO_BITMAP_MAX_LEN: usize = WORD_LEN * WORD_LEN * WORD_LEN; /// A bit array structure supporting logarithmic-time bit scan operations. /// /// All valid instantiations implement [`PrioBitmap`]. pub type FixedPrioBitmap<const LEN: usize> = If! { if (LEN <= WORD_LEN) { OneLevelPrioBitmap<LEN> } else if (LEN <= WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN - 1) / WORD_LEN}>, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else if (LEN <= WORD_LEN * WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)}>, {(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)} >, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else { TooManyLevels } }; /// Get an instantiation of `OneLevelPrioBitmapImpl` capable of storing `LEN` /// entries. #[doc(hidden)] pub type OneLevelPrioBitmap<const LEN: usize> = If! { if (LEN == 0) { () } else if (LEN <= 8 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u8, LEN> } else if (LEN <= 16 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u16, LEN> } else if (LEN <= 32 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u32, LEN> } else if (LEN <= 64 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u64, LEN> } else if (LEN <= 128 && LEN <= WORD_LEN) { OneLevelPrioBitmapImpl<u128, LEN> } else { TooManyLevels } }; /// Trait for [`FixedPrioBitmap`]. /// /// All methods panic when the given bit position is out of range. pub trait PrioBitmap: Init + Send + Sync + Clone + Copy + fmt::Debug +'static { /// Get the bit at the specified position. fn get(&self, i: usize) -> bool; /// Clear the bit at the specified position. fn clear(&mut self, i: usize); /// Set the bit at the specified position. fn set(&mut self, i: usize); /// Get the position of the first set bit. fn find_set(&self) -> Option<usize>; } impl PrioBitmap for () { fn get(&self, _: usize) -> bool { unreachable!() } fn clear(&mut self, _: usize) { unreachable!() } fn set(&mut self, _: usize) { unreachable!() } fn find_set(&self) -> Option<usize> { None } } /// Stores `LEN` (≤ `T::BITS`) entries. #[doc(hidden)] #[derive(Clone, Copy)] pub struct OneLevelPrioBitmapImpl<T, const LEN: usize> { bits: T, } impl<T: BinInteger, const LEN: usize> Init for OneLevelPrioBitmapImpl<T, LEN> { const INIT: Self = Self { bits: T::INIT }; } impl<T: BinInteger, const LEN: usize> fmt::Debug for OneLevelPrioBitmapImpl<T, LEN> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.bits.one_digits()).finish() } } impl<T: BinInteger, const LEN: usize> PrioBitmap for OneLevelPrioBitmapImpl<T, LEN> { fn get(&self, i: usize) -> bool { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.get_bit(i as u32) } fn clear(&mut self, i: usize) { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.clear_bit(i as u32); } fn set(&mut self, i: usize) { assert!(i < LEN && i < usize::try_from(T::BITS).unwrap()); self.bits.set_bit(i as u32); } fn find_set(&self) -> Option<usize> { if LEN <= usize::BITS as usize { // Use an optimized version of `trailing_zeros` let bits = self.bits.to_usize().unwrap(); let i = trailing_zeros::<LEN>(bits); if i == usize::BITS { None } else { Some(i as usize) } } else { let i = self.bits.trailing_zeros(); if i == T::BITS { None } else { Some(i as usize) } } } } /// Stores `WORD_LEN * LEN` entries. `T` must implement `PrioBitmap` and /// be able to store `LEN` entries. #[doc(hidden)] #[derive(Clone, Copy)] pub struct TwoLevelPrioBitmapImpl<T, const LEN: usize> { // Invariant: `first.get(i) == (second[i]!= 0)` first: T, second: [Word; LEN], } type Word = usize; const WORD_LEN: usize = core::mem::size_of::<Word>() * 8; impl<T: PrioBitmap, const LEN: usize> Init for TwoLevelPrioBitmapImpl<T, LEN> { const INIT: Self = Self { first: T::INIT, second: [0; LEN], }; } impl<T: PrioBitmap, const LEN: usize> fmt::Debug for TwoLevelPrioBitmapImpl<T, LEN> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list() .entries( self.second .iter() .enumerate() .map(|(group_i, group)| { group .one_digits() .map(move |subgroup_i| subgroup_i as usize + group_i * WORD_LEN) }) .flatten(), ) .finish() } } impl<T: PrioBitmap, const LEN: usize> PrioBitmap for TwoLevelPrioBitmapImpl<T, LEN> { fn get(&self, i: usize) -> bool { self.second[i / WORD_LEN].get_bit(u32::try_from(i % WORD_LEN).unwrap()) } fn clear(&mut self, i: usize) { let group = &mut self.second[i / WORD_LEN]; group.clear_bit(u32::try_from(i % WORD_LEN).unwrap()); if *group == 0 { self.first.clear(i / WORD_LEN); } } fn set(&mut self, i: usize) { let group = &mut self.second[i / WORD_LEN]; group.set_bit(u32::try_from(i % WORD_LEN).unwrap()); self.first.set(i / WORD_LEN); } fn find_set(&self) -> Option<usize> { self.first.find_set().map(|group_i| { let group = self.second[group_i]; let subgroup_i = group.trailing_zeros() as usize; debug_assert_ne!(subgroup_i, WORD_LEN); subgroup_i as usize + group_i * WORD_LEN }) } } /// Indicates the requested size is not supported. #[doc(hidden)] #[non_exhaustive] pub struct TooManyLevels {} #[cfg(test)] mod tests { use super::*; use quickcheck_macros::quickcheck; use std::collections::BTreeSet; struct BTreePrioBitmap(BTreeSet<usize>); impl BTreePrioBitmap { fn ne
-> Self { Self(BTreeSet::new()) } fn enum_set_bits(&self) -> Vec<usize> { self.0.iter().cloned().collect() } fn clear(&mut self, i: usize) { self.0.remove(&i); } fn set(&mut self, i: usize) { self.0.insert(i); } fn find_set(&self) -> Option<usize> { self.0.iter().next().cloned() } } /// A modifying operation on `PrioBitmap`. #[derive(Debug)] enum Cmd { Insert(usize), Remove(usize), } /// Map random bytes to operations on `PrioBitmap`. fn interpret(bytecode: &[u8], bitmap_len: usize) -> impl Iterator<Item = Cmd> + '_ { let mut i = 0; let mut known_set_bits = Vec::new(); std::iter::from_fn(move || { if bitmap_len == 0 { None } else if let Some(instr) = bytecode.get(i..i + 5) { i += 5; let value = u32::from_le_bytes([instr[1], instr[2], instr[3], instr[4]]) as usize; if instr[0] % 2 == 0 || known_set_bits.is_empty() { let bit = value % bitmap_len; known_set_bits.push(bit); Some(Cmd::Insert(bit)) } else { let i = value % known_set_bits.len(); let bit = known_set_bits.swap_remove(i); Some(Cmd::Remove(bit)) } } else { None } }) } fn enum_set_bits(bitmap: &impl PrioBitmap, bitmap_len: usize) -> Vec<usize> { (0..bitmap_len).filter(|&i| bitmap.get(i)).collect() } fn test_inner<T: PrioBitmap>(bytecode: Vec<u8>, size: usize) { let mut subject = T::INIT; let mut reference = BTreePrioBitmap::new(); log::info!("size = {}", size); for cmd in interpret(&bytecode, size) { log::trace!(" {:?}", cmd); match cmd { Cmd::Insert(bit) => { subject.set(bit); reference.set(bit); } Cmd::Remove(bit) => { subject.clear(bit); reference.clear(bit); } } assert_eq!(subject.find_set(), reference.find_set()); } assert_eq!(subject.find_set(), reference.find_set()); assert_eq!(enum_set_bits(&subject, size), reference.enum_set_bits()); } macro_rules! gen_test { ($(#[$m:meta])* mod $name:ident, $size:literal) => { $(#[$m])* mod $name { use super::*; #[quickcheck] fn test(bytecode: Vec<u8>) { test_inner::<FixedPrioBitmap<$size>>(bytecode, $size); } } }; } gen_test!(mod size_0, 0); gen_test!(mod size_1, 1); gen_test!(mod size_10, 10); gen_test!(mod size_100, 100); gen_test!(mod size_1000, 1000); gen_test!( #[cfg(any(target_pointer_width = "32", target_pointer_width = "64", target_pointer_width = "128"))] mod size_10000, 10000 ); gen_test!( #[cfg(any(target_pointer_width = "64", target_pointer_width = "128"))] mod size_100000, 100000 ); }
w()
identifier_name
criterion.rs
use std::cmp; use std::fmt::Show; use std::io::Command; use std::num; use bencher::Bencher; use fs; use outliers::Outliers; use plot; use statistics::{Estimate,Estimates,Mean,Median,MedianAbsDev,Sample,StdDev}; use stream::Stream; use target::{Function,FunctionFamily,Program,Target}; use time::prefix::{Mili,Nano}; use time::traits::{Milisecond,Nanosecond,Second}; use time::types::Ns; use time; /// The "criterion" for the benchmark, which is also the benchmark "manager" #[experimental] pub struct Criterion { confidence_level: f64, measurement_time: Ns<u64>, noise_threshold: f64, nresamples: uint, sample_size: uint, significance_level: f64, warm_up_time: Ns<u64>, } #[experimental] impl Criterion { /// This is the default criterion: /// /// * Confidence level: 0.95 /// * Measurement time: 10 ms /// * Noise threshold: 0.01 (1%) /// * Bootstrap with 100 000 resamples /// * Sample size: 100 measurements /// * Significance level: 0.05 /// * Warm-up time: 1 s #[experimental] pub fn default() -> Criterion { Criterion { confidence_level: 0.95, measurement_time: 10.ms().to::<Nano>(), noise_threshold: 0.01, nresamples: 100_000, sample_size: 100, significance_level: 0.05, warm_up_time: 1.s().to::<Nano>(), } } /// Changes the confidence level /// /// The confidence level is used to calculate the confidence intervals of the estimates #[experimental] pub fn confidence_level(&mut self, cl: f64) -> &mut Criterion { assert!(cl > 0.0 && cl < 1.0); self.confidence_level = cl; self } /// Change the measurement time /// /// The program/function under test is iterated for `measurement_time` ms. And the average run /// time is reported as a measurement #[experimental] pub fn measurement_time(&mut self, ms: u64) -> &mut Criterion { self.measurement_time = ms.ms().to::<Nano>(); self } /// Changes the noise threshold /// /// When comparing benchmark results, only relative changes of the execution time above this /// threshold are considered significant #[experimental] pub fn noise_threshold(&mut self, nt: f64) -> &mut Criterion { assert!(nt >= 0.0); self.noise_threshold = nt; self } /// Changes the number of resamples /// /// Number of resamples to use for bootstraping via case resampling #[experimental] pub fn nresamples(&mut self, n: uint) -> &mut Criterion
/// Changes the size of a sample /// /// A sample consists of severals measurements #[experimental] pub fn sample_size(&mut self, n: uint) -> &mut Criterion { self.sample_size = n; self } /// Changes the significance level /// /// Significance level to use for hypothesis testing #[experimental] pub fn significance_level(&mut self, sl: f64) -> &mut Criterion { assert!(sl > 0.0 && sl < 1.0); self.significance_level = sl; self } /// Changes the warm up time /// /// The program/function under test is executed during `warm_up_time` ms before the real /// measurement starts #[experimental] pub fn warm_up_time(&mut self, ms: u64) -> &mut Criterion { self.warm_up_time = ms.ms().to::<Nano>(); self } /// Benchmark a function. See `Bench::iter()` for an example of how `fun` should look #[experimental] pub fn bench(&mut self, id: &str, fun: fn (&mut Bencher)) -> &mut Criterion { local_data_key!(clock: Ns<f64>); if clock.get().is_none() { clock.replace(Some(clock_cost(self))); } // TODO Use clock cost to set a minimum `measurement_time` bench(id, Function::<()>(fun), self); println!(""); self } /// Benchmark a family of functions /// /// `fun` will be benchmarked under each input /// /// For example, if you want to benchmark `Vec::from_elem` with different size, use these /// arguments: /// /// let fun = |b, n| Vec::from_elem(n, 0u); /// let inputs = [100, 10_000, 1_000_000]; /// /// This is equivalent to calling `bench` on each of the following functions: /// /// let fun1 = |b| Vec::from_elem(100, 0u); /// let fun2 = |b| Vec::from_elem(10_000, 0u); /// let fun3 = |b| Vec::from_elem(1_000_000, 0u); #[experimental] pub fn bench_family<I: Show>( &mut self, id: &str, fun: fn (&mut Bencher, &I), inputs: &[I]) -> &mut Criterion { for input in inputs.iter() { let id = format!("{}/{}", id, input); bench(id.as_slice(), FunctionFamily(fun, input), self); } print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } /// Benchmark an external program /// /// The program must conform to the following specification: /// /// extern crate time; /// /// fn main() { /// // Optional: Get the program arguments /// let args = std::os::args(); /// /// for line in std::io::stdio::stdin().lines() { /// // Get number of iterations to do /// let iters: u64 = from_str(line.unwrap().as_slice().trim()).unwrap(); /// /// // Setup /// /// // (For best results, use a monotonic timer) /// let start = time::precise_time_ns(); /// for _ in range(0, iters) { /// // Routine to benchmark goes here /// } /// let end = time::precise_time_ns(); /// /// // Teardown /// /// // Report back the time (in nanoseconds) required to execute the routine /// // `iters` times /// println!("{}", end - start); /// } /// } /// /// For example, to benchmark a python script use the following command /// /// let cmd = Command::new("python3").args(["-O", "clock.py"]); #[experimental] pub fn bench_prog(&mut self, id: &str, prog: &Command) -> &mut Criterion { bench(id, Program::<()>(Stream::spawn(prog)), self); println!(""); self } /// Benchmark an external program under various inputs /// /// For example, to benchmark a python script under various inputs, use this combination: /// /// let cmd = Command::new("python3").args(["-O", "fib.py"]); /// let inputs = [5u, 10, 15]; /// /// This is equivalent to calling `bench_prog` on each of the following commands: /// /// let cmd1 = Command::new("python3").args(["-O", "fib.py", "5"]); /// let cmd2 = Command::new("python3").args(["-O", "fib.py", "10"]); /// let cmd2 = Command::new("python3").args(["-O", "fib.py", "15"]); #[experimental] pub fn bench_prog_family<I: Show>( &mut self, id: &str, prog: &Command, inputs: &[I]) -> &mut Criterion { for input in inputs.iter() { let id = format!("{}/{}", id, input); self.bench_prog(id.as_slice(), prog.clone().arg(format!("{}", input))); } print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } /// Summarize the results stored under the `.criterion/${id}` folder /// /// Note that `bench_family` and `bench_prog_family` internally call the `summarize` method #[experimental] pub fn summarize(&mut self, id: &str) -> &mut Criterion { print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } } // FIXME Sorry! Everything below this point is a mess :/ fn bench<I>(id: &str, mut target: Target<I>, criterion: &Criterion) { println!("Benchmarking {}", id); rename_new_dir_to_base(id); build_directory_skeleton(id); let root = Path::new(".criterion").join(id); let base_dir = root.join("base"); let change_dir = root.join("change"); let new_dir = root.join("new"); match target { Program(_) => { let _clock_cost = external_clock_cost(&mut target, criterion, &new_dir.join("clock"), id); // TODO use clock_cost to set minimal measurement_time }, _ => {}, } let sample = take_sample(&mut target, criterion).unwrap(); sample.save(&new_dir.join("sample.json")); plot::sample(&sample, new_dir.join("points.svg"), id); plot::pdf(&sample, new_dir.join("pdf.svg"), id); let outliers = Outliers::classify(sample.as_slice()); outliers.report(); outliers.save(&new_dir.join("outliers/classification.json")); plot::outliers(&outliers, new_dir.join("outliers/boxplot.svg"), id); println!("> Estimating the statistics of the sample"); let nresamples = criterion.nresamples; let cl = criterion.confidence_level; println!(" > Bootstrapping the sample with {} resamples", nresamples); let (estimates, distributions) = sample.bootstrap([Mean, Median, StdDev, MedianAbsDev], nresamples, cl); estimates.save(&new_dir.join("bootstrap/estimates.json")); report_time(&estimates); plot::time_distributions(&distributions, &estimates, &new_dir.join("bootstrap/distribution"), id); if!base_dir.exists() { return; } println!("{}: Comparing with previous sample", id); let base_sample = Sample::<Vec<f64>>::load(&base_dir.join("sample.json")); let both_dir = root.join("both"); plot::both::pdfs(&base_sample, &sample, both_dir.join("pdfs.svg"), id); plot::both::points(&base_sample, &sample, both_dir.join("points.svg"), id); println!("> H0: Both samples belong to the same population"); println!(" > Bootstrapping with {} resamples", nresamples); let t_statistic = sample.t_test(&base_sample); let t_distribution = sample.bootstrap_t_test(&base_sample, nresamples, cl); let t = t_statistic.abs(); let hits = t_distribution.as_slice().iter().filter(|&&x| x > t || x < -t).count(); let p_value = hits as f64 / nresamples as f64; let sl = criterion.significance_level; let different_population = p_value < sl; println!(" > p = {}", p_value); println!(" > {} reject the null hypothesis", if different_population { "Strong evidence to" } else { "Can't" }) plot::t_test(t_statistic, &t_distribution, change_dir.join("bootstrap/t_test.svg"), id); let nresamples_sqrt = (nresamples as f64).sqrt().ceil() as uint; let nresamples = nresamples_sqrt * nresamples_sqrt; println!("> Estimating relative change of statistics"); println!(" > Bootstrapping with {} resamples", nresamples); let (estimates, distributions) = sample.bootstrap_compare(&base_sample, [Mean, Median], nresamples_sqrt, cl); estimates.save(&change_dir.join("bootstrap/estimates.json")); report_change(&estimates); plot::ratio_distributions(&distributions, &estimates, &change_dir.join("bootstrap/distribution"), id); let threshold = criterion.noise_threshold; let mut regressed = vec!(); for &statistic in [Mean, Median].iter() { let estimate = estimates.get(statistic); let result = compare_to_threshold(estimate, threshold); let p = estimate.point_estimate(); match result { Improved => { println!(" > {} has improved by {:.2}%", statistic, -100.0 * p); regressed.push(false); }, Regressed => { println!(" > {} has regressed by {:.2}%", statistic, 100.0 * p); regressed.push(true); }, NonSignificant => { regressed.push(false); }, } } if different_population && regressed.iter().all(|&x| x) { fail!("{} has regressed", id); } } fn external_clock_cost<I>( target: &mut Target<I>, criterion: &Criterion, dir: &Path, id: &str, ) -> Ns<f64> { println!("> Estimating the cost of a clock call"); let wu_time = criterion.warm_up_time; println!(" > Warming up for {}", wu_time.to::<Mili>()); let init = time::now(); while time::now() - init < wu_time { target.run(0); } println!(" > Collecting {} measurements", criterion.sample_size); let sample = Sample::new( range(0, criterion.sample_size). map(|_| target.run(0).unwrap() as f64). collect::<Vec<f64>>()); let clock_cost = sample.compute(Median); println!(" > {}: {}", Median, format_time(clock_cost)); fs::mkdirp(dir); plot::sample(&sample, dir.join("points.svg"), format!("{}/clock_cost", id)); plot::pdf(&sample, dir.join("pdf.svg"), format!("{}/clock_cost", id)); clock_cost.ns() } fn extrapolate_iters(iters: u64, took: Ns<u64>, want: Ns<u64>) -> (Ns<f64>, u64) { let e_iters = cmp::max(want * iters / took, 1); let e_time = (took * e_iters).cast::<f64>() / iters as f64; (e_time, e_iters) } fn time_now(b: &mut Bencher) { b.iter(|| time::now()); } fn clock_cost(criterion: &Criterion) -> Ns<f64> { println!("Estimating the cost of `precise_time_ns`"); let sample = take_sample(&mut Function::<()>(time_now), criterion); let median = sample.unwrap().compute(Mean).ns(); println!("> Median: {}\n", median); median } fn take_sample<I>(t: &mut Target<I>, criterion: &Criterion) -> Ns<Sample<Vec<f64>>> { let wu_time = criterion.warm_up_time; println!("> Warming up for {}", wu_time.to::<Mili>()) let (took, iters) = t.warm_up(wu_time); let m_time = criterion.measurement_time; let (m_time, m_iters) = extrapolate_iters(iters, took, m_time); let sample_size = criterion.sample_size; println!("> Collecting {} measurements, {} iters each in estimated {}", sample_size, m_iters, format_time((m_time * sample_size as f64).unwrap())); let sample = t.bench(sample_size, m_iters).unwrap(); sample.ns() } fn rename_new_dir_to_base(id: &str) { let root_dir = Path::new(".criterion").join(id); let base_dir = root_dir.join("base"); let new_dir = root_dir.join("new"); if base_dir.exists() { fs::rmrf(&base_dir) } if new_dir.exists() { fs::mv(&new_dir, &base_dir) }; } fn build_directory_skeleton(id: &str) { let root = Path::new(".criterion").join(id); fs::mkdirp(&root.join("both")); fs::mkdirp(&root.join("change/bootstrap/distribution")); fs::mkdirp(&root.join("new/bootstrap/distribution")); fs::mkdirp(&root.join("new/outliers")); } fn format_short(n: f64) -> String { if n < 10.0 { format!("{:.4}", n) } else if n < 100.0 { format!("{:.3}", n) } else if n < 1000.0 { format!("{:.2}", n) } else { format!("{}", n) } } fn format_signed_short(n: f64) -> String { let n_abs = n.abs(); if n_abs < 10.0 { format!("{:+.4}", n) } else if n_abs < 100.0 { format!("{:+.3}", n) } else if n_abs < 1000.0 { format!("{:+.2}", n) } else { format!("{:+}", n) } } fn report_time(estimates: &Estimates) { for &statistic in [Mean, Median, StdDev, MedianAbsDev].iter() { let estimate = estimates.get(statistic); let p = format_time(estimate.point_estimate()); let ci = estimate.confidence_interval(); let lb = format_time(ci.lower_bound()); let ub = format_time(ci.upper_bound()); let se = format_time(estimate.standard_error()); let cl = ci.confidence_level(); println!(" > {:<7} {} ± {} [{} {}] {}% CI", statistic, p, se, lb, ub, cl * 100.0); } } fn format_time(ns: f64) -> String { if ns < 1.0 { format!("{:>6} ps", format_short(ns * 1e3)) } else if ns < num::pow(10.0, 3) { format!("{:>6} ns", format_short(ns)) } else if ns < num::pow(10.0, 6) { format!("{:>6} us", format_short(ns / 1e3)) } else if ns < num::pow(10.0, 9) { format!("{:>6} ms", format_short(ns / 1e6)) } else { format!("{:>6} s", format_short(ns / 1e9)) } } fn report_change(estimates: &Estimates) { for &statistic in [Mean, Median].iter() { let estimate = estimates.get(statistic); let p = format_change(estimate.point_estimate(), true); let ci = estimate.confidence_interval(); let lb = format_change(ci.lower_bound(), true); let ub = format_change(ci.upper_bound(), true); let se = format_change(estimate.standard_error(), false); let cl = ci.confidence_level(); println!(" > {:<7} {} ± {} [{} {}] {}% CI", statistic, p, se, lb, ub, cl * 100.0); } } fn format_change(pct: f64, signed: bool) -> String { if signed { format!("{:>+6}%", format_signed_short(pct * 1e2)) } else { format!("{:>6}%", format_short(pct * 1e2)) } } enum ComparisonResult { Improved, Regressed, NonSignificant, } fn compare_to_threshold(estimate: &Estimate, noise: f64) -> ComparisonResult { let ci = estimate.confidence_interval(); let lb = ci.lower_bound(); let ub = ci.upper_bound(); if lb < -noise && ub < -noise { Improved } else if lb > noise && ub > noise { Regressed } else { NonSignificant } }
{ self.nresamples = n; self }
identifier_body
criterion.rs
use std::cmp; use std::fmt::Show; use std::io::Command; use std::num; use bencher::Bencher; use fs; use outliers::Outliers; use plot; use statistics::{Estimate,Estimates,Mean,Median,MedianAbsDev,Sample,StdDev}; use stream::Stream; use target::{Function,FunctionFamily,Program,Target}; use time::prefix::{Mili,Nano}; use time::traits::{Milisecond,Nanosecond,Second}; use time::types::Ns; use time; /// The "criterion" for the benchmark, which is also the benchmark "manager" #[experimental] pub struct Criterion { confidence_level: f64, measurement_time: Ns<u64>, noise_threshold: f64, nresamples: uint, sample_size: uint, significance_level: f64, warm_up_time: Ns<u64>, } #[experimental] impl Criterion { /// This is the default criterion: /// /// * Confidence level: 0.95 /// * Measurement time: 10 ms /// * Noise threshold: 0.01 (1%) /// * Bootstrap with 100 000 resamples /// * Sample size: 100 measurements /// * Significance level: 0.05 /// * Warm-up time: 1 s #[experimental] pub fn default() -> Criterion { Criterion { confidence_level: 0.95, measurement_time: 10.ms().to::<Nano>(), noise_threshold: 0.01, nresamples: 100_000, sample_size: 100, significance_level: 0.05, warm_up_time: 1.s().to::<Nano>(), } } /// Changes the confidence level /// /// The confidence level is used to calculate the confidence intervals of the estimates #[experimental] pub fn confidence_level(&mut self, cl: f64) -> &mut Criterion { assert!(cl > 0.0 && cl < 1.0); self.confidence_level = cl; self } /// Change the measurement time /// /// The program/function under test is iterated for `measurement_time` ms. And the average run /// time is reported as a measurement #[experimental] pub fn measurement_time(&mut self, ms: u64) -> &mut Criterion { self.measurement_time = ms.ms().to::<Nano>(); self } /// Changes the noise threshold /// /// When comparing benchmark results, only relative changes of the execution time above this /// threshold are considered significant #[experimental] pub fn noise_threshold(&mut self, nt: f64) -> &mut Criterion { assert!(nt >= 0.0); self.noise_threshold = nt; self } /// Changes the number of resamples /// /// Number of resamples to use for bootstraping via case resampling #[experimental] pub fn nresamples(&mut self, n: uint) -> &mut Criterion { self.nresamples = n; self } /// Changes the size of a sample /// /// A sample consists of severals measurements #[experimental] pub fn sample_size(&mut self, n: uint) -> &mut Criterion { self.sample_size = n; self } /// Changes the significance level /// /// Significance level to use for hypothesis testing #[experimental] pub fn
(&mut self, sl: f64) -> &mut Criterion { assert!(sl > 0.0 && sl < 1.0); self.significance_level = sl; self } /// Changes the warm up time /// /// The program/function under test is executed during `warm_up_time` ms before the real /// measurement starts #[experimental] pub fn warm_up_time(&mut self, ms: u64) -> &mut Criterion { self.warm_up_time = ms.ms().to::<Nano>(); self } /// Benchmark a function. See `Bench::iter()` for an example of how `fun` should look #[experimental] pub fn bench(&mut self, id: &str, fun: fn (&mut Bencher)) -> &mut Criterion { local_data_key!(clock: Ns<f64>); if clock.get().is_none() { clock.replace(Some(clock_cost(self))); } // TODO Use clock cost to set a minimum `measurement_time` bench(id, Function::<()>(fun), self); println!(""); self } /// Benchmark a family of functions /// /// `fun` will be benchmarked under each input /// /// For example, if you want to benchmark `Vec::from_elem` with different size, use these /// arguments: /// /// let fun = |b, n| Vec::from_elem(n, 0u); /// let inputs = [100, 10_000, 1_000_000]; /// /// This is equivalent to calling `bench` on each of the following functions: /// /// let fun1 = |b| Vec::from_elem(100, 0u); /// let fun2 = |b| Vec::from_elem(10_000, 0u); /// let fun3 = |b| Vec::from_elem(1_000_000, 0u); #[experimental] pub fn bench_family<I: Show>( &mut self, id: &str, fun: fn (&mut Bencher, &I), inputs: &[I]) -> &mut Criterion { for input in inputs.iter() { let id = format!("{}/{}", id, input); bench(id.as_slice(), FunctionFamily(fun, input), self); } print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } /// Benchmark an external program /// /// The program must conform to the following specification: /// /// extern crate time; /// /// fn main() { /// // Optional: Get the program arguments /// let args = std::os::args(); /// /// for line in std::io::stdio::stdin().lines() { /// // Get number of iterations to do /// let iters: u64 = from_str(line.unwrap().as_slice().trim()).unwrap(); /// /// // Setup /// /// // (For best results, use a monotonic timer) /// let start = time::precise_time_ns(); /// for _ in range(0, iters) { /// // Routine to benchmark goes here /// } /// let end = time::precise_time_ns(); /// /// // Teardown /// /// // Report back the time (in nanoseconds) required to execute the routine /// // `iters` times /// println!("{}", end - start); /// } /// } /// /// For example, to benchmark a python script use the following command /// /// let cmd = Command::new("python3").args(["-O", "clock.py"]); #[experimental] pub fn bench_prog(&mut self, id: &str, prog: &Command) -> &mut Criterion { bench(id, Program::<()>(Stream::spawn(prog)), self); println!(""); self } /// Benchmark an external program under various inputs /// /// For example, to benchmark a python script under various inputs, use this combination: /// /// let cmd = Command::new("python3").args(["-O", "fib.py"]); /// let inputs = [5u, 10, 15]; /// /// This is equivalent to calling `bench_prog` on each of the following commands: /// /// let cmd1 = Command::new("python3").args(["-O", "fib.py", "5"]); /// let cmd2 = Command::new("python3").args(["-O", "fib.py", "10"]); /// let cmd2 = Command::new("python3").args(["-O", "fib.py", "15"]); #[experimental] pub fn bench_prog_family<I: Show>( &mut self, id: &str, prog: &Command, inputs: &[I]) -> &mut Criterion { for input in inputs.iter() { let id = format!("{}/{}", id, input); self.bench_prog(id.as_slice(), prog.clone().arg(format!("{}", input))); } print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } /// Summarize the results stored under the `.criterion/${id}` folder /// /// Note that `bench_family` and `bench_prog_family` internally call the `summarize` method #[experimental] pub fn summarize(&mut self, id: &str) -> &mut Criterion { print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } } // FIXME Sorry! Everything below this point is a mess :/ fn bench<I>(id: &str, mut target: Target<I>, criterion: &Criterion) { println!("Benchmarking {}", id); rename_new_dir_to_base(id); build_directory_skeleton(id); let root = Path::new(".criterion").join(id); let base_dir = root.join("base"); let change_dir = root.join("change"); let new_dir = root.join("new"); match target { Program(_) => { let _clock_cost = external_clock_cost(&mut target, criterion, &new_dir.join("clock"), id); // TODO use clock_cost to set minimal measurement_time }, _ => {}, } let sample = take_sample(&mut target, criterion).unwrap(); sample.save(&new_dir.join("sample.json")); plot::sample(&sample, new_dir.join("points.svg"), id); plot::pdf(&sample, new_dir.join("pdf.svg"), id); let outliers = Outliers::classify(sample.as_slice()); outliers.report(); outliers.save(&new_dir.join("outliers/classification.json")); plot::outliers(&outliers, new_dir.join("outliers/boxplot.svg"), id); println!("> Estimating the statistics of the sample"); let nresamples = criterion.nresamples; let cl = criterion.confidence_level; println!(" > Bootstrapping the sample with {} resamples", nresamples); let (estimates, distributions) = sample.bootstrap([Mean, Median, StdDev, MedianAbsDev], nresamples, cl); estimates.save(&new_dir.join("bootstrap/estimates.json")); report_time(&estimates); plot::time_distributions(&distributions, &estimates, &new_dir.join("bootstrap/distribution"), id); if!base_dir.exists() { return; } println!("{}: Comparing with previous sample", id); let base_sample = Sample::<Vec<f64>>::load(&base_dir.join("sample.json")); let both_dir = root.join("both"); plot::both::pdfs(&base_sample, &sample, both_dir.join("pdfs.svg"), id); plot::both::points(&base_sample, &sample, both_dir.join("points.svg"), id); println!("> H0: Both samples belong to the same population"); println!(" > Bootstrapping with {} resamples", nresamples); let t_statistic = sample.t_test(&base_sample); let t_distribution = sample.bootstrap_t_test(&base_sample, nresamples, cl); let t = t_statistic.abs(); let hits = t_distribution.as_slice().iter().filter(|&&x| x > t || x < -t).count(); let p_value = hits as f64 / nresamples as f64; let sl = criterion.significance_level; let different_population = p_value < sl; println!(" > p = {}", p_value); println!(" > {} reject the null hypothesis", if different_population { "Strong evidence to" } else { "Can't" }) plot::t_test(t_statistic, &t_distribution, change_dir.join("bootstrap/t_test.svg"), id); let nresamples_sqrt = (nresamples as f64).sqrt().ceil() as uint; let nresamples = nresamples_sqrt * nresamples_sqrt; println!("> Estimating relative change of statistics"); println!(" > Bootstrapping with {} resamples", nresamples); let (estimates, distributions) = sample.bootstrap_compare(&base_sample, [Mean, Median], nresamples_sqrt, cl); estimates.save(&change_dir.join("bootstrap/estimates.json")); report_change(&estimates); plot::ratio_distributions(&distributions, &estimates, &change_dir.join("bootstrap/distribution"), id); let threshold = criterion.noise_threshold; let mut regressed = vec!(); for &statistic in [Mean, Median].iter() { let estimate = estimates.get(statistic); let result = compare_to_threshold(estimate, threshold); let p = estimate.point_estimate(); match result { Improved => { println!(" > {} has improved by {:.2}%", statistic, -100.0 * p); regressed.push(false); }, Regressed => { println!(" > {} has regressed by {:.2}%", statistic, 100.0 * p); regressed.push(true); }, NonSignificant => { regressed.push(false); }, } } if different_population && regressed.iter().all(|&x| x) { fail!("{} has regressed", id); } } fn external_clock_cost<I>( target: &mut Target<I>, criterion: &Criterion, dir: &Path, id: &str, ) -> Ns<f64> { println!("> Estimating the cost of a clock call"); let wu_time = criterion.warm_up_time; println!(" > Warming up for {}", wu_time.to::<Mili>()); let init = time::now(); while time::now() - init < wu_time { target.run(0); } println!(" > Collecting {} measurements", criterion.sample_size); let sample = Sample::new( range(0, criterion.sample_size). map(|_| target.run(0).unwrap() as f64). collect::<Vec<f64>>()); let clock_cost = sample.compute(Median); println!(" > {}: {}", Median, format_time(clock_cost)); fs::mkdirp(dir); plot::sample(&sample, dir.join("points.svg"), format!("{}/clock_cost", id)); plot::pdf(&sample, dir.join("pdf.svg"), format!("{}/clock_cost", id)); clock_cost.ns() } fn extrapolate_iters(iters: u64, took: Ns<u64>, want: Ns<u64>) -> (Ns<f64>, u64) { let e_iters = cmp::max(want * iters / took, 1); let e_time = (took * e_iters).cast::<f64>() / iters as f64; (e_time, e_iters) } fn time_now(b: &mut Bencher) { b.iter(|| time::now()); } fn clock_cost(criterion: &Criterion) -> Ns<f64> { println!("Estimating the cost of `precise_time_ns`"); let sample = take_sample(&mut Function::<()>(time_now), criterion); let median = sample.unwrap().compute(Mean).ns(); println!("> Median: {}\n", median); median } fn take_sample<I>(t: &mut Target<I>, criterion: &Criterion) -> Ns<Sample<Vec<f64>>> { let wu_time = criterion.warm_up_time; println!("> Warming up for {}", wu_time.to::<Mili>()) let (took, iters) = t.warm_up(wu_time); let m_time = criterion.measurement_time; let (m_time, m_iters) = extrapolate_iters(iters, took, m_time); let sample_size = criterion.sample_size; println!("> Collecting {} measurements, {} iters each in estimated {}", sample_size, m_iters, format_time((m_time * sample_size as f64).unwrap())); let sample = t.bench(sample_size, m_iters).unwrap(); sample.ns() } fn rename_new_dir_to_base(id: &str) { let root_dir = Path::new(".criterion").join(id); let base_dir = root_dir.join("base"); let new_dir = root_dir.join("new"); if base_dir.exists() { fs::rmrf(&base_dir) } if new_dir.exists() { fs::mv(&new_dir, &base_dir) }; } fn build_directory_skeleton(id: &str) { let root = Path::new(".criterion").join(id); fs::mkdirp(&root.join("both")); fs::mkdirp(&root.join("change/bootstrap/distribution")); fs::mkdirp(&root.join("new/bootstrap/distribution")); fs::mkdirp(&root.join("new/outliers")); } fn format_short(n: f64) -> String { if n < 10.0 { format!("{:.4}", n) } else if n < 100.0 { format!("{:.3}", n) } else if n < 1000.0 { format!("{:.2}", n) } else { format!("{}", n) } } fn format_signed_short(n: f64) -> String { let n_abs = n.abs(); if n_abs < 10.0 { format!("{:+.4}", n) } else if n_abs < 100.0 { format!("{:+.3}", n) } else if n_abs < 1000.0 { format!("{:+.2}", n) } else { format!("{:+}", n) } } fn report_time(estimates: &Estimates) { for &statistic in [Mean, Median, StdDev, MedianAbsDev].iter() { let estimate = estimates.get(statistic); let p = format_time(estimate.point_estimate()); let ci = estimate.confidence_interval(); let lb = format_time(ci.lower_bound()); let ub = format_time(ci.upper_bound()); let se = format_time(estimate.standard_error()); let cl = ci.confidence_level(); println!(" > {:<7} {} ± {} [{} {}] {}% CI", statistic, p, se, lb, ub, cl * 100.0); } } fn format_time(ns: f64) -> String { if ns < 1.0 { format!("{:>6} ps", format_short(ns * 1e3)) } else if ns < num::pow(10.0, 3) { format!("{:>6} ns", format_short(ns)) } else if ns < num::pow(10.0, 6) { format!("{:>6} us", format_short(ns / 1e3)) } else if ns < num::pow(10.0, 9) { format!("{:>6} ms", format_short(ns / 1e6)) } else { format!("{:>6} s", format_short(ns / 1e9)) } } fn report_change(estimates: &Estimates) { for &statistic in [Mean, Median].iter() { let estimate = estimates.get(statistic); let p = format_change(estimate.point_estimate(), true); let ci = estimate.confidence_interval(); let lb = format_change(ci.lower_bound(), true); let ub = format_change(ci.upper_bound(), true); let se = format_change(estimate.standard_error(), false); let cl = ci.confidence_level(); println!(" > {:<7} {} ± {} [{} {}] {}% CI", statistic, p, se, lb, ub, cl * 100.0); } } fn format_change(pct: f64, signed: bool) -> String { if signed { format!("{:>+6}%", format_signed_short(pct * 1e2)) } else { format!("{:>6}%", format_short(pct * 1e2)) } } enum ComparisonResult { Improved, Regressed, NonSignificant, } fn compare_to_threshold(estimate: &Estimate, noise: f64) -> ComparisonResult { let ci = estimate.confidence_interval(); let lb = ci.lower_bound(); let ub = ci.upper_bound(); if lb < -noise && ub < -noise { Improved } else if lb > noise && ub > noise { Regressed } else { NonSignificant } }
significance_level
identifier_name
criterion.rs
use std::cmp; use std::fmt::Show; use std::io::Command; use std::num; use bencher::Bencher; use fs; use outliers::Outliers; use plot; use statistics::{Estimate,Estimates,Mean,Median,MedianAbsDev,Sample,StdDev}; use stream::Stream; use target::{Function,FunctionFamily,Program,Target}; use time::prefix::{Mili,Nano}; use time::traits::{Milisecond,Nanosecond,Second}; use time::types::Ns; use time; /// The "criterion" for the benchmark, which is also the benchmark "manager" #[experimental] pub struct Criterion { confidence_level: f64, measurement_time: Ns<u64>, noise_threshold: f64, nresamples: uint, sample_size: uint, significance_level: f64, warm_up_time: Ns<u64>, } #[experimental] impl Criterion { /// This is the default criterion: /// /// * Confidence level: 0.95 /// * Measurement time: 10 ms /// * Noise threshold: 0.01 (1%) /// * Bootstrap with 100 000 resamples /// * Sample size: 100 measurements /// * Significance level: 0.05 /// * Warm-up time: 1 s #[experimental] pub fn default() -> Criterion { Criterion { confidence_level: 0.95, measurement_time: 10.ms().to::<Nano>(), noise_threshold: 0.01, nresamples: 100_000, sample_size: 100, significance_level: 0.05, warm_up_time: 1.s().to::<Nano>(), } } /// Changes the confidence level /// /// The confidence level is used to calculate the confidence intervals of the estimates #[experimental] pub fn confidence_level(&mut self, cl: f64) -> &mut Criterion { assert!(cl > 0.0 && cl < 1.0); self.confidence_level = cl; self } /// Change the measurement time /// /// The program/function under test is iterated for `measurement_time` ms. And the average run /// time is reported as a measurement #[experimental] pub fn measurement_time(&mut self, ms: u64) -> &mut Criterion { self.measurement_time = ms.ms().to::<Nano>(); self } /// Changes the noise threshold /// /// When comparing benchmark results, only relative changes of the execution time above this /// threshold are considered significant #[experimental] pub fn noise_threshold(&mut self, nt: f64) -> &mut Criterion { assert!(nt >= 0.0); self.noise_threshold = nt; self } /// Changes the number of resamples /// /// Number of resamples to use for bootstraping via case resampling #[experimental] pub fn nresamples(&mut self, n: uint) -> &mut Criterion { self.nresamples = n; self } /// Changes the size of a sample /// /// A sample consists of severals measurements #[experimental] pub fn sample_size(&mut self, n: uint) -> &mut Criterion { self.sample_size = n; self } /// Changes the significance level /// /// Significance level to use for hypothesis testing #[experimental] pub fn significance_level(&mut self, sl: f64) -> &mut Criterion { assert!(sl > 0.0 && sl < 1.0); self.significance_level = sl; self } /// Changes the warm up time /// /// The program/function under test is executed during `warm_up_time` ms before the real /// measurement starts #[experimental] pub fn warm_up_time(&mut self, ms: u64) -> &mut Criterion { self.warm_up_time = ms.ms().to::<Nano>(); self } /// Benchmark a function. See `Bench::iter()` for an example of how `fun` should look #[experimental] pub fn bench(&mut self, id: &str, fun: fn (&mut Bencher)) -> &mut Criterion { local_data_key!(clock: Ns<f64>); if clock.get().is_none() { clock.replace(Some(clock_cost(self))); } // TODO Use clock cost to set a minimum `measurement_time` bench(id, Function::<()>(fun), self); println!(""); self } /// Benchmark a family of functions /// /// `fun` will be benchmarked under each input /// /// For example, if you want to benchmark `Vec::from_elem` with different size, use these /// arguments: /// /// let fun = |b, n| Vec::from_elem(n, 0u); /// let inputs = [100, 10_000, 1_000_000]; /// /// This is equivalent to calling `bench` on each of the following functions: /// /// let fun1 = |b| Vec::from_elem(100, 0u); /// let fun2 = |b| Vec::from_elem(10_000, 0u); /// let fun3 = |b| Vec::from_elem(1_000_000, 0u); #[experimental] pub fn bench_family<I: Show>( &mut self, id: &str, fun: fn (&mut Bencher, &I), inputs: &[I]) -> &mut Criterion { for input in inputs.iter() { let id = format!("{}/{}", id, input); bench(id.as_slice(), FunctionFamily(fun, input), self); } print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } /// Benchmark an external program /// /// The program must conform to the following specification: /// /// extern crate time; /// /// fn main() { /// // Optional: Get the program arguments /// let args = std::os::args(); /// /// for line in std::io::stdio::stdin().lines() { /// // Get number of iterations to do /// let iters: u64 = from_str(line.unwrap().as_slice().trim()).unwrap(); /// /// // Setup /// /// // (For best results, use a monotonic timer) /// let start = time::precise_time_ns(); /// for _ in range(0, iters) { /// // Routine to benchmark goes here /// } /// let end = time::precise_time_ns(); /// /// // Teardown /// /// // Report back the time (in nanoseconds) required to execute the routine /// // `iters` times /// println!("{}", end - start); /// } /// } /// /// For example, to benchmark a python script use the following command /// /// let cmd = Command::new("python3").args(["-O", "clock.py"]); #[experimental] pub fn bench_prog(&mut self, id: &str, prog: &Command) -> &mut Criterion { bench(id, Program::<()>(Stream::spawn(prog)), self); println!(""); self } /// Benchmark an external program under various inputs /// /// For example, to benchmark a python script under various inputs, use this combination: /// /// let cmd = Command::new("python3").args(["-O", "fib.py"]); /// let inputs = [5u, 10, 15]; /// /// This is equivalent to calling `bench_prog` on each of the following commands: /// /// let cmd1 = Command::new("python3").args(["-O", "fib.py", "5"]); /// let cmd2 = Command::new("python3").args(["-O", "fib.py", "10"]); /// let cmd2 = Command::new("python3").args(["-O", "fib.py", "15"]); #[experimental] pub fn bench_prog_family<I: Show>( &mut self, id: &str, prog: &Command, inputs: &[I]) -> &mut Criterion { for input in inputs.iter() { let id = format!("{}/{}", id, input); self.bench_prog(id.as_slice(), prog.clone().arg(format!("{}", input))); } print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } /// Summarize the results stored under the `.criterion/${id}` folder /// /// Note that `bench_family` and `bench_prog_family` internally call the `summarize` method #[experimental] pub fn summarize(&mut self, id: &str) -> &mut Criterion { print!("Summarizing results of {}... ", id); plot::summarize(&Path::new(".criterion").join(id), id); println!("DONE\n"); self } } // FIXME Sorry! Everything below this point is a mess :/ fn bench<I>(id: &str, mut target: Target<I>, criterion: &Criterion) { println!("Benchmarking {}", id); rename_new_dir_to_base(id); build_directory_skeleton(id); let root = Path::new(".criterion").join(id); let base_dir = root.join("base"); let change_dir = root.join("change"); let new_dir = root.join("new"); match target { Program(_) => { let _clock_cost = external_clock_cost(&mut target, criterion, &new_dir.join("clock"), id); // TODO use clock_cost to set minimal measurement_time }, _ => {}, } let sample = take_sample(&mut target, criterion).unwrap(); sample.save(&new_dir.join("sample.json")); plot::sample(&sample, new_dir.join("points.svg"), id); plot::pdf(&sample, new_dir.join("pdf.svg"), id); let outliers = Outliers::classify(sample.as_slice()); outliers.report(); outliers.save(&new_dir.join("outliers/classification.json")); plot::outliers(&outliers, new_dir.join("outliers/boxplot.svg"), id); println!("> Estimating the statistics of the sample"); let nresamples = criterion.nresamples; let cl = criterion.confidence_level; println!(" > Bootstrapping the sample with {} resamples", nresamples); let (estimates, distributions) = sample.bootstrap([Mean, Median, StdDev, MedianAbsDev], nresamples, cl); estimates.save(&new_dir.join("bootstrap/estimates.json")); report_time(&estimates); plot::time_distributions(&distributions, &estimates, &new_dir.join("bootstrap/distribution"), id); if!base_dir.exists() { return; } println!("{}: Comparing with previous sample", id); let base_sample = Sample::<Vec<f64>>::load(&base_dir.join("sample.json")); let both_dir = root.join("both"); plot::both::pdfs(&base_sample, &sample, both_dir.join("pdfs.svg"), id); plot::both::points(&base_sample, &sample, both_dir.join("points.svg"), id); println!("> H0: Both samples belong to the same population"); println!(" > Bootstrapping with {} resamples", nresamples); let t_statistic = sample.t_test(&base_sample); let t_distribution = sample.bootstrap_t_test(&base_sample, nresamples, cl); let t = t_statistic.abs(); let hits = t_distribution.as_slice().iter().filter(|&&x| x > t || x < -t).count(); let p_value = hits as f64 / nresamples as f64; let sl = criterion.significance_level; let different_population = p_value < sl; println!(" > p = {}", p_value); println!(" > {} reject the null hypothesis", if different_population { "Strong evidence to" } else { "Can't" }) plot::t_test(t_statistic, &t_distribution, change_dir.join("bootstrap/t_test.svg"), id); let nresamples_sqrt = (nresamples as f64).sqrt().ceil() as uint; let nresamples = nresamples_sqrt * nresamples_sqrt; println!("> Estimating relative change of statistics"); println!(" > Bootstrapping with {} resamples", nresamples); let (estimates, distributions) = sample.bootstrap_compare(&base_sample, [Mean, Median], nresamples_sqrt, cl); estimates.save(&change_dir.join("bootstrap/estimates.json")); report_change(&estimates); plot::ratio_distributions(&distributions, &estimates, &change_dir.join("bootstrap/distribution"), id); let threshold = criterion.noise_threshold; let mut regressed = vec!(); for &statistic in [Mean, Median].iter() { let estimate = estimates.get(statistic); let result = compare_to_threshold(estimate, threshold); let p = estimate.point_estimate(); match result { Improved => { println!(" > {} has improved by {:.2}%", statistic, -100.0 * p); regressed.push(false); }, Regressed => { println!(" > {} has regressed by {:.2}%", statistic, 100.0 * p); regressed.push(true); }, NonSignificant => { regressed.push(false); }, } } if different_population && regressed.iter().all(|&x| x) { fail!("{} has regressed", id); } } fn external_clock_cost<I>( target: &mut Target<I>, criterion: &Criterion, dir: &Path, id: &str, ) -> Ns<f64> { println!("> Estimating the cost of a clock call"); let wu_time = criterion.warm_up_time; println!(" > Warming up for {}", wu_time.to::<Mili>()); let init = time::now(); while time::now() - init < wu_time { target.run(0); } println!(" > Collecting {} measurements", criterion.sample_size); let sample = Sample::new( range(0, criterion.sample_size). map(|_| target.run(0).unwrap() as f64). collect::<Vec<f64>>()); let clock_cost = sample.compute(Median); println!(" > {}: {}", Median, format_time(clock_cost)); fs::mkdirp(dir); plot::sample(&sample, dir.join("points.svg"), format!("{}/clock_cost", id)); plot::pdf(&sample, dir.join("pdf.svg"), format!("{}/clock_cost", id)); clock_cost.ns() } fn extrapolate_iters(iters: u64, took: Ns<u64>, want: Ns<u64>) -> (Ns<f64>, u64) { let e_iters = cmp::max(want * iters / took, 1); let e_time = (took * e_iters).cast::<f64>() / iters as f64; (e_time, e_iters) } fn time_now(b: &mut Bencher) { b.iter(|| time::now()); } fn clock_cost(criterion: &Criterion) -> Ns<f64> { println!("Estimating the cost of `precise_time_ns`"); let sample = take_sample(&mut Function::<()>(time_now), criterion); let median = sample.unwrap().compute(Mean).ns(); println!("> Median: {}\n", median); median } fn take_sample<I>(t: &mut Target<I>, criterion: &Criterion) -> Ns<Sample<Vec<f64>>> { let wu_time = criterion.warm_up_time; println!("> Warming up for {}", wu_time.to::<Mili>()) let (took, iters) = t.warm_up(wu_time); let m_time = criterion.measurement_time; let (m_time, m_iters) = extrapolate_iters(iters, took, m_time); let sample_size = criterion.sample_size; println!("> Collecting {} measurements, {} iters each in estimated {}", sample_size, m_iters, format_time((m_time * sample_size as f64).unwrap())); let sample = t.bench(sample_size, m_iters).unwrap(); sample.ns() } fn rename_new_dir_to_base(id: &str) { let root_dir = Path::new(".criterion").join(id); let base_dir = root_dir.join("base"); let new_dir = root_dir.join("new"); if base_dir.exists() { fs::rmrf(&base_dir) } if new_dir.exists() { fs::mv(&new_dir, &base_dir) }; } fn build_directory_skeleton(id: &str) { let root = Path::new(".criterion").join(id); fs::mkdirp(&root.join("both")); fs::mkdirp(&root.join("change/bootstrap/distribution")); fs::mkdirp(&root.join("new/bootstrap/distribution")); fs::mkdirp(&root.join("new/outliers")); } fn format_short(n: f64) -> String { if n < 10.0 { format!("{:.4}", n) } else if n < 100.0 { format!("{:.3}", n) } else if n < 1000.0 { format!("{:.2}", n) } else { format!("{}", n) } } fn format_signed_short(n: f64) -> String { let n_abs = n.abs(); if n_abs < 10.0 { format!("{:+.4}", n) } else if n_abs < 100.0 { format!("{:+.3}", n) } else if n_abs < 1000.0 { format!("{:+.2}", n) } else { format!("{:+}", n) } } fn report_time(estimates: &Estimates) { for &statistic in [Mean, Median, StdDev, MedianAbsDev].iter() { let estimate = estimates.get(statistic); let p = format_time(estimate.point_estimate()); let ci = estimate.confidence_interval(); let lb = format_time(ci.lower_bound()); let ub = format_time(ci.upper_bound()); let se = format_time(estimate.standard_error()); let cl = ci.confidence_level(); println!(" > {:<7} {} ± {} [{} {}] {}% CI", statistic, p, se, lb, ub, cl * 100.0);
} } fn format_time(ns: f64) -> String { if ns < 1.0 { format!("{:>6} ps", format_short(ns * 1e3)) } else if ns < num::pow(10.0, 3) { format!("{:>6} ns", format_short(ns)) } else if ns < num::pow(10.0, 6) { format!("{:>6} us", format_short(ns / 1e3)) } else if ns < num::pow(10.0, 9) { format!("{:>6} ms", format_short(ns / 1e6)) } else { format!("{:>6} s", format_short(ns / 1e9)) } } fn report_change(estimates: &Estimates) { for &statistic in [Mean, Median].iter() { let estimate = estimates.get(statistic); let p = format_change(estimate.point_estimate(), true); let ci = estimate.confidence_interval(); let lb = format_change(ci.lower_bound(), true); let ub = format_change(ci.upper_bound(), true); let se = format_change(estimate.standard_error(), false); let cl = ci.confidence_level(); println!(" > {:<7} {} ± {} [{} {}] {}% CI", statistic, p, se, lb, ub, cl * 100.0); } } fn format_change(pct: f64, signed: bool) -> String { if signed { format!("{:>+6}%", format_signed_short(pct * 1e2)) } else { format!("{:>6}%", format_short(pct * 1e2)) } } enum ComparisonResult { Improved, Regressed, NonSignificant, } fn compare_to_threshold(estimate: &Estimate, noise: f64) -> ComparisonResult { let ci = estimate.confidence_interval(); let lb = ci.lower_bound(); let ub = ci.upper_bound(); if lb < -noise && ub < -noise { Improved } else if lb > noise && ub > noise { Regressed } else { NonSignificant } }
random_line_split
mod.rs
pub(crate) mod css; mod css_function; mod error; pub mod formalargs; mod imports; mod media; pub mod selectors; mod span; pub(crate) mod strings; mod unit; pub(crate) mod util; pub mod value; pub(crate) use self::strings::name; pub use error::ParseError; pub(crate) use span::DebugBytes; pub(crate) use span::{position, Span}; use self::formalargs::{call_args, formal_args}; use self::selectors::selectors; use self::strings::{ custom_value, sass_string, sass_string_dq, sass_string_sq, }; use self::util::{ comment2, ignore_comments, ignore_space, opt_spacelike, semi_or_end, spacelike, }; use self::value::{ dictionary, function_call_or_string, single_value, value_expression, }; use crate::input::{SourceFile, SourceName, SourcePos}; use crate::sass::parser::{variable_declaration2, variable_declaration_mod}; use crate::sass::{Callable, FormalArgs, Item, Name, Selectors, Value}; use crate::value::ListSeparator; #[cfg(test)] use crate::value::{Numeric, Unit}; use crate::Error; use imports::{forward2, import2, use2}; use nom::branch::alt; use nom::bytes::complete::{is_a, is_not, tag}; use nom::character::complete::one_of; use nom::combinator::{ all_consuming, into, map, map_res, opt, peek, value, verify, }; use nom::multi::{many0, many_till, separated_list0, separated_list1}; use nom::sequence::{delimited, pair, preceded, terminated}; use nom::IResult; use std::str::{from_utf8, Utf8Error}; /// A Parsing Result; ok gives a span for the rest of the data and a parsed T. pub(crate) type PResult<'a, T> = IResult<Span<'a>, T>; pub(crate) fn code_span(value: &[u8]) -> SourcePos { SourceFile::scss_bytes(value, SourceName::root("(rsass)")).into() } pub(crate) fn input_span(value: impl Into<Vec<u8>>) -> SourcePos { SourceFile::scss_bytes(value, SourceName::root("-")).into() } /// Parse a scss value. /// /// Returns a single value (or an error). pub fn parse_value_data(data: &[u8]) -> Result<Value, Error> { let data = code_span(data); let value = all_consuming(value_expression)(data.borrow()); Ok(ParseError::check(value)?) } #[test] fn test_parse_value_data_1() -> Result<(), Error> { let v = parse_value_data(b"17em")?; assert_eq!(Value::Numeric(Numeric::new(17, Unit::Em)), v); Ok(()) } #[test] fn test_parse_value_data_2() -> Result<(), Error> { let v = parse_value_data(b"17em;"); assert!(v.is_err()); Ok(()) } pub(crate) fn sassfile(input: Span) -> PResult<Vec<Item>> { preceded( opt(tag("\u{feff}".as_bytes())), map( many_till( preceded(opt_spacelike, top_level_item), all_consuming(opt_spacelike), ), |(v, _eof)| v, ), )(input) } fn top_level_item(input: Span) -> PResult<Item> { let (rest, tag) = alt((tag("$"), tag("/*"), tag("@"), tag("")))(input)?; match tag.fragment() { b"$" => into(variable_declaration2)(rest), b"/*" => comment_item(rest), b"@" => at_rule2(input), b"" => alt((into(variable_declaration_mod), rule))(input), _ => unreachable!(), } } fn comment_item(input: Span) -> PResult<Item> { map(comment2, Item::Comment)(input) } fn rule(input: Span) -> PResult<Item> { map(pair(rule_start, body_block2), |(selectors, body)| { Item::Rule(selectors, body) })(input) } fn rule_start(input: Span) -> PResult<Selectors> { terminated(selectors, terminated(opt(is_a(", \t\r\n")), tag("{")))(input) } fn body_item(input: Span) -> PResult<Item> { let (rest, tag) = alt((tag("$"), tag("/*"), tag(";"), tag("@"), tag("--"), tag("")))( input, )?; match tag.fragment() { b"$" => into(variable_declaration2)(rest), b"/*" => comment_item(rest), b";" => Ok((rest, Item::None)), b"@" => at_rule2(input), b"--" => { let result = custom_property(rest); if result.is_err() { // Note use of `input` rather than `rest` here. if let Ok((rest, rule)) = rule(input) { return Ok((rest, rule)); } } result } b"" => match rule_start(rest) { Ok((rest, selectors)) => { let (rest, body) = body_block2(rest)?; Ok((rest, Item::Rule(selectors, body))) } Err(_) => property_or_namespace_rule(rest), }, _ => unreachable!(), } } /// What follows the `@at-root` tag. fn at_root2(input: Span) -> PResult<Item> { preceded( opt_spacelike, map( pair( map(opt(selectors), |s| s.unwrap_or_else(Selectors::root)), body_block, ), |(selectors, body)| Item::AtRoot(selectors, body), ), )(input) } /// What follows the `@include` tag. fn mixin_call<'a>(start: Span, input: Span<'a>) -> PResult<'a, Item> { let (rest, n1) = terminated(name, opt_spacelike)(input)?; let (rest, n2) = opt(preceded(tag("."), name))(rest)?; let name = n2.map(|n2| format!("{n1}.{n2}")).unwrap_or(n1); let (rest, _) = opt_spacelike(rest)?; let (rest0, args) = terminated(opt(call_args), opt_spacelike)(rest)?; let (rest, t) = alt((tag("using"), tag("{"), tag("")))(rest0)?; let (end, body) = match t.fragment() { b"using" => { let (end, args) = preceded(opt_spacelike, formal_args)(rest)?; let (rest, body) = preceded(opt_spacelike, body_block)(end)?; let decl = rest0.up_to(&end).to_owned(); (rest, Some(Callable::new(args, body, decl))) } b"{" => { let (rest, body) = body_block(rest0)?; let decl = rest0.up_to(&rest).to_owned(); (rest, Some(Callable::no_args(body, decl))) } _ => { let (rest, _) = opt(tag(";"))(rest)?; (rest, None) } }; let pos = start.up_to(&rest).to_owned(); Ok(( end, Item::MixinCall(name, args.unwrap_or_default(), body, pos), )) } /// When we know that `input0` starts with an `@` sign. fn at_rule2(input0: Span) -> PResult<Item> { let (input, name) = delimited(tag("@"), sass_string, opt_spacelike)(input0)?; match name.single_raw().unwrap_or("") { "at-root" => at_root2(input), "charset" => charset2(input), "content" => content_stmt2(input), "debug" => map(expression_argument, Item::Debug)(input), "each" => each_loop2(input), "error" => { let (end, v) = value_expression(input)?; let (rest, _) = opt(tag(";"))(end)?; let pos = input0.up_to(&end).to_owned(); Ok((rest, Item::Error(v, pos))) } "extend" => map( delimited( opt_spacelike, selectors, preceded(opt_spacelike, tag(";")), ), Item::Extend, )(input), "for" => for_loop2(input), "forward" => forward2(input0, input), "function" => function_declaration2(input), "if" => if_statement2(input), "import" => import2(input), "include" => mixin_call(input0, input), "media" => media::rule(input0, input), "mixin" => mixin_declaration2(input), "return" => return_stmt2(input0, input), "use" => use2(input0, input), "warn" => map(expression_argument, Item::Warn)(input), "while" => while_loop2(input), _ => unknown_atrule(name, input0, input), } } fn unknown_atrule<'a>( name: SassString, start: Span, input: Span<'a>, ) -> PResult<'a, Item> { let (input, args) = terminated(opt(unknown_rule_args), opt(ignore_space))(input)?; fn x_args(value: Value) -> Value { match value { Value::Variable(name, _pos) => { Value::Literal(SassString::from(format!("${name}"))) } Value::Map(map) => Value::Map( map.into_iter() .map(|(k, v)| (x_args(k), x_args(v))) .collect(), ), value => value, } } let (rest, body) = if input.first() == Some(&b'{') { map(body_block, Some)(input)? } else { value(None, semi_or_end)(input)? }; Ok(( rest, Item::AtRule { name, args: args.map_or(Value::Null, x_args), body, pos: start.up_to(&input).to_owned(), }, )) } fn expression_argument(input: Span) -> PResult<Value> { terminated(value_expression, opt(tag(";")))(input) } fn charset2(input: Span) -> PResult<Item> { use nom::combinator::map_opt; map_opt( terminated( alt((sass_string_dq, sass_string_sq, sass_string)), semi_or_end, ), |s| { s.single_raw().and_then(|s| { if s.eq_ignore_ascii_case("UTF-8") { Some(Item::None) } else { None } }) }, )(input) } /// Arguments to an unkown at rule. fn unknown_rule_args(input: Span) -> PResult<Value> { let (input, args) = separated_list0( preceded(tag(","), opt_spacelike), map( many0(preceded( opt(ignore_space), alt(( terminated( alt(( function_call_or_string, dictionary, map( delimited(tag("("), media::args, tag(")")), |v| Value::Paren(Box::new(v), true), ), map(sass_string_dq, Value::Literal), map(sass_string_sq, Value::Literal), )), alt(( value((), all_consuming(tag(""))), value((), peek(one_of(") \r\n\t{,;"))), )), ), map(map_res(is_not("\"'{};#"), input_to_str), |s| { Value::Literal(s.trim_end().into()) }), )), )), |args| list_or_single(args, ListSeparator::Space), ), )(input)?; Ok((input, list_or_single(args, ListSeparator::Comma))) } #[cfg(test)] pub(crate) fn check_parse<T>( parser: impl Fn(Span) -> PResult<T>, value: &[u8], ) -> Result<T, ParseError> { ParseError::check(parser(code_span(value).borrow())) } fn if_statement_inner(input: Span) -> PResult<Item> { preceded( terminated(verify(name, |n: &String| n == "if"), opt_spacelike), if_statement2, )(input) } fn if_statement2(input: Span) -> PResult<Item> { let (input, cond) = terminated(value_expression, opt_spacelike)(input)?; let (input, body) = body_block(input)?; let (input2, word) = opt(delimited( preceded(opt_spacelike, tag("@")), name, opt_spacelike, ))(input)?; match word.as_ref().map(AsRef::as_ref) { Some("else") => { let (input2, else_body) = alt(( body_block, map(if_statement_inner, |s| vec![s]), ))(input2)?; Ok((input2, Item::IfStatement(cond, body, else_body))) } Some("elseif") => { let (input2, else_body) = if_statement2(input2)?; Ok((input2, Item::IfStatement(cond, body, vec![else_body]))) } _ => Ok((input, Item::IfStatement(cond, body, vec![]))), } } /// The part of an each look that follows the `@each`. fn each_loop2(input: Span) -> PResult<Item> { let (input, names) = separated_list1( delimited(opt_spacelike, tag(","), opt_spacelike), map(preceded(tag("$"), name), Name::from), )(input)?; let (input, values) = delimited( delimited(spacelike, tag("in"), spacelike), value_expression, opt_spacelike, )(input)?; let (input, body) = body_block(input)?; Ok((input, Item::Each(names, values, body))) } /// A for loop after the initial `@for`. fn for_loop2(input: Span) -> PResult<Item> { let (input, name) = delimited(tag("$"), name, spacelike)(input)?; let (input, from) = delimited( terminated(tag("from"), spacelike), single_value, spacelike, )(input)?; let (input, inclusive) = terminated( alt((value(true, tag("through")), value(false, tag("to")))), spacelike, )(input)?; let (input, to) = terminated(single_value, opt_spacelike)(input)?; let (input, body) = body_block(input)?; Ok(( input, Item::For { name: name.into(), from: Box::new(from), to: Box::new(to), inclusive, body, }, )) } fn while_loop2(input: Span) -> PResult<Item> { let (input, cond) = terminated(value_expression, opt_spacelike)(input)?; let (input, body) = body_block(input)?; Ok((input, Item::While(cond, body))) } fn mixin_declaration2(input: Span) -> PResult<Item> { let (rest, name) = terminated(name, opt_spacelike)(input)?; let (rest, args) = opt(formal_args)(rest)?; let (end, body) = preceded(opt_spacelike, body_block)(rest)?; let args = args.unwrap_or_else(FormalArgs::none); let decl = input.up_to(&rest).to_owned(); Ok(( end, Item::MixinDeclaration(name, Callable { args, body, decl }), )) } fn function_declaration2(input: Span) -> PResult<Item> { let (end, name) = terminated(name, opt_spacelike)(input)?; let (end, args) = formal_args(end)?; let (rest, body) = preceded(opt_spacelike, body_block)(end)?; let decl = input.up_to(&end).to_owned(); Ok(( rest, Item::FunctionDeclaration(name, Callable { args, body, decl }), )) } fn return_stmt2<'a>(start: Span, input: Span<'a>) -> PResult<'a, Item> { let (input, v) = delimited(opt_spacelike, value_expression, opt_spacelike)(input)?; let pos = start.up_to(&input).to_owned(); let (input, _) = opt(tag(";"))(input)?; Ok((input, Item::Return(v, pos))) } /// The "rest" of an `@content` statement is just an optional terminator fn content_stmt2(input: Span) -> PResult<Item> { let (rest, _) = opt_spacelike(input)?; let (rest, args) = opt(call_args)(rest)?; let (rest, _) = opt(tag(";"))(rest)?; let pos = input.up_to(&rest).to_owned(); Ok((rest, Item::Content(args.unwrap_or_default(), pos))) } fn custom_property(input: Span) -> PResult<Item> { let (rest, name) = terminated(opt(sass_string), tag(":"))(input)?; let mut name = name.unwrap_or_else(|| SassString::from("")); // The dashes was parsed before calling this method. name.prepend("--"); let (rest, value) = terminated(custom_value, alt((tag(";"), peek(tag("}")))))(rest)?; Ok((rest, Item::CustomProperty(name, value))) } fn property_or_namespace_rule(input: Span) -> PResult<Item> { let (start_val, name) = terminated( alt(( map(preceded(tag("*"), sass_string), |mut s| { s.prepend("*"); s }), sass_string, )), delimited(ignore_comments, tag(":"), ignore_comments), )(input)?; let (input, val) = opt(value_expression)(start_val)?; let pos = start_val.up_to(&input).to_owned(); let (input, _) = opt_spacelike(input)?;
}; let (input, body) = match next.fragment() { b"{" => map(body_block2, Some)(input)?, b";" => (input, None), b"" => (input, None), _ => (input, None), // error? }; let (input, _) = opt_spacelike(input)?; Ok((input, ns_or_prop_item(name, val, body, pos))) } use crate::sass::SassString; fn ns_or_prop_item( name: SassString, value: Option<Value>, body: Option<Vec<Item>>, pos: SourcePos, ) -> Item { if let Some(body) = body { Item::NamespaceRule(name, value.unwrap_or(Value::Null), body) } else if let Some(value) = value { Item::Property(name, value, pos) } else { unreachable!() } } fn body_block(input: Span) -> PResult<Vec<Item>> { preceded(tag("{"), body_block2)(input) } fn body_block2(input: Span) -> PResult<Vec<Item>> { let (input, (v, _end)) = preceded( opt_spacelike, many_till( terminated(body_item, opt_spacelike), terminated(terminated(tag("}"), opt_spacelike), opt(tag(";"))), ), )(input)?; Ok((input, v)) } fn input_to_str(s: Span) -> Result<&str, Utf8Error> { from_utf8(s.fragment()) } fn input_to_string(s: Span) -> Result<String, Utf8Error> { from_utf8(s.fragment()).map(String::from) } fn list_or_single(list: Vec<Value>, sep: ListSeparator) -> Value { if list.len() == 1 { list.into_iter().next().unwrap() } else { Value::List(list, Some(sep), false) } }
let (input, next) = if val.is_some() { alt((tag("{"), tag(";"), tag("")))(input)? } else { tag("{")(input)?
random_line_split
mod.rs
pub(crate) mod css; mod css_function; mod error; pub mod formalargs; mod imports; mod media; pub mod selectors; mod span; pub(crate) mod strings; mod unit; pub(crate) mod util; pub mod value; pub(crate) use self::strings::name; pub use error::ParseError; pub(crate) use span::DebugBytes; pub(crate) use span::{position, Span}; use self::formalargs::{call_args, formal_args}; use self::selectors::selectors; use self::strings::{ custom_value, sass_string, sass_string_dq, sass_string_sq, }; use self::util::{ comment2, ignore_comments, ignore_space, opt_spacelike, semi_or_end, spacelike, }; use self::value::{ dictionary, function_call_or_string, single_value, value_expression, }; use crate::input::{SourceFile, SourceName, SourcePos}; use crate::sass::parser::{variable_declaration2, variable_declaration_mod}; use crate::sass::{Callable, FormalArgs, Item, Name, Selectors, Value}; use crate::value::ListSeparator; #[cfg(test)] use crate::value::{Numeric, Unit}; use crate::Error; use imports::{forward2, import2, use2}; use nom::branch::alt; use nom::bytes::complete::{is_a, is_not, tag}; use nom::character::complete::one_of; use nom::combinator::{ all_consuming, into, map, map_res, opt, peek, value, verify, }; use nom::multi::{many0, many_till, separated_list0, separated_list1}; use nom::sequence::{delimited, pair, preceded, terminated}; use nom::IResult; use std::str::{from_utf8, Utf8Error}; /// A Parsing Result; ok gives a span for the rest of the data and a parsed T. pub(crate) type PResult<'a, T> = IResult<Span<'a>, T>; pub(crate) fn code_span(value: &[u8]) -> SourcePos { SourceFile::scss_bytes(value, SourceName::root("(rsass)")).into() } pub(crate) fn input_span(value: impl Into<Vec<u8>>) -> SourcePos { SourceFile::scss_bytes(value, SourceName::root("-")).into() } /// Parse a scss value. /// /// Returns a single value (or an error). pub fn
(data: &[u8]) -> Result<Value, Error> { let data = code_span(data); let value = all_consuming(value_expression)(data.borrow()); Ok(ParseError::check(value)?) } #[test] fn test_parse_value_data_1() -> Result<(), Error> { let v = parse_value_data(b"17em")?; assert_eq!(Value::Numeric(Numeric::new(17, Unit::Em)), v); Ok(()) } #[test] fn test_parse_value_data_2() -> Result<(), Error> { let v = parse_value_data(b"17em;"); assert!(v.is_err()); Ok(()) } pub(crate) fn sassfile(input: Span) -> PResult<Vec<Item>> { preceded( opt(tag("\u{feff}".as_bytes())), map( many_till( preceded(opt_spacelike, top_level_item), all_consuming(opt_spacelike), ), |(v, _eof)| v, ), )(input) } fn top_level_item(input: Span) -> PResult<Item> { let (rest, tag) = alt((tag("$"), tag("/*"), tag("@"), tag("")))(input)?; match tag.fragment() { b"$" => into(variable_declaration2)(rest), b"/*" => comment_item(rest), b"@" => at_rule2(input), b"" => alt((into(variable_declaration_mod), rule))(input), _ => unreachable!(), } } fn comment_item(input: Span) -> PResult<Item> { map(comment2, Item::Comment)(input) } fn rule(input: Span) -> PResult<Item> { map(pair(rule_start, body_block2), |(selectors, body)| { Item::Rule(selectors, body) })(input) } fn rule_start(input: Span) -> PResult<Selectors> { terminated(selectors, terminated(opt(is_a(", \t\r\n")), tag("{")))(input) } fn body_item(input: Span) -> PResult<Item> { let (rest, tag) = alt((tag("$"), tag("/*"), tag(";"), tag("@"), tag("--"), tag("")))( input, )?; match tag.fragment() { b"$" => into(variable_declaration2)(rest), b"/*" => comment_item(rest), b";" => Ok((rest, Item::None)), b"@" => at_rule2(input), b"--" => { let result = custom_property(rest); if result.is_err() { // Note use of `input` rather than `rest` here. if let Ok((rest, rule)) = rule(input) { return Ok((rest, rule)); } } result } b"" => match rule_start(rest) { Ok((rest, selectors)) => { let (rest, body) = body_block2(rest)?; Ok((rest, Item::Rule(selectors, body))) } Err(_) => property_or_namespace_rule(rest), }, _ => unreachable!(), } } /// What follows the `@at-root` tag. fn at_root2(input: Span) -> PResult<Item> { preceded( opt_spacelike, map( pair( map(opt(selectors), |s| s.unwrap_or_else(Selectors::root)), body_block, ), |(selectors, body)| Item::AtRoot(selectors, body), ), )(input) } /// What follows the `@include` tag. fn mixin_call<'a>(start: Span, input: Span<'a>) -> PResult<'a, Item> { let (rest, n1) = terminated(name, opt_spacelike)(input)?; let (rest, n2) = opt(preceded(tag("."), name))(rest)?; let name = n2.map(|n2| format!("{n1}.{n2}")).unwrap_or(n1); let (rest, _) = opt_spacelike(rest)?; let (rest0, args) = terminated(opt(call_args), opt_spacelike)(rest)?; let (rest, t) = alt((tag("using"), tag("{"), tag("")))(rest0)?; let (end, body) = match t.fragment() { b"using" => { let (end, args) = preceded(opt_spacelike, formal_args)(rest)?; let (rest, body) = preceded(opt_spacelike, body_block)(end)?; let decl = rest0.up_to(&end).to_owned(); (rest, Some(Callable::new(args, body, decl))) } b"{" => { let (rest, body) = body_block(rest0)?; let decl = rest0.up_to(&rest).to_owned(); (rest, Some(Callable::no_args(body, decl))) } _ => { let (rest, _) = opt(tag(";"))(rest)?; (rest, None) } }; let pos = start.up_to(&rest).to_owned(); Ok(( end, Item::MixinCall(name, args.unwrap_or_default(), body, pos), )) } /// When we know that `input0` starts with an `@` sign. fn at_rule2(input0: Span) -> PResult<Item> { let (input, name) = delimited(tag("@"), sass_string, opt_spacelike)(input0)?; match name.single_raw().unwrap_or("") { "at-root" => at_root2(input), "charset" => charset2(input), "content" => content_stmt2(input), "debug" => map(expression_argument, Item::Debug)(input), "each" => each_loop2(input), "error" => { let (end, v) = value_expression(input)?; let (rest, _) = opt(tag(";"))(end)?; let pos = input0.up_to(&end).to_owned(); Ok((rest, Item::Error(v, pos))) } "extend" => map( delimited( opt_spacelike, selectors, preceded(opt_spacelike, tag(";")), ), Item::Extend, )(input), "for" => for_loop2(input), "forward" => forward2(input0, input), "function" => function_declaration2(input), "if" => if_statement2(input), "import" => import2(input), "include" => mixin_call(input0, input), "media" => media::rule(input0, input), "mixin" => mixin_declaration2(input), "return" => return_stmt2(input0, input), "use" => use2(input0, input), "warn" => map(expression_argument, Item::Warn)(input), "while" => while_loop2(input), _ => unknown_atrule(name, input0, input), } } fn unknown_atrule<'a>( name: SassString, start: Span, input: Span<'a>, ) -> PResult<'a, Item> { let (input, args) = terminated(opt(unknown_rule_args), opt(ignore_space))(input)?; fn x_args(value: Value) -> Value { match value { Value::Variable(name, _pos) => { Value::Literal(SassString::from(format!("${name}"))) } Value::Map(map) => Value::Map( map.into_iter() .map(|(k, v)| (x_args(k), x_args(v))) .collect(), ), value => value, } } let (rest, body) = if input.first() == Some(&b'{') { map(body_block, Some)(input)? } else { value(None, semi_or_end)(input)? }; Ok(( rest, Item::AtRule { name, args: args.map_or(Value::Null, x_args), body, pos: start.up_to(&input).to_owned(), }, )) } fn expression_argument(input: Span) -> PResult<Value> { terminated(value_expression, opt(tag(";")))(input) } fn charset2(input: Span) -> PResult<Item> { use nom::combinator::map_opt; map_opt( terminated( alt((sass_string_dq, sass_string_sq, sass_string)), semi_or_end, ), |s| { s.single_raw().and_then(|s| { if s.eq_ignore_ascii_case("UTF-8") { Some(Item::None) } else { None } }) }, )(input) } /// Arguments to an unkown at rule. fn unknown_rule_args(input: Span) -> PResult<Value> { let (input, args) = separated_list0( preceded(tag(","), opt_spacelike), map( many0(preceded( opt(ignore_space), alt(( terminated( alt(( function_call_or_string, dictionary, map( delimited(tag("("), media::args, tag(")")), |v| Value::Paren(Box::new(v), true), ), map(sass_string_dq, Value::Literal), map(sass_string_sq, Value::Literal), )), alt(( value((), all_consuming(tag(""))), value((), peek(one_of(") \r\n\t{,;"))), )), ), map(map_res(is_not("\"'{};#"), input_to_str), |s| { Value::Literal(s.trim_end().into()) }), )), )), |args| list_or_single(args, ListSeparator::Space), ), )(input)?; Ok((input, list_or_single(args, ListSeparator::Comma))) } #[cfg(test)] pub(crate) fn check_parse<T>( parser: impl Fn(Span) -> PResult<T>, value: &[u8], ) -> Result<T, ParseError> { ParseError::check(parser(code_span(value).borrow())) } fn if_statement_inner(input: Span) -> PResult<Item> { preceded( terminated(verify(name, |n: &String| n == "if"), opt_spacelike), if_statement2, )(input) } fn if_statement2(input: Span) -> PResult<Item> { let (input, cond) = terminated(value_expression, opt_spacelike)(input)?; let (input, body) = body_block(input)?; let (input2, word) = opt(delimited( preceded(opt_spacelike, tag("@")), name, opt_spacelike, ))(input)?; match word.as_ref().map(AsRef::as_ref) { Some("else") => { let (input2, else_body) = alt(( body_block, map(if_statement_inner, |s| vec![s]), ))(input2)?; Ok((input2, Item::IfStatement(cond, body, else_body))) } Some("elseif") => { let (input2, else_body) = if_statement2(input2)?; Ok((input2, Item::IfStatement(cond, body, vec![else_body]))) } _ => Ok((input, Item::IfStatement(cond, body, vec![]))), } } /// The part of an each look that follows the `@each`. fn each_loop2(input: Span) -> PResult<Item> { let (input, names) = separated_list1( delimited(opt_spacelike, tag(","), opt_spacelike), map(preceded(tag("$"), name), Name::from), )(input)?; let (input, values) = delimited( delimited(spacelike, tag("in"), spacelike), value_expression, opt_spacelike, )(input)?; let (input, body) = body_block(input)?; Ok((input, Item::Each(names, values, body))) } /// A for loop after the initial `@for`. fn for_loop2(input: Span) -> PResult<Item> { let (input, name) = delimited(tag("$"), name, spacelike)(input)?; let (input, from) = delimited( terminated(tag("from"), spacelike), single_value, spacelike, )(input)?; let (input, inclusive) = terminated( alt((value(true, tag("through")), value(false, tag("to")))), spacelike, )(input)?; let (input, to) = terminated(single_value, opt_spacelike)(input)?; let (input, body) = body_block(input)?; Ok(( input, Item::For { name: name.into(), from: Box::new(from), to: Box::new(to), inclusive, body, }, )) } fn while_loop2(input: Span) -> PResult<Item> { let (input, cond) = terminated(value_expression, opt_spacelike)(input)?; let (input, body) = body_block(input)?; Ok((input, Item::While(cond, body))) } fn mixin_declaration2(input: Span) -> PResult<Item> { let (rest, name) = terminated(name, opt_spacelike)(input)?; let (rest, args) = opt(formal_args)(rest)?; let (end, body) = preceded(opt_spacelike, body_block)(rest)?; let args = args.unwrap_or_else(FormalArgs::none); let decl = input.up_to(&rest).to_owned(); Ok(( end, Item::MixinDeclaration(name, Callable { args, body, decl }), )) } fn function_declaration2(input: Span) -> PResult<Item> { let (end, name) = terminated(name, opt_spacelike)(input)?; let (end, args) = formal_args(end)?; let (rest, body) = preceded(opt_spacelike, body_block)(end)?; let decl = input.up_to(&end).to_owned(); Ok(( rest, Item::FunctionDeclaration(name, Callable { args, body, decl }), )) } fn return_stmt2<'a>(start: Span, input: Span<'a>) -> PResult<'a, Item> { let (input, v) = delimited(opt_spacelike, value_expression, opt_spacelike)(input)?; let pos = start.up_to(&input).to_owned(); let (input, _) = opt(tag(";"))(input)?; Ok((input, Item::Return(v, pos))) } /// The "rest" of an `@content` statement is just an optional terminator fn content_stmt2(input: Span) -> PResult<Item> { let (rest, _) = opt_spacelike(input)?; let (rest, args) = opt(call_args)(rest)?; let (rest, _) = opt(tag(";"))(rest)?; let pos = input.up_to(&rest).to_owned(); Ok((rest, Item::Content(args.unwrap_or_default(), pos))) } fn custom_property(input: Span) -> PResult<Item> { let (rest, name) = terminated(opt(sass_string), tag(":"))(input)?; let mut name = name.unwrap_or_else(|| SassString::from("")); // The dashes was parsed before calling this method. name.prepend("--"); let (rest, value) = terminated(custom_value, alt((tag(";"), peek(tag("}")))))(rest)?; Ok((rest, Item::CustomProperty(name, value))) } fn property_or_namespace_rule(input: Span) -> PResult<Item> { let (start_val, name) = terminated( alt(( map(preceded(tag("*"), sass_string), |mut s| { s.prepend("*"); s }), sass_string, )), delimited(ignore_comments, tag(":"), ignore_comments), )(input)?; let (input, val) = opt(value_expression)(start_val)?; let pos = start_val.up_to(&input).to_owned(); let (input, _) = opt_spacelike(input)?; let (input, next) = if val.is_some() { alt((tag("{"), tag(";"), tag("")))(input)? } else { tag("{")(input)? }; let (input, body) = match next.fragment() { b"{" => map(body_block2, Some)(input)?, b";" => (input, None), b"" => (input, None), _ => (input, None), // error? }; let (input, _) = opt_spacelike(input)?; Ok((input, ns_or_prop_item(name, val, body, pos))) } use crate::sass::SassString; fn ns_or_prop_item( name: SassString, value: Option<Value>, body: Option<Vec<Item>>, pos: SourcePos, ) -> Item { if let Some(body) = body { Item::NamespaceRule(name, value.unwrap_or(Value::Null), body) } else if let Some(value) = value { Item::Property(name, value, pos) } else { unreachable!() } } fn body_block(input: Span) -> PResult<Vec<Item>> { preceded(tag("{"), body_block2)(input) } fn body_block2(input: Span) -> PResult<Vec<Item>> { let (input, (v, _end)) = preceded( opt_spacelike, many_till( terminated(body_item, opt_spacelike), terminated(terminated(tag("}"), opt_spacelike), opt(tag(";"))), ), )(input)?; Ok((input, v)) } fn input_to_str(s: Span) -> Result<&str, Utf8Error> { from_utf8(s.fragment()) } fn input_to_string(s: Span) -> Result<String, Utf8Error> { from_utf8(s.fragment()).map(String::from) } fn list_or_single(list: Vec<Value>, sep: ListSeparator) -> Value { if list.len() == 1 { list.into_iter().next().unwrap() } else { Value::List(list, Some(sep), false) } }
parse_value_data
identifier_name
mod.rs
pub(crate) mod css; mod css_function; mod error; pub mod formalargs; mod imports; mod media; pub mod selectors; mod span; pub(crate) mod strings; mod unit; pub(crate) mod util; pub mod value; pub(crate) use self::strings::name; pub use error::ParseError; pub(crate) use span::DebugBytes; pub(crate) use span::{position, Span}; use self::formalargs::{call_args, formal_args}; use self::selectors::selectors; use self::strings::{ custom_value, sass_string, sass_string_dq, sass_string_sq, }; use self::util::{ comment2, ignore_comments, ignore_space, opt_spacelike, semi_or_end, spacelike, }; use self::value::{ dictionary, function_call_or_string, single_value, value_expression, }; use crate::input::{SourceFile, SourceName, SourcePos}; use crate::sass::parser::{variable_declaration2, variable_declaration_mod}; use crate::sass::{Callable, FormalArgs, Item, Name, Selectors, Value}; use crate::value::ListSeparator; #[cfg(test)] use crate::value::{Numeric, Unit}; use crate::Error; use imports::{forward2, import2, use2}; use nom::branch::alt; use nom::bytes::complete::{is_a, is_not, tag}; use nom::character::complete::one_of; use nom::combinator::{ all_consuming, into, map, map_res, opt, peek, value, verify, }; use nom::multi::{many0, many_till, separated_list0, separated_list1}; use nom::sequence::{delimited, pair, preceded, terminated}; use nom::IResult; use std::str::{from_utf8, Utf8Error}; /// A Parsing Result; ok gives a span for the rest of the data and a parsed T. pub(crate) type PResult<'a, T> = IResult<Span<'a>, T>; pub(crate) fn code_span(value: &[u8]) -> SourcePos { SourceFile::scss_bytes(value, SourceName::root("(rsass)")).into() } pub(crate) fn input_span(value: impl Into<Vec<u8>>) -> SourcePos { SourceFile::scss_bytes(value, SourceName::root("-")).into() } /// Parse a scss value. /// /// Returns a single value (or an error). pub fn parse_value_data(data: &[u8]) -> Result<Value, Error> { let data = code_span(data); let value = all_consuming(value_expression)(data.borrow()); Ok(ParseError::check(value)?) } #[test] fn test_parse_value_data_1() -> Result<(), Error> { let v = parse_value_data(b"17em")?; assert_eq!(Value::Numeric(Numeric::new(17, Unit::Em)), v); Ok(()) } #[test] fn test_parse_value_data_2() -> Result<(), Error> { let v = parse_value_data(b"17em;"); assert!(v.is_err()); Ok(()) } pub(crate) fn sassfile(input: Span) -> PResult<Vec<Item>> { preceded( opt(tag("\u{feff}".as_bytes())), map( many_till( preceded(opt_spacelike, top_level_item), all_consuming(opt_spacelike), ), |(v, _eof)| v, ), )(input) } fn top_level_item(input: Span) -> PResult<Item> { let (rest, tag) = alt((tag("$"), tag("/*"), tag("@"), tag("")))(input)?; match tag.fragment() { b"$" => into(variable_declaration2)(rest), b"/*" => comment_item(rest), b"@" => at_rule2(input), b"" => alt((into(variable_declaration_mod), rule))(input), _ => unreachable!(), } } fn comment_item(input: Span) -> PResult<Item> { map(comment2, Item::Comment)(input) } fn rule(input: Span) -> PResult<Item> { map(pair(rule_start, body_block2), |(selectors, body)| { Item::Rule(selectors, body) })(input) } fn rule_start(input: Span) -> PResult<Selectors> { terminated(selectors, terminated(opt(is_a(", \t\r\n")), tag("{")))(input) } fn body_item(input: Span) -> PResult<Item> { let (rest, tag) = alt((tag("$"), tag("/*"), tag(";"), tag("@"), tag("--"), tag("")))( input, )?; match tag.fragment() { b"$" => into(variable_declaration2)(rest), b"/*" => comment_item(rest), b";" => Ok((rest, Item::None)), b"@" => at_rule2(input), b"--" => { let result = custom_property(rest); if result.is_err() { // Note use of `input` rather than `rest` here. if let Ok((rest, rule)) = rule(input) { return Ok((rest, rule)); } } result } b"" => match rule_start(rest) { Ok((rest, selectors)) => { let (rest, body) = body_block2(rest)?; Ok((rest, Item::Rule(selectors, body))) } Err(_) => property_or_namespace_rule(rest), }, _ => unreachable!(), } } /// What follows the `@at-root` tag. fn at_root2(input: Span) -> PResult<Item> { preceded( opt_spacelike, map( pair( map(opt(selectors), |s| s.unwrap_or_else(Selectors::root)), body_block, ), |(selectors, body)| Item::AtRoot(selectors, body), ), )(input) } /// What follows the `@include` tag. fn mixin_call<'a>(start: Span, input: Span<'a>) -> PResult<'a, Item> { let (rest, n1) = terminated(name, opt_spacelike)(input)?; let (rest, n2) = opt(preceded(tag("."), name))(rest)?; let name = n2.map(|n2| format!("{n1}.{n2}")).unwrap_or(n1); let (rest, _) = opt_spacelike(rest)?; let (rest0, args) = terminated(opt(call_args), opt_spacelike)(rest)?; let (rest, t) = alt((tag("using"), tag("{"), tag("")))(rest0)?; let (end, body) = match t.fragment() { b"using" => { let (end, args) = preceded(opt_spacelike, formal_args)(rest)?; let (rest, body) = preceded(opt_spacelike, body_block)(end)?; let decl = rest0.up_to(&end).to_owned(); (rest, Some(Callable::new(args, body, decl))) } b"{" => { let (rest, body) = body_block(rest0)?; let decl = rest0.up_to(&rest).to_owned(); (rest, Some(Callable::no_args(body, decl))) } _ => { let (rest, _) = opt(tag(";"))(rest)?; (rest, None) } }; let pos = start.up_to(&rest).to_owned(); Ok(( end, Item::MixinCall(name, args.unwrap_or_default(), body, pos), )) } /// When we know that `input0` starts with an `@` sign. fn at_rule2(input0: Span) -> PResult<Item> { let (input, name) = delimited(tag("@"), sass_string, opt_spacelike)(input0)?; match name.single_raw().unwrap_or("") { "at-root" => at_root2(input), "charset" => charset2(input), "content" => content_stmt2(input), "debug" => map(expression_argument, Item::Debug)(input), "each" => each_loop2(input), "error" => { let (end, v) = value_expression(input)?; let (rest, _) = opt(tag(";"))(end)?; let pos = input0.up_to(&end).to_owned(); Ok((rest, Item::Error(v, pos))) } "extend" => map( delimited( opt_spacelike, selectors, preceded(opt_spacelike, tag(";")), ), Item::Extend, )(input), "for" => for_loop2(input), "forward" => forward2(input0, input), "function" => function_declaration2(input), "if" => if_statement2(input), "import" => import2(input), "include" => mixin_call(input0, input), "media" => media::rule(input0, input), "mixin" => mixin_declaration2(input), "return" => return_stmt2(input0, input), "use" => use2(input0, input), "warn" => map(expression_argument, Item::Warn)(input), "while" => while_loop2(input), _ => unknown_atrule(name, input0, input), } } fn unknown_atrule<'a>( name: SassString, start: Span, input: Span<'a>, ) -> PResult<'a, Item>
}; Ok(( rest, Item::AtRule { name, args: args.map_or(Value::Null, x_args), body, pos: start.up_to(&input).to_owned(), }, )) } fn expression_argument(input: Span) -> PResult<Value> { terminated(value_expression, opt(tag(";")))(input) } fn charset2(input: Span) -> PResult<Item> { use nom::combinator::map_opt; map_opt( terminated( alt((sass_string_dq, sass_string_sq, sass_string)), semi_or_end, ), |s| { s.single_raw().and_then(|s| { if s.eq_ignore_ascii_case("UTF-8") { Some(Item::None) } else { None } }) }, )(input) } /// Arguments to an unkown at rule. fn unknown_rule_args(input: Span) -> PResult<Value> { let (input, args) = separated_list0( preceded(tag(","), opt_spacelike), map( many0(preceded( opt(ignore_space), alt(( terminated( alt(( function_call_or_string, dictionary, map( delimited(tag("("), media::args, tag(")")), |v| Value::Paren(Box::new(v), true), ), map(sass_string_dq, Value::Literal), map(sass_string_sq, Value::Literal), )), alt(( value((), all_consuming(tag(""))), value((), peek(one_of(") \r\n\t{,;"))), )), ), map(map_res(is_not("\"'{};#"), input_to_str), |s| { Value::Literal(s.trim_end().into()) }), )), )), |args| list_or_single(args, ListSeparator::Space), ), )(input)?; Ok((input, list_or_single(args, ListSeparator::Comma))) } #[cfg(test)] pub(crate) fn check_parse<T>( parser: impl Fn(Span) -> PResult<T>, value: &[u8], ) -> Result<T, ParseError> { ParseError::check(parser(code_span(value).borrow())) } fn if_statement_inner(input: Span) -> PResult<Item> { preceded( terminated(verify(name, |n: &String| n == "if"), opt_spacelike), if_statement2, )(input) } fn if_statement2(input: Span) -> PResult<Item> { let (input, cond) = terminated(value_expression, opt_spacelike)(input)?; let (input, body) = body_block(input)?; let (input2, word) = opt(delimited( preceded(opt_spacelike, tag("@")), name, opt_spacelike, ))(input)?; match word.as_ref().map(AsRef::as_ref) { Some("else") => { let (input2, else_body) = alt(( body_block, map(if_statement_inner, |s| vec![s]), ))(input2)?; Ok((input2, Item::IfStatement(cond, body, else_body))) } Some("elseif") => { let (input2, else_body) = if_statement2(input2)?; Ok((input2, Item::IfStatement(cond, body, vec![else_body]))) } _ => Ok((input, Item::IfStatement(cond, body, vec![]))), } } /// The part of an each look that follows the `@each`. fn each_loop2(input: Span) -> PResult<Item> { let (input, names) = separated_list1( delimited(opt_spacelike, tag(","), opt_spacelike), map(preceded(tag("$"), name), Name::from), )(input)?; let (input, values) = delimited( delimited(spacelike, tag("in"), spacelike), value_expression, opt_spacelike, )(input)?; let (input, body) = body_block(input)?; Ok((input, Item::Each(names, values, body))) } /// A for loop after the initial `@for`. fn for_loop2(input: Span) -> PResult<Item> { let (input, name) = delimited(tag("$"), name, spacelike)(input)?; let (input, from) = delimited( terminated(tag("from"), spacelike), single_value, spacelike, )(input)?; let (input, inclusive) = terminated( alt((value(true, tag("through")), value(false, tag("to")))), spacelike, )(input)?; let (input, to) = terminated(single_value, opt_spacelike)(input)?; let (input, body) = body_block(input)?; Ok(( input, Item::For { name: name.into(), from: Box::new(from), to: Box::new(to), inclusive, body, }, )) } fn while_loop2(input: Span) -> PResult<Item> { let (input, cond) = terminated(value_expression, opt_spacelike)(input)?; let (input, body) = body_block(input)?; Ok((input, Item::While(cond, body))) } fn mixin_declaration2(input: Span) -> PResult<Item> { let (rest, name) = terminated(name, opt_spacelike)(input)?; let (rest, args) = opt(formal_args)(rest)?; let (end, body) = preceded(opt_spacelike, body_block)(rest)?; let args = args.unwrap_or_else(FormalArgs::none); let decl = input.up_to(&rest).to_owned(); Ok(( end, Item::MixinDeclaration(name, Callable { args, body, decl }), )) } fn function_declaration2(input: Span) -> PResult<Item> { let (end, name) = terminated(name, opt_spacelike)(input)?; let (end, args) = formal_args(end)?; let (rest, body) = preceded(opt_spacelike, body_block)(end)?; let decl = input.up_to(&end).to_owned(); Ok(( rest, Item::FunctionDeclaration(name, Callable { args, body, decl }), )) } fn return_stmt2<'a>(start: Span, input: Span<'a>) -> PResult<'a, Item> { let (input, v) = delimited(opt_spacelike, value_expression, opt_spacelike)(input)?; let pos = start.up_to(&input).to_owned(); let (input, _) = opt(tag(";"))(input)?; Ok((input, Item::Return(v, pos))) } /// The "rest" of an `@content` statement is just an optional terminator fn content_stmt2(input: Span) -> PResult<Item> { let (rest, _) = opt_spacelike(input)?; let (rest, args) = opt(call_args)(rest)?; let (rest, _) = opt(tag(";"))(rest)?; let pos = input.up_to(&rest).to_owned(); Ok((rest, Item::Content(args.unwrap_or_default(), pos))) } fn custom_property(input: Span) -> PResult<Item> { let (rest, name) = terminated(opt(sass_string), tag(":"))(input)?; let mut name = name.unwrap_or_else(|| SassString::from("")); // The dashes was parsed before calling this method. name.prepend("--"); let (rest, value) = terminated(custom_value, alt((tag(";"), peek(tag("}")))))(rest)?; Ok((rest, Item::CustomProperty(name, value))) } fn property_or_namespace_rule(input: Span) -> PResult<Item> { let (start_val, name) = terminated( alt(( map(preceded(tag("*"), sass_string), |mut s| { s.prepend("*"); s }), sass_string, )), delimited(ignore_comments, tag(":"), ignore_comments), )(input)?; let (input, val) = opt(value_expression)(start_val)?; let pos = start_val.up_to(&input).to_owned(); let (input, _) = opt_spacelike(input)?; let (input, next) = if val.is_some() { alt((tag("{"), tag(";"), tag("")))(input)? } else { tag("{")(input)? }; let (input, body) = match next.fragment() { b"{" => map(body_block2, Some)(input)?, b";" => (input, None), b"" => (input, None), _ => (input, None), // error? }; let (input, _) = opt_spacelike(input)?; Ok((input, ns_or_prop_item(name, val, body, pos))) } use crate::sass::SassString; fn ns_or_prop_item( name: SassString, value: Option<Value>, body: Option<Vec<Item>>, pos: SourcePos, ) -> Item { if let Some(body) = body { Item::NamespaceRule(name, value.unwrap_or(Value::Null), body) } else if let Some(value) = value { Item::Property(name, value, pos) } else { unreachable!() } } fn body_block(input: Span) -> PResult<Vec<Item>> { preceded(tag("{"), body_block2)(input) } fn body_block2(input: Span) -> PResult<Vec<Item>> { let (input, (v, _end)) = preceded( opt_spacelike, many_till( terminated(body_item, opt_spacelike), terminated(terminated(tag("}"), opt_spacelike), opt(tag(";"))), ), )(input)?; Ok((input, v)) } fn input_to_str(s: Span) -> Result<&str, Utf8Error> { from_utf8(s.fragment()) } fn input_to_string(s: Span) -> Result<String, Utf8Error> { from_utf8(s.fragment()).map(String::from) } fn list_or_single(list: Vec<Value>, sep: ListSeparator) -> Value { if list.len() == 1 { list.into_iter().next().unwrap() } else { Value::List(list, Some(sep), false) } }
{ let (input, args) = terminated(opt(unknown_rule_args), opt(ignore_space))(input)?; fn x_args(value: Value) -> Value { match value { Value::Variable(name, _pos) => { Value::Literal(SassString::from(format!("${name}"))) } Value::Map(map) => Value::Map( map.into_iter() .map(|(k, v)| (x_args(k), x_args(v))) .collect(), ), value => value, } } let (rest, body) = if input.first() == Some(&b'{') { map(body_block, Some)(input)? } else { value(None, semi_or_end)(input)?
identifier_body
game.rs
use crate::abtest::ABTestMode; use crate::debug::DebugMode; use crate::edit::EditMode; use crate::helpers::ID; use crate::mission::MissionEditMode; use crate::render::DrawOptions; use crate::sandbox::SandboxMode; use crate::tutorial::TutorialMode; use crate::ui::{EditorState, Flags, ShowEverything, UI}; use abstutil::elapsed_seconds; use ezgui::{hotkey, Canvas, EventCtx, EventLoopMode, GfxCtx, Key, UserInput, Wizard, GUI}; use geom::{Duration, Line, Pt2D, Speed}; use map_model::Map; use rand::seq::SliceRandom; use rand::Rng; use rand_xorshift::XorShiftRng; use std::path::PathBuf; use std::time::Instant; // This is the top-level of the GUI logic. This module should just manage interactions between the // top-level game states. pub struct GameState { pub mode: Mode, pub ui: UI, } // TODO Need to reset_sim() when entering Edit, Tutorial, Mission, or ABTest and when leaving // Tutorial and ABTest. Expressing this manually right now is quite tedious; maybe having on_enter // and on_exit would be cleaner. pub enum Mode { SplashScreen(Wizard, Option<(Screensaver, XorShiftRng)>), Edit(EditMode), Tutorial(TutorialMode), Sandbox(SandboxMode), Debug(DebugMode), Mission(MissionEditMode), ABTest(ABTestMode), } impl GameState { pub fn new(flags: Flags, ctx: &mut EventCtx) -> GameState { let splash =!flags.no_splash &&!format!("{}", flags.sim_flags.load.display()).contains("data/save"); let mut rng = flags.sim_flags.make_rng(); let mut game = GameState { mode: Mode::Sandbox(SandboxMode::new(ctx)), ui: UI::new(flags, ctx), }; let rand_focus_pt = game .ui .primary .map .all_buildings() .choose(&mut rng) .and_then(|b| ID::Building(b.id).canonical_point(&game.ui.primary)) .or_else(|| { game.ui .primary .map .all_lanes() .choose(&mut rng) .and_then(|l| ID::Lane(l.id).canonical_point(&game.ui.primary)) }) .expect("Can't get canonical_point of a random building or lane"); if splash { ctx.canvas.center_on_map_pt(rand_focus_pt); game.mode = Mode::SplashScreen( Wizard::new(), Some(( Screensaver::start_bounce(&mut rng, ctx.canvas, &game.ui.primary.map), rng, )), ); } else { match abstutil::read_json::<EditorState>("../editor_state.json") { Ok(ref loaded) if game.ui.primary.map.get_name() == &loaded.map_name => { println!("Loaded previous editor_state.json"); ctx.canvas.cam_x = loaded.cam_x; ctx.canvas.cam_y = loaded.cam_y; ctx.canvas.cam_zoom = loaded.cam_zoom; } _ => { println!("Couldn't load editor_state.json or it's for a different map, so just focusing on an arbitrary building"); ctx.canvas.center_on_map_pt(rand_focus_pt); } } } game } fn save_editor_state(&self, canvas: &Canvas) { let state = EditorState { map_name: self.ui.primary.map.get_name().clone(), cam_x: canvas.cam_x, cam_y: canvas.cam_y, cam_zoom: canvas.cam_zoom, }; // TODO maybe make state line up with the map, so loading from a new map doesn't break abstutil::write_json("../editor_state.json", &state) .expect("Saving editor_state.json failed"); println!("Saved editor_state.json"); } } impl GUI for GameState { fn event(&mut self, ctx: &mut EventCtx) -> EventLoopMode { match self.mode { Mode::SplashScreen(ref mut wizard, ref mut maybe_screensaver) => { let anim = maybe_screensaver.is_some(); if let Some((ref mut screensaver, ref mut rng)) = maybe_screensaver { screensaver.update(rng, ctx.input, ctx.canvas, &self.ui.primary.map); } if let Some(new_mode) = splash_screen(wizard, ctx, &mut self.ui, maybe_screensaver) { self.mode = new_mode; } else if wizard.aborted() { self.before_quit(ctx.canvas); std::process::exit(0); } if anim { EventLoopMode::Animation } else { EventLoopMode::InputOnly } } Mode::Edit(_) => EditMode::event(self, ctx), Mode::Tutorial(_) => TutorialMode::event(self, ctx), Mode::Sandbox(_) => SandboxMode::event(self, ctx), Mode::Debug(_) => DebugMode::event(self, ctx), Mode::Mission(_) => MissionEditMode::event(self, ctx), Mode::ABTest(_) => ABTestMode::event(self, ctx), } } fn draw(&self, g: &mut GfxCtx) { match self.mode { Mode::SplashScreen(ref wizard, _) => { self.ui.draw( g, DrawOptions::new(), &self.ui.primary.sim, &ShowEverything::new(), ); wizard.draw(g); } Mode::Edit(_) => EditMode::draw(self, g), Mode::Tutorial(_) => TutorialMode::draw(self, g), Mode::Sandbox(_) => SandboxMode::draw(self, g), Mode::Debug(_) => DebugMode::draw(self, g), Mode::Mission(_) => MissionEditMode::draw(self, g), Mode::ABTest(_) => ABTestMode::draw(self, g), } /*println!( "{} uploads, {} draw calls", g.get_num_uploads(), g.num_draw_calls );*/ } fn
(&self, canvas: &Canvas) { println!( "********************************************************************************" ); println!("UI broke! Primary sim:"); self.ui.primary.sim.dump_before_abort(); if let Mode::ABTest(ref abtest) = self.mode { if let Some(ref s) = abtest.secondary { println!("Secondary sim:"); s.sim.dump_before_abort(); } } self.save_editor_state(canvas); } fn before_quit(&self, canvas: &Canvas) { self.save_editor_state(canvas); self.ui.cs.save(); println!("Saved color_scheme.json"); } fn profiling_enabled(&self) -> bool { self.ui.primary.current_flags.enable_profiler } } const SPEED: Speed = Speed::const_meters_per_second(20.0); pub struct Screensaver { line: Line, started: Instant, } impl Screensaver { fn start_bounce(rng: &mut XorShiftRng, canvas: &mut Canvas, map: &Map) -> Screensaver { let at = canvas.center_to_map_pt(); let bounds = map.get_bounds(); // TODO Ideally bounce off the edge of the map let goto = Pt2D::new( rng.gen_range(0.0, bounds.max_x), rng.gen_range(0.0, bounds.max_y), ); canvas.cam_zoom = 10.0; canvas.center_on_map_pt(at); Screensaver { line: Line::new(at, goto), started: Instant::now(), } } fn update( &mut self, rng: &mut XorShiftRng, input: &mut UserInput, canvas: &mut Canvas, map: &Map, ) { if input.nonblocking_is_update_event() { input.use_update_event(); let dist_along = Duration::seconds(elapsed_seconds(self.started)) * SPEED; if dist_along < self.line.length() { canvas.center_on_map_pt(self.line.dist_along(dist_along)); } else { *self = Screensaver::start_bounce(rng, canvas, map) } } } } fn splash_screen( raw_wizard: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI, maybe_screensaver: &mut Option<(Screensaver, XorShiftRng)>, ) -> Option<Mode> { let mut wizard = raw_wizard.wrap(ctx); let sandbox = "Sandbox mode"; let load_map = "Load another map"; let edit = "Edit map"; let tutorial = "Tutorial"; let debug = "Debug mode"; let mission = "Mission Edit Mode"; let abtest = "A/B Test Mode"; let about = "About"; let quit = "Quit"; // Loop because we might go from About -> top-level menu repeatedly, and recursion is scary. loop { // TODO No hotkey for quit because it's just the normal menu escape? match wizard .choose_string_hotkeys( "Welcome to A/B Street!", vec![ (hotkey(Key::S), sandbox), (hotkey(Key::L), load_map), (hotkey(Key::E), edit), (hotkey(Key::T), tutorial), (hotkey(Key::D), debug), (hotkey(Key::M), mission), (hotkey(Key::A), abtest), (None, about), (None, quit), ], )? .as_str() { x if x == sandbox => break Some(Mode::Sandbox(SandboxMode::new(ctx))), x if x == load_map => { let current_map = ui.primary.map.get_name().to_string(); if let Some((name, _)) = wizard.choose_something_no_keys::<String>( "Load which map?", Box::new(move || { abstutil::list_all_objects("maps", "") .into_iter() .filter(|(n, _)| n!= &current_map) .collect() }), ) { // This retains no state, but that's probably fine. let mut flags = ui.primary.current_flags.clone(); flags.sim_flags.load = PathBuf::from(format!("../data/maps/{}.bin", name)); *ui = UI::new(flags, ctx); break Some(Mode::Sandbox(SandboxMode::new(ctx))); } else if wizard.aborted() { break Some(Mode::SplashScreen(Wizard::new(), maybe_screensaver.take())); } else { break None; } } x if x == edit => break Some(Mode::Edit(EditMode::new(ctx, ui))), x if x == tutorial => break Some(Mode::Tutorial(TutorialMode::new(ctx, ui))), x if x == debug => break Some(Mode::Debug(DebugMode::new(ctx, ui))), x if x == mission => break Some(Mode::Mission(MissionEditMode::new(ctx, ui))), x if x == abtest => break Some(Mode::ABTest(ABTestMode::new(ctx, ui))), x if x == about => { if wizard.acknowledge( "About A/B Street", vec![ "Author: Dustin Carlino ([email protected])", "http://github.com/dabreegster/abstreet", "Map data from OpenStreetMap and King County GIS", "", "Press ENTER to continue", ], ) { continue; } else { break None; } } x if x == quit => { // Not important to call before_quit... if we're here, we're bouncing around // aimlessly anyway std::process::exit(0); } _ => unreachable!(), } } }
dump_before_abort
identifier_name
game.rs
use crate::abtest::ABTestMode; use crate::debug::DebugMode; use crate::edit::EditMode; use crate::helpers::ID; use crate::mission::MissionEditMode; use crate::render::DrawOptions; use crate::sandbox::SandboxMode; use crate::tutorial::TutorialMode; use crate::ui::{EditorState, Flags, ShowEverything, UI}; use abstutil::elapsed_seconds; use ezgui::{hotkey, Canvas, EventCtx, EventLoopMode, GfxCtx, Key, UserInput, Wizard, GUI}; use geom::{Duration, Line, Pt2D, Speed}; use map_model::Map; use rand::seq::SliceRandom; use rand::Rng; use rand_xorshift::XorShiftRng; use std::path::PathBuf; use std::time::Instant; // This is the top-level of the GUI logic. This module should just manage interactions between the // top-level game states. pub struct GameState { pub mode: Mode, pub ui: UI, } // TODO Need to reset_sim() when entering Edit, Tutorial, Mission, or ABTest and when leaving // Tutorial and ABTest. Expressing this manually right now is quite tedious; maybe having on_enter // and on_exit would be cleaner. pub enum Mode { SplashScreen(Wizard, Option<(Screensaver, XorShiftRng)>), Edit(EditMode), Tutorial(TutorialMode), Sandbox(SandboxMode), Debug(DebugMode), Mission(MissionEditMode), ABTest(ABTestMode), } impl GameState { pub fn new(flags: Flags, ctx: &mut EventCtx) -> GameState { let splash =!flags.no_splash &&!format!("{}", flags.sim_flags.load.display()).contains("data/save"); let mut rng = flags.sim_flags.make_rng(); let mut game = GameState { mode: Mode::Sandbox(SandboxMode::new(ctx)), ui: UI::new(flags, ctx), }; let rand_focus_pt = game .ui .primary .map .all_buildings() .choose(&mut rng) .and_then(|b| ID::Building(b.id).canonical_point(&game.ui.primary)) .or_else(|| { game.ui .primary .map .all_lanes() .choose(&mut rng) .and_then(|l| ID::Lane(l.id).canonical_point(&game.ui.primary)) }) .expect("Can't get canonical_point of a random building or lane"); if splash { ctx.canvas.center_on_map_pt(rand_focus_pt); game.mode = Mode::SplashScreen( Wizard::new(), Some(( Screensaver::start_bounce(&mut rng, ctx.canvas, &game.ui.primary.map), rng, )), ); } else { match abstutil::read_json::<EditorState>("../editor_state.json") { Ok(ref loaded) if game.ui.primary.map.get_name() == &loaded.map_name => { println!("Loaded previous editor_state.json"); ctx.canvas.cam_x = loaded.cam_x; ctx.canvas.cam_y = loaded.cam_y; ctx.canvas.cam_zoom = loaded.cam_zoom; } _ => { println!("Couldn't load editor_state.json or it's for a different map, so just focusing on an arbitrary building"); ctx.canvas.center_on_map_pt(rand_focus_pt); } } } game } fn save_editor_state(&self, canvas: &Canvas) { let state = EditorState { map_name: self.ui.primary.map.get_name().clone(), cam_x: canvas.cam_x, cam_y: canvas.cam_y, cam_zoom: canvas.cam_zoom, }; // TODO maybe make state line up with the map, so loading from a new map doesn't break abstutil::write_json("../editor_state.json", &state) .expect("Saving editor_state.json failed"); println!("Saved editor_state.json"); } } impl GUI for GameState { fn event(&mut self, ctx: &mut EventCtx) -> EventLoopMode { match self.mode { Mode::SplashScreen(ref mut wizard, ref mut maybe_screensaver) => { let anim = maybe_screensaver.is_some(); if let Some((ref mut screensaver, ref mut rng)) = maybe_screensaver { screensaver.update(rng, ctx.input, ctx.canvas, &self.ui.primary.map); } if let Some(new_mode) = splash_screen(wizard, ctx, &mut self.ui, maybe_screensaver) { self.mode = new_mode; } else if wizard.aborted() { self.before_quit(ctx.canvas); std::process::exit(0); } if anim { EventLoopMode::Animation } else { EventLoopMode::InputOnly } } Mode::Edit(_) => EditMode::event(self, ctx), Mode::Tutorial(_) => TutorialMode::event(self, ctx), Mode::Sandbox(_) => SandboxMode::event(self, ctx), Mode::Debug(_) => DebugMode::event(self, ctx), Mode::Mission(_) => MissionEditMode::event(self, ctx), Mode::ABTest(_) => ABTestMode::event(self, ctx), } } fn draw(&self, g: &mut GfxCtx) { match self.mode { Mode::SplashScreen(ref wizard, _) => { self.ui.draw( g, DrawOptions::new(), &self.ui.primary.sim, &ShowEverything::new(), ); wizard.draw(g); } Mode::Edit(_) => EditMode::draw(self, g), Mode::Tutorial(_) => TutorialMode::draw(self, g), Mode::Sandbox(_) => SandboxMode::draw(self, g), Mode::Debug(_) => DebugMode::draw(self, g), Mode::Mission(_) => MissionEditMode::draw(self, g), Mode::ABTest(_) => ABTestMode::draw(self, g), } /*println!( "{} uploads, {} draw calls", g.get_num_uploads(), g.num_draw_calls );*/ } fn dump_before_abort(&self, canvas: &Canvas) { println!( "********************************************************************************" ); println!("UI broke! Primary sim:"); self.ui.primary.sim.dump_before_abort(); if let Mode::ABTest(ref abtest) = self.mode { if let Some(ref s) = abtest.secondary { println!("Secondary sim:"); s.sim.dump_before_abort(); } } self.save_editor_state(canvas); } fn before_quit(&self, canvas: &Canvas) { self.save_editor_state(canvas); self.ui.cs.save(); println!("Saved color_scheme.json"); } fn profiling_enabled(&self) -> bool { self.ui.primary.current_flags.enable_profiler } } const SPEED: Speed = Speed::const_meters_per_second(20.0); pub struct Screensaver { line: Line, started: Instant, } impl Screensaver { fn start_bounce(rng: &mut XorShiftRng, canvas: &mut Canvas, map: &Map) -> Screensaver { let at = canvas.center_to_map_pt(); let bounds = map.get_bounds(); // TODO Ideally bounce off the edge of the map
rng.gen_range(0.0, bounds.max_y), ); canvas.cam_zoom = 10.0; canvas.center_on_map_pt(at); Screensaver { line: Line::new(at, goto), started: Instant::now(), } } fn update( &mut self, rng: &mut XorShiftRng, input: &mut UserInput, canvas: &mut Canvas, map: &Map, ) { if input.nonblocking_is_update_event() { input.use_update_event(); let dist_along = Duration::seconds(elapsed_seconds(self.started)) * SPEED; if dist_along < self.line.length() { canvas.center_on_map_pt(self.line.dist_along(dist_along)); } else { *self = Screensaver::start_bounce(rng, canvas, map) } } } } fn splash_screen( raw_wizard: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI, maybe_screensaver: &mut Option<(Screensaver, XorShiftRng)>, ) -> Option<Mode> { let mut wizard = raw_wizard.wrap(ctx); let sandbox = "Sandbox mode"; let load_map = "Load another map"; let edit = "Edit map"; let tutorial = "Tutorial"; let debug = "Debug mode"; let mission = "Mission Edit Mode"; let abtest = "A/B Test Mode"; let about = "About"; let quit = "Quit"; // Loop because we might go from About -> top-level menu repeatedly, and recursion is scary. loop { // TODO No hotkey for quit because it's just the normal menu escape? match wizard .choose_string_hotkeys( "Welcome to A/B Street!", vec![ (hotkey(Key::S), sandbox), (hotkey(Key::L), load_map), (hotkey(Key::E), edit), (hotkey(Key::T), tutorial), (hotkey(Key::D), debug), (hotkey(Key::M), mission), (hotkey(Key::A), abtest), (None, about), (None, quit), ], )? .as_str() { x if x == sandbox => break Some(Mode::Sandbox(SandboxMode::new(ctx))), x if x == load_map => { let current_map = ui.primary.map.get_name().to_string(); if let Some((name, _)) = wizard.choose_something_no_keys::<String>( "Load which map?", Box::new(move || { abstutil::list_all_objects("maps", "") .into_iter() .filter(|(n, _)| n!= &current_map) .collect() }), ) { // This retains no state, but that's probably fine. let mut flags = ui.primary.current_flags.clone(); flags.sim_flags.load = PathBuf::from(format!("../data/maps/{}.bin", name)); *ui = UI::new(flags, ctx); break Some(Mode::Sandbox(SandboxMode::new(ctx))); } else if wizard.aborted() { break Some(Mode::SplashScreen(Wizard::new(), maybe_screensaver.take())); } else { break None; } } x if x == edit => break Some(Mode::Edit(EditMode::new(ctx, ui))), x if x == tutorial => break Some(Mode::Tutorial(TutorialMode::new(ctx, ui))), x if x == debug => break Some(Mode::Debug(DebugMode::new(ctx, ui))), x if x == mission => break Some(Mode::Mission(MissionEditMode::new(ctx, ui))), x if x == abtest => break Some(Mode::ABTest(ABTestMode::new(ctx, ui))), x if x == about => { if wizard.acknowledge( "About A/B Street", vec![ "Author: Dustin Carlino ([email protected])", "http://github.com/dabreegster/abstreet", "Map data from OpenStreetMap and King County GIS", "", "Press ENTER to continue", ], ) { continue; } else { break None; } } x if x == quit => { // Not important to call before_quit... if we're here, we're bouncing around // aimlessly anyway std::process::exit(0); } _ => unreachable!(), } } }
let goto = Pt2D::new( rng.gen_range(0.0, bounds.max_x),
random_line_split
game.rs
use crate::abtest::ABTestMode; use crate::debug::DebugMode; use crate::edit::EditMode; use crate::helpers::ID; use crate::mission::MissionEditMode; use crate::render::DrawOptions; use crate::sandbox::SandboxMode; use crate::tutorial::TutorialMode; use crate::ui::{EditorState, Flags, ShowEverything, UI}; use abstutil::elapsed_seconds; use ezgui::{hotkey, Canvas, EventCtx, EventLoopMode, GfxCtx, Key, UserInput, Wizard, GUI}; use geom::{Duration, Line, Pt2D, Speed}; use map_model::Map; use rand::seq::SliceRandom; use rand::Rng; use rand_xorshift::XorShiftRng; use std::path::PathBuf; use std::time::Instant; // This is the top-level of the GUI logic. This module should just manage interactions between the // top-level game states. pub struct GameState { pub mode: Mode, pub ui: UI, } // TODO Need to reset_sim() when entering Edit, Tutorial, Mission, or ABTest and when leaving // Tutorial and ABTest. Expressing this manually right now is quite tedious; maybe having on_enter // and on_exit would be cleaner. pub enum Mode { SplashScreen(Wizard, Option<(Screensaver, XorShiftRng)>), Edit(EditMode), Tutorial(TutorialMode), Sandbox(SandboxMode), Debug(DebugMode), Mission(MissionEditMode), ABTest(ABTestMode), } impl GameState { pub fn new(flags: Flags, ctx: &mut EventCtx) -> GameState
.map .all_lanes() .choose(&mut rng) .and_then(|l| ID::Lane(l.id).canonical_point(&game.ui.primary)) }) .expect("Can't get canonical_point of a random building or lane"); if splash { ctx.canvas.center_on_map_pt(rand_focus_pt); game.mode = Mode::SplashScreen( Wizard::new(), Some(( Screensaver::start_bounce(&mut rng, ctx.canvas, &game.ui.primary.map), rng, )), ); } else { match abstutil::read_json::<EditorState>("../editor_state.json") { Ok(ref loaded) if game.ui.primary.map.get_name() == &loaded.map_name => { println!("Loaded previous editor_state.json"); ctx.canvas.cam_x = loaded.cam_x; ctx.canvas.cam_y = loaded.cam_y; ctx.canvas.cam_zoom = loaded.cam_zoom; } _ => { println!("Couldn't load editor_state.json or it's for a different map, so just focusing on an arbitrary building"); ctx.canvas.center_on_map_pt(rand_focus_pt); } } } game } fn save_editor_state(&self, canvas: &Canvas) { let state = EditorState { map_name: self.ui.primary.map.get_name().clone(), cam_x: canvas.cam_x, cam_y: canvas.cam_y, cam_zoom: canvas.cam_zoom, }; // TODO maybe make state line up with the map, so loading from a new map doesn't break abstutil::write_json("../editor_state.json", &state) .expect("Saving editor_state.json failed"); println!("Saved editor_state.json"); } } impl GUI for GameState { fn event(&mut self, ctx: &mut EventCtx) -> EventLoopMode { match self.mode { Mode::SplashScreen(ref mut wizard, ref mut maybe_screensaver) => { let anim = maybe_screensaver.is_some(); if let Some((ref mut screensaver, ref mut rng)) = maybe_screensaver { screensaver.update(rng, ctx.input, ctx.canvas, &self.ui.primary.map); } if let Some(new_mode) = splash_screen(wizard, ctx, &mut self.ui, maybe_screensaver) { self.mode = new_mode; } else if wizard.aborted() { self.before_quit(ctx.canvas); std::process::exit(0); } if anim { EventLoopMode::Animation } else { EventLoopMode::InputOnly } } Mode::Edit(_) => EditMode::event(self, ctx), Mode::Tutorial(_) => TutorialMode::event(self, ctx), Mode::Sandbox(_) => SandboxMode::event(self, ctx), Mode::Debug(_) => DebugMode::event(self, ctx), Mode::Mission(_) => MissionEditMode::event(self, ctx), Mode::ABTest(_) => ABTestMode::event(self, ctx), } } fn draw(&self, g: &mut GfxCtx) { match self.mode { Mode::SplashScreen(ref wizard, _) => { self.ui.draw( g, DrawOptions::new(), &self.ui.primary.sim, &ShowEverything::new(), ); wizard.draw(g); } Mode::Edit(_) => EditMode::draw(self, g), Mode::Tutorial(_) => TutorialMode::draw(self, g), Mode::Sandbox(_) => SandboxMode::draw(self, g), Mode::Debug(_) => DebugMode::draw(self, g), Mode::Mission(_) => MissionEditMode::draw(self, g), Mode::ABTest(_) => ABTestMode::draw(self, g), } /*println!( "{} uploads, {} draw calls", g.get_num_uploads(), g.num_draw_calls );*/ } fn dump_before_abort(&self, canvas: &Canvas) { println!( "********************************************************************************" ); println!("UI broke! Primary sim:"); self.ui.primary.sim.dump_before_abort(); if let Mode::ABTest(ref abtest) = self.mode { if let Some(ref s) = abtest.secondary { println!("Secondary sim:"); s.sim.dump_before_abort(); } } self.save_editor_state(canvas); } fn before_quit(&self, canvas: &Canvas) { self.save_editor_state(canvas); self.ui.cs.save(); println!("Saved color_scheme.json"); } fn profiling_enabled(&self) -> bool { self.ui.primary.current_flags.enable_profiler } } const SPEED: Speed = Speed::const_meters_per_second(20.0); pub struct Screensaver { line: Line, started: Instant, } impl Screensaver { fn start_bounce(rng: &mut XorShiftRng, canvas: &mut Canvas, map: &Map) -> Screensaver { let at = canvas.center_to_map_pt(); let bounds = map.get_bounds(); // TODO Ideally bounce off the edge of the map let goto = Pt2D::new( rng.gen_range(0.0, bounds.max_x), rng.gen_range(0.0, bounds.max_y), ); canvas.cam_zoom = 10.0; canvas.center_on_map_pt(at); Screensaver { line: Line::new(at, goto), started: Instant::now(), } } fn update( &mut self, rng: &mut XorShiftRng, input: &mut UserInput, canvas: &mut Canvas, map: &Map, ) { if input.nonblocking_is_update_event() { input.use_update_event(); let dist_along = Duration::seconds(elapsed_seconds(self.started)) * SPEED; if dist_along < self.line.length() { canvas.center_on_map_pt(self.line.dist_along(dist_along)); } else { *self = Screensaver::start_bounce(rng, canvas, map) } } } } fn splash_screen( raw_wizard: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI, maybe_screensaver: &mut Option<(Screensaver, XorShiftRng)>, ) -> Option<Mode> { let mut wizard = raw_wizard.wrap(ctx); let sandbox = "Sandbox mode"; let load_map = "Load another map"; let edit = "Edit map"; let tutorial = "Tutorial"; let debug = "Debug mode"; let mission = "Mission Edit Mode"; let abtest = "A/B Test Mode"; let about = "About"; let quit = "Quit"; // Loop because we might go from About -> top-level menu repeatedly, and recursion is scary. loop { // TODO No hotkey for quit because it's just the normal menu escape? match wizard .choose_string_hotkeys( "Welcome to A/B Street!", vec![ (hotkey(Key::S), sandbox), (hotkey(Key::L), load_map), (hotkey(Key::E), edit), (hotkey(Key::T), tutorial), (hotkey(Key::D), debug), (hotkey(Key::M), mission), (hotkey(Key::A), abtest), (None, about), (None, quit), ], )? .as_str() { x if x == sandbox => break Some(Mode::Sandbox(SandboxMode::new(ctx))), x if x == load_map => { let current_map = ui.primary.map.get_name().to_string(); if let Some((name, _)) = wizard.choose_something_no_keys::<String>( "Load which map?", Box::new(move || { abstutil::list_all_objects("maps", "") .into_iter() .filter(|(n, _)| n!= &current_map) .collect() }), ) { // This retains no state, but that's probably fine. let mut flags = ui.primary.current_flags.clone(); flags.sim_flags.load = PathBuf::from(format!("../data/maps/{}.bin", name)); *ui = UI::new(flags, ctx); break Some(Mode::Sandbox(SandboxMode::new(ctx))); } else if wizard.aborted() { break Some(Mode::SplashScreen(Wizard::new(), maybe_screensaver.take())); } else { break None; } } x if x == edit => break Some(Mode::Edit(EditMode::new(ctx, ui))), x if x == tutorial => break Some(Mode::Tutorial(TutorialMode::new(ctx, ui))), x if x == debug => break Some(Mode::Debug(DebugMode::new(ctx, ui))), x if x == mission => break Some(Mode::Mission(MissionEditMode::new(ctx, ui))), x if x == abtest => break Some(Mode::ABTest(ABTestMode::new(ctx, ui))), x if x == about => { if wizard.acknowledge( "About A/B Street", vec![ "Author: Dustin Carlino ([email protected])", "http://github.com/dabreegster/abstreet", "Map data from OpenStreetMap and King County GIS", "", "Press ENTER to continue", ], ) { continue; } else { break None; } } x if x == quit => { // Not important to call before_quit... if we're here, we're bouncing around // aimlessly anyway std::process::exit(0); } _ => unreachable!(), } } }
{ let splash = !flags.no_splash && !format!("{}", flags.sim_flags.load.display()).contains("data/save"); let mut rng = flags.sim_flags.make_rng(); let mut game = GameState { mode: Mode::Sandbox(SandboxMode::new(ctx)), ui: UI::new(flags, ctx), }; let rand_focus_pt = game .ui .primary .map .all_buildings() .choose(&mut rng) .and_then(|b| ID::Building(b.id).canonical_point(&game.ui.primary)) .or_else(|| { game.ui .primary
identifier_body
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use std::slice::Iter; use num::{One, Zero}; use crate::algorithm::utilities::remove_sparse_indices; use crate::data::linear_algebra::SparseTuple; use crate::data::linear_algebra::traits::{SparseComparator, SparseElement}; use crate::data::linear_algebra::traits::NotZero; use crate::data::linear_algebra::vector::{DenseVector, Vector}; /// A sparse vector using a `Vec` with (row, value) combinations as back-end. Indices start at /// `0`. /// /// TODO(ENHANCEMENT): Consider making this backed by a `HashMap`. #[derive(Eq, PartialEq, Clone, Debug)] pub struct Sparse<F, C> { data: Vec<SparseTuple<F>>, len: usize, /// The level that comparison is done at: a single reference to the underlying data. phantom_comparison_type: PhantomData<C>, } impl<F, C> Sparse<F, C> { fn get_data_index(&self, i: usize) -> Result<usize, usize> { self.data.binary_search_by_key(&i, |&(index, _)| index) } fn set_zero(&mut self, i: usize) { if let Ok(index) = self.get_data_index(i) { self.data.remove(index); } } /// Increase the length of the vector by passing with zeros. pub fn extend(&mut self, extra_len: usize) { self.len += extra_len; } /// Convert the inner data structure into an iterator, consuming the struct. pub fn into_iter(self) -> impl Iterator<Item=SparseTuple<F>> { self.data.into_iter() } } impl<F, C> Vector<F> for Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { type Inner = SparseTuple<F>; /// Create a vector of length `len` from `data`. /// /// Requires that values close to zero are already filtered. fn new(data: Vec<Self::Inner>, len: usize) -> Self { debug_assert!(data.iter().all(|&(i, _)| i < len)); debug_assert!(data.is_sorted_by_key(|&(i, _)| i)); debug_assert!(data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert_ne!(len, 0); debug_assert!(data.len() <= len); Self { data, len, phantom_comparison_type: PhantomData, } } fn sparse_inner_product<'a, H, G: 'a, I: Iterator<Item=&'a SparseTuple<G>>>(&self, column: I) -> H where H: Zero + AddAssign<F>, for<'r> &'r F: Mul<&'r G, Output=F>, { let mut total = H::zero(); let mut i = 0; for (index, value) in column { while i < self.data.len() && self.data[i].0 < *index { i += 1; } if i < self.data.len() && self.data[i].0 == *index { total += &self.data[i].1 * value; i += 1; } if i == self.len { break; } } total } /// Append a non-zero value. fn push_value(&mut self, value: F) { debug_assert!(value.borrow().is_not_zero()); self.data.push((self.len, value)); self.len += 1; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. fn
(&mut self, i: usize, value: F) { debug_assert!(i < self.len); debug_assert!(value.borrow().is_not_zero()); match self.get_data_index(i) { Ok(index) => self.data[index].1 = value, Err(index) => self.data.insert(index, (i, value)), } } fn get(&self, index: usize) -> Option<&F> { debug_assert!(index < self.len); self.get_data_index(index).ok().map(|i| &self.data[i].1) } /// Remove elements. /// /// # Arguments /// /// * `indices` is assumed sorted. fn remove_indices(&mut self, indices: &[usize]) { debug_assert!(indices.is_sorted()); // All values are unique debug_assert!(indices.iter().collect::<HashSet<_>>().len() == indices.len()); debug_assert!(indices.iter().all(|&i| i < self.len)); debug_assert!(indices.len() < self.len); remove_sparse_indices(&mut self.data, indices); self.len -= indices.len(); } fn iter_values(&self) -> Iter<Self::Inner> { self.data.iter() } /// The length of this vector. fn len(&self) -> usize { self.len } /// Whether this vector has zero size. fn is_empty(&self) -> bool { self.len == 0 } /// The size of this vector in memory. fn size(&self) -> usize { self.data.len() } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Create a `SparseVector` representation of standard basis unit vector e_i. /// /// # Arguments /// /// * `i`: Only index where there should be a 1. Note that indexing starts at zero, and runs /// until (not through) `len`. /// * `len`: Size of the `SparseVector`. #[must_use] pub fn standard_basis_vector(i: usize, len: usize) -> Self where F: One + Clone, { debug_assert!(i < len); Self::new(vec![(i, F::one())], len) } /// Add the multiple of another row to this row. /// /// # Arguments /// /// * `multiple`: Non-zero constant that all elements of the `other` vector are multiplied with. /// * `other`: Vector to add a multiple of to this vector. /// /// # Return value /// /// A new `SparseVector`. /// /// # Note /// /// The implementation of this method doesn't look pretty, but it seems to be reasonably fast. /// If this method is too slow, it might be wise to consider the switching of the `SparseVector` /// storage backend from a `Vec` to a `HashMap`. pub fn add_multiple_of_row<H>(&mut self, multiple: &F, other: &Sparse<F, C>) where H: Zero + Add<F, Output=H>, F: Add<F, Output=H> + From<H>, for<'r> &'r F: Mul<&'r F, Output=F>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(multiple.borrow().is_not_zero()); let mut new_tuples = Vec::new(); let mut j = 0; let old_data = mem::replace(&mut self.data, Vec::with_capacity(0)); for (i, value) in old_data { while j < other.data.len() && other.data[j].0 < i { let new_value = multiple * &other.data[j].1; new_tuples.push((other.data[j].0, new_value.into())); j += 1; } if j < other.data.len() && i == other.data[j].0 { let new_value = value + multiple * &other.data[j].1; if!new_value.is_zero() { new_tuples.push((i, new_value.into())); } j += 1; } else { new_tuples.push((i, value)); } } for (j, value) in &other.data[j..] { new_tuples.push((*j, multiple * value)); } self.data = new_tuples; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. pub fn shift_value<G>(&mut self, i: usize, value: G) where F: PartialEq<G> + AddAssign<G> + From<G>, for<'r> &'r G: Neg<Output=G>, { debug_assert!(i < self.len); match self.get_data_index(i) { Ok(index) => { if self.data[index].1 == -&value { self.set_zero(i); } else { self.data[index].1 += value; } }, Err(index) => self.data.insert(index, (i, From::from(value))), } } /// Multiply each element of the vector by a value. pub fn element_wise_multiply(&mut self, value: &F) where for<'r> F: NotZero + MulAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v *= value; } self.data.retain(|(_, v)| v.is_not_zero()); } /// Divide each element of the vector by a value. pub fn element_wise_divide(&mut self, value: &F) where for<'r> F: NotZero + DivAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v /= value; } self.data.retain(|(_, v)| v.is_not_zero()); } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product_with_dense<'a, F2, O: 'a>(&'a self, other: &'a DenseVector<F2>) -> O where F: Borrow<O>, F2: Borrow<O> + PartialEq + Display + Debug, O: Sum, &'a O: Mul<&'a O, Output=O>, { debug_assert_eq!(other.len(), self.len()); self.data.iter().map(|(i, value)| other[*i].borrow() * value.borrow()).sum() } /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product<'a, O, F2>(&'a self, other: &'a Sparse<F2, C>) -> O where O: Zero + AddAssign<C>, F2: SparseElement<C>, // We choose to have multiplication output at the C level, because it would also be nonzero // if both F and F2 values are not zero. &'a C: Mul<&'a C, Output=C>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(self.data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert!(other.data.iter().all(|(_, v)| v.borrow().is_not_zero())); let mut self_lowest = 0; let mut other_lowest = 0; let mut total = O::zero(); while self_lowest < self.data.len() && other_lowest < other.data.len() { let self_sought = self.data[self_lowest].0; let other_sought = other.data[other_lowest].0; match self_sought.cmp(&other_sought) { Ordering::Less => { match self.data[self_lowest..].binary_search_by_key(&other_sought, |&(i, _)| i) { Err(diff) => { self_lowest += diff; other_lowest += 1; }, Ok(diff) => { total += self.data[self_lowest + diff].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += diff + 1; other_lowest += 1; }, } }, Ordering::Greater => { match other.data[other_lowest..].binary_search_by_key(&self_sought, |&(i, _)| i) { Err(diff) => { self_lowest += 1; other_lowest += diff; }, Ok(diff) => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest + diff].1.borrow(); self_lowest += 1; other_lowest += diff + 1; }, } }, Ordering::Equal => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += 1; other_lowest += 1; }, } } total } } impl<F: SparseElement<C>, C: SparseComparator> Display for Sparse<F, C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (index, value) in &self.data { writeln!(f, "({} {}), ", index, value)?; } writeln!(f) } }
set
identifier_name
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use std::slice::Iter; use num::{One, Zero}; use crate::algorithm::utilities::remove_sparse_indices; use crate::data::linear_algebra::SparseTuple; use crate::data::linear_algebra::traits::{SparseComparator, SparseElement}; use crate::data::linear_algebra::traits::NotZero; use crate::data::linear_algebra::vector::{DenseVector, Vector}; /// A sparse vector using a `Vec` with (row, value) combinations as back-end. Indices start at /// `0`. /// /// TODO(ENHANCEMENT): Consider making this backed by a `HashMap`. #[derive(Eq, PartialEq, Clone, Debug)] pub struct Sparse<F, C> { data: Vec<SparseTuple<F>>, len: usize, /// The level that comparison is done at: a single reference to the underlying data. phantom_comparison_type: PhantomData<C>, } impl<F, C> Sparse<F, C> { fn get_data_index(&self, i: usize) -> Result<usize, usize> { self.data.binary_search_by_key(&i, |&(index, _)| index) } fn set_zero(&mut self, i: usize) { if let Ok(index) = self.get_data_index(i) { self.data.remove(index); } } /// Increase the length of the vector by passing with zeros. pub fn extend(&mut self, extra_len: usize) { self.len += extra_len; } /// Convert the inner data structure into an iterator, consuming the struct. pub fn into_iter(self) -> impl Iterator<Item=SparseTuple<F>> { self.data.into_iter() } } impl<F, C> Vector<F> for Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { type Inner = SparseTuple<F>; /// Create a vector of length `len` from `data`. /// /// Requires that values close to zero are already filtered. fn new(data: Vec<Self::Inner>, len: usize) -> Self { debug_assert!(data.iter().all(|&(i, _)| i < len)); debug_assert!(data.is_sorted_by_key(|&(i, _)| i)); debug_assert!(data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert_ne!(len, 0); debug_assert!(data.len() <= len); Self { data, len, phantom_comparison_type: PhantomData, } } fn sparse_inner_product<'a, H, G: 'a, I: Iterator<Item=&'a SparseTuple<G>>>(&self, column: I) -> H where H: Zero + AddAssign<F>, for<'r> &'r F: Mul<&'r G, Output=F>, { let mut total = H::zero(); let mut i = 0; for (index, value) in column { while i < self.data.len() && self.data[i].0 < *index { i += 1; } if i < self.data.len() && self.data[i].0 == *index { total += &self.data[i].1 * value; i += 1; } if i == self.len { break; } } total } /// Append a non-zero value. fn push_value(&mut self, value: F) { debug_assert!(value.borrow().is_not_zero()); self.data.push((self.len, value)); self.len += 1; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. fn set(&mut self, i: usize, value: F) { debug_assert!(i < self.len); debug_assert!(value.borrow().is_not_zero()); match self.get_data_index(i) { Ok(index) => self.data[index].1 = value, Err(index) => self.data.insert(index, (i, value)), } } fn get(&self, index: usize) -> Option<&F> { debug_assert!(index < self.len); self.get_data_index(index).ok().map(|i| &self.data[i].1) } /// Remove elements. /// /// # Arguments /// /// * `indices` is assumed sorted. fn remove_indices(&mut self, indices: &[usize]) { debug_assert!(indices.is_sorted()); // All values are unique debug_assert!(indices.iter().collect::<HashSet<_>>().len() == indices.len()); debug_assert!(indices.iter().all(|&i| i < self.len)); debug_assert!(indices.len() < self.len); remove_sparse_indices(&mut self.data, indices); self.len -= indices.len(); } fn iter_values(&self) -> Iter<Self::Inner> { self.data.iter() } /// The length of this vector. fn len(&self) -> usize { self.len } /// Whether this vector has zero size. fn is_empty(&self) -> bool { self.len == 0 } /// The size of this vector in memory. fn size(&self) -> usize { self.data.len() } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Create a `SparseVector` representation of standard basis unit vector e_i. /// /// # Arguments /// /// * `i`: Only index where there should be a 1. Note that indexing starts at zero, and runs /// until (not through) `len`. /// * `len`: Size of the `SparseVector`. #[must_use] pub fn standard_basis_vector(i: usize, len: usize) -> Self where F: One + Clone, { debug_assert!(i < len); Self::new(vec![(i, F::one())], len) } /// Add the multiple of another row to this row. /// /// # Arguments /// /// * `multiple`: Non-zero constant that all elements of the `other` vector are multiplied with. /// * `other`: Vector to add a multiple of to this vector. /// /// # Return value /// /// A new `SparseVector`. /// /// # Note /// /// The implementation of this method doesn't look pretty, but it seems to be reasonably fast. /// If this method is too slow, it might be wise to consider the switching of the `SparseVector` /// storage backend from a `Vec` to a `HashMap`. pub fn add_multiple_of_row<H>(&mut self, multiple: &F, other: &Sparse<F, C>) where H: Zero + Add<F, Output=H>, F: Add<F, Output=H> + From<H>, for<'r> &'r F: Mul<&'r F, Output=F>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(multiple.borrow().is_not_zero()); let mut new_tuples = Vec::new(); let mut j = 0; let old_data = mem::replace(&mut self.data, Vec::with_capacity(0)); for (i, value) in old_data { while j < other.data.len() && other.data[j].0 < i { let new_value = multiple * &other.data[j].1; new_tuples.push((other.data[j].0, new_value.into())); j += 1; } if j < other.data.len() && i == other.data[j].0 { let new_value = value + multiple * &other.data[j].1; if!new_value.is_zero() { new_tuples.push((i, new_value.into())); } j += 1; } else { new_tuples.push((i, value)); } } for (j, value) in &other.data[j..] { new_tuples.push((*j, multiple * value)); } self.data = new_tuples; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. pub fn shift_value<G>(&mut self, i: usize, value: G) where F: PartialEq<G> + AddAssign<G> + From<G>, for<'r> &'r G: Neg<Output=G>, { debug_assert!(i < self.len); match self.get_data_index(i) { Ok(index) => { if self.data[index].1 == -&value { self.set_zero(i); } else { self.data[index].1 += value; } }, Err(index) => self.data.insert(index, (i, From::from(value))), } } /// Multiply each element of the vector by a value. pub fn element_wise_multiply(&mut self, value: &F) where for<'r> F: NotZero + MulAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v *= value; } self.data.retain(|(_, v)| v.is_not_zero()); } /// Divide each element of the vector by a value. pub fn element_wise_divide(&mut self, value: &F) where for<'r> F: NotZero + DivAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v /= value; } self.data.retain(|(_, v)| v.is_not_zero()); } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product_with_dense<'a, F2, O: 'a>(&'a self, other: &'a DenseVector<F2>) -> O where F: Borrow<O>, F2: Borrow<O> + PartialEq + Display + Debug, O: Sum, &'a O: Mul<&'a O, Output=O>, { debug_assert_eq!(other.len(), self.len()); self.data.iter().map(|(i, value)| other[*i].borrow() * value.borrow()).sum() } /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product<'a, O, F2>(&'a self, other: &'a Sparse<F2, C>) -> O where O: Zero + AddAssign<C>, F2: SparseElement<C>, // We choose to have multiplication output at the C level, because it would also be nonzero // if both F and F2 values are not zero. &'a C: Mul<&'a C, Output=C>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(self.data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert!(other.data.iter().all(|(_, v)| v.borrow().is_not_zero())); let mut self_lowest = 0; let mut other_lowest = 0; let mut total = O::zero(); while self_lowest < self.data.len() && other_lowest < other.data.len() { let self_sought = self.data[self_lowest].0; let other_sought = other.data[other_lowest].0; match self_sought.cmp(&other_sought) { Ordering::Less => { match self.data[self_lowest..].binary_search_by_key(&other_sought, |&(i, _)| i) { Err(diff) => { self_lowest += diff; other_lowest += 1; }, Ok(diff) => { total += self.data[self_lowest + diff].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += diff + 1; other_lowest += 1; }, } }, Ordering::Greater => { match other.data[other_lowest..].binary_search_by_key(&self_sought, |&(i, _)| i) { Err(diff) => { self_lowest += 1; other_lowest += diff; }, Ok(diff) => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest + diff].1.borrow(); self_lowest += 1; other_lowest += diff + 1; }, } }, Ordering::Equal => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += 1; other_lowest += 1; }, } } total } } impl<F: SparseElement<C>, C: SparseComparator> Display for Sparse<F, C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (index, value) in &self.data { writeln!(f, "({} {}), ", index, value)?; }
} }
writeln!(f)
random_line_split
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use std::slice::Iter; use num::{One, Zero}; use crate::algorithm::utilities::remove_sparse_indices; use crate::data::linear_algebra::SparseTuple; use crate::data::linear_algebra::traits::{SparseComparator, SparseElement}; use crate::data::linear_algebra::traits::NotZero; use crate::data::linear_algebra::vector::{DenseVector, Vector}; /// A sparse vector using a `Vec` with (row, value) combinations as back-end. Indices start at /// `0`. /// /// TODO(ENHANCEMENT): Consider making this backed by a `HashMap`. #[derive(Eq, PartialEq, Clone, Debug)] pub struct Sparse<F, C> { data: Vec<SparseTuple<F>>, len: usize, /// The level that comparison is done at: a single reference to the underlying data. phantom_comparison_type: PhantomData<C>, } impl<F, C> Sparse<F, C> { fn get_data_index(&self, i: usize) -> Result<usize, usize> { self.data.binary_search_by_key(&i, |&(index, _)| index) } fn set_zero(&mut self, i: usize) { if let Ok(index) = self.get_data_index(i) { self.data.remove(index); } } /// Increase the length of the vector by passing with zeros. pub fn extend(&mut self, extra_len: usize) { self.len += extra_len; } /// Convert the inner data structure into an iterator, consuming the struct. pub fn into_iter(self) -> impl Iterator<Item=SparseTuple<F>> { self.data.into_iter() } } impl<F, C> Vector<F> for Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { type Inner = SparseTuple<F>; /// Create a vector of length `len` from `data`. /// /// Requires that values close to zero are already filtered. fn new(data: Vec<Self::Inner>, len: usize) -> Self { debug_assert!(data.iter().all(|&(i, _)| i < len)); debug_assert!(data.is_sorted_by_key(|&(i, _)| i)); debug_assert!(data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert_ne!(len, 0); debug_assert!(data.len() <= len); Self { data, len, phantom_comparison_type: PhantomData, } } fn sparse_inner_product<'a, H, G: 'a, I: Iterator<Item=&'a SparseTuple<G>>>(&self, column: I) -> H where H: Zero + AddAssign<F>, for<'r> &'r F: Mul<&'r G, Output=F>, { let mut total = H::zero(); let mut i = 0; for (index, value) in column { while i < self.data.len() && self.data[i].0 < *index { i += 1; } if i < self.data.len() && self.data[i].0 == *index { total += &self.data[i].1 * value; i += 1; } if i == self.len { break; } } total } /// Append a non-zero value. fn push_value(&mut self, value: F) { debug_assert!(value.borrow().is_not_zero()); self.data.push((self.len, value)); self.len += 1; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. fn set(&mut self, i: usize, value: F) { debug_assert!(i < self.len); debug_assert!(value.borrow().is_not_zero()); match self.get_data_index(i) { Ok(index) => self.data[index].1 = value, Err(index) => self.data.insert(index, (i, value)), } } fn get(&self, index: usize) -> Option<&F> { debug_assert!(index < self.len); self.get_data_index(index).ok().map(|i| &self.data[i].1) } /// Remove elements. /// /// # Arguments /// /// * `indices` is assumed sorted. fn remove_indices(&mut self, indices: &[usize]) { debug_assert!(indices.is_sorted()); // All values are unique debug_assert!(indices.iter().collect::<HashSet<_>>().len() == indices.len()); debug_assert!(indices.iter().all(|&i| i < self.len)); debug_assert!(indices.len() < self.len); remove_sparse_indices(&mut self.data, indices); self.len -= indices.len(); } fn iter_values(&self) -> Iter<Self::Inner> { self.data.iter() } /// The length of this vector. fn len(&self) -> usize
/// Whether this vector has zero size. fn is_empty(&self) -> bool { self.len == 0 } /// The size of this vector in memory. fn size(&self) -> usize { self.data.len() } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Create a `SparseVector` representation of standard basis unit vector e_i. /// /// # Arguments /// /// * `i`: Only index where there should be a 1. Note that indexing starts at zero, and runs /// until (not through) `len`. /// * `len`: Size of the `SparseVector`. #[must_use] pub fn standard_basis_vector(i: usize, len: usize) -> Self where F: One + Clone, { debug_assert!(i < len); Self::new(vec![(i, F::one())], len) } /// Add the multiple of another row to this row. /// /// # Arguments /// /// * `multiple`: Non-zero constant that all elements of the `other` vector are multiplied with. /// * `other`: Vector to add a multiple of to this vector. /// /// # Return value /// /// A new `SparseVector`. /// /// # Note /// /// The implementation of this method doesn't look pretty, but it seems to be reasonably fast. /// If this method is too slow, it might be wise to consider the switching of the `SparseVector` /// storage backend from a `Vec` to a `HashMap`. pub fn add_multiple_of_row<H>(&mut self, multiple: &F, other: &Sparse<F, C>) where H: Zero + Add<F, Output=H>, F: Add<F, Output=H> + From<H>, for<'r> &'r F: Mul<&'r F, Output=F>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(multiple.borrow().is_not_zero()); let mut new_tuples = Vec::new(); let mut j = 0; let old_data = mem::replace(&mut self.data, Vec::with_capacity(0)); for (i, value) in old_data { while j < other.data.len() && other.data[j].0 < i { let new_value = multiple * &other.data[j].1; new_tuples.push((other.data[j].0, new_value.into())); j += 1; } if j < other.data.len() && i == other.data[j].0 { let new_value = value + multiple * &other.data[j].1; if!new_value.is_zero() { new_tuples.push((i, new_value.into())); } j += 1; } else { new_tuples.push((i, value)); } } for (j, value) in &other.data[j..] { new_tuples.push((*j, multiple * value)); } self.data = new_tuples; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. pub fn shift_value<G>(&mut self, i: usize, value: G) where F: PartialEq<G> + AddAssign<G> + From<G>, for<'r> &'r G: Neg<Output=G>, { debug_assert!(i < self.len); match self.get_data_index(i) { Ok(index) => { if self.data[index].1 == -&value { self.set_zero(i); } else { self.data[index].1 += value; } }, Err(index) => self.data.insert(index, (i, From::from(value))), } } /// Multiply each element of the vector by a value. pub fn element_wise_multiply(&mut self, value: &F) where for<'r> F: NotZero + MulAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v *= value; } self.data.retain(|(_, v)| v.is_not_zero()); } /// Divide each element of the vector by a value. pub fn element_wise_divide(&mut self, value: &F) where for<'r> F: NotZero + DivAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v /= value; } self.data.retain(|(_, v)| v.is_not_zero()); } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product_with_dense<'a, F2, O: 'a>(&'a self, other: &'a DenseVector<F2>) -> O where F: Borrow<O>, F2: Borrow<O> + PartialEq + Display + Debug, O: Sum, &'a O: Mul<&'a O, Output=O>, { debug_assert_eq!(other.len(), self.len()); self.data.iter().map(|(i, value)| other[*i].borrow() * value.borrow()).sum() } /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product<'a, O, F2>(&'a self, other: &'a Sparse<F2, C>) -> O where O: Zero + AddAssign<C>, F2: SparseElement<C>, // We choose to have multiplication output at the C level, because it would also be nonzero // if both F and F2 values are not zero. &'a C: Mul<&'a C, Output=C>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(self.data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert!(other.data.iter().all(|(_, v)| v.borrow().is_not_zero())); let mut self_lowest = 0; let mut other_lowest = 0; let mut total = O::zero(); while self_lowest < self.data.len() && other_lowest < other.data.len() { let self_sought = self.data[self_lowest].0; let other_sought = other.data[other_lowest].0; match self_sought.cmp(&other_sought) { Ordering::Less => { match self.data[self_lowest..].binary_search_by_key(&other_sought, |&(i, _)| i) { Err(diff) => { self_lowest += diff; other_lowest += 1; }, Ok(diff) => { total += self.data[self_lowest + diff].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += diff + 1; other_lowest += 1; }, } }, Ordering::Greater => { match other.data[other_lowest..].binary_search_by_key(&self_sought, |&(i, _)| i) { Err(diff) => { self_lowest += 1; other_lowest += diff; }, Ok(diff) => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest + diff].1.borrow(); self_lowest += 1; other_lowest += diff + 1; }, } }, Ordering::Equal => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += 1; other_lowest += 1; }, } } total } } impl<F: SparseElement<C>, C: SparseComparator> Display for Sparse<F, C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (index, value) in &self.data { writeln!(f, "({} {}), ", index, value)?; } writeln!(f) } }
{ self.len }
identifier_body
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use std::slice::Iter; use num::{One, Zero}; use crate::algorithm::utilities::remove_sparse_indices; use crate::data::linear_algebra::SparseTuple; use crate::data::linear_algebra::traits::{SparseComparator, SparseElement}; use crate::data::linear_algebra::traits::NotZero; use crate::data::linear_algebra::vector::{DenseVector, Vector}; /// A sparse vector using a `Vec` with (row, value) combinations as back-end. Indices start at /// `0`. /// /// TODO(ENHANCEMENT): Consider making this backed by a `HashMap`. #[derive(Eq, PartialEq, Clone, Debug)] pub struct Sparse<F, C> { data: Vec<SparseTuple<F>>, len: usize, /// The level that comparison is done at: a single reference to the underlying data. phantom_comparison_type: PhantomData<C>, } impl<F, C> Sparse<F, C> { fn get_data_index(&self, i: usize) -> Result<usize, usize> { self.data.binary_search_by_key(&i, |&(index, _)| index) } fn set_zero(&mut self, i: usize) { if let Ok(index) = self.get_data_index(i) { self.data.remove(index); } } /// Increase the length of the vector by passing with zeros. pub fn extend(&mut self, extra_len: usize) { self.len += extra_len; } /// Convert the inner data structure into an iterator, consuming the struct. pub fn into_iter(self) -> impl Iterator<Item=SparseTuple<F>> { self.data.into_iter() } } impl<F, C> Vector<F> for Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { type Inner = SparseTuple<F>; /// Create a vector of length `len` from `data`. /// /// Requires that values close to zero are already filtered. fn new(data: Vec<Self::Inner>, len: usize) -> Self { debug_assert!(data.iter().all(|&(i, _)| i < len)); debug_assert!(data.is_sorted_by_key(|&(i, _)| i)); debug_assert!(data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert_ne!(len, 0); debug_assert!(data.len() <= len); Self { data, len, phantom_comparison_type: PhantomData, } } fn sparse_inner_product<'a, H, G: 'a, I: Iterator<Item=&'a SparseTuple<G>>>(&self, column: I) -> H where H: Zero + AddAssign<F>, for<'r> &'r F: Mul<&'r G, Output=F>, { let mut total = H::zero(); let mut i = 0; for (index, value) in column { while i < self.data.len() && self.data[i].0 < *index { i += 1; } if i < self.data.len() && self.data[i].0 == *index { total += &self.data[i].1 * value; i += 1; } if i == self.len { break; } } total } /// Append a non-zero value. fn push_value(&mut self, value: F) { debug_assert!(value.borrow().is_not_zero()); self.data.push((self.len, value)); self.len += 1; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. fn set(&mut self, i: usize, value: F) { debug_assert!(i < self.len); debug_assert!(value.borrow().is_not_zero()); match self.get_data_index(i) { Ok(index) => self.data[index].1 = value, Err(index) => self.data.insert(index, (i, value)), } } fn get(&self, index: usize) -> Option<&F> { debug_assert!(index < self.len); self.get_data_index(index).ok().map(|i| &self.data[i].1) } /// Remove elements. /// /// # Arguments /// /// * `indices` is assumed sorted. fn remove_indices(&mut self, indices: &[usize]) { debug_assert!(indices.is_sorted()); // All values are unique debug_assert!(indices.iter().collect::<HashSet<_>>().len() == indices.len()); debug_assert!(indices.iter().all(|&i| i < self.len)); debug_assert!(indices.len() < self.len); remove_sparse_indices(&mut self.data, indices); self.len -= indices.len(); } fn iter_values(&self) -> Iter<Self::Inner> { self.data.iter() } /// The length of this vector. fn len(&self) -> usize { self.len } /// Whether this vector has zero size. fn is_empty(&self) -> bool { self.len == 0 } /// The size of this vector in memory. fn size(&self) -> usize { self.data.len() } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Create a `SparseVector` representation of standard basis unit vector e_i. /// /// # Arguments /// /// * `i`: Only index where there should be a 1. Note that indexing starts at zero, and runs /// until (not through) `len`. /// * `len`: Size of the `SparseVector`. #[must_use] pub fn standard_basis_vector(i: usize, len: usize) -> Self where F: One + Clone, { debug_assert!(i < len); Self::new(vec![(i, F::one())], len) } /// Add the multiple of another row to this row. /// /// # Arguments /// /// * `multiple`: Non-zero constant that all elements of the `other` vector are multiplied with. /// * `other`: Vector to add a multiple of to this vector. /// /// # Return value /// /// A new `SparseVector`. /// /// # Note /// /// The implementation of this method doesn't look pretty, but it seems to be reasonably fast. /// If this method is too slow, it might be wise to consider the switching of the `SparseVector` /// storage backend from a `Vec` to a `HashMap`. pub fn add_multiple_of_row<H>(&mut self, multiple: &F, other: &Sparse<F, C>) where H: Zero + Add<F, Output=H>, F: Add<F, Output=H> + From<H>, for<'r> &'r F: Mul<&'r F, Output=F>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(multiple.borrow().is_not_zero()); let mut new_tuples = Vec::new(); let mut j = 0; let old_data = mem::replace(&mut self.data, Vec::with_capacity(0)); for (i, value) in old_data { while j < other.data.len() && other.data[j].0 < i { let new_value = multiple * &other.data[j].1; new_tuples.push((other.data[j].0, new_value.into())); j += 1; } if j < other.data.len() && i == other.data[j].0 { let new_value = value + multiple * &other.data[j].1; if!new_value.is_zero() { new_tuples.push((i, new_value.into())); } j += 1; } else { new_tuples.push((i, value)); } } for (j, value) in &other.data[j..] { new_tuples.push((*j, multiple * value)); } self.data = new_tuples; } /// Set the value at index `i` to `value`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. pub fn shift_value<G>(&mut self, i: usize, value: G) where F: PartialEq<G> + AddAssign<G> + From<G>, for<'r> &'r G: Neg<Output=G>, { debug_assert!(i < self.len); match self.get_data_index(i) { Ok(index) => { if self.data[index].1 == -&value { self.set_zero(i); } else { self.data[index].1 += value; } }, Err(index) => self.data.insert(index, (i, From::from(value))), } } /// Multiply each element of the vector by a value. pub fn element_wise_multiply(&mut self, value: &F) where for<'r> F: NotZero + MulAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v *= value; } self.data.retain(|(_, v)| v.is_not_zero()); } /// Divide each element of the vector by a value. pub fn element_wise_divide(&mut self, value: &F) where for<'r> F: NotZero + DivAssign<&'r F>, { debug_assert!(value.borrow().is_not_zero()); for (_, v) in &mut self.data { *v /= value; } self.data.retain(|(_, v)| v.is_not_zero()); } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product_with_dense<'a, F2, O: 'a>(&'a self, other: &'a DenseVector<F2>) -> O where F: Borrow<O>, F2: Borrow<O> + PartialEq + Display + Debug, O: Sum, &'a O: Mul<&'a O, Output=O>, { debug_assert_eq!(other.len(), self.len()); self.data.iter().map(|(i, value)| other[*i].borrow() * value.borrow()).sum() } /// Calculate the inner product between two vectors. /// /// # Arguments /// /// * `other`: Vector to calculate inner product with. /// /// # Return value /// /// The inner product. #[must_use] pub fn inner_product<'a, O, F2>(&'a self, other: &'a Sparse<F2, C>) -> O where O: Zero + AddAssign<C>, F2: SparseElement<C>, // We choose to have multiplication output at the C level, because it would also be nonzero // if both F and F2 values are not zero. &'a C: Mul<&'a C, Output=C>, { debug_assert_eq!(other.len(), self.len()); debug_assert!(self.data.iter().all(|(_, v)| v.borrow().is_not_zero())); debug_assert!(other.data.iter().all(|(_, v)| v.borrow().is_not_zero())); let mut self_lowest = 0; let mut other_lowest = 0; let mut total = O::zero(); while self_lowest < self.data.len() && other_lowest < other.data.len() { let self_sought = self.data[self_lowest].0; let other_sought = other.data[other_lowest].0; match self_sought.cmp(&other_sought) { Ordering::Less =>
, Ordering::Greater => { match other.data[other_lowest..].binary_search_by_key(&self_sought, |&(i, _)| i) { Err(diff) => { self_lowest += 1; other_lowest += diff; }, Ok(diff) => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest + diff].1.borrow(); self_lowest += 1; other_lowest += diff + 1; }, } }, Ordering::Equal => { total += self.data[self_lowest].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += 1; other_lowest += 1; }, } } total } } impl<F: SparseElement<C>, C: SparseComparator> Display for Sparse<F, C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (index, value) in &self.data { writeln!(f, "({} {}), ", index, value)?; } writeln!(f) } }
{ match self.data[self_lowest..].binary_search_by_key(&other_sought, |&(i, _)| i) { Err(diff) => { self_lowest += diff; other_lowest += 1; }, Ok(diff) => { total += self.data[self_lowest + diff].1.borrow() * other.data[other_lowest].1.borrow(); self_lowest += diff + 1; other_lowest += 1; }, } }
conditional_block
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] use std::collections::HashMap; use std::env; use std::future::Future; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::future::FutureExt; use itertools::Itertools; use parking_lot::Mutex; use tokio::runtime::{Builder, Handle, Runtime}; use tokio::task::{Id, JoinError, JoinHandle, JoinSet}; /// Copy our (thread-local or task-local) stdio destination and current workunit parent into /// the task. The former ensures that when a pantsd thread kicks off a future, any stdio done /// by it ends up in the pantsd log as we expect. The latter ensures that when a new workunit /// is created it has an accurate handle to its parent. fn future_with_correct_context<F: Future>(future: F) -> impl Future<Output = F::Output> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: It is important that the first portion of this method is synchronous (meaning that this // method cannot be `async`), because that means that it will run on the thread that calls it. // The second, async portion of the method will run in the spawned Task. stdio::scope_task_destination(stdio_destination, async move { workunit_store::scope_task_workunit_store_handle(workunit_store_handle, future).await }) } /// /// Executors come in two flavors: /// * "borrowed" /// * Created with `Self::new()`, or `self::to_borrowed()`. /// * A borrowed Executor will not be shut down when all handles are dropped, and shutdown /// methods will have no impact. /// * Used when multiple runs of Pants will borrow a single Executor owned by `pantsd`, and in /// unit tests where the Runtime is created by macros. /// * "owned" /// * Created with `Self::new_owned()`. /// * When all handles of a owned Executor are dropped, its Runtime will be shut down. /// Additionally, the explicit shutdown methods can be used to shut down the Executor for all /// clones. /// #[derive(Debug, Clone)] pub struct Executor { runtime: Arc<Mutex<Option<Runtime>>>, handle: Handle, } impl Executor { /// /// Creates an Executor for an existing tokio::Runtime (generally provided by tokio's macros). /// /// The returned Executor will have a lifecycle independent of the Runtime, meaning that dropping /// all clones of the Executor will not cause the Runtime to be shut down. Likewise, the owner of /// the Runtime must ensure that it is kept alive longer than all Executor instances, because /// existence of a Handle does not prevent a Runtime from shutting down. This is guaranteed by /// the scope of the tokio::{test, main} macros. /// pub fn new() -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: Handle::current(), } } /// /// Gets a reference to a global static Executor with an owned tokio::Runtime, initializing it /// with the given thread configuration if this is the first usage. /// /// NB: The global static Executor eases lifecycle issues when consumed from Python, where we /// need thread configurability, but also want to know reliably when the Runtime will shutdown /// (which, because it is static, will only be at the entire process' exit). /// pub fn new_owned<F>( num_worker_threads: usize, max_threads: usize, on_thread_start: F, ) -> Result<Executor, String> where F: Fn() + Send + Sync +'static, { let mut runtime_builder = Builder::new_multi_thread(); runtime_builder .worker_threads(num_worker_threads) .max_blocking_threads(max_threads - num_worker_threads) .enable_all(); if env::var("PANTS_DEBUG").is_ok() { runtime_builder.on_thread_start(on_thread_start); }; let runtime = runtime_builder .build() .map_err(|e| format!("Failed to start the runtime: {e}"))?; let handle = runtime.handle().clone(); Ok(Executor { runtime: Arc::new(Mutex::new(Some(runtime))), handle, }) } /// /// Creates a clone of this Executor which is disconnected from shutdown events. See the `Executor` /// rustdoc. /// pub fn to_borrowed(&self) -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: self.handle.clone(), } } /// /// Enter the runtime context associated with this Executor. This should be used in situations /// where threads not started by the runtime need access to it via task-local variables. /// pub fn enter<F, R>(&self, f: F) -> R where F: FnOnce() -> R,
/// /// Run a Future on a tokio Runtime as a new Task, and return a Future handle to it. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, rescue_join_error: impl FnOnce(JoinError) -> O, ) -> impl Future<Output = O> { self.native_spawn(future).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Run a Future on a tokio Runtime as a new Task, and return a JoinHandle. /// pub fn native_spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, ) -> JoinHandle<O> { self.handle.spawn(future_with_correct_context(future)) } /// /// Run a Future and return its resolved Result. /// /// This should never be called from in a Future context, and should only ever be called in /// something that resembles a main method. /// /// Even after this method returns, work `spawn`ed into the background may continue to run on the /// threads owned by this Executor. /// pub fn block_on<F: Future>(&self, future: F) -> F::Output { // Make sure to copy our (thread-local) logging destination into the task. // When a daemon thread kicks off a future, it should log like a daemon thread (and similarly // for a user-facing thread). self.handle.block_on(future_with_correct_context(future)) } /// /// Spawn a Future on a threadpool specifically reserved for I/O tasks which are allowed to be /// long-running. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, rescue_join_error: impl FnOnce(JoinError) -> R, ) -> impl Future<Output = R> { self.native_spawn_blocking(f).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Spawn a Future on threads specifically reserved for I/O tasks which are allowed to be /// long-running and return a JoinHandle /// pub fn native_spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, ) -> JoinHandle<R> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: We unwrap here because the only thing that should cause an error in a spawned task is a // panic, in which case we want to propagate that. self.handle.spawn_blocking(move || { stdio::set_thread_destination(stdio_destination); workunit_store::set_thread_workunit_store_handle(workunit_store_handle); f() }) } /// Return a reference to this executor's runtime handle. pub fn handle(&self) -> &Handle { &self.handle } /// /// A blocking call to shut down the Runtime associated with this "owned" Executor. If tasks do /// not shut down within the given timeout, they are leaked. /// /// This method has no effect for "borrowed" Executors: see the `Executor` rustdoc. /// pub fn shutdown(&self, timeout: Duration) { let Some(runtime) = self.runtime.lock().take() else { return; }; let start = Instant::now(); runtime.shutdown_timeout(timeout + Duration::from_millis(250)); if start.elapsed() > timeout { // Leaked tasks could lead to panics in some cases (see #16105), so warn for them. log::warn!("Executor shutdown took unexpectedly long: tasks were likely leaked!"); } } /// Returns true if `shutdown` has been called for this Executor. Always returns true for /// borrowed Executors. pub fn is_shutdown(&self) -> bool { self.runtime.lock().is_none() } } /// Store "tail" tasks which are async tasks that can execute concurrently with regular /// build actions. Tail tasks block completion of a session until all of them have been /// completed (subject to a timeout). #[derive(Clone)] pub struct TailTasks { inner: Arc<Mutex<Option<TailTasksInner>>>, } struct TailTasksInner { id_to_name: HashMap<Id, String>, task_set: JoinSet<()>, } impl TailTasks { pub fn new() -> Self { Self { inner: Arc::new(Mutex::new(Some(TailTasksInner { id_to_name: HashMap::new(), task_set: JoinSet::new(), }))), } } /// Spawn a tail task with the given name. pub fn spawn_on<F>(&self, name: &str, handle: &Handle, task: F) where F: Future<Output = ()>, F: Send +'static, { let task = future_with_correct_context(task); let mut guard = self.inner.lock(); let inner = match &mut *guard { Some(inner) => inner, None => { log::warn!( "Session end task `{}` submitted after session completed.", name ); return; } }; let h = inner.task_set.spawn_on(task, handle); inner.id_to_name.insert(h.id(), name.to_string()); } /// Wait for all tail tasks to complete subject to the given timeout. If tasks /// fail or do not complete, log that fact. pub async fn wait(self, timeout: Duration) { let mut inner = match self.inner.lock().take() { Some(inner) => inner, None => { log::debug!("Session end tasks awaited multiple times!"); return; } }; if inner.task_set.is_empty() { return; } log::debug!( "waiting for {} session end task(s) to complete", inner.task_set.len() ); let mut timeout = tokio::time::sleep(timeout).boxed(); loop { tokio::select! { // Use biased mode to prefer an expired timeout over joining on remaining tasks. biased; // Exit monitoring loop if timeout expires. _ = &mut timeout => break, next_result = inner.task_set.join_next_with_id() => { match next_result { Some(Ok((id, _))) => { if let Some(name) = inner.id_to_name.get(&id) { log::trace!("Session end task `{name}` completed successfully"); } else { log::debug!("Session end task completed successfully but name not found."); } inner.id_to_name.remove(&id); }, Some(Err(err)) => { let name = inner.id_to_name.get(&err.id()); log::error!("Session end task `{name:?}` failed: {err:?}"); } None => break, } } } } if inner.task_set.is_empty() { log::debug!("all session end tasks completed successfully"); } else { log::debug!( "{} session end task(s) failed to complete within timeout: {}", inner.task_set.len(), inner.id_to_name.values().join(", "), ); inner.task_set.abort_all(); } } }
{ let _context = self.handle.enter(); f() }
identifier_body
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] use std::collections::HashMap; use std::env; use std::future::Future; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::future::FutureExt; use itertools::Itertools; use parking_lot::Mutex; use tokio::runtime::{Builder, Handle, Runtime}; use tokio::task::{Id, JoinError, JoinHandle, JoinSet}; /// Copy our (thread-local or task-local) stdio destination and current workunit parent into /// the task. The former ensures that when a pantsd thread kicks off a future, any stdio done /// by it ends up in the pantsd log as we expect. The latter ensures that when a new workunit /// is created it has an accurate handle to its parent. fn future_with_correct_context<F: Future>(future: F) -> impl Future<Output = F::Output> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: It is important that the first portion of this method is synchronous (meaning that this // method cannot be `async`), because that means that it will run on the thread that calls it. // The second, async portion of the method will run in the spawned Task. stdio::scope_task_destination(stdio_destination, async move { workunit_store::scope_task_workunit_store_handle(workunit_store_handle, future).await }) } /// /// Executors come in two flavors: /// * "borrowed" /// * Created with `Self::new()`, or `self::to_borrowed()`. /// * A borrowed Executor will not be shut down when all handles are dropped, and shutdown /// methods will have no impact. /// * Used when multiple runs of Pants will borrow a single Executor owned by `pantsd`, and in /// unit tests where the Runtime is created by macros. /// * "owned" /// * Created with `Self::new_owned()`. /// * When all handles of a owned Executor are dropped, its Runtime will be shut down. /// Additionally, the explicit shutdown methods can be used to shut down the Executor for all /// clones. /// #[derive(Debug, Clone)] pub struct Executor { runtime: Arc<Mutex<Option<Runtime>>>, handle: Handle, } impl Executor { /// /// Creates an Executor for an existing tokio::Runtime (generally provided by tokio's macros). /// /// The returned Executor will have a lifecycle independent of the Runtime, meaning that dropping /// all clones of the Executor will not cause the Runtime to be shut down. Likewise, the owner of /// the Runtime must ensure that it is kept alive longer than all Executor instances, because /// existence of a Handle does not prevent a Runtime from shutting down. This is guaranteed by /// the scope of the tokio::{test, main} macros. /// pub fn new() -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: Handle::current(), } } /// /// Gets a reference to a global static Executor with an owned tokio::Runtime, initializing it /// with the given thread configuration if this is the first usage. /// /// NB: The global static Executor eases lifecycle issues when consumed from Python, where we /// need thread configurability, but also want to know reliably when the Runtime will shutdown /// (which, because it is static, will only be at the entire process' exit). /// pub fn new_owned<F>( num_worker_threads: usize, max_threads: usize, on_thread_start: F, ) -> Result<Executor, String> where F: Fn() + Send + Sync +'static, { let mut runtime_builder = Builder::new_multi_thread(); runtime_builder .worker_threads(num_worker_threads) .max_blocking_threads(max_threads - num_worker_threads) .enable_all(); if env::var("PANTS_DEBUG").is_ok() { runtime_builder.on_thread_start(on_thread_start); }; let runtime = runtime_builder .build() .map_err(|e| format!("Failed to start the runtime: {e}"))?; let handle = runtime.handle().clone(); Ok(Executor { runtime: Arc::new(Mutex::new(Some(runtime))), handle, }) } /// /// Creates a clone of this Executor which is disconnected from shutdown events. See the `Executor` /// rustdoc. /// pub fn to_borrowed(&self) -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: self.handle.clone(), } } /// /// Enter the runtime context associated with this Executor. This should be used in situations /// where threads not started by the runtime need access to it via task-local variables. /// pub fn enter<F, R>(&self, f: F) -> R where F: FnOnce() -> R, { let _context = self.handle.enter(); f() } /// /// Run a Future on a tokio Runtime as a new Task, and return a Future handle to it. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, rescue_join_error: impl FnOnce(JoinError) -> O, ) -> impl Future<Output = O> { self.native_spawn(future).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Run a Future on a tokio Runtime as a new Task, and return a JoinHandle. /// pub fn native_spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, ) -> JoinHandle<O> { self.handle.spawn(future_with_correct_context(future)) } /// /// Run a Future and return its resolved Result. /// /// This should never be called from in a Future context, and should only ever be called in /// something that resembles a main method. /// /// Even after this method returns, work `spawn`ed into the background may continue to run on the /// threads owned by this Executor. /// pub fn block_on<F: Future>(&self, future: F) -> F::Output { // Make sure to copy our (thread-local) logging destination into the task. // When a daemon thread kicks off a future, it should log like a daemon thread (and similarly // for a user-facing thread). self.handle.block_on(future_with_correct_context(future)) } /// /// Spawn a Future on a threadpool specifically reserved for I/O tasks which are allowed to be /// long-running. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, rescue_join_error: impl FnOnce(JoinError) -> R, ) -> impl Future<Output = R> { self.native_spawn_blocking(f).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Spawn a Future on threads specifically reserved for I/O tasks which are allowed to be /// long-running and return a JoinHandle /// pub fn native_spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, ) -> JoinHandle<R> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: We unwrap here because the only thing that should cause an error in a spawned task is a // panic, in which case we want to propagate that. self.handle.spawn_blocking(move || { stdio::set_thread_destination(stdio_destination); workunit_store::set_thread_workunit_store_handle(workunit_store_handle); f() }) } /// Return a reference to this executor's runtime handle. pub fn handle(&self) -> &Handle { &self.handle } /// /// A blocking call to shut down the Runtime associated with this "owned" Executor. If tasks do /// not shut down within the given timeout, they are leaked. /// /// This method has no effect for "borrowed" Executors: see the `Executor` rustdoc. /// pub fn shutdown(&self, timeout: Duration) { let Some(runtime) = self.runtime.lock().take() else { return; }; let start = Instant::now(); runtime.shutdown_timeout(timeout + Duration::from_millis(250)); if start.elapsed() > timeout { // Leaked tasks could lead to panics in some cases (see #16105), so warn for them. log::warn!("Executor shutdown took unexpectedly long: tasks were likely leaked!"); } } /// Returns true if `shutdown` has been called for this Executor. Always returns true for /// borrowed Executors. pub fn is_shutdown(&self) -> bool { self.runtime.lock().is_none() } } /// Store "tail" tasks which are async tasks that can execute concurrently with regular /// build actions. Tail tasks block completion of a session until all of them have been /// completed (subject to a timeout). #[derive(Clone)] pub struct TailTasks { inner: Arc<Mutex<Option<TailTasksInner>>>, } struct TailTasksInner { id_to_name: HashMap<Id, String>, task_set: JoinSet<()>, } impl TailTasks { pub fn new() -> Self { Self { inner: Arc::new(Mutex::new(Some(TailTasksInner { id_to_name: HashMap::new(), task_set: JoinSet::new(), }))), } } /// Spawn a tail task with the given name. pub fn spawn_on<F>(&self, name: &str, handle: &Handle, task: F) where F: Future<Output = ()>, F: Send +'static, { let task = future_with_correct_context(task); let mut guard = self.inner.lock(); let inner = match &mut *guard { Some(inner) => inner, None => { log::warn!( "Session end task `{}` submitted after session completed.", name ); return; } }; let h = inner.task_set.spawn_on(task, handle); inner.id_to_name.insert(h.id(), name.to_string()); } /// Wait for all tail tasks to complete subject to the given timeout. If tasks /// fail or do not complete, log that fact. pub async fn wait(self, timeout: Duration) { let mut inner = match self.inner.lock().take() { Some(inner) => inner, None => { log::debug!("Session end tasks awaited multiple times!"); return; } };
log::debug!( "waiting for {} session end task(s) to complete", inner.task_set.len() ); let mut timeout = tokio::time::sleep(timeout).boxed(); loop { tokio::select! { // Use biased mode to prefer an expired timeout over joining on remaining tasks. biased; // Exit monitoring loop if timeout expires. _ = &mut timeout => break, next_result = inner.task_set.join_next_with_id() => { match next_result { Some(Ok((id, _))) => { if let Some(name) = inner.id_to_name.get(&id) { log::trace!("Session end task `{name}` completed successfully"); } else { log::debug!("Session end task completed successfully but name not found."); } inner.id_to_name.remove(&id); }, Some(Err(err)) => { let name = inner.id_to_name.get(&err.id()); log::error!("Session end task `{name:?}` failed: {err:?}"); } None => break, } } } } if inner.task_set.is_empty() { log::debug!("all session end tasks completed successfully"); } else { log::debug!( "{} session end task(s) failed to complete within timeout: {}", inner.task_set.len(), inner.id_to_name.values().join(", "), ); inner.task_set.abort_all(); } } }
if inner.task_set.is_empty() { return; }
random_line_split
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] use std::collections::HashMap; use std::env; use std::future::Future; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::future::FutureExt; use itertools::Itertools; use parking_lot::Mutex; use tokio::runtime::{Builder, Handle, Runtime}; use tokio::task::{Id, JoinError, JoinHandle, JoinSet}; /// Copy our (thread-local or task-local) stdio destination and current workunit parent into /// the task. The former ensures that when a pantsd thread kicks off a future, any stdio done /// by it ends up in the pantsd log as we expect. The latter ensures that when a new workunit /// is created it has an accurate handle to its parent. fn future_with_correct_context<F: Future>(future: F) -> impl Future<Output = F::Output> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: It is important that the first portion of this method is synchronous (meaning that this // method cannot be `async`), because that means that it will run on the thread that calls it. // The second, async portion of the method will run in the spawned Task. stdio::scope_task_destination(stdio_destination, async move { workunit_store::scope_task_workunit_store_handle(workunit_store_handle, future).await }) } /// /// Executors come in two flavors: /// * "borrowed" /// * Created with `Self::new()`, or `self::to_borrowed()`. /// * A borrowed Executor will not be shut down when all handles are dropped, and shutdown /// methods will have no impact. /// * Used when multiple runs of Pants will borrow a single Executor owned by `pantsd`, and in /// unit tests where the Runtime is created by macros. /// * "owned" /// * Created with `Self::new_owned()`. /// * When all handles of a owned Executor are dropped, its Runtime will be shut down. /// Additionally, the explicit shutdown methods can be used to shut down the Executor for all /// clones. /// #[derive(Debug, Clone)] pub struct Executor { runtime: Arc<Mutex<Option<Runtime>>>, handle: Handle, } impl Executor { /// /// Creates an Executor for an existing tokio::Runtime (generally provided by tokio's macros). /// /// The returned Executor will have a lifecycle independent of the Runtime, meaning that dropping /// all clones of the Executor will not cause the Runtime to be shut down. Likewise, the owner of /// the Runtime must ensure that it is kept alive longer than all Executor instances, because /// existence of a Handle does not prevent a Runtime from shutting down. This is guaranteed by /// the scope of the tokio::{test, main} macros. /// pub fn new() -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: Handle::current(), } } /// /// Gets a reference to a global static Executor with an owned tokio::Runtime, initializing it /// with the given thread configuration if this is the first usage. /// /// NB: The global static Executor eases lifecycle issues when consumed from Python, where we /// need thread configurability, but also want to know reliably when the Runtime will shutdown /// (which, because it is static, will only be at the entire process' exit). /// pub fn new_owned<F>( num_worker_threads: usize, max_threads: usize, on_thread_start: F, ) -> Result<Executor, String> where F: Fn() + Send + Sync +'static, { let mut runtime_builder = Builder::new_multi_thread(); runtime_builder .worker_threads(num_worker_threads) .max_blocking_threads(max_threads - num_worker_threads) .enable_all(); if env::var("PANTS_DEBUG").is_ok() { runtime_builder.on_thread_start(on_thread_start); }; let runtime = runtime_builder .build() .map_err(|e| format!("Failed to start the runtime: {e}"))?; let handle = runtime.handle().clone(); Ok(Executor { runtime: Arc::new(Mutex::new(Some(runtime))), handle, }) } /// /// Creates a clone of this Executor which is disconnected from shutdown events. See the `Executor` /// rustdoc. /// pub fn to_borrowed(&self) -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: self.handle.clone(), } } /// /// Enter the runtime context associated with this Executor. This should be used in situations /// where threads not started by the runtime need access to it via task-local variables. /// pub fn enter<F, R>(&self, f: F) -> R where F: FnOnce() -> R, { let _context = self.handle.enter(); f() } /// /// Run a Future on a tokio Runtime as a new Task, and return a Future handle to it. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, rescue_join_error: impl FnOnce(JoinError) -> O, ) -> impl Future<Output = O> { self.native_spawn(future).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Run a Future on a tokio Runtime as a new Task, and return a JoinHandle. /// pub fn native_spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, ) -> JoinHandle<O> { self.handle.spawn(future_with_correct_context(future)) } /// /// Run a Future and return its resolved Result. /// /// This should never be called from in a Future context, and should only ever be called in /// something that resembles a main method. /// /// Even after this method returns, work `spawn`ed into the background may continue to run on the /// threads owned by this Executor. /// pub fn block_on<F: Future>(&self, future: F) -> F::Output { // Make sure to copy our (thread-local) logging destination into the task. // When a daemon thread kicks off a future, it should log like a daemon thread (and similarly // for a user-facing thread). self.handle.block_on(future_with_correct_context(future)) } /// /// Spawn a Future on a threadpool specifically reserved for I/O tasks which are allowed to be /// long-running. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, rescue_join_error: impl FnOnce(JoinError) -> R, ) -> impl Future<Output = R> { self.native_spawn_blocking(f).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Spawn a Future on threads specifically reserved for I/O tasks which are allowed to be /// long-running and return a JoinHandle /// pub fn native_spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, ) -> JoinHandle<R> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: We unwrap here because the only thing that should cause an error in a spawned task is a // panic, in which case we want to propagate that. self.handle.spawn_blocking(move || { stdio::set_thread_destination(stdio_destination); workunit_store::set_thread_workunit_store_handle(workunit_store_handle); f() }) } /// Return a reference to this executor's runtime handle. pub fn handle(&self) -> &Handle { &self.handle } /// /// A blocking call to shut down the Runtime associated with this "owned" Executor. If tasks do /// not shut down within the given timeout, they are leaked. /// /// This method has no effect for "borrowed" Executors: see the `Executor` rustdoc. /// pub fn shutdown(&self, timeout: Duration) { let Some(runtime) = self.runtime.lock().take() else { return; }; let start = Instant::now(); runtime.shutdown_timeout(timeout + Duration::from_millis(250)); if start.elapsed() > timeout { // Leaked tasks could lead to panics in some cases (see #16105), so warn for them. log::warn!("Executor shutdown took unexpectedly long: tasks were likely leaked!"); } } /// Returns true if `shutdown` has been called for this Executor. Always returns true for /// borrowed Executors. pub fn is_shutdown(&self) -> bool { self.runtime.lock().is_none() } } /// Store "tail" tasks which are async tasks that can execute concurrently with regular /// build actions. Tail tasks block completion of a session until all of them have been /// completed (subject to a timeout). #[derive(Clone)] pub struct TailTasks { inner: Arc<Mutex<Option<TailTasksInner>>>, } struct TailTasksInner { id_to_name: HashMap<Id, String>, task_set: JoinSet<()>, } impl TailTasks { pub fn new() -> Self { Self { inner: Arc::new(Mutex::new(Some(TailTasksInner { id_to_name: HashMap::new(), task_set: JoinSet::new(), }))), } } /// Spawn a tail task with the given name. pub fn
<F>(&self, name: &str, handle: &Handle, task: F) where F: Future<Output = ()>, F: Send +'static, { let task = future_with_correct_context(task); let mut guard = self.inner.lock(); let inner = match &mut *guard { Some(inner) => inner, None => { log::warn!( "Session end task `{}` submitted after session completed.", name ); return; } }; let h = inner.task_set.spawn_on(task, handle); inner.id_to_name.insert(h.id(), name.to_string()); } /// Wait for all tail tasks to complete subject to the given timeout. If tasks /// fail or do not complete, log that fact. pub async fn wait(self, timeout: Duration) { let mut inner = match self.inner.lock().take() { Some(inner) => inner, None => { log::debug!("Session end tasks awaited multiple times!"); return; } }; if inner.task_set.is_empty() { return; } log::debug!( "waiting for {} session end task(s) to complete", inner.task_set.len() ); let mut timeout = tokio::time::sleep(timeout).boxed(); loop { tokio::select! { // Use biased mode to prefer an expired timeout over joining on remaining tasks. biased; // Exit monitoring loop if timeout expires. _ = &mut timeout => break, next_result = inner.task_set.join_next_with_id() => { match next_result { Some(Ok((id, _))) => { if let Some(name) = inner.id_to_name.get(&id) { log::trace!("Session end task `{name}` completed successfully"); } else { log::debug!("Session end task completed successfully but name not found."); } inner.id_to_name.remove(&id); }, Some(Err(err)) => { let name = inner.id_to_name.get(&err.id()); log::error!("Session end task `{name:?}` failed: {err:?}"); } None => break, } } } } if inner.task_set.is_empty() { log::debug!("all session end tasks completed successfully"); } else { log::debug!( "{} session end task(s) failed to complete within timeout: {}", inner.task_set.len(), inner.id_to_name.values().join(", "), ); inner.task_set.abort_all(); } } }
spawn_on
identifier_name
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] use std::collections::HashMap; use std::env; use std::future::Future; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::future::FutureExt; use itertools::Itertools; use parking_lot::Mutex; use tokio::runtime::{Builder, Handle, Runtime}; use tokio::task::{Id, JoinError, JoinHandle, JoinSet}; /// Copy our (thread-local or task-local) stdio destination and current workunit parent into /// the task. The former ensures that when a pantsd thread kicks off a future, any stdio done /// by it ends up in the pantsd log as we expect. The latter ensures that when a new workunit /// is created it has an accurate handle to its parent. fn future_with_correct_context<F: Future>(future: F) -> impl Future<Output = F::Output> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: It is important that the first portion of this method is synchronous (meaning that this // method cannot be `async`), because that means that it will run on the thread that calls it. // The second, async portion of the method will run in the spawned Task. stdio::scope_task_destination(stdio_destination, async move { workunit_store::scope_task_workunit_store_handle(workunit_store_handle, future).await }) } /// /// Executors come in two flavors: /// * "borrowed" /// * Created with `Self::new()`, or `self::to_borrowed()`. /// * A borrowed Executor will not be shut down when all handles are dropped, and shutdown /// methods will have no impact. /// * Used when multiple runs of Pants will borrow a single Executor owned by `pantsd`, and in /// unit tests where the Runtime is created by macros. /// * "owned" /// * Created with `Self::new_owned()`. /// * When all handles of a owned Executor are dropped, its Runtime will be shut down. /// Additionally, the explicit shutdown methods can be used to shut down the Executor for all /// clones. /// #[derive(Debug, Clone)] pub struct Executor { runtime: Arc<Mutex<Option<Runtime>>>, handle: Handle, } impl Executor { /// /// Creates an Executor for an existing tokio::Runtime (generally provided by tokio's macros). /// /// The returned Executor will have a lifecycle independent of the Runtime, meaning that dropping /// all clones of the Executor will not cause the Runtime to be shut down. Likewise, the owner of /// the Runtime must ensure that it is kept alive longer than all Executor instances, because /// existence of a Handle does not prevent a Runtime from shutting down. This is guaranteed by /// the scope of the tokio::{test, main} macros. /// pub fn new() -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: Handle::current(), } } /// /// Gets a reference to a global static Executor with an owned tokio::Runtime, initializing it /// with the given thread configuration if this is the first usage. /// /// NB: The global static Executor eases lifecycle issues when consumed from Python, where we /// need thread configurability, but also want to know reliably when the Runtime will shutdown /// (which, because it is static, will only be at the entire process' exit). /// pub fn new_owned<F>( num_worker_threads: usize, max_threads: usize, on_thread_start: F, ) -> Result<Executor, String> where F: Fn() + Send + Sync +'static, { let mut runtime_builder = Builder::new_multi_thread(); runtime_builder .worker_threads(num_worker_threads) .max_blocking_threads(max_threads - num_worker_threads) .enable_all(); if env::var("PANTS_DEBUG").is_ok() { runtime_builder.on_thread_start(on_thread_start); }; let runtime = runtime_builder .build() .map_err(|e| format!("Failed to start the runtime: {e}"))?; let handle = runtime.handle().clone(); Ok(Executor { runtime: Arc::new(Mutex::new(Some(runtime))), handle, }) } /// /// Creates a clone of this Executor which is disconnected from shutdown events. See the `Executor` /// rustdoc. /// pub fn to_borrowed(&self) -> Executor { Self { runtime: Arc::new(Mutex::new(None)), handle: self.handle.clone(), } } /// /// Enter the runtime context associated with this Executor. This should be used in situations /// where threads not started by the runtime need access to it via task-local variables. /// pub fn enter<F, R>(&self, f: F) -> R where F: FnOnce() -> R, { let _context = self.handle.enter(); f() } /// /// Run a Future on a tokio Runtime as a new Task, and return a Future handle to it. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, rescue_join_error: impl FnOnce(JoinError) -> O, ) -> impl Future<Output = O> { self.native_spawn(future).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Run a Future on a tokio Runtime as a new Task, and return a JoinHandle. /// pub fn native_spawn<O: Send +'static, F: Future<Output = O> + Send +'static>( &self, future: F, ) -> JoinHandle<O> { self.handle.spawn(future_with_correct_context(future)) } /// /// Run a Future and return its resolved Result. /// /// This should never be called from in a Future context, and should only ever be called in /// something that resembles a main method. /// /// Even after this method returns, work `spawn`ed into the background may continue to run on the /// threads owned by this Executor. /// pub fn block_on<F: Future>(&self, future: F) -> F::Output { // Make sure to copy our (thread-local) logging destination into the task. // When a daemon thread kicks off a future, it should log like a daemon thread (and similarly // for a user-facing thread). self.handle.block_on(future_with_correct_context(future)) } /// /// Spawn a Future on a threadpool specifically reserved for I/O tasks which are allowed to be /// long-running. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, the computation will still continue to completion: see /// <https://docs.rs/tokio/0.2.20/tokio/task/struct.JoinHandle.html> /// pub fn spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, rescue_join_error: impl FnOnce(JoinError) -> R, ) -> impl Future<Output = R> { self.native_spawn_blocking(f).map(|res| match res { Ok(o) => o, Err(e) => rescue_join_error(e), }) } /// /// Spawn a Future on threads specifically reserved for I/O tasks which are allowed to be /// long-running and return a JoinHandle /// pub fn native_spawn_blocking<F: FnOnce() -> R + Send +'static, R: Send +'static>( &self, f: F, ) -> JoinHandle<R> { let stdio_destination = stdio::get_destination(); let workunit_store_handle = workunit_store::get_workunit_store_handle(); // NB: We unwrap here because the only thing that should cause an error in a spawned task is a // panic, in which case we want to propagate that. self.handle.spawn_blocking(move || { stdio::set_thread_destination(stdio_destination); workunit_store::set_thread_workunit_store_handle(workunit_store_handle); f() }) } /// Return a reference to this executor's runtime handle. pub fn handle(&self) -> &Handle { &self.handle } /// /// A blocking call to shut down the Runtime associated with this "owned" Executor. If tasks do /// not shut down within the given timeout, they are leaked. /// /// This method has no effect for "borrowed" Executors: see the `Executor` rustdoc. /// pub fn shutdown(&self, timeout: Duration) { let Some(runtime) = self.runtime.lock().take() else { return; }; let start = Instant::now(); runtime.shutdown_timeout(timeout + Duration::from_millis(250)); if start.elapsed() > timeout { // Leaked tasks could lead to panics in some cases (see #16105), so warn for them. log::warn!("Executor shutdown took unexpectedly long: tasks were likely leaked!"); } } /// Returns true if `shutdown` has been called for this Executor. Always returns true for /// borrowed Executors. pub fn is_shutdown(&self) -> bool { self.runtime.lock().is_none() } } /// Store "tail" tasks which are async tasks that can execute concurrently with regular /// build actions. Tail tasks block completion of a session until all of them have been /// completed (subject to a timeout). #[derive(Clone)] pub struct TailTasks { inner: Arc<Mutex<Option<TailTasksInner>>>, } struct TailTasksInner { id_to_name: HashMap<Id, String>, task_set: JoinSet<()>, } impl TailTasks { pub fn new() -> Self { Self { inner: Arc::new(Mutex::new(Some(TailTasksInner { id_to_name: HashMap::new(), task_set: JoinSet::new(), }))), } } /// Spawn a tail task with the given name. pub fn spawn_on<F>(&self, name: &str, handle: &Handle, task: F) where F: Future<Output = ()>, F: Send +'static, { let task = future_with_correct_context(task); let mut guard = self.inner.lock(); let inner = match &mut *guard { Some(inner) => inner, None => { log::warn!( "Session end task `{}` submitted after session completed.", name ); return; } }; let h = inner.task_set.spawn_on(task, handle); inner.id_to_name.insert(h.id(), name.to_string()); } /// Wait for all tail tasks to complete subject to the given timeout. If tasks /// fail or do not complete, log that fact. pub async fn wait(self, timeout: Duration) { let mut inner = match self.inner.lock().take() { Some(inner) => inner, None => { log::debug!("Session end tasks awaited multiple times!"); return; } }; if inner.task_set.is_empty() { return; } log::debug!( "waiting for {} session end task(s) to complete", inner.task_set.len() ); let mut timeout = tokio::time::sleep(timeout).boxed(); loop { tokio::select! { // Use biased mode to prefer an expired timeout over joining on remaining tasks. biased; // Exit monitoring loop if timeout expires. _ = &mut timeout => break, next_result = inner.task_set.join_next_with_id() => { match next_result { Some(Ok((id, _))) => { if let Some(name) = inner.id_to_name.get(&id) { log::trace!("Session end task `{name}` completed successfully"); } else { log::debug!("Session end task completed successfully but name not found."); } inner.id_to_name.remove(&id); }, Some(Err(err)) => { let name = inner.id_to_name.get(&err.id()); log::error!("Session end task `{name:?}` failed: {err:?}"); } None => break, } } } } if inner.task_set.is_empty() { log::debug!("all session end tasks completed successfully"); } else
} }
{ log::debug!( "{} session end task(s) failed to complete within timeout: {}", inner.task_set.len(), inner.id_to_name.values().join(", "), ); inner.task_set.abort_all(); }
conditional_block
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtime_environ::ir; pub use self::tls::TlsRestore; extern "C" { fn RegisterSetjmp( jmp_buf: *mut *const u8, callback: extern "C" fn(*mut u8), payload: *mut u8, ) -> i32; fn Unwind(jmp_buf: *const u8) ->!; } cfg_if::cfg_if! { if #[cfg(target_os = "macos")] { mod macos; use macos as sys; } else if #[cfg(unix)] { mod unix; use unix as sys; } else if #[cfg(target_os = "windows")] { mod windows; use windows as sys; } } pub use sys::SignalHandler; /// This function performs the low-overhead platform-specific initialization /// that we want to do eagerly to ensure a more-deterministic global process /// state. /// /// This is especially relevant for signal handlers since handler ordering /// depends on installation order: the wasm signal handler must run *before* /// the other crash handlers and since POSIX signal handlers work LIFO, this /// function needs to be called at the end of the startup process, after other /// handlers have been installed. This function can thus be called multiple /// times, having no effect after the first call. pub fn init_traps() { static INIT: Once = Once::new(); INIT.call_once(|| unsafe { sys::platform_init() }); } /// Raises a user-defined trap immediately. /// /// This function performs as-if a wasm trap was just executed, only the trap /// has a dynamic payload associated with it which is user-provided. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_user_trap(data: Box<dyn Error + Send + Sync>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::UserTrap(data))) } /// Raises a trap from inside library code immediately. /// /// This function performs as-if a wasm trap was just executed. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_lib_trap(trap: Trap) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::LibTrap(trap))) } /// Carries a Rust panic across wasm code and resumes the panic on the other /// side. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn resume_panic(payload: Box<dyn Any + Send>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::Panic(payload))) } /// Stores trace message with backtrace. #[derive(Debug)] pub enum Trap { /// A user-raised trap through `raise_user_trap`. User(Box<dyn Error + Send + Sync>), /// A trap raised from jit code Jit { /// The program counter in JIT code where this trap happened. pc: usize, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, /// An indicator for whether this may have been a trap generated from an /// interrupt, used for switching what would otherwise be a stack /// overflow trap to be an interrupt trap. maybe_interrupted: bool, }, /// A trap raised from a wasm libcall Wasm { /// Code of the trap. trap_code: ir::TrapCode, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, }, /// A trap indicating that the runtime was unable to allocate sufficient memory. OOM { /// Native stack backtrace at the time the OOM occurred backtrace: Backtrace, }, } impl Trap { /// Construct a new Wasm trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn wasm(trap_code: ir::TrapCode) -> Self { let backtrace = Backtrace::new_unresolved(); Trap::Wasm { trap_code, backtrace, } } /// Construct a new OOM trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn oom() -> Self { let backtrace = Backtrace::new_unresolved(); Trap::OOM { backtrace } } } /// Catches any wasm traps that happen within the execution of `closure`, /// returning them as a `Result`. /// /// Highly unsafe since `closure` won't have any dtors run. pub unsafe fn catch_traps<F>(trap_info: &impl TrapInfo, mut closure: F) -> Result<(), Trap> where F: FnMut(), { sys::lazy_per_thread_init()?; return CallThreadState::new(trap_info).with(|cx| { RegisterSetjmp( cx.jmp_buf.as_ptr(), call_closure::<F>, &mut closure as *mut F as *mut u8, ) }); extern "C" fn call_closure<F>(payload: *mut u8) where F: FnMut(), { unsafe { (*(payload as *mut F))() } } } /// Runs `func` with the last `trap_info` object registered by `catch_traps`. /// /// Calls `func` with `None` if `catch_traps` wasn't previously called from this /// stack frame. pub fn with_last_info<R>(func: impl FnOnce(Option<&dyn Any>) -> R) -> R { tls::with(|state| func(state.map(|s| s.trap_info.as_any()))) } /// Invokes the contextually-defined context's out-of-gas function. /// /// (basically delegates to `wasmtime::Store::out_of_gas`) pub fn out_of_gas() { tls::with(|state| state.unwrap().trap_info.out_of_gas()) } /// Temporary state stored on the stack which is registered in the `tls` module /// below for calls into wasm. pub struct CallThreadState<'a> { unwind: Cell<UnwindReason>, jmp_buf: Cell<*const u8>, handling_trap: Cell<bool>, trap_info: &'a (dyn TrapInfo + 'a), prev: Cell<tls::Ptr>, } /// A package of functionality needed by `catch_traps` to figure out what to do /// when handling a trap. /// /// Note that this is an `unsafe` trait at least because it's being run in the /// context of a synchronous signal handler, so it needs to be careful to not /// access too much state in answering these queries. pub unsafe trait TrapInfo { /// Converts this object into an `Any` to dynamically check its type. fn as_any(&self) -> &dyn Any; /// Returns whether the given program counter lies within wasm code, /// indicating whether we should handle a trap or not. fn is_wasm_trap(&self, pc: usize) -> bool; /// Uses `call` to call a custom signal handler, if one is specified. /// /// Returns `true` if `call` returns true, otherwise returns `false`. fn custom_signal_handler(&self, call: &dyn Fn(&SignalHandler) -> bool) -> bool; /// Returns the maximum size, in bytes, the wasm native stack is allowed to /// grow to. fn max_wasm_stack(&self) -> usize; /// Callback invoked whenever WebAssembly has entirely consumed the fuel /// that it was allotted. /// /// This function may return, and it may also `raise_lib_trap`. fn out_of_gas(&self); /// Returns the VM interrupts to use for interrupting Wasm code. fn interrupts(&self) -> &VMInterrupts; } enum UnwindReason { None, Panic(Box<dyn Any + Send>), UserTrap(Box<dyn Error + Send + Sync>), LibTrap(Trap), JitTrap { backtrace: Backtrace, pc: usize }, } impl<'a> CallThreadState<'a> { fn new(trap_info: &'a (dyn TrapInfo + 'a)) -> CallThreadState<'a> { CallThreadState { unwind: Cell::new(UnwindReason::None), jmp_buf: Cell::new(ptr::null()), handling_trap: Cell::new(false), trap_info, prev: Cell::new(ptr::null()), } } fn with(self, closure: impl FnOnce(&CallThreadState) -> i32) -> Result<(), Trap>
backtrace, maybe_interrupted, }) } UnwindReason::Panic(panic) => { debug_assert_eq!(ret, 0); std::panic::resume_unwind(panic) } } } /// Checks and/or initializes the wasm native call stack limit. /// /// This function will inspect the current state of the stack and calling /// context to determine which of three buckets we're in: /// /// 1. We are the first wasm call on the stack. This means that we need to /// set up a stack limit where beyond which if the native wasm stack /// pointer goes beyond forces a trap. For now we simply reserve an /// arbitrary chunk of bytes (1 MB from roughly the current native stack /// pointer). This logic will likely get tweaked over time. /// /// 2. We aren't the first wasm call on the stack. In this scenario the wasm /// stack limit is already configured. This case of wasm -> host -> wasm /// we assume that the native stack consumed by the host is accounted for /// in the initial stack limit calculation. That means that in this /// scenario we do nothing. /// /// 3. We were previously interrupted. In this case we consume the interrupt /// here and return a trap, clearing the interrupt and allowing the next /// wasm call to proceed. /// /// The return value here is a trap for case 3, a noop destructor in case 2, /// and a meaningful destructor in case 1 /// /// For more information about interrupts and stack limits see /// `crates/environ/src/cranelift.rs`. /// /// Note that this function must be called with `self` on the stack, not the /// heap/etc. fn update_stack_limit(&self) -> Result<impl Drop + '_, Trap> { // Determine the stack pointer where, after which, any wasm code will // immediately trap. This is checked on the entry to all wasm functions. // // Note that this isn't 100% precise. We are requested to give wasm // `max_wasm_stack` bytes, but what we're actually doing is giving wasm // probably a little less than `max_wasm_stack` because we're // calculating the limit relative to this function's approximate stack // pointer. Wasm will be executed on a frame beneath this one (or next // to it). In any case it's expected to be at most a few hundred bytes // of slop one way or another. When wasm is typically given a MB or so // (a million bytes) the slop shouldn't matter too much. let wasm_stack_limit = psm::stack_pointer() as usize - self.trap_info.max_wasm_stack(); let interrupts = self.trap_info.interrupts(); let reset_stack_limit = match interrupts.stack_limit.compare_exchange( usize::max_value(), wasm_stack_limit, SeqCst, SeqCst, ) { Ok(_) => { // We're the first wasm on the stack so we've now reserved the // `max_wasm_stack` bytes of native stack space for wasm. // Nothing left to do here now except reset back when we're // done. true } Err(n) if n == wasmtime_environ::INTERRUPTED => { // This means that an interrupt happened before we actually // called this function, which means that we're now // considered interrupted. Be sure to consume this interrupt // as part of this process too. interrupts.stack_limit.store(usize::max_value(), SeqCst); return Err(Trap::Wasm { trap_code: ir::TrapCode::Interrupt, backtrace: Backtrace::new_unresolved(), }); } Err(_) => { // The stack limit was previously set by a previous wasm // call on the stack. We leave the original stack limit for // wasm in place in that case, and don't reset the stack // limit when we're done. false } }; struct Reset<'a>(bool, &'a AtomicUsize); impl Drop for Reset<'_> { fn drop(&mut self) { if self.0 { self.1.store(usize::max_value(), SeqCst); } } } Ok(Reset(reset_stack_limit, &interrupts.stack_limit)) } fn unwind_with(&self, reason: UnwindReason) ->! { self.unwind.replace(reason); unsafe { Unwind(self.jmp_buf.get()); } } /// Trap handler using our thread-local state. /// /// * `pc` - the program counter the trap happened at /// * `call_handler` - a closure used to invoke the platform-specific /// signal handler for each instance, if available. /// /// Attempts to handle the trap if it's a wasm trap. Returns a few /// different things: /// /// * null - the trap didn't look like a wasm trap and should continue as a /// trap /// * 1 as a pointer - the trap was handled by a custom trap handler on an /// instance, and the trap handler should quickly return. /// * a different pointer - a jmp_buf buffer to longjmp to, meaning that /// the wasm trap was succesfully handled. fn jmp_buf_if_trap( &self, pc: *const u8, call_handler: impl Fn(&SignalHandler) -> bool, ) -> *const u8 { // If we hit a fault while handling a previous trap, that's quite bad, // so bail out and let the system handle this recursive segfault. // // Otherwise flag ourselves as handling a trap, do the trap handling, // and reset our trap handling flag. if self.handling_trap.replace(true) { return ptr::null(); } let _reset = ResetCell(&self.handling_trap, false); // If we haven't even started to handle traps yet, bail out. if self.jmp_buf.get().is_null() { return ptr::null(); } // First up see if any instance registered has a custom trap handler, // in which case run them all. If anything handles the trap then we // return that the trap was handled. if self.trap_info.custom_signal_handler(&call_handler) { return 1 as *const _; } // If this fault wasn't in wasm code, then it's not our problem if!self.trap_info.is_wasm_trap(pc as usize) { return ptr::null(); } // If all that passed then this is indeed a wasm trap, so return the // `jmp_buf` passed to `Unwind` to resume. self.jmp_buf.get() } fn capture_backtrace(&self, pc: *const u8) { let backtrace = Backtrace::new_unresolved(); self.unwind.replace(UnwindReason::JitTrap { backtrace, pc: pc as usize, }); } } struct ResetCell<'a, T: Copy>(&'a Cell<T>, T); impl<T: Copy> Drop for ResetCell<'_, T> { fn drop(&mut self) { self.0.set(self.1); } } // A private inner module for managing the TLS state that we require across // calls in wasm. The WebAssembly code is called from C++ and then a trap may // happen which requires us to read some contextual state to figure out what to // do with the trap. This `tls` module is used to persist that information from // the caller to the trap site. mod tls { use super::CallThreadState; use std::mem; use std::ptr; pub use raw::Ptr; // An even *more* inner module for dealing with TLS. This actually has the // thread local variable and has functions to access the variable. // // Note that this is specially done to fully encapsulate that the accessors // for tls must not be inlined. Wasmtime's async support employs stack // switching which can resume execution on different OS threads. This means // that borrows of our TLS pointer must never live across accesses because // otherwise the access may be split across two threads and cause unsafety. // // This also means that extra care is taken by the runtime to save/restore // these TLS values when the runtime may have crossed threads. mod raw { use super::CallThreadState; use std::cell::Cell; use std::ptr; pub type Ptr = *const CallThreadState<'static>; thread_local!(static PTR: Cell<Ptr> = Cell::new(ptr::null())); #[inline(never)] // see module docs for why this is here pub fn replace(val: Ptr) -> Ptr { // Mark the current thread as handling interrupts for this specific // CallThreadState: may clobber the previous entry. super::super::sys::register_tls(val); PTR.with(|p| p.replace(val)) } #[inline(never)] // see module docs for why this is here pub fn get() -> Ptr { PTR.with(|p| p.get()) } } /// Opaque state used to help control TLS state across stack switches for /// async support. pub struct TlsRestore(raw::Ptr); impl TlsRestore { /// Takes the TLS state that is currently configured and returns a /// token that is used to replace it later. /// /// This is not a safe operation since it's intended to only be used /// with stack switching found with fibers and async wasmtime. pub unsafe fn take() -> TlsRestore { // Our tls pointer must be set at this time, and it must not be // null. We need to restore the previous pointer since we're // removing ourselves from the call-stack, and in the process we // null out our own previous field for safety in case it's // accidentally used later. let raw = raw::get(); assert!(!raw.is_null()); let prev = (*raw).prev.replace(ptr::null()); raw::replace(prev); TlsRestore(raw) } /// Restores a previous tls state back into this thread's TLS. /// /// This is unsafe because it's intended to only be used within the /// context of stack switching within wasmtime. pub unsafe fn replace(self) -> Result<(), super::Trap> { // When replacing to the previous value of TLS, we might have // crossed a thread: make sure the trap-handling lazy initializer // runs. super::sys::lazy_per_thread_init()?; // We need to configure our previous TLS pointer to whatever is in // TLS at this time, and then we set the current state to ourselves. let prev = raw::get(); assert!((*self.0).prev.get().is_null()); (*self.0).prev.set(prev); raw::replace(self.0); Ok(()) } } /// Configures thread local state such that for the duration of the /// execution of `closure` any call to `with` will yield `ptr`, unless this /// is recursively called again. pub fn set<R>(state: &CallThreadState<'_>, closure: impl FnOnce() -> R) -> R { struct Reset<'a, 'b>(&'a CallThreadState<'b>); impl Drop for Reset<'_, '_> { fn drop(&mut self) { raw::replace(self.0.prev.replace(ptr::null())); } } // Note that this extension of the lifetime to `'static` should be // safe because we only ever access it below with an anonymous // lifetime, meaning `'static` never leaks out of this module. let ptr = unsafe { mem::transmute::<*const CallThreadState<'_>, *const CallThreadState<'static>>(state) }; let prev = raw::replace(ptr); state.prev.set(prev); let _reset = Reset(state); closure() } /// Returns the last pointer configured with `set` above. Panics if `set` /// has not been previously called. pub fn with<R>(closure: impl FnOnce(Option<&CallThreadState<'_>>) -> R) -> R { let p = raw::get(); unsafe { closure(if p.is_null() { None } else { Some(&*p) }) } } }
{ let _reset = self.update_stack_limit()?; let ret = tls::set(&self, || closure(&self)); match self.unwind.replace(UnwindReason::None) { UnwindReason::None => { debug_assert_eq!(ret, 1); Ok(()) } UnwindReason::UserTrap(data) => { debug_assert_eq!(ret, 0); Err(Trap::User(data)) } UnwindReason::LibTrap(trap) => Err(trap), UnwindReason::JitTrap { backtrace, pc } => { debug_assert_eq!(ret, 0); let interrupts = self.trap_info.interrupts(); let maybe_interrupted = interrupts.stack_limit.load(SeqCst) == wasmtime_environ::INTERRUPTED; Err(Trap::Jit { pc,
identifier_body
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtime_environ::ir; pub use self::tls::TlsRestore; extern "C" { fn RegisterSetjmp( jmp_buf: *mut *const u8, callback: extern "C" fn(*mut u8), payload: *mut u8, ) -> i32; fn Unwind(jmp_buf: *const u8) ->!; } cfg_if::cfg_if! { if #[cfg(target_os = "macos")] { mod macos; use macos as sys; } else if #[cfg(unix)] { mod unix; use unix as sys; } else if #[cfg(target_os = "windows")] { mod windows; use windows as sys; } } pub use sys::SignalHandler; /// This function performs the low-overhead platform-specific initialization /// that we want to do eagerly to ensure a more-deterministic global process /// state. /// /// This is especially relevant for signal handlers since handler ordering /// depends on installation order: the wasm signal handler must run *before* /// the other crash handlers and since POSIX signal handlers work LIFO, this /// function needs to be called at the end of the startup process, after other /// handlers have been installed. This function can thus be called multiple /// times, having no effect after the first call. pub fn init_traps() { static INIT: Once = Once::new(); INIT.call_once(|| unsafe { sys::platform_init() }); } /// Raises a user-defined trap immediately. /// /// This function performs as-if a wasm trap was just executed, only the trap /// has a dynamic payload associated with it which is user-provided. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_user_trap(data: Box<dyn Error + Send + Sync>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::UserTrap(data))) } /// Raises a trap from inside library code immediately. /// /// This function performs as-if a wasm trap was just executed. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_lib_trap(trap: Trap) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::LibTrap(trap))) } /// Carries a Rust panic across wasm code and resumes the panic on the other /// side. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn resume_panic(payload: Box<dyn Any + Send>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::Panic(payload))) } /// Stores trace message with backtrace. #[derive(Debug)] pub enum Trap { /// A user-raised trap through `raise_user_trap`. User(Box<dyn Error + Send + Sync>), /// A trap raised from jit code Jit { /// The program counter in JIT code where this trap happened. pc: usize, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, /// An indicator for whether this may have been a trap generated from an /// interrupt, used for switching what would otherwise be a stack /// overflow trap to be an interrupt trap. maybe_interrupted: bool, }, /// A trap raised from a wasm libcall Wasm { /// Code of the trap. trap_code: ir::TrapCode, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, }, /// A trap indicating that the runtime was unable to allocate sufficient memory. OOM { /// Native stack backtrace at the time the OOM occurred backtrace: Backtrace, }, } impl Trap { /// Construct a new Wasm trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn wasm(trap_code: ir::TrapCode) -> Self { let backtrace = Backtrace::new_unresolved(); Trap::Wasm { trap_code, backtrace, } } /// Construct a new OOM trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn oom() -> Self { let backtrace = Backtrace::new_unresolved(); Trap::OOM { backtrace } } } /// Catches any wasm traps that happen within the execution of `closure`, /// returning them as a `Result`. /// /// Highly unsafe since `closure` won't have any dtors run. pub unsafe fn catch_traps<F>(trap_info: &impl TrapInfo, mut closure: F) -> Result<(), Trap> where F: FnMut(), { sys::lazy_per_thread_init()?; return CallThreadState::new(trap_info).with(|cx| { RegisterSetjmp( cx.jmp_buf.as_ptr(), call_closure::<F>, &mut closure as *mut F as *mut u8, ) }); extern "C" fn call_closure<F>(payload: *mut u8) where F: FnMut(), { unsafe { (*(payload as *mut F))() } } } /// Runs `func` with the last `trap_info` object registered by `catch_traps`. /// /// Calls `func` with `None` if `catch_traps` wasn't previously called from this /// stack frame. pub fn with_last_info<R>(func: impl FnOnce(Option<&dyn Any>) -> R) -> R { tls::with(|state| func(state.map(|s| s.trap_info.as_any()))) } /// Invokes the contextually-defined context's out-of-gas function. /// /// (basically delegates to `wasmtime::Store::out_of_gas`) pub fn out_of_gas() { tls::with(|state| state.unwrap().trap_info.out_of_gas()) } /// Temporary state stored on the stack which is registered in the `tls` module /// below for calls into wasm. pub struct CallThreadState<'a> { unwind: Cell<UnwindReason>, jmp_buf: Cell<*const u8>, handling_trap: Cell<bool>, trap_info: &'a (dyn TrapInfo + 'a), prev: Cell<tls::Ptr>, } /// A package of functionality needed by `catch_traps` to figure out what to do /// when handling a trap. /// /// Note that this is an `unsafe` trait at least because it's being run in the /// context of a synchronous signal handler, so it needs to be careful to not /// access too much state in answering these queries. pub unsafe trait TrapInfo { /// Converts this object into an `Any` to dynamically check its type. fn as_any(&self) -> &dyn Any; /// Returns whether the given program counter lies within wasm code, /// indicating whether we should handle a trap or not. fn is_wasm_trap(&self, pc: usize) -> bool; /// Uses `call` to call a custom signal handler, if one is specified. /// /// Returns `true` if `call` returns true, otherwise returns `false`. fn custom_signal_handler(&self, call: &dyn Fn(&SignalHandler) -> bool) -> bool; /// Returns the maximum size, in bytes, the wasm native stack is allowed to /// grow to. fn max_wasm_stack(&self) -> usize; /// Callback invoked whenever WebAssembly has entirely consumed the fuel /// that it was allotted. /// /// This function may return, and it may also `raise_lib_trap`. fn out_of_gas(&self); /// Returns the VM interrupts to use for interrupting Wasm code. fn interrupts(&self) -> &VMInterrupts; } enum UnwindReason { None, Panic(Box<dyn Any + Send>), UserTrap(Box<dyn Error + Send + Sync>), LibTrap(Trap), JitTrap { backtrace: Backtrace, pc: usize }, } impl<'a> CallThreadState<'a> { fn new(trap_info: &'a (dyn TrapInfo + 'a)) -> CallThreadState<'a> { CallThreadState { unwind: Cell::new(UnwindReason::None), jmp_buf: Cell::new(ptr::null()), handling_trap: Cell::new(false), trap_info, prev: Cell::new(ptr::null()), } } fn with(self, closure: impl FnOnce(&CallThreadState) -> i32) -> Result<(), Trap> { let _reset = self.update_stack_limit()?; let ret = tls::set(&self, || closure(&self)); match self.unwind.replace(UnwindReason::None) { UnwindReason::None => { debug_assert_eq!(ret, 1); Ok(()) } UnwindReason::UserTrap(data) => { debug_assert_eq!(ret, 0); Err(Trap::User(data)) } UnwindReason::LibTrap(trap) => Err(trap), UnwindReason::JitTrap { backtrace, pc } => { debug_assert_eq!(ret, 0); let interrupts = self.trap_info.interrupts(); let maybe_interrupted = interrupts.stack_limit.load(SeqCst) == wasmtime_environ::INTERRUPTED; Err(Trap::Jit { pc, backtrace, maybe_interrupted, }) } UnwindReason::Panic(panic) => { debug_assert_eq!(ret, 0); std::panic::resume_unwind(panic) } } } /// Checks and/or initializes the wasm native call stack limit. /// /// This function will inspect the current state of the stack and calling /// context to determine which of three buckets we're in: /// /// 1. We are the first wasm call on the stack. This means that we need to /// set up a stack limit where beyond which if the native wasm stack /// pointer goes beyond forces a trap. For now we simply reserve an /// arbitrary chunk of bytes (1 MB from roughly the current native stack /// pointer). This logic will likely get tweaked over time. /// /// 2. We aren't the first wasm call on the stack. In this scenario the wasm /// stack limit is already configured. This case of wasm -> host -> wasm /// we assume that the native stack consumed by the host is accounted for /// in the initial stack limit calculation. That means that in this /// scenario we do nothing. /// /// 3. We were previously interrupted. In this case we consume the interrupt /// here and return a trap, clearing the interrupt and allowing the next /// wasm call to proceed. /// /// The return value here is a trap for case 3, a noop destructor in case 2, /// and a meaningful destructor in case 1 /// /// For more information about interrupts and stack limits see /// `crates/environ/src/cranelift.rs`. /// /// Note that this function must be called with `self` on the stack, not the /// heap/etc. fn update_stack_limit(&self) -> Result<impl Drop + '_, Trap> { // Determine the stack pointer where, after which, any wasm code will // immediately trap. This is checked on the entry to all wasm functions. // // Note that this isn't 100% precise. We are requested to give wasm // `max_wasm_stack` bytes, but what we're actually doing is giving wasm // probably a little less than `max_wasm_stack` because we're // calculating the limit relative to this function's approximate stack // pointer. Wasm will be executed on a frame beneath this one (or next // to it). In any case it's expected to be at most a few hundred bytes // of slop one way or another. When wasm is typically given a MB or so // (a million bytes) the slop shouldn't matter too much. let wasm_stack_limit = psm::stack_pointer() as usize - self.trap_info.max_wasm_stack(); let interrupts = self.trap_info.interrupts(); let reset_stack_limit = match interrupts.stack_limit.compare_exchange( usize::max_value(), wasm_stack_limit, SeqCst, SeqCst, ) { Ok(_) => { // We're the first wasm on the stack so we've now reserved the // `max_wasm_stack` bytes of native stack space for wasm. // Nothing left to do here now except reset back when we're // done. true } Err(n) if n == wasmtime_environ::INTERRUPTED => { // This means that an interrupt happened before we actually // called this function, which means that we're now // considered interrupted. Be sure to consume this interrupt // as part of this process too. interrupts.stack_limit.store(usize::max_value(), SeqCst); return Err(Trap::Wasm { trap_code: ir::TrapCode::Interrupt, backtrace: Backtrace::new_unresolved(), }); } Err(_) => { // The stack limit was previously set by a previous wasm // call on the stack. We leave the original stack limit for // wasm in place in that case, and don't reset the stack // limit when we're done. false } }; struct Reset<'a>(bool, &'a AtomicUsize); impl Drop for Reset<'_> { fn drop(&mut self) { if self.0 { self.1.store(usize::max_value(), SeqCst); } } } Ok(Reset(reset_stack_limit, &interrupts.stack_limit)) } fn unwind_with(&self, reason: UnwindReason) ->! { self.unwind.replace(reason); unsafe { Unwind(self.jmp_buf.get()); } } /// Trap handler using our thread-local state. /// /// * `pc` - the program counter the trap happened at /// * `call_handler` - a closure used to invoke the platform-specific /// signal handler for each instance, if available. /// /// Attempts to handle the trap if it's a wasm trap. Returns a few /// different things: /// /// * null - the trap didn't look like a wasm trap and should continue as a /// trap /// * 1 as a pointer - the trap was handled by a custom trap handler on an /// instance, and the trap handler should quickly return. /// * a different pointer - a jmp_buf buffer to longjmp to, meaning that /// the wasm trap was succesfully handled. fn jmp_buf_if_trap( &self, pc: *const u8, call_handler: impl Fn(&SignalHandler) -> bool, ) -> *const u8 { // If we hit a fault while handling a previous trap, that's quite bad, // so bail out and let the system handle this recursive segfault. // // Otherwise flag ourselves as handling a trap, do the trap handling, // and reset our trap handling flag. if self.handling_trap.replace(true) { return ptr::null(); } let _reset = ResetCell(&self.handling_trap, false); // If we haven't even started to handle traps yet, bail out. if self.jmp_buf.get().is_null() { return ptr::null(); } // First up see if any instance registered has a custom trap handler, // in which case run them all. If anything handles the trap then we // return that the trap was handled. if self.trap_info.custom_signal_handler(&call_handler) { return 1 as *const _; } // If this fault wasn't in wasm code, then it's not our problem if!self.trap_info.is_wasm_trap(pc as usize) { return ptr::null(); } // If all that passed then this is indeed a wasm trap, so return the // `jmp_buf` passed to `Unwind` to resume. self.jmp_buf.get() } fn capture_backtrace(&self, pc: *const u8) { let backtrace = Backtrace::new_unresolved(); self.unwind.replace(UnwindReason::JitTrap { backtrace, pc: pc as usize, }); } } struct ResetCell<'a, T: Copy>(&'a Cell<T>, T); impl<T: Copy> Drop for ResetCell<'_, T> { fn drop(&mut self) { self.0.set(self.1); } } // A private inner module for managing the TLS state that we require across // calls in wasm. The WebAssembly code is called from C++ and then a trap may // happen which requires us to read some contextual state to figure out what to // do with the trap. This `tls` module is used to persist that information from // the caller to the trap site. mod tls { use super::CallThreadState; use std::mem; use std::ptr; pub use raw::Ptr; // An even *more* inner module for dealing with TLS. This actually has the // thread local variable and has functions to access the variable. // // Note that this is specially done to fully encapsulate that the accessors // for tls must not be inlined. Wasmtime's async support employs stack // switching which can resume execution on different OS threads. This means // that borrows of our TLS pointer must never live across accesses because // otherwise the access may be split across two threads and cause unsafety. // // This also means that extra care is taken by the runtime to save/restore // these TLS values when the runtime may have crossed threads. mod raw { use super::CallThreadState; use std::cell::Cell; use std::ptr; pub type Ptr = *const CallThreadState<'static>; thread_local!(static PTR: Cell<Ptr> = Cell::new(ptr::null())); #[inline(never)] // see module docs for why this is here pub fn
(val: Ptr) -> Ptr { // Mark the current thread as handling interrupts for this specific // CallThreadState: may clobber the previous entry. super::super::sys::register_tls(val); PTR.with(|p| p.replace(val)) } #[inline(never)] // see module docs for why this is here pub fn get() -> Ptr { PTR.with(|p| p.get()) } } /// Opaque state used to help control TLS state across stack switches for /// async support. pub struct TlsRestore(raw::Ptr); impl TlsRestore { /// Takes the TLS state that is currently configured and returns a /// token that is used to replace it later. /// /// This is not a safe operation since it's intended to only be used /// with stack switching found with fibers and async wasmtime. pub unsafe fn take() -> TlsRestore { // Our tls pointer must be set at this time, and it must not be // null. We need to restore the previous pointer since we're // removing ourselves from the call-stack, and in the process we // null out our own previous field for safety in case it's // accidentally used later. let raw = raw::get(); assert!(!raw.is_null()); let prev = (*raw).prev.replace(ptr::null()); raw::replace(prev); TlsRestore(raw) } /// Restores a previous tls state back into this thread's TLS. /// /// This is unsafe because it's intended to only be used within the /// context of stack switching within wasmtime. pub unsafe fn replace(self) -> Result<(), super::Trap> { // When replacing to the previous value of TLS, we might have // crossed a thread: make sure the trap-handling lazy initializer // runs. super::sys::lazy_per_thread_init()?; // We need to configure our previous TLS pointer to whatever is in // TLS at this time, and then we set the current state to ourselves. let prev = raw::get(); assert!((*self.0).prev.get().is_null()); (*self.0).prev.set(prev); raw::replace(self.0); Ok(()) } } /// Configures thread local state such that for the duration of the /// execution of `closure` any call to `with` will yield `ptr`, unless this /// is recursively called again. pub fn set<R>(state: &CallThreadState<'_>, closure: impl FnOnce() -> R) -> R { struct Reset<'a, 'b>(&'a CallThreadState<'b>); impl Drop for Reset<'_, '_> { fn drop(&mut self) { raw::replace(self.0.prev.replace(ptr::null())); } } // Note that this extension of the lifetime to `'static` should be // safe because we only ever access it below with an anonymous // lifetime, meaning `'static` never leaks out of this module. let ptr = unsafe { mem::transmute::<*const CallThreadState<'_>, *const CallThreadState<'static>>(state) }; let prev = raw::replace(ptr); state.prev.set(prev); let _reset = Reset(state); closure() } /// Returns the last pointer configured with `set` above. Panics if `set` /// has not been previously called. pub fn with<R>(closure: impl FnOnce(Option<&CallThreadState<'_>>) -> R) -> R { let p = raw::get(); unsafe { closure(if p.is_null() { None } else { Some(&*p) }) } } }
replace
identifier_name
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtime_environ::ir; pub use self::tls::TlsRestore; extern "C" { fn RegisterSetjmp( jmp_buf: *mut *const u8, callback: extern "C" fn(*mut u8), payload: *mut u8, ) -> i32; fn Unwind(jmp_buf: *const u8) ->!; } cfg_if::cfg_if! { if #[cfg(target_os = "macos")] { mod macos; use macos as sys; } else if #[cfg(unix)] { mod unix; use unix as sys; } else if #[cfg(target_os = "windows")] { mod windows; use windows as sys; } } pub use sys::SignalHandler; /// This function performs the low-overhead platform-specific initialization /// that we want to do eagerly to ensure a more-deterministic global process /// state. /// /// This is especially relevant for signal handlers since handler ordering /// depends on installation order: the wasm signal handler must run *before* /// the other crash handlers and since POSIX signal handlers work LIFO, this /// function needs to be called at the end of the startup process, after other /// handlers have been installed. This function can thus be called multiple /// times, having no effect after the first call. pub fn init_traps() { static INIT: Once = Once::new(); INIT.call_once(|| unsafe { sys::platform_init() }); } /// Raises a user-defined trap immediately. /// /// This function performs as-if a wasm trap was just executed, only the trap /// has a dynamic payload associated with it which is user-provided. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_user_trap(data: Box<dyn Error + Send + Sync>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::UserTrap(data))) } /// Raises a trap from inside library code immediately. /// /// This function performs as-if a wasm trap was just executed. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_lib_trap(trap: Trap) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::LibTrap(trap))) } /// Carries a Rust panic across wasm code and resumes the panic on the other /// side. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn resume_panic(payload: Box<dyn Any + Send>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::Panic(payload))) } /// Stores trace message with backtrace. #[derive(Debug)] pub enum Trap { /// A user-raised trap through `raise_user_trap`. User(Box<dyn Error + Send + Sync>), /// A trap raised from jit code Jit { /// The program counter in JIT code where this trap happened. pc: usize, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, /// An indicator for whether this may have been a trap generated from an /// interrupt, used for switching what would otherwise be a stack /// overflow trap to be an interrupt trap. maybe_interrupted: bool, }, /// A trap raised from a wasm libcall Wasm { /// Code of the trap. trap_code: ir::TrapCode, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, }, /// A trap indicating that the runtime was unable to allocate sufficient memory. OOM { /// Native stack backtrace at the time the OOM occurred backtrace: Backtrace, }, } impl Trap { /// Construct a new Wasm trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn wasm(trap_code: ir::TrapCode) -> Self { let backtrace = Backtrace::new_unresolved(); Trap::Wasm { trap_code, backtrace, } } /// Construct a new OOM trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn oom() -> Self { let backtrace = Backtrace::new_unresolved(); Trap::OOM { backtrace } } } /// Catches any wasm traps that happen within the execution of `closure`, /// returning them as a `Result`. /// /// Highly unsafe since `closure` won't have any dtors run. pub unsafe fn catch_traps<F>(trap_info: &impl TrapInfo, mut closure: F) -> Result<(), Trap> where F: FnMut(), { sys::lazy_per_thread_init()?; return CallThreadState::new(trap_info).with(|cx| { RegisterSetjmp( cx.jmp_buf.as_ptr(), call_closure::<F>, &mut closure as *mut F as *mut u8, ) }); extern "C" fn call_closure<F>(payload: *mut u8) where F: FnMut(), { unsafe { (*(payload as *mut F))() } } } /// Runs `func` with the last `trap_info` object registered by `catch_traps`. /// /// Calls `func` with `None` if `catch_traps` wasn't previously called from this /// stack frame. pub fn with_last_info<R>(func: impl FnOnce(Option<&dyn Any>) -> R) -> R { tls::with(|state| func(state.map(|s| s.trap_info.as_any())))
} /// Invokes the contextually-defined context's out-of-gas function. /// /// (basically delegates to `wasmtime::Store::out_of_gas`) pub fn out_of_gas() { tls::with(|state| state.unwrap().trap_info.out_of_gas()) } /// Temporary state stored on the stack which is registered in the `tls` module /// below for calls into wasm. pub struct CallThreadState<'a> { unwind: Cell<UnwindReason>, jmp_buf: Cell<*const u8>, handling_trap: Cell<bool>, trap_info: &'a (dyn TrapInfo + 'a), prev: Cell<tls::Ptr>, } /// A package of functionality needed by `catch_traps` to figure out what to do /// when handling a trap. /// /// Note that this is an `unsafe` trait at least because it's being run in the /// context of a synchronous signal handler, so it needs to be careful to not /// access too much state in answering these queries. pub unsafe trait TrapInfo { /// Converts this object into an `Any` to dynamically check its type. fn as_any(&self) -> &dyn Any; /// Returns whether the given program counter lies within wasm code, /// indicating whether we should handle a trap or not. fn is_wasm_trap(&self, pc: usize) -> bool; /// Uses `call` to call a custom signal handler, if one is specified. /// /// Returns `true` if `call` returns true, otherwise returns `false`. fn custom_signal_handler(&self, call: &dyn Fn(&SignalHandler) -> bool) -> bool; /// Returns the maximum size, in bytes, the wasm native stack is allowed to /// grow to. fn max_wasm_stack(&self) -> usize; /// Callback invoked whenever WebAssembly has entirely consumed the fuel /// that it was allotted. /// /// This function may return, and it may also `raise_lib_trap`. fn out_of_gas(&self); /// Returns the VM interrupts to use for interrupting Wasm code. fn interrupts(&self) -> &VMInterrupts; } enum UnwindReason { None, Panic(Box<dyn Any + Send>), UserTrap(Box<dyn Error + Send + Sync>), LibTrap(Trap), JitTrap { backtrace: Backtrace, pc: usize }, } impl<'a> CallThreadState<'a> { fn new(trap_info: &'a (dyn TrapInfo + 'a)) -> CallThreadState<'a> { CallThreadState { unwind: Cell::new(UnwindReason::None), jmp_buf: Cell::new(ptr::null()), handling_trap: Cell::new(false), trap_info, prev: Cell::new(ptr::null()), } } fn with(self, closure: impl FnOnce(&CallThreadState) -> i32) -> Result<(), Trap> { let _reset = self.update_stack_limit()?; let ret = tls::set(&self, || closure(&self)); match self.unwind.replace(UnwindReason::None) { UnwindReason::None => { debug_assert_eq!(ret, 1); Ok(()) } UnwindReason::UserTrap(data) => { debug_assert_eq!(ret, 0); Err(Trap::User(data)) } UnwindReason::LibTrap(trap) => Err(trap), UnwindReason::JitTrap { backtrace, pc } => { debug_assert_eq!(ret, 0); let interrupts = self.trap_info.interrupts(); let maybe_interrupted = interrupts.stack_limit.load(SeqCst) == wasmtime_environ::INTERRUPTED; Err(Trap::Jit { pc, backtrace, maybe_interrupted, }) } UnwindReason::Panic(panic) => { debug_assert_eq!(ret, 0); std::panic::resume_unwind(panic) } } } /// Checks and/or initializes the wasm native call stack limit. /// /// This function will inspect the current state of the stack and calling /// context to determine which of three buckets we're in: /// /// 1. We are the first wasm call on the stack. This means that we need to /// set up a stack limit where beyond which if the native wasm stack /// pointer goes beyond forces a trap. For now we simply reserve an /// arbitrary chunk of bytes (1 MB from roughly the current native stack /// pointer). This logic will likely get tweaked over time. /// /// 2. We aren't the first wasm call on the stack. In this scenario the wasm /// stack limit is already configured. This case of wasm -> host -> wasm /// we assume that the native stack consumed by the host is accounted for /// in the initial stack limit calculation. That means that in this /// scenario we do nothing. /// /// 3. We were previously interrupted. In this case we consume the interrupt /// here and return a trap, clearing the interrupt and allowing the next /// wasm call to proceed. /// /// The return value here is a trap for case 3, a noop destructor in case 2, /// and a meaningful destructor in case 1 /// /// For more information about interrupts and stack limits see /// `crates/environ/src/cranelift.rs`. /// /// Note that this function must be called with `self` on the stack, not the /// heap/etc. fn update_stack_limit(&self) -> Result<impl Drop + '_, Trap> { // Determine the stack pointer where, after which, any wasm code will // immediately trap. This is checked on the entry to all wasm functions. // // Note that this isn't 100% precise. We are requested to give wasm // `max_wasm_stack` bytes, but what we're actually doing is giving wasm // probably a little less than `max_wasm_stack` because we're // calculating the limit relative to this function's approximate stack // pointer. Wasm will be executed on a frame beneath this one (or next // to it). In any case it's expected to be at most a few hundred bytes // of slop one way or another. When wasm is typically given a MB or so // (a million bytes) the slop shouldn't matter too much. let wasm_stack_limit = psm::stack_pointer() as usize - self.trap_info.max_wasm_stack(); let interrupts = self.trap_info.interrupts(); let reset_stack_limit = match interrupts.stack_limit.compare_exchange( usize::max_value(), wasm_stack_limit, SeqCst, SeqCst, ) { Ok(_) => { // We're the first wasm on the stack so we've now reserved the // `max_wasm_stack` bytes of native stack space for wasm. // Nothing left to do here now except reset back when we're // done. true } Err(n) if n == wasmtime_environ::INTERRUPTED => { // This means that an interrupt happened before we actually // called this function, which means that we're now // considered interrupted. Be sure to consume this interrupt // as part of this process too. interrupts.stack_limit.store(usize::max_value(), SeqCst); return Err(Trap::Wasm { trap_code: ir::TrapCode::Interrupt, backtrace: Backtrace::new_unresolved(), }); } Err(_) => { // The stack limit was previously set by a previous wasm // call on the stack. We leave the original stack limit for // wasm in place in that case, and don't reset the stack // limit when we're done. false } }; struct Reset<'a>(bool, &'a AtomicUsize); impl Drop for Reset<'_> { fn drop(&mut self) { if self.0 { self.1.store(usize::max_value(), SeqCst); } } } Ok(Reset(reset_stack_limit, &interrupts.stack_limit)) } fn unwind_with(&self, reason: UnwindReason) ->! { self.unwind.replace(reason); unsafe { Unwind(self.jmp_buf.get()); } } /// Trap handler using our thread-local state. /// /// * `pc` - the program counter the trap happened at /// * `call_handler` - a closure used to invoke the platform-specific /// signal handler for each instance, if available. /// /// Attempts to handle the trap if it's a wasm trap. Returns a few /// different things: /// /// * null - the trap didn't look like a wasm trap and should continue as a /// trap /// * 1 as a pointer - the trap was handled by a custom trap handler on an /// instance, and the trap handler should quickly return. /// * a different pointer - a jmp_buf buffer to longjmp to, meaning that /// the wasm trap was succesfully handled. fn jmp_buf_if_trap( &self, pc: *const u8, call_handler: impl Fn(&SignalHandler) -> bool, ) -> *const u8 { // If we hit a fault while handling a previous trap, that's quite bad, // so bail out and let the system handle this recursive segfault. // // Otherwise flag ourselves as handling a trap, do the trap handling, // and reset our trap handling flag. if self.handling_trap.replace(true) { return ptr::null(); } let _reset = ResetCell(&self.handling_trap, false); // If we haven't even started to handle traps yet, bail out. if self.jmp_buf.get().is_null() { return ptr::null(); } // First up see if any instance registered has a custom trap handler, // in which case run them all. If anything handles the trap then we // return that the trap was handled. if self.trap_info.custom_signal_handler(&call_handler) { return 1 as *const _; } // If this fault wasn't in wasm code, then it's not our problem if!self.trap_info.is_wasm_trap(pc as usize) { return ptr::null(); } // If all that passed then this is indeed a wasm trap, so return the // `jmp_buf` passed to `Unwind` to resume. self.jmp_buf.get() } fn capture_backtrace(&self, pc: *const u8) { let backtrace = Backtrace::new_unresolved(); self.unwind.replace(UnwindReason::JitTrap { backtrace, pc: pc as usize, }); } } struct ResetCell<'a, T: Copy>(&'a Cell<T>, T); impl<T: Copy> Drop for ResetCell<'_, T> { fn drop(&mut self) { self.0.set(self.1); } } // A private inner module for managing the TLS state that we require across // calls in wasm. The WebAssembly code is called from C++ and then a trap may // happen which requires us to read some contextual state to figure out what to // do with the trap. This `tls` module is used to persist that information from // the caller to the trap site. mod tls { use super::CallThreadState; use std::mem; use std::ptr; pub use raw::Ptr; // An even *more* inner module for dealing with TLS. This actually has the // thread local variable and has functions to access the variable. // // Note that this is specially done to fully encapsulate that the accessors // for tls must not be inlined. Wasmtime's async support employs stack // switching which can resume execution on different OS threads. This means // that borrows of our TLS pointer must never live across accesses because // otherwise the access may be split across two threads and cause unsafety. // // This also means that extra care is taken by the runtime to save/restore // these TLS values when the runtime may have crossed threads. mod raw { use super::CallThreadState; use std::cell::Cell; use std::ptr; pub type Ptr = *const CallThreadState<'static>; thread_local!(static PTR: Cell<Ptr> = Cell::new(ptr::null())); #[inline(never)] // see module docs for why this is here pub fn replace(val: Ptr) -> Ptr { // Mark the current thread as handling interrupts for this specific // CallThreadState: may clobber the previous entry. super::super::sys::register_tls(val); PTR.with(|p| p.replace(val)) } #[inline(never)] // see module docs for why this is here pub fn get() -> Ptr { PTR.with(|p| p.get()) } } /// Opaque state used to help control TLS state across stack switches for /// async support. pub struct TlsRestore(raw::Ptr); impl TlsRestore { /// Takes the TLS state that is currently configured and returns a /// token that is used to replace it later. /// /// This is not a safe operation since it's intended to only be used /// with stack switching found with fibers and async wasmtime. pub unsafe fn take() -> TlsRestore { // Our tls pointer must be set at this time, and it must not be // null. We need to restore the previous pointer since we're // removing ourselves from the call-stack, and in the process we // null out our own previous field for safety in case it's // accidentally used later. let raw = raw::get(); assert!(!raw.is_null()); let prev = (*raw).prev.replace(ptr::null()); raw::replace(prev); TlsRestore(raw) } /// Restores a previous tls state back into this thread's TLS. /// /// This is unsafe because it's intended to only be used within the /// context of stack switching within wasmtime. pub unsafe fn replace(self) -> Result<(), super::Trap> { // When replacing to the previous value of TLS, we might have // crossed a thread: make sure the trap-handling lazy initializer // runs. super::sys::lazy_per_thread_init()?; // We need to configure our previous TLS pointer to whatever is in // TLS at this time, and then we set the current state to ourselves. let prev = raw::get(); assert!((*self.0).prev.get().is_null()); (*self.0).prev.set(prev); raw::replace(self.0); Ok(()) } } /// Configures thread local state such that for the duration of the /// execution of `closure` any call to `with` will yield `ptr`, unless this /// is recursively called again. pub fn set<R>(state: &CallThreadState<'_>, closure: impl FnOnce() -> R) -> R { struct Reset<'a, 'b>(&'a CallThreadState<'b>); impl Drop for Reset<'_, '_> { fn drop(&mut self) { raw::replace(self.0.prev.replace(ptr::null())); } } // Note that this extension of the lifetime to `'static` should be // safe because we only ever access it below with an anonymous // lifetime, meaning `'static` never leaks out of this module. let ptr = unsafe { mem::transmute::<*const CallThreadState<'_>, *const CallThreadState<'static>>(state) }; let prev = raw::replace(ptr); state.prev.set(prev); let _reset = Reset(state); closure() } /// Returns the last pointer configured with `set` above. Panics if `set` /// has not been previously called. pub fn with<R>(closure: impl FnOnce(Option<&CallThreadState<'_>>) -> R) -> R { let p = raw::get(); unsafe { closure(if p.is_null() { None } else { Some(&*p) }) } } }
random_line_split
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtime_environ::ir; pub use self::tls::TlsRestore; extern "C" { fn RegisterSetjmp( jmp_buf: *mut *const u8, callback: extern "C" fn(*mut u8), payload: *mut u8, ) -> i32; fn Unwind(jmp_buf: *const u8) ->!; } cfg_if::cfg_if! { if #[cfg(target_os = "macos")] { mod macos; use macos as sys; } else if #[cfg(unix)] { mod unix; use unix as sys; } else if #[cfg(target_os = "windows")] { mod windows; use windows as sys; } } pub use sys::SignalHandler; /// This function performs the low-overhead platform-specific initialization /// that we want to do eagerly to ensure a more-deterministic global process /// state. /// /// This is especially relevant for signal handlers since handler ordering /// depends on installation order: the wasm signal handler must run *before* /// the other crash handlers and since POSIX signal handlers work LIFO, this /// function needs to be called at the end of the startup process, after other /// handlers have been installed. This function can thus be called multiple /// times, having no effect after the first call. pub fn init_traps() { static INIT: Once = Once::new(); INIT.call_once(|| unsafe { sys::platform_init() }); } /// Raises a user-defined trap immediately. /// /// This function performs as-if a wasm trap was just executed, only the trap /// has a dynamic payload associated with it which is user-provided. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_user_trap(data: Box<dyn Error + Send + Sync>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::UserTrap(data))) } /// Raises a trap from inside library code immediately. /// /// This function performs as-if a wasm trap was just executed. This trap /// payload is then returned from `catch_traps` below. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn raise_lib_trap(trap: Trap) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::LibTrap(trap))) } /// Carries a Rust panic across wasm code and resumes the panic on the other /// side. /// /// # Safety /// /// Only safe to call when wasm code is on the stack, aka `catch_traps` must /// have been previously called. Additionally no Rust destructors can be on the /// stack. They will be skipped and not executed. pub unsafe fn resume_panic(payload: Box<dyn Any + Send>) ->! { tls::with(|info| info.unwrap().unwind_with(UnwindReason::Panic(payload))) } /// Stores trace message with backtrace. #[derive(Debug)] pub enum Trap { /// A user-raised trap through `raise_user_trap`. User(Box<dyn Error + Send + Sync>), /// A trap raised from jit code Jit { /// The program counter in JIT code where this trap happened. pc: usize, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, /// An indicator for whether this may have been a trap generated from an /// interrupt, used for switching what would otherwise be a stack /// overflow trap to be an interrupt trap. maybe_interrupted: bool, }, /// A trap raised from a wasm libcall Wasm { /// Code of the trap. trap_code: ir::TrapCode, /// Native stack backtrace at the time the trap occurred backtrace: Backtrace, }, /// A trap indicating that the runtime was unable to allocate sufficient memory. OOM { /// Native stack backtrace at the time the OOM occurred backtrace: Backtrace, }, } impl Trap { /// Construct a new Wasm trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn wasm(trap_code: ir::TrapCode) -> Self { let backtrace = Backtrace::new_unresolved(); Trap::Wasm { trap_code, backtrace, } } /// Construct a new OOM trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn oom() -> Self { let backtrace = Backtrace::new_unresolved(); Trap::OOM { backtrace } } } /// Catches any wasm traps that happen within the execution of `closure`, /// returning them as a `Result`. /// /// Highly unsafe since `closure` won't have any dtors run. pub unsafe fn catch_traps<F>(trap_info: &impl TrapInfo, mut closure: F) -> Result<(), Trap> where F: FnMut(), { sys::lazy_per_thread_init()?; return CallThreadState::new(trap_info).with(|cx| { RegisterSetjmp( cx.jmp_buf.as_ptr(), call_closure::<F>, &mut closure as *mut F as *mut u8, ) }); extern "C" fn call_closure<F>(payload: *mut u8) where F: FnMut(), { unsafe { (*(payload as *mut F))() } } } /// Runs `func` with the last `trap_info` object registered by `catch_traps`. /// /// Calls `func` with `None` if `catch_traps` wasn't previously called from this /// stack frame. pub fn with_last_info<R>(func: impl FnOnce(Option<&dyn Any>) -> R) -> R { tls::with(|state| func(state.map(|s| s.trap_info.as_any()))) } /// Invokes the contextually-defined context's out-of-gas function. /// /// (basically delegates to `wasmtime::Store::out_of_gas`) pub fn out_of_gas() { tls::with(|state| state.unwrap().trap_info.out_of_gas()) } /// Temporary state stored on the stack which is registered in the `tls` module /// below for calls into wasm. pub struct CallThreadState<'a> { unwind: Cell<UnwindReason>, jmp_buf: Cell<*const u8>, handling_trap: Cell<bool>, trap_info: &'a (dyn TrapInfo + 'a), prev: Cell<tls::Ptr>, } /// A package of functionality needed by `catch_traps` to figure out what to do /// when handling a trap. /// /// Note that this is an `unsafe` trait at least because it's being run in the /// context of a synchronous signal handler, so it needs to be careful to not /// access too much state in answering these queries. pub unsafe trait TrapInfo { /// Converts this object into an `Any` to dynamically check its type. fn as_any(&self) -> &dyn Any; /// Returns whether the given program counter lies within wasm code, /// indicating whether we should handle a trap or not. fn is_wasm_trap(&self, pc: usize) -> bool; /// Uses `call` to call a custom signal handler, if one is specified. /// /// Returns `true` if `call` returns true, otherwise returns `false`. fn custom_signal_handler(&self, call: &dyn Fn(&SignalHandler) -> bool) -> bool; /// Returns the maximum size, in bytes, the wasm native stack is allowed to /// grow to. fn max_wasm_stack(&self) -> usize; /// Callback invoked whenever WebAssembly has entirely consumed the fuel /// that it was allotted. /// /// This function may return, and it may also `raise_lib_trap`. fn out_of_gas(&self); /// Returns the VM interrupts to use for interrupting Wasm code. fn interrupts(&self) -> &VMInterrupts; } enum UnwindReason { None, Panic(Box<dyn Any + Send>), UserTrap(Box<dyn Error + Send + Sync>), LibTrap(Trap), JitTrap { backtrace: Backtrace, pc: usize }, } impl<'a> CallThreadState<'a> { fn new(trap_info: &'a (dyn TrapInfo + 'a)) -> CallThreadState<'a> { CallThreadState { unwind: Cell::new(UnwindReason::None), jmp_buf: Cell::new(ptr::null()), handling_trap: Cell::new(false), trap_info, prev: Cell::new(ptr::null()), } } fn with(self, closure: impl FnOnce(&CallThreadState) -> i32) -> Result<(), Trap> { let _reset = self.update_stack_limit()?; let ret = tls::set(&self, || closure(&self)); match self.unwind.replace(UnwindReason::None) { UnwindReason::None => { debug_assert_eq!(ret, 1); Ok(()) } UnwindReason::UserTrap(data) => { debug_assert_eq!(ret, 0); Err(Trap::User(data)) } UnwindReason::LibTrap(trap) => Err(trap), UnwindReason::JitTrap { backtrace, pc } => { debug_assert_eq!(ret, 0); let interrupts = self.trap_info.interrupts(); let maybe_interrupted = interrupts.stack_limit.load(SeqCst) == wasmtime_environ::INTERRUPTED; Err(Trap::Jit { pc, backtrace, maybe_interrupted, }) } UnwindReason::Panic(panic) => { debug_assert_eq!(ret, 0); std::panic::resume_unwind(panic) } } } /// Checks and/or initializes the wasm native call stack limit. /// /// This function will inspect the current state of the stack and calling /// context to determine which of three buckets we're in: /// /// 1. We are the first wasm call on the stack. This means that we need to /// set up a stack limit where beyond which if the native wasm stack /// pointer goes beyond forces a trap. For now we simply reserve an /// arbitrary chunk of bytes (1 MB from roughly the current native stack /// pointer). This logic will likely get tweaked over time. /// /// 2. We aren't the first wasm call on the stack. In this scenario the wasm /// stack limit is already configured. This case of wasm -> host -> wasm /// we assume that the native stack consumed by the host is accounted for /// in the initial stack limit calculation. That means that in this /// scenario we do nothing. /// /// 3. We were previously interrupted. In this case we consume the interrupt /// here and return a trap, clearing the interrupt and allowing the next /// wasm call to proceed. /// /// The return value here is a trap for case 3, a noop destructor in case 2, /// and a meaningful destructor in case 1 /// /// For more information about interrupts and stack limits see /// `crates/environ/src/cranelift.rs`. /// /// Note that this function must be called with `self` on the stack, not the /// heap/etc. fn update_stack_limit(&self) -> Result<impl Drop + '_, Trap> { // Determine the stack pointer where, after which, any wasm code will // immediately trap. This is checked on the entry to all wasm functions. // // Note that this isn't 100% precise. We are requested to give wasm // `max_wasm_stack` bytes, but what we're actually doing is giving wasm // probably a little less than `max_wasm_stack` because we're // calculating the limit relative to this function's approximate stack // pointer. Wasm will be executed on a frame beneath this one (or next // to it). In any case it's expected to be at most a few hundred bytes // of slop one way or another. When wasm is typically given a MB or so // (a million bytes) the slop shouldn't matter too much. let wasm_stack_limit = psm::stack_pointer() as usize - self.trap_info.max_wasm_stack(); let interrupts = self.trap_info.interrupts(); let reset_stack_limit = match interrupts.stack_limit.compare_exchange( usize::max_value(), wasm_stack_limit, SeqCst, SeqCst, ) { Ok(_) => { // We're the first wasm on the stack so we've now reserved the // `max_wasm_stack` bytes of native stack space for wasm. // Nothing left to do here now except reset back when we're // done. true } Err(n) if n == wasmtime_environ::INTERRUPTED => { // This means that an interrupt happened before we actually // called this function, which means that we're now // considered interrupted. Be sure to consume this interrupt // as part of this process too. interrupts.stack_limit.store(usize::max_value(), SeqCst); return Err(Trap::Wasm { trap_code: ir::TrapCode::Interrupt, backtrace: Backtrace::new_unresolved(), }); } Err(_) =>
}; struct Reset<'a>(bool, &'a AtomicUsize); impl Drop for Reset<'_> { fn drop(&mut self) { if self.0 { self.1.store(usize::max_value(), SeqCst); } } } Ok(Reset(reset_stack_limit, &interrupts.stack_limit)) } fn unwind_with(&self, reason: UnwindReason) ->! { self.unwind.replace(reason); unsafe { Unwind(self.jmp_buf.get()); } } /// Trap handler using our thread-local state. /// /// * `pc` - the program counter the trap happened at /// * `call_handler` - a closure used to invoke the platform-specific /// signal handler for each instance, if available. /// /// Attempts to handle the trap if it's a wasm trap. Returns a few /// different things: /// /// * null - the trap didn't look like a wasm trap and should continue as a /// trap /// * 1 as a pointer - the trap was handled by a custom trap handler on an /// instance, and the trap handler should quickly return. /// * a different pointer - a jmp_buf buffer to longjmp to, meaning that /// the wasm trap was succesfully handled. fn jmp_buf_if_trap( &self, pc: *const u8, call_handler: impl Fn(&SignalHandler) -> bool, ) -> *const u8 { // If we hit a fault while handling a previous trap, that's quite bad, // so bail out and let the system handle this recursive segfault. // // Otherwise flag ourselves as handling a trap, do the trap handling, // and reset our trap handling flag. if self.handling_trap.replace(true) { return ptr::null(); } let _reset = ResetCell(&self.handling_trap, false); // If we haven't even started to handle traps yet, bail out. if self.jmp_buf.get().is_null() { return ptr::null(); } // First up see if any instance registered has a custom trap handler, // in which case run them all. If anything handles the trap then we // return that the trap was handled. if self.trap_info.custom_signal_handler(&call_handler) { return 1 as *const _; } // If this fault wasn't in wasm code, then it's not our problem if!self.trap_info.is_wasm_trap(pc as usize) { return ptr::null(); } // If all that passed then this is indeed a wasm trap, so return the // `jmp_buf` passed to `Unwind` to resume. self.jmp_buf.get() } fn capture_backtrace(&self, pc: *const u8) { let backtrace = Backtrace::new_unresolved(); self.unwind.replace(UnwindReason::JitTrap { backtrace, pc: pc as usize, }); } } struct ResetCell<'a, T: Copy>(&'a Cell<T>, T); impl<T: Copy> Drop for ResetCell<'_, T> { fn drop(&mut self) { self.0.set(self.1); } } // A private inner module for managing the TLS state that we require across // calls in wasm. The WebAssembly code is called from C++ and then a trap may // happen which requires us to read some contextual state to figure out what to // do with the trap. This `tls` module is used to persist that information from // the caller to the trap site. mod tls { use super::CallThreadState; use std::mem; use std::ptr; pub use raw::Ptr; // An even *more* inner module for dealing with TLS. This actually has the // thread local variable and has functions to access the variable. // // Note that this is specially done to fully encapsulate that the accessors // for tls must not be inlined. Wasmtime's async support employs stack // switching which can resume execution on different OS threads. This means // that borrows of our TLS pointer must never live across accesses because // otherwise the access may be split across two threads and cause unsafety. // // This also means that extra care is taken by the runtime to save/restore // these TLS values when the runtime may have crossed threads. mod raw { use super::CallThreadState; use std::cell::Cell; use std::ptr; pub type Ptr = *const CallThreadState<'static>; thread_local!(static PTR: Cell<Ptr> = Cell::new(ptr::null())); #[inline(never)] // see module docs for why this is here pub fn replace(val: Ptr) -> Ptr { // Mark the current thread as handling interrupts for this specific // CallThreadState: may clobber the previous entry. super::super::sys::register_tls(val); PTR.with(|p| p.replace(val)) } #[inline(never)] // see module docs for why this is here pub fn get() -> Ptr { PTR.with(|p| p.get()) } } /// Opaque state used to help control TLS state across stack switches for /// async support. pub struct TlsRestore(raw::Ptr); impl TlsRestore { /// Takes the TLS state that is currently configured and returns a /// token that is used to replace it later. /// /// This is not a safe operation since it's intended to only be used /// with stack switching found with fibers and async wasmtime. pub unsafe fn take() -> TlsRestore { // Our tls pointer must be set at this time, and it must not be // null. We need to restore the previous pointer since we're // removing ourselves from the call-stack, and in the process we // null out our own previous field for safety in case it's // accidentally used later. let raw = raw::get(); assert!(!raw.is_null()); let prev = (*raw).prev.replace(ptr::null()); raw::replace(prev); TlsRestore(raw) } /// Restores a previous tls state back into this thread's TLS. /// /// This is unsafe because it's intended to only be used within the /// context of stack switching within wasmtime. pub unsafe fn replace(self) -> Result<(), super::Trap> { // When replacing to the previous value of TLS, we might have // crossed a thread: make sure the trap-handling lazy initializer // runs. super::sys::lazy_per_thread_init()?; // We need to configure our previous TLS pointer to whatever is in // TLS at this time, and then we set the current state to ourselves. let prev = raw::get(); assert!((*self.0).prev.get().is_null()); (*self.0).prev.set(prev); raw::replace(self.0); Ok(()) } } /// Configures thread local state such that for the duration of the /// execution of `closure` any call to `with` will yield `ptr`, unless this /// is recursively called again. pub fn set<R>(state: &CallThreadState<'_>, closure: impl FnOnce() -> R) -> R { struct Reset<'a, 'b>(&'a CallThreadState<'b>); impl Drop for Reset<'_, '_> { fn drop(&mut self) { raw::replace(self.0.prev.replace(ptr::null())); } } // Note that this extension of the lifetime to `'static` should be // safe because we only ever access it below with an anonymous // lifetime, meaning `'static` never leaks out of this module. let ptr = unsafe { mem::transmute::<*const CallThreadState<'_>, *const CallThreadState<'static>>(state) }; let prev = raw::replace(ptr); state.prev.set(prev); let _reset = Reset(state); closure() } /// Returns the last pointer configured with `set` above. Panics if `set` /// has not been previously called. pub fn with<R>(closure: impl FnOnce(Option<&CallThreadState<'_>>) -> R) -> R { let p = raw::get(); unsafe { closure(if p.is_null() { None } else { Some(&*p) }) } } }
{ // The stack limit was previously set by a previous wasm // call on the stack. We leave the original stack limit for // wasm in place in that case, and don't reset the stack // limit when we're done. false }
conditional_block
lifecycle.rs
env, process, mem::{ MaybeUninit, }, sync::{ atomic::Ordering, }, path::{ Path, }, ffi::{ OsStr, }, }; use thread_id; use atomig::{Atom}; use once_cell::{ sync::{ OnceCell, }, }; use crate::*; use crate::MrapiStatusFlag::*; use crate::internal::db::{ MrapiDatabase, MrapiDomainData, MrapiDomainState, MrapiNodeState, MrapiProcessData, MrapiProcessState, MRAPI_MGR, MRAPI_SEM, access_database_pre, access_database_post, }; //pub static RESOURCE_ROOT: LateStatic<MrapiResource<'static>> = LateStatic::new(); // root of the resource tree //threadlocal!(ALARM_STRUCT: struct sigaction); // used for testing resource tree thread_local! { pub static MRAPI_PID: OnceCell<MrapiUint32> = OnceCell::new(); pub static MRAPI_PROC: OnceCell<MrapiUint32> = OnceCell::new(); pub static MRAPI_TID: OnceCell<MrapiUint32> = OnceCell::new(); pub static MRAPI_NINDEX: OnceCell<MrapiUint> = OnceCell::new(); pub static MRAPI_DINDEX: OnceCell<MrapiUint> = OnceCell::new(); pub static MRAPI_PINDEX: OnceCell<MrapiUint> = OnceCell::new(); pub static MRAPI_NODE_ID: OnceCell<MrapiNode> = OnceCell::new(); pub static MRAPI_DOMAIN_ID: OnceCell<MrapiDomain> = OnceCell::new(); } // finer grained locks for these sections of the database. thread_local! { pub static SEMS_SEM: OnceCell<Semaphore> = OnceCell::new(); // sems array pub static SHMEMS_SEM: OnceCell<Semaphore> = OnceCell::new(); // shmems array pub static REQUESTS_SEM: OnceCell<Semaphore> = OnceCell::new(); // requests array pub static RMEMS_SEM: OnceCell<Semaphore> = OnceCell::new(); // rmems array } // Keep copies of global objects for comparison thread_local! { pub static REQUESTS_GLOBAL: OnceCell<Semaphore> = OnceCell::new(); pub static SEMS_GLOBAL: OnceCell<Semaphore> = OnceCell::new(); pub static SHMEMS_GLOBAL: OnceCell<Semaphore> = OnceCell::new(); pub static RMEMS_GLOBAL: OnceCell<Semaphore> = OnceCell::new(); } // Tell the system whether or not to use the finer-grained locking pub const use_global_only: bool = false; /// Returns the initialized characteristics of this thread #[allow(dead_code)] fn whoami() -> Result<(MrapiNode, MrapiUint, MrapiDomain, MrapiUint), MrapiStatusFlag> { let mut initialized: bool; let mut result: Result<(MrapiNode, MrapiUint, MrapiDomain, MrapiUint), MrapiStatusFlag>; match MRAPI_MGR.get() { None => { initialized = false; result = Err(MrapiErrDbNotInitialized); }, Some(_) => { initialized = true; }, }; if!initialized { return result; } MRAPI_PID.with(|pid| { match pid.get() { None => { initialized = false; result = Err(MrapiErrProcessNotRegistered); }, Some(_) => { initialized = true; }, } }); if!initialized { return result; } Ok(( MRAPI_NODE_ID.with(|id| { match id.get() { None => 0, Some(v) => *v, } }), MRAPI_NINDEX.with(|index| { match index.get() { None => 0, Some(v) => *v, } }), MRAPI_DOMAIN_ID.with(|id| { match id.get() { None => 0, Some(v) => *v, } }), MRAPI_DINDEX.with(|index| { match index.get() { None => 0, Some(v) => *v, } }), )) } /// Checks if the given domain_id/node_id is already assoc w/ this pid/tid #[allow(dead_code)] fn initialized() -> bool { match whoami() { Ok(_) => true, Err(_) => false, } } fn finalize_node_locked(d: MrapiUint, n: MrapiUint) { let mrapi_db = MrapiDatabase::global_db(); let dpacked = &mrapi_db.domains[d].state.load(Ordering::Relaxed); let dstate: MrapiDomainState = Atom::unpack(*dpacked); let npacked = &mrapi_db.domains[d].nodes[n].state.load(Ordering::Relaxed); let mut nstate: MrapiNodeState = Atom::unpack(*npacked); let domain_id = dstate.domain_id(); let node_num = nstate.node_num(); mrapi_dprintf!(2, "mrapi::internal::lifecycle::finalize_node_locked dindex={} nindex={} domain={} node={}", d, n, domain_id, node_num); // Mark the node as finalized nstate.set_valid(MRAPI_FALSE); nstate.set_allocated(MRAPI_FALSE); &mrapi_db.domains[d].nodes[n].state.store(Atom::pack(nstate), Ordering::Relaxed); // Rundown the node's process association let p = mrapi_db.domains[d].nodes[n].proc_num; let ppacked = &mrapi_db.processes[p].state.load(Ordering::Relaxed); let pstate: MrapiProcessState = Atom::unpack(*ppacked); if pstate.valid() { let num_nodes = mrapi_db.processes[p].num_nodes.fetch_sub(1, Ordering::Relaxed); if 0 >= num_nodes { // Last node in this process, remove process references in shared memory for s in 0..MRAPI_MAX_SHMEMS { if mrapi_db.shmems[s].valid { &mrapi_db.shmems[s].set_process(p, 0); } } unsafe { mrapi_db.processes[p] = MaybeUninit::zeroed().assume_init(); }; } } unsafe { mrapi_db.domains[d].nodes[n] = MaybeUninit::zeroed().assume_init(); }; &mrapi_db.domains[d].num_nodes.fetch_sub(1, Ordering::Relaxed); // Decrement the shmem reference count if necessary for shmem in 0..MRAPI_MAX_SHMEMS { if mrapi_db.shmems[shmem].valid == MRAPI_TRUE { if mrapi_db.domains[d].nodes[n].shmems[shmem] == 1 { // If this node was a user of this shm, decrement the ref count mrapi_db.shmems[shmem].refs -= 1; } // If the reference count is 0, free the shared memory resource if mrapi_db.shmems[shmem].refs == 0 { drop(&mrapi_db.shmems[shmem].mem[p]); } } } // Decrement the sem reference count if necessary for sem in 0..MRAPI_MAX_SEMS { if mrapi_db.sems[sem].valid == MRAPI_TRUE { if mrapi_db.domains[d].nodes[n].sems[sem] == 1 { mrapi_db.domains[d].nodes[n].sems[sem] = 0; // If this node was a user of this sem, decrement the ref count if mrapi_db.sems[sem].refs.fetch_sub(1, Ordering::Relaxed) <= 0 { // If the reference count is 0 free the resource mrapi_db.sems[sem].valid = MRAPI_FALSE; } } } } } fn free_resources(panic: MrapiBoolean) { let mut last_node_standing = MRAPI_TRUE; let mut last_node_standing_for_this_process = MRAPI_TRUE; let pid = process::id(); let semref = MrapiSemRef::new(MrapiDatabase::global_sem(), 0, MRAPI_FALSE); // Try to lock the database let locked = access_database_pre(&semref, MRAPI_FALSE); mrapi_dprintf!(1, "mrapi::internal::lifecycle::free_resources panic: {} freeing any existing resources", panic); match MRAPI_MGR.get() { None => { }, Some(_) => { // Finalize this node match whoami() { Ok((node, n, domain_num, d)) => { finalize_node_locked(d, n); }, Err(_) => { }, } // If we are in panic mode, then forcefully finalize all other nodes that belong to this process if panic { let mrapi_db = MrapiDatabase::global_db(); for d in 0..MRAPI_MAX_DOMAINS { for n in 0..MRAPI_MAX_NODES { let npacked = &mrapi_db.domains[d].nodes[n].state.load(Ordering::Relaxed); let nstate: MrapiNodeState = Atom::unpack(*npacked); if nstate.valid() == MRAPI_TRUE { let p = *&mrapi_db.domains[d].nodes[n].proc_num as usize; let ppacked = &mrapi_db.processes[p].state.load(Ordering::Relaxed); let pstate: MrapiProcessState = Atom::unpack(*ppacked); if pstate.pid() == pid { finalize_node_locked(d, n); } } } } for p in 0..MRAPI_MAX_PROCESSES { let ppacked = &mrapi_db.processes[p].state.load(Ordering::Relaxed); let pstate: MrapiProcessState = Atom::unpack(*ppacked); if pstate.valid() == MRAPI_TRUE && pstate.pid() == pid { let mut process = &mut mrapi_db.processes[p]; process.clear(); break; } } } } } } /* { mrapi_boolean_t rc = MRAPI_TRUE; uint32_t d, n, p; mrapi_domain_t domain_num; mrapi_database* mrapi_db_local = NULL; mrapi_node_t node; #if (__unix__) pid_t pid = getpid(); #else pid_t pid = (pid_t)GetCurrentProcessId(); #endif //!(__unix__) mrapi_boolean_t last_man_standing = MRAPI_TRUE; mrapi_boolean_t last_man_standing_for_this_process = MRAPI_TRUE; mrapi_boolean_t locked; // try to lock the database mrapi_impl_sem_ref_t ref = { semid, 0, MRAPI_FALSE }; locked = mrapi_impl_access_database_pre(ref, MRAPI_FALSE); mrapi_dprintf(1, "mrapi_impl_free_resources (panic=%d): freeing any existing resources in the database mrapi_db=%p semid=%x shmemid=%x\n", panic, mrapi_db, semid, shmemid); if (mrapi_db) { // finalize this node if (mrapi_impl_whoami(&node, &n, &domain_num, &d)) { mrapi_impl_finalize_node_locked(d, n); } // if we are in panic mode, then forcefully finalize all other nodes that belong to this process if (panic) { for (d = 0; d < MRAPI_MAX_DOMAINS; d++) { for (n = 0; n < MRAPI_MAX_NODES; n++) { mrapi_node_state nstate; mrapi_assert(sys_atomic_read(NULL, &mrapi_db->domains[d].nodes[n].state, &nstate, sizeof(mrapi_db->domains[d].nodes[n].state))); if (nstate.data.valid == MRAPI_TRUE) { mrapi_uint_t p = mrapi_db->domains[d].nodes[n].proc_num; mrapi_process_state pstate; mrapi_assert(sys_atomic_read(NULL, &mrapi_db->processes[p].state, &pstate, sizeof(mrapi_db->processes[p].state))); if (pstate.data.pid == pid) { mrapi_impl_finalize_node_locked(d, n); } } } } for (p = 0; p < MRAPI_MAX_PROCESSES; p++) { mrapi_process_state pstate; mrapi_assert(sys_atomic_read(NULL, &mrapi_db->processes[p].state, &pstate, sizeof(mrapi_db->processes[p].state))); if ((pstate.data.valid == MRAPI_TRUE) && (pstate.data.pid == pid)) { #if!(__unix) if (NULL!= mrapi_db->processes[p].hAtomicEvt) { CloseHandle(mrapi_db->processes[p].hAtomicEvt); } #endif //!(__unix) memset(&mrapi_db->processes[p], 0, sizeof(mrapi_process_data)); break; } } } // see if there are any valid nodes left in the system and for this process for (d = 0; d < MRAPI_MAX_DOMAINS; d++) { for (n = 0; n < MRAPI_MAX_NODES; n++) { mrapi_node_state nstate; mrapi_assert(sys_atomic_read(NULL, &mrapi_db->domains[d].nodes[n].state, &nstate, sizeof(mrapi_db->domains[d].nodes[n].state))); if (nstate.data.valid == MRAPI_TRUE) { mrapi_process_state pstate; p = mrapi_db->domains[d].nodes[n].proc_num; mrapi_assert(sys_atomic_read(NULL, &mrapi_db->processes[p].state, &pstate, sizeof(mrapi_db->processes[p].state))); last_man_standing = MRAPI_FALSE; if (pstate.data.pid == pid) { last_man_standing_for_this_process = MRAPI_FALSE; } } } } if (panic) { mrapi_assert(last_man_standing_for_this_process); } // if there are no other valid nodes in the whole system, then free the sems if (last_man_standing) { mrapi_dprintf(1, "mrapi_impl_free_resources: freeing mrapi internal semaphore and shared memory\n"); // free the mrapi internal semaphores if (sems_semid!= sems_global) { rc = sys_sem_delete(sems_semid); sems_semid = -1; if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_sem_delete (mrapi_db) failed\n"); } } if (shmems_semid!= shmems_global) { rc = sys_sem_delete(shmems_semid); shmems_semid = -1; if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_sem_delete (mrapi_db) failed\n"); } } if (rmems_semid!= rmems_global) { rc = sys_sem_delete(rmems_semid); rmems_semid = -1; if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_sem_delete (mrapi_db) failed\n"); } } if (requests_semid!= requests_global) { rc = sys_sem_delete(requests_semid); requests_semid = -1; if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_sem_delete (mrapi_db) failed\n"); } } } // if there are no other valid nodes for this process, then detach from shared memory if (last_man_standing_for_this_process) { mrapi_status_t status = 0; mrapi_atomic_op op = { MRAPI_ATOM_CLOSEPROC, 0 }; // Signal remote processes to unlink this process mrapi_impl_atomic_forward(0, &op, &status); memset(&mrapi_db->processes[mrapi_pindex], 0, sizeof(mrapi_process_data)); // detach from the mrapi internal shared memory mrapi_dprintf(1, "mrapi_impl_free_resources: detaching from mrapi internal shared memory\n"); mrapi_db_local = mrapi_db; sys_atomic_xchg_ptr(NULL, (uintptr_t*)&mrapi_db, (uintptr_t)NULL, (uintptr_t*)NULL); rc = sys_shmem_detach(mrapi_db_local); if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_shmem detach (mrapi_db) failed\n"); } } // if there are no other valid nodes in the whole system, then free the shared memory if (last_man_standing) { // free the mrapi internal shared memory rc = sys_shmem_delete(shmemid); if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_shmem_delete (mrapi_db) failed\n"); } mrapi_db = NULL; shmemid = -1; } // if we locked the database and didn't delete it, then we need to unlock it if (locked) { if (!last_man_standing) { // unlock the database mrapi_impl_sem_ref_t ref = { semid, 0 }; mrapi_assert(mrapi_impl_access_database_post(ref)); } } if (last_man_standing) { // free the global semaphore last rc = sys_sem_delete(semid); semid = -1; if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_sem_delete (mrapi_db) failed\n"); } } } return last_man_standing; } */ /// Create or get the semaphore corresponding to the key fn create_sys_semaphore(num_locks: usize, key: u32, lock: MrapiBoolean) -> Option<Semaphore> { let max_tries: u32 = 0xffffffff; let trycount: u32 = 0; while trycount < max_tries { trycount += 1; let sem = match sem_create(key, num_locks) { Some(v) => v, None => { match sem_get(key, num_locks) { Some(v) => v, None => Semaphore::default(), } }, }; if sem!= Semaphore::default() { if lock { let sr = MrapiSemRef::new(&sem, 0, false); while trycount < max_tries { match sr.trylock() { Ok(v) => { if v { return Some(sem); } }, Err(_) => { }, } sysvr4::os_yield(); } } } } None } /// Initializes the MRAPI internal layer (sets up the database and semaphore) /// /// # Arguments /// /// domain_id - collection of nodes that share resources /// node_id - task that synchronizes with other nodes in a domain /// /// # Errors /// /// MrapiDbNotInitialized /// MrapiNodeInitfailed /// MrapiAtomOpNoforward #[allow(unused_variables)] pub fn initialize(domain_id: MrapiDomain, node_id: MrapiNode) -> Result<MrapiStatus, MrapiStatusFlag> { static use_uid: MrapiBoolean = MRAPI_TRUE; // associate this node w/ a pid,tid pair so that we can recognize the caller on later calls mrapi_dprintf!(1, "mrapi::internal::lifecycle::initialize ({},{});", domain_id, node_id); if initialized() { return Err(MrapiErrNodeInitfailed); }; // Get process name let proc_name = env::args().next() .as_ref() .map(Path::new) .and_then(Path::file_name) .and_then(OsStr::to_str); let buff = proc_name.unwrap().to_owned() + "_mrapi"; let mut key: u32; let mut db_key: u32; let mut sems_key: u32; let mut shmems_key: u32; let mut rmems_key: u32; let mut requests_key: u32; if use_uid { key = common::crc::crc32_compute_buf(0, &buff); db_key = common::crc::crc32_compute_buf(key, &(buff + "_db")); sems_key = common::crc::crc32_compute_buf(key, &(buff + "_sems")); shmems_key = common::crc::crc32_compute_buf(key, &(buff + "_shmems")); rmems_key = common::crc::crc32_compute_buf(key, &(buff + "_rmems")); requests_key = common::crc::crc32_compute_buf(key, &(buff + "_requests")); } else { key = match os_file_key("", 'z' as u32) { Some(v) => v, None => { mrapi_dprintf!(1, "MRAPI ERROR: Invalid file key"); 0 }, }; db_key = key + 10; sems_key = key + 20; shmems_key = key + 30; rmems_key = key + 40; requests_key = key + 50; } // 1) setup the global database // get/create the shared memory database MrapiDatabase::initialize_db(domain_id, node_id, db_key); // 2) create or get the semaphore and lock it // we loop here and inside of create_sys_semaphore because of the following race condition: // initialize finalize // 1: create/get sem 1: lock sem // 2: lock sem 2: check db: any valid nodes? // 3: setup db & add self 3a: no -> delete db & delete sem // 4: unlock sem 3b: yes-> unlock sem // // finalize-1 can occur between initialize-1 and initialize-2 which will cause initialize-2 // to fail because the semaphore no longer exists. let sem_local = match create_sys_semaphore(1, key, MRAPI_TRUE) { None => { mrapi_dprintf!(1, "MRAPI ERROR: Unable to get the semaphore key: {}", key); return Err(MrapiErrNodeInitfailed); }, Some(v) => v, }; mrapi_dprintf!(1, "mrapi_impl_initialize lock acquired, now adding node to database"); // At this point we've managed to acquire and lock the semaphore... // NOTE: with use_global_only it's important to write to the globals only while // we have the semaphore otherwise we introduce race conditions. This // is why we are using the local variable id until everything is set up. // set the global semaphore reference MrapiDatabase::initialize_sem(sem_local); // get or create our finer grained locks // in addition to a lock on the sems array, every lock (rwl,sem,mutex) has it's own // database semaphore, this allows us to access different locks in parallel let sems_sem = create_sys_semaphore(MRAPI_MAX_SEMS + 1, sems_key, MRAPI_FALSE); if use_global_only || sems_sem.is_none() { SEMS_GLOBAL.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); SEMS_SEM.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); } else { SEMS_SEM.with(|sem| { sem.set(sems_sem.unwrap()); }); } let shmems_sem = create_sys_semaphore(1, shmems_key, MRAPI_FALSE); if shmems_sem.is_none() { SHMEMS_GLOBAL.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); SHMEMS_SEM.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); } else { SHMEMS_SEM.with(|sem| { sem.set(shmems_sem.unwrap()); }); } let rmems_sem = create_sys_semaphore(1, rmems_key, MRAPI_FALSE); if rmems_sem.is_none() { RMEMS_GLOBAL.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); RMEMS_SEM.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); } else { RMEMS_SEM.with(|sem| { sem.set(rmems_sem.unwrap()); }); } let requests_sem = create_sys_semaphore(1, requests_key, MRAPI_FALSE); if requests_sem.is_none() { REQUESTS_GLOBAL.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); REQUESTS_SEM.with(|sem| { sem.set(MrapiDatabase::global_sem().clone()); }); } else { REQUESTS_SEM.with(|sem| { sem.set(rmems_sem.unwrap()); }); } // Get our identity let pid = process::id(); let tid = thread_id::get() as MrapiUint32; MRAPI_PID.with(|id| { id.set(pid); }); MRAPI_PROC.with(|id| { id.set(pid); });
let mrapi_db = MrapiDatabase::global_db(); // 3) Add the process/node/domain to the database let mut d: usize = 0; let mut n: usize = 0; let mut p: usize = 0; // First see if this domain already exists for d in 0..MRAPI_MAX_DOMAINS { let packed = &mrapi_db.domains[d].state.load(Ordering::Relaxed); let dstate: MrapiDomainState = Atom::unpack(*packed); if dstate.domain_id() == domain_id as MrapiUint32 { break; } } if d == MRAPI_MAX_DOMAINS { // Find first available entry for d in 0..MRAPI_MAX_DOMAINS { let packed = &mrapi_db.domains[d].state.load(Ordering::Relaxed); let mut oldstate: MrapiDomainState = Atom::unpack(*packed); let mut newstate = oldstate; oldstate.set_allocated(MRAPI_FALSE); newstate.set_domain_id(domain_id as MrapiUint32); newstate.set_allocated(MRAPI_TRUE); match &mrapi_db.domains[d].state.compare_exchange( Atom::pack(oldstate), Atom::pack(newstate), Ordering::Acquire, Ordering::Relaxed) { Ok(_) => { break; }, Err(_) => continue, } } } if d!= MRAPI_MAX_DOMAINS { // now find an available node index... for n in 0..MRAPI_MAX_NODES { let packed = &mrapi_db.domains[d].nodes[n].state.load(Ordering::Relaxed); let state: MrapiNodeState = Atom::unpack(*packed); // Even though initialized() is checked by mrapi, we have to check again here because // initialized() and initalize() are not atomic at the top layer if state.allocated() && state.node_num() == node_id as MrapiUint32 { // this node already exists for this domain mrapi_dprintf!(1, "This node ({}) already exists for this domain ({})", node_id, domain_id); break; } } if n == MRAPI_MAX_NODES { // it didn't exist so find the first available entry for n in 0..MRAPI_MAX_NODES { let packed = &mrapi_db.domains[d].nodes[n].state.load(Ordering::Relaxed); let mut oldstate: MrapiNodeState = Atom::unpack(*packed); let mut newstate = oldstate; oldstate.set_allocated(MRAPI_FALSE); newstate.set_node_num(node_id as MrapiUint32
MRAPI_TID.with(|id| { id.set(tid); }); // Seed random number generator os_srand(tid);
random_line_split
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump to the last level (level 1) retrive /// its address and then move to the offsets. pub use self::entry::*; ///FrameAllocator is the method used to create Frames from Pages use memory::{PAGE_SIZE, Frame, FrameAllocator}; // needed later use self::table::{Table, Level4}; pub use self::mapper::Mapper; use core::ptr::Unique; use core::ops::{Deref, DerefMut}; use self::temporary_page::TemporaryPage; use multiboot2::BootInformation; //use acpi::rsdp; use acpi::*; use core::mem; use core::option; //use self::paging::PhysicalAddress; //use self::entry::HUGE_PAGE; mod entry; mod table; mod mapper; ///Used to temporary map a frame to virtal address mod temporary_page; const ENTRY_COUNT: usize = 512; pub type PhysicalAddress = usize; pub type VirtualAddress = usize; /// Copy so that it can be used after passing'map_to' and similar functions. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Page { number: usize, } impl Page { /// The address space is split into two halves, high/low, where the higher /// half contains addresses and the sign extentions, the lower half contains /// just adresses. This is checked here with an assert. pub fn containing_address(address: VirtualAddress) -> Page { assert!(address < 0x0000_8000_0000_0000 || address >= 0xffff_8000_0000_0000, "invalid address: 0x{:x}", address); Page { number: address / PAGE_SIZE } } /// Takes a VirtualAddress and calculates start address fn start_address(&self) -> PhysicalAddress { self.number * PAGE_SIZE } /// Calculates the p4-starting index/point fn p4_index(&self) -> usize { (self.number >> 27) & 0o777 } /// Calculates the p3-starting index/point fn p3_index(&self) -> usize { (self.number >> 18) & 0o777 } /// Calculates the p2-starting index/point fn p2_index(&self) -> usize { (self.number >> 9) & 0o777 } /// Calculates the p1-starting index/point fn p1_index(&self) -> usize { (self.number >> 0) & 0o777 } /// Returns inclusive range iterator of pages pub fn range_inclusive(start: Page, end: Page) -> PageIter { PageIter { start: start, end: end } } } pub struct PageIter { start: Page, end: Page } impl Iterator for PageIter { type Item = Page; fn next(&mut self) -> Option<Page> { if self.start <= self.end { let page = self.start; self.start.number += 1; Some(page) } else { None } } } pub struct ActivePageTable { mapper: Mapper, } /// Dereference the ActivePageTable /// Returns reference to Mapper impl Deref for ActivePageTable { type Target = Mapper; fn deref(&self) -> &Mapper { &self.mapper } } /// Dereference the ActivePageTable /// Returns a mutable reference to Mapper impl DerefMut for ActivePageTable { fn deref_mut(&mut self) -> &mut Mapper { &mut self.mapper } } /// Does the recursive mapping to the four levels of page tables. impl ActivePageTable { unsafe fn new() -> ActivePageTable { ActivePageTable { mapper: Mapper::new(), } } /// Module that temporarily changes the recursive mapping. /// It overwrites the 511th P4 entry and points it to the /// inactive table frame. /// "It overwrites the 511th P4 entry and points it to the inactive table frame. Then it flushes the translation lookaside buffer (TLB), which still contains some old translations. We need to flush all pages that are part of the recursive mapping, so the easiest way is to flush the TLB completely."" pub fn with<F>(&mut self, table: &mut InactivePageTable, temporary_page: &mut temporary_page::TemporaryPage, f: F) where F: FnOnce(&mut Mapper) { use x86::{controlregs, tlb}; let flush_tlb = || unsafe { tlb::flush_all() }; { let backup = Frame::containing_address ( unsafe { controlregs::cr3() } as usize); // map temporary_page to current p4 table let p4_table = temporary_page.map_table_frame(backup.clone(), self); // overwrite recursive mapping self.p4_mut()[511].set(table.p4_frame.clone(), PRESENT | WRITABLE); flush_tlb(); // execute f in the new context f(self); // restore recursive mapping to original p4 table p4_table[511].set(backup, PRESENT | WRITABLE); flush_tlb(); } temporary_page.unmap(self); } pub fn switch(&mut self, new_table: InactivePageTable) -> InactivePageTable { use x86::controlregs; let old_table = InactivePageTable { p4_frame: Frame::containing_address( unsafe { controlregs::cr3() } as usize), }; unsafe { controlregs::cr3_write(new_table.p4_frame.start_address() as u64); } old_table } } pub struct InactivePageTable { p4_frame: Frame, } /// Creates valid, inactive page tables that are zeroed and recursively mapped. impl InactivePageTable { pub fn new(frame: Frame, active_table: &mut ActivePageTable, temporary_page: &mut TemporaryPage) -> InactivePageTable { { // The 'active_table' and 'temporary_table' arguments needs to // be in a inner scope to ensure shadowing since the table // variable exclusively borrows temporary_page as long as it's alive let table = temporary_page.map_table_frame(frame.clone(), active_table); // Zeroing table is done here *duh* table.zero(); // Recursive mapping for the table table[511].set(frame.clone(), PRESENT | WRITABLE); } temporary_page.unmap(active_table); InactivePageTable {p4_frame: frame } }
use core::ops::Range; // Create a temporary page at some page number, in this case 0xcafebabe let mut temporary_page = TemporaryPage::new(Page { number: 0xcafebabe }, allocator); // Created by constructor let mut active_table = unsafe { ActivePageTable::new() }; // Created by constructor let mut new_table = { let frame = allocator.allocate_frame().expect("no more frames"); InactivePageTable::new(frame, &mut active_table, &mut temporary_page) }; active_table.with(&mut new_table, &mut temporary_page, |mapper| { let elf_sections_tag = boot_info.elf_sections_tag() .expect("Memory map tag required"); // Identity map the allocated kernel sections // Skip sections that are not loaded to memory. // We require pages to be aligned, see src/arch/x86_64/linker.ld for implementations for section in elf_sections_tag.sections() { if!section.is_allocated() { // section is not loaded to memory continue; } assert!(section.addr as usize % PAGE_SIZE == 0, "sections need to be page aligned"); // println!("mapping section at addr: {:#x}, size: {:#x}", // section.addr, // section.size); let flags = EntryFlags::from_elf_section_flags(section); let start_frame = Frame::containing_address(section.start_address()); let end_frame = Frame::containing_address(section.end_address() - 1); // 'range_inclusive' iterates over all frames on a section for frame in Frame::range_inclusive(start_frame, end_frame) { mapper.identity_map(frame, flags, allocator); } } // identity map the VGA text buffer let vga_buffer_frame = Frame::containing_address(0xb8000); mapper.identity_map(vga_buffer_frame, WRITABLE, allocator); // identity map the multiboot info structure let multiboot_start = Frame::containing_address(boot_info.start_address()); let multiboot_end = Frame::containing_address(boot_info.end_address() - 1); for frame in Frame::range_inclusive(multiboot_start, multiboot_end) { mapper.identity_map(frame, PRESENT, allocator); } for (start, end, next) in &mut sdt_loc.into_iter() { //println!("Allocating addresses {:x} to {:x} and {:x}", start, end, next); let start_addr = Frame::containing_address(start); let end_addr = Frame::containing_address(end); for frame in Frame::range_inclusive(start_addr, end_addr) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, PRESENT, allocator); } } if next!= 0 { let next_header_frame = Frame::containing_address(next); if mapper.is_unused(&next_header_frame, allocator) { mapper.identity_map(next_header_frame, PRESENT, allocator); } } } let ioapic_start = Frame::containing_address(sdt_loc.ioapic_start); let ioapic_end = Frame::containing_address(sdt_loc.ioapic_end); for frame in Frame::range_inclusive(ioapic_start, ioapic_end) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, WRITABLE, allocator); } } let lapic_addr = Frame::containing_address(sdt_loc.lapic_ctrl); if mapper.is_unused(&lapic_addr, allocator) { mapper.identity_map(lapic_addr, WRITABLE, allocator); } }); // TODO: Delete when appropriate let old_table = active_table.switch(new_table); //println!("NEW TABLE!!!"); // TODO: Delete when appropriate let old_p4_page = Page::containing_address(old_table.p4_frame.start_address()); active_table.unmap(old_p4_page, allocator); //println!("guard page at {:#x}", old_p4_page.start_address()); active_table } /// Basic tresting of different page table levels and allocations as well as mapping specific bits in specific levels pub fn test_paging<A>(allocator: &mut A) where A: FrameAllocator { let mut page_table = unsafe { ActivePageTable::new() }; // test translate println!("Some = {:?}", page_table.translate(0)); // second P1 entry println!("Some = {:?}", page_table.translate(4096)); // second P2 entry println!("Some = {:?}", page_table.translate(512 * 4096)); // 300th P2 entry println!("Some = {:?}", page_table.translate(300 * 512 * 4096)); // second P3 entry println!("None = {:?}", page_table.translate(512 * 512 * 4096)); // last mapped byte println!("Some = {:?}", page_table.translate(512 * 512 * 4096 - 1)); // test map_to // 42th P3 entry let addr = 42 * 512 * 512 * 4096; let page = Page::containing_address(addr); let frame = allocator.allocate_frame().expect("no more frames"); println!("None = {:?}, map to {:?}", page_table.translate(addr), frame); page_table.map_to(page, frame, EntryFlags::empty(), allocator); println!("Some = {:?}", page_table.translate(addr)); println!("next free frame: {:?}", allocator.allocate_frame()); // test unmap println!("{:#x}", unsafe { *(Page::containing_address(addr).start_address() as *const u64) }); page_table.unmap(Page::containing_address(addr), allocator); println!("None = {:?}", page_table.translate(addr)); }
} /// Remaps the kernel sections by creating a temporary page. pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation, sdt_loc: &mut SDT_Loc) -> ActivePageTable where A: FrameAllocator{
random_line_split
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump to the last level (level 1) retrive /// its address and then move to the offsets. pub use self::entry::*; ///FrameAllocator is the method used to create Frames from Pages use memory::{PAGE_SIZE, Frame, FrameAllocator}; // needed later use self::table::{Table, Level4}; pub use self::mapper::Mapper; use core::ptr::Unique; use core::ops::{Deref, DerefMut}; use self::temporary_page::TemporaryPage; use multiboot2::BootInformation; //use acpi::rsdp; use acpi::*; use core::mem; use core::option; //use self::paging::PhysicalAddress; //use self::entry::HUGE_PAGE; mod entry; mod table; mod mapper; ///Used to temporary map a frame to virtal address mod temporary_page; const ENTRY_COUNT: usize = 512; pub type PhysicalAddress = usize; pub type VirtualAddress = usize; /// Copy so that it can be used after passing'map_to' and similar functions. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Page { number: usize, } impl Page { /// The address space is split into two halves, high/low, where the higher /// half contains addresses and the sign extentions, the lower half contains /// just adresses. This is checked here with an assert. pub fn containing_address(address: VirtualAddress) -> Page { assert!(address < 0x0000_8000_0000_0000 || address >= 0xffff_8000_0000_0000, "invalid address: 0x{:x}", address); Page { number: address / PAGE_SIZE } } /// Takes a VirtualAddress and calculates start address fn start_address(&self) -> PhysicalAddress { self.number * PAGE_SIZE } /// Calculates the p4-starting index/point fn p4_index(&self) -> usize { (self.number >> 27) & 0o777 } /// Calculates the p3-starting index/point fn p3_index(&self) -> usize { (self.number >> 18) & 0o777 } /// Calculates the p2-starting index/point fn p2_index(&self) -> usize { (self.number >> 9) & 0o777 } /// Calculates the p1-starting index/point fn p1_index(&self) -> usize
/// Returns inclusive range iterator of pages pub fn range_inclusive(start: Page, end: Page) -> PageIter { PageIter { start: start, end: end } } } pub struct PageIter { start: Page, end: Page } impl Iterator for PageIter { type Item = Page; fn next(&mut self) -> Option<Page> { if self.start <= self.end { let page = self.start; self.start.number += 1; Some(page) } else { None } } } pub struct ActivePageTable { mapper: Mapper, } /// Dereference the ActivePageTable /// Returns reference to Mapper impl Deref for ActivePageTable { type Target = Mapper; fn deref(&self) -> &Mapper { &self.mapper } } /// Dereference the ActivePageTable /// Returns a mutable reference to Mapper impl DerefMut for ActivePageTable { fn deref_mut(&mut self) -> &mut Mapper { &mut self.mapper } } /// Does the recursive mapping to the four levels of page tables. impl ActivePageTable { unsafe fn new() -> ActivePageTable { ActivePageTable { mapper: Mapper::new(), } } /// Module that temporarily changes the recursive mapping. /// It overwrites the 511th P4 entry and points it to the /// inactive table frame. /// "It overwrites the 511th P4 entry and points it to the inactive table frame. Then it flushes the translation lookaside buffer (TLB), which still contains some old translations. We need to flush all pages that are part of the recursive mapping, so the easiest way is to flush the TLB completely."" pub fn with<F>(&mut self, table: &mut InactivePageTable, temporary_page: &mut temporary_page::TemporaryPage, f: F) where F: FnOnce(&mut Mapper) { use x86::{controlregs, tlb}; let flush_tlb = || unsafe { tlb::flush_all() }; { let backup = Frame::containing_address ( unsafe { controlregs::cr3() } as usize); // map temporary_page to current p4 table let p4_table = temporary_page.map_table_frame(backup.clone(), self); // overwrite recursive mapping self.p4_mut()[511].set(table.p4_frame.clone(), PRESENT | WRITABLE); flush_tlb(); // execute f in the new context f(self); // restore recursive mapping to original p4 table p4_table[511].set(backup, PRESENT | WRITABLE); flush_tlb(); } temporary_page.unmap(self); } pub fn switch(&mut self, new_table: InactivePageTable) -> InactivePageTable { use x86::controlregs; let old_table = InactivePageTable { p4_frame: Frame::containing_address( unsafe { controlregs::cr3() } as usize), }; unsafe { controlregs::cr3_write(new_table.p4_frame.start_address() as u64); } old_table } } pub struct InactivePageTable { p4_frame: Frame, } /// Creates valid, inactive page tables that are zeroed and recursively mapped. impl InactivePageTable { pub fn new(frame: Frame, active_table: &mut ActivePageTable, temporary_page: &mut TemporaryPage) -> InactivePageTable { { // The 'active_table' and 'temporary_table' arguments needs to // be in a inner scope to ensure shadowing since the table // variable exclusively borrows temporary_page as long as it's alive let table = temporary_page.map_table_frame(frame.clone(), active_table); // Zeroing table is done here *duh* table.zero(); // Recursive mapping for the table table[511].set(frame.clone(), PRESENT | WRITABLE); } temporary_page.unmap(active_table); InactivePageTable {p4_frame: frame } } } /// Remaps the kernel sections by creating a temporary page. pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation, sdt_loc: &mut SDT_Loc) -> ActivePageTable where A: FrameAllocator{ use core::ops::Range; // Create a temporary page at some page number, in this case 0xcafebabe let mut temporary_page = TemporaryPage::new(Page { number: 0xcafebabe }, allocator); // Created by constructor let mut active_table = unsafe { ActivePageTable::new() }; // Created by constructor let mut new_table = { let frame = allocator.allocate_frame().expect("no more frames"); InactivePageTable::new(frame, &mut active_table, &mut temporary_page) }; active_table.with(&mut new_table, &mut temporary_page, |mapper| { let elf_sections_tag = boot_info.elf_sections_tag() .expect("Memory map tag required"); // Identity map the allocated kernel sections // Skip sections that are not loaded to memory. // We require pages to be aligned, see src/arch/x86_64/linker.ld for implementations for section in elf_sections_tag.sections() { if!section.is_allocated() { // section is not loaded to memory continue; } assert!(section.addr as usize % PAGE_SIZE == 0, "sections need to be page aligned"); // println!("mapping section at addr: {:#x}, size: {:#x}", // section.addr, // section.size); let flags = EntryFlags::from_elf_section_flags(section); let start_frame = Frame::containing_address(section.start_address()); let end_frame = Frame::containing_address(section.end_address() - 1); // 'range_inclusive' iterates over all frames on a section for frame in Frame::range_inclusive(start_frame, end_frame) { mapper.identity_map(frame, flags, allocator); } } // identity map the VGA text buffer let vga_buffer_frame = Frame::containing_address(0xb8000); mapper.identity_map(vga_buffer_frame, WRITABLE, allocator); // identity map the multiboot info structure let multiboot_start = Frame::containing_address(boot_info.start_address()); let multiboot_end = Frame::containing_address(boot_info.end_address() - 1); for frame in Frame::range_inclusive(multiboot_start, multiboot_end) { mapper.identity_map(frame, PRESENT, allocator); } for (start, end, next) in &mut sdt_loc.into_iter() { //println!("Allocating addresses {:x} to {:x} and {:x}", start, end, next); let start_addr = Frame::containing_address(start); let end_addr = Frame::containing_address(end); for frame in Frame::range_inclusive(start_addr, end_addr) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, PRESENT, allocator); } } if next!= 0 { let next_header_frame = Frame::containing_address(next); if mapper.is_unused(&next_header_frame, allocator) { mapper.identity_map(next_header_frame, PRESENT, allocator); } } } let ioapic_start = Frame::containing_address(sdt_loc.ioapic_start); let ioapic_end = Frame::containing_address(sdt_loc.ioapic_end); for frame in Frame::range_inclusive(ioapic_start, ioapic_end) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, WRITABLE, allocator); } } let lapic_addr = Frame::containing_address(sdt_loc.lapic_ctrl); if mapper.is_unused(&lapic_addr, allocator) { mapper.identity_map(lapic_addr, WRITABLE, allocator); } }); // TODO: Delete when appropriate let old_table = active_table.switch(new_table); //println!("NEW TABLE!!!"); // TODO: Delete when appropriate let old_p4_page = Page::containing_address(old_table.p4_frame.start_address()); active_table.unmap(old_p4_page, allocator); //println!("guard page at {:#x}", old_p4_page.start_address()); active_table } /// Basic tresting of different page table levels and allocations as well as mapping specific bits in specific levels pub fn test_paging<A>(allocator: &mut A) where A: FrameAllocator { let mut page_table = unsafe { ActivePageTable::new() }; // test translate println!("Some = {:?}", page_table.translate(0)); // second P1 entry println!("Some = {:?}", page_table.translate(4096)); // second P2 entry println!("Some = {:?}", page_table.translate(512 * 4096)); // 300th P2 entry println!("Some = {:?}", page_table.translate(300 * 512 * 4096)); // second P3 entry println!("None = {:?}", page_table.translate(512 * 512 * 4096)); // last mapped byte println!("Some = {:?}", page_table.translate(512 * 512 * 4096 - 1)); // test map_to // 42th P3 entry let addr = 42 * 512 * 512 * 4096; let page = Page::containing_address(addr); let frame = allocator.allocate_frame().expect("no more frames"); println!("None = {:?}, map to {:?}", page_table.translate(addr), frame); page_table.map_to(page, frame, EntryFlags::empty(), allocator); println!("Some = {:?}", page_table.translate(addr)); println!("next free frame: {:?}", allocator.allocate_frame()); // test unmap println!("{:#x}", unsafe { *(Page::containing_address(addr).start_address() as *const u64) }); page_table.unmap(Page::containing_address(addr), allocator); println!("None = {:?}", page_table.translate(addr)); }
{ (self.number >> 0) & 0o777 }
identifier_body
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump to the last level (level 1) retrive /// its address and then move to the offsets. pub use self::entry::*; ///FrameAllocator is the method used to create Frames from Pages use memory::{PAGE_SIZE, Frame, FrameAllocator}; // needed later use self::table::{Table, Level4}; pub use self::mapper::Mapper; use core::ptr::Unique; use core::ops::{Deref, DerefMut}; use self::temporary_page::TemporaryPage; use multiboot2::BootInformation; //use acpi::rsdp; use acpi::*; use core::mem; use core::option; //use self::paging::PhysicalAddress; //use self::entry::HUGE_PAGE; mod entry; mod table; mod mapper; ///Used to temporary map a frame to virtal address mod temporary_page; const ENTRY_COUNT: usize = 512; pub type PhysicalAddress = usize; pub type VirtualAddress = usize; /// Copy so that it can be used after passing'map_to' and similar functions. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Page { number: usize, } impl Page { /// The address space is split into two halves, high/low, where the higher /// half contains addresses and the sign extentions, the lower half contains /// just adresses. This is checked here with an assert. pub fn containing_address(address: VirtualAddress) -> Page { assert!(address < 0x0000_8000_0000_0000 || address >= 0xffff_8000_0000_0000, "invalid address: 0x{:x}", address); Page { number: address / PAGE_SIZE } } /// Takes a VirtualAddress and calculates start address fn start_address(&self) -> PhysicalAddress { self.number * PAGE_SIZE } /// Calculates the p4-starting index/point fn p4_index(&self) -> usize { (self.number >> 27) & 0o777 } /// Calculates the p3-starting index/point fn p3_index(&self) -> usize { (self.number >> 18) & 0o777 } /// Calculates the p2-starting index/point fn p2_index(&self) -> usize { (self.number >> 9) & 0o777 } /// Calculates the p1-starting index/point fn
(&self) -> usize { (self.number >> 0) & 0o777 } /// Returns inclusive range iterator of pages pub fn range_inclusive(start: Page, end: Page) -> PageIter { PageIter { start: start, end: end } } } pub struct PageIter { start: Page, end: Page } impl Iterator for PageIter { type Item = Page; fn next(&mut self) -> Option<Page> { if self.start <= self.end { let page = self.start; self.start.number += 1; Some(page) } else { None } } } pub struct ActivePageTable { mapper: Mapper, } /// Dereference the ActivePageTable /// Returns reference to Mapper impl Deref for ActivePageTable { type Target = Mapper; fn deref(&self) -> &Mapper { &self.mapper } } /// Dereference the ActivePageTable /// Returns a mutable reference to Mapper impl DerefMut for ActivePageTable { fn deref_mut(&mut self) -> &mut Mapper { &mut self.mapper } } /// Does the recursive mapping to the four levels of page tables. impl ActivePageTable { unsafe fn new() -> ActivePageTable { ActivePageTable { mapper: Mapper::new(), } } /// Module that temporarily changes the recursive mapping. /// It overwrites the 511th P4 entry and points it to the /// inactive table frame. /// "It overwrites the 511th P4 entry and points it to the inactive table frame. Then it flushes the translation lookaside buffer (TLB), which still contains some old translations. We need to flush all pages that are part of the recursive mapping, so the easiest way is to flush the TLB completely."" pub fn with<F>(&mut self, table: &mut InactivePageTable, temporary_page: &mut temporary_page::TemporaryPage, f: F) where F: FnOnce(&mut Mapper) { use x86::{controlregs, tlb}; let flush_tlb = || unsafe { tlb::flush_all() }; { let backup = Frame::containing_address ( unsafe { controlregs::cr3() } as usize); // map temporary_page to current p4 table let p4_table = temporary_page.map_table_frame(backup.clone(), self); // overwrite recursive mapping self.p4_mut()[511].set(table.p4_frame.clone(), PRESENT | WRITABLE); flush_tlb(); // execute f in the new context f(self); // restore recursive mapping to original p4 table p4_table[511].set(backup, PRESENT | WRITABLE); flush_tlb(); } temporary_page.unmap(self); } pub fn switch(&mut self, new_table: InactivePageTable) -> InactivePageTable { use x86::controlregs; let old_table = InactivePageTable { p4_frame: Frame::containing_address( unsafe { controlregs::cr3() } as usize), }; unsafe { controlregs::cr3_write(new_table.p4_frame.start_address() as u64); } old_table } } pub struct InactivePageTable { p4_frame: Frame, } /// Creates valid, inactive page tables that are zeroed and recursively mapped. impl InactivePageTable { pub fn new(frame: Frame, active_table: &mut ActivePageTable, temporary_page: &mut TemporaryPage) -> InactivePageTable { { // The 'active_table' and 'temporary_table' arguments needs to // be in a inner scope to ensure shadowing since the table // variable exclusively borrows temporary_page as long as it's alive let table = temporary_page.map_table_frame(frame.clone(), active_table); // Zeroing table is done here *duh* table.zero(); // Recursive mapping for the table table[511].set(frame.clone(), PRESENT | WRITABLE); } temporary_page.unmap(active_table); InactivePageTable {p4_frame: frame } } } /// Remaps the kernel sections by creating a temporary page. pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation, sdt_loc: &mut SDT_Loc) -> ActivePageTable where A: FrameAllocator{ use core::ops::Range; // Create a temporary page at some page number, in this case 0xcafebabe let mut temporary_page = TemporaryPage::new(Page { number: 0xcafebabe }, allocator); // Created by constructor let mut active_table = unsafe { ActivePageTable::new() }; // Created by constructor let mut new_table = { let frame = allocator.allocate_frame().expect("no more frames"); InactivePageTable::new(frame, &mut active_table, &mut temporary_page) }; active_table.with(&mut new_table, &mut temporary_page, |mapper| { let elf_sections_tag = boot_info.elf_sections_tag() .expect("Memory map tag required"); // Identity map the allocated kernel sections // Skip sections that are not loaded to memory. // We require pages to be aligned, see src/arch/x86_64/linker.ld for implementations for section in elf_sections_tag.sections() { if!section.is_allocated() { // section is not loaded to memory continue; } assert!(section.addr as usize % PAGE_SIZE == 0, "sections need to be page aligned"); // println!("mapping section at addr: {:#x}, size: {:#x}", // section.addr, // section.size); let flags = EntryFlags::from_elf_section_flags(section); let start_frame = Frame::containing_address(section.start_address()); let end_frame = Frame::containing_address(section.end_address() - 1); // 'range_inclusive' iterates over all frames on a section for frame in Frame::range_inclusive(start_frame, end_frame) { mapper.identity_map(frame, flags, allocator); } } // identity map the VGA text buffer let vga_buffer_frame = Frame::containing_address(0xb8000); mapper.identity_map(vga_buffer_frame, WRITABLE, allocator); // identity map the multiboot info structure let multiboot_start = Frame::containing_address(boot_info.start_address()); let multiboot_end = Frame::containing_address(boot_info.end_address() - 1); for frame in Frame::range_inclusive(multiboot_start, multiboot_end) { mapper.identity_map(frame, PRESENT, allocator); } for (start, end, next) in &mut sdt_loc.into_iter() { //println!("Allocating addresses {:x} to {:x} and {:x}", start, end, next); let start_addr = Frame::containing_address(start); let end_addr = Frame::containing_address(end); for frame in Frame::range_inclusive(start_addr, end_addr) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, PRESENT, allocator); } } if next!= 0 { let next_header_frame = Frame::containing_address(next); if mapper.is_unused(&next_header_frame, allocator) { mapper.identity_map(next_header_frame, PRESENT, allocator); } } } let ioapic_start = Frame::containing_address(sdt_loc.ioapic_start); let ioapic_end = Frame::containing_address(sdt_loc.ioapic_end); for frame in Frame::range_inclusive(ioapic_start, ioapic_end) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, WRITABLE, allocator); } } let lapic_addr = Frame::containing_address(sdt_loc.lapic_ctrl); if mapper.is_unused(&lapic_addr, allocator) { mapper.identity_map(lapic_addr, WRITABLE, allocator); } }); // TODO: Delete when appropriate let old_table = active_table.switch(new_table); //println!("NEW TABLE!!!"); // TODO: Delete when appropriate let old_p4_page = Page::containing_address(old_table.p4_frame.start_address()); active_table.unmap(old_p4_page, allocator); //println!("guard page at {:#x}", old_p4_page.start_address()); active_table } /// Basic tresting of different page table levels and allocations as well as mapping specific bits in specific levels pub fn test_paging<A>(allocator: &mut A) where A: FrameAllocator { let mut page_table = unsafe { ActivePageTable::new() }; // test translate println!("Some = {:?}", page_table.translate(0)); // second P1 entry println!("Some = {:?}", page_table.translate(4096)); // second P2 entry println!("Some = {:?}", page_table.translate(512 * 4096)); // 300th P2 entry println!("Some = {:?}", page_table.translate(300 * 512 * 4096)); // second P3 entry println!("None = {:?}", page_table.translate(512 * 512 * 4096)); // last mapped byte println!("Some = {:?}", page_table.translate(512 * 512 * 4096 - 1)); // test map_to // 42th P3 entry let addr = 42 * 512 * 512 * 4096; let page = Page::containing_address(addr); let frame = allocator.allocate_frame().expect("no more frames"); println!("None = {:?}, map to {:?}", page_table.translate(addr), frame); page_table.map_to(page, frame, EntryFlags::empty(), allocator); println!("Some = {:?}", page_table.translate(addr)); println!("next free frame: {:?}", allocator.allocate_frame()); // test unmap println!("{:#x}", unsafe { *(Page::containing_address(addr).start_address() as *const u64) }); page_table.unmap(Page::containing_address(addr), allocator); println!("None = {:?}", page_table.translate(addr)); }
p1_index
identifier_name
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump to the last level (level 1) retrive /// its address and then move to the offsets. pub use self::entry::*; ///FrameAllocator is the method used to create Frames from Pages use memory::{PAGE_SIZE, Frame, FrameAllocator}; // needed later use self::table::{Table, Level4}; pub use self::mapper::Mapper; use core::ptr::Unique; use core::ops::{Deref, DerefMut}; use self::temporary_page::TemporaryPage; use multiboot2::BootInformation; //use acpi::rsdp; use acpi::*; use core::mem; use core::option; //use self::paging::PhysicalAddress; //use self::entry::HUGE_PAGE; mod entry; mod table; mod mapper; ///Used to temporary map a frame to virtal address mod temporary_page; const ENTRY_COUNT: usize = 512; pub type PhysicalAddress = usize; pub type VirtualAddress = usize; /// Copy so that it can be used after passing'map_to' and similar functions. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Page { number: usize, } impl Page { /// The address space is split into two halves, high/low, where the higher /// half contains addresses and the sign extentions, the lower half contains /// just adresses. This is checked here with an assert. pub fn containing_address(address: VirtualAddress) -> Page { assert!(address < 0x0000_8000_0000_0000 || address >= 0xffff_8000_0000_0000, "invalid address: 0x{:x}", address); Page { number: address / PAGE_SIZE } } /// Takes a VirtualAddress and calculates start address fn start_address(&self) -> PhysicalAddress { self.number * PAGE_SIZE } /// Calculates the p4-starting index/point fn p4_index(&self) -> usize { (self.number >> 27) & 0o777 } /// Calculates the p3-starting index/point fn p3_index(&self) -> usize { (self.number >> 18) & 0o777 } /// Calculates the p2-starting index/point fn p2_index(&self) -> usize { (self.number >> 9) & 0o777 } /// Calculates the p1-starting index/point fn p1_index(&self) -> usize { (self.number >> 0) & 0o777 } /// Returns inclusive range iterator of pages pub fn range_inclusive(start: Page, end: Page) -> PageIter { PageIter { start: start, end: end } } } pub struct PageIter { start: Page, end: Page } impl Iterator for PageIter { type Item = Page; fn next(&mut self) -> Option<Page> { if self.start <= self.end { let page = self.start; self.start.number += 1; Some(page) } else { None } } } pub struct ActivePageTable { mapper: Mapper, } /// Dereference the ActivePageTable /// Returns reference to Mapper impl Deref for ActivePageTable { type Target = Mapper; fn deref(&self) -> &Mapper { &self.mapper } } /// Dereference the ActivePageTable /// Returns a mutable reference to Mapper impl DerefMut for ActivePageTable { fn deref_mut(&mut self) -> &mut Mapper { &mut self.mapper } } /// Does the recursive mapping to the four levels of page tables. impl ActivePageTable { unsafe fn new() -> ActivePageTable { ActivePageTable { mapper: Mapper::new(), } } /// Module that temporarily changes the recursive mapping. /// It overwrites the 511th P4 entry and points it to the /// inactive table frame. /// "It overwrites the 511th P4 entry and points it to the inactive table frame. Then it flushes the translation lookaside buffer (TLB), which still contains some old translations. We need to flush all pages that are part of the recursive mapping, so the easiest way is to flush the TLB completely."" pub fn with<F>(&mut self, table: &mut InactivePageTable, temporary_page: &mut temporary_page::TemporaryPage, f: F) where F: FnOnce(&mut Mapper) { use x86::{controlregs, tlb}; let flush_tlb = || unsafe { tlb::flush_all() }; { let backup = Frame::containing_address ( unsafe { controlregs::cr3() } as usize); // map temporary_page to current p4 table let p4_table = temporary_page.map_table_frame(backup.clone(), self); // overwrite recursive mapping self.p4_mut()[511].set(table.p4_frame.clone(), PRESENT | WRITABLE); flush_tlb(); // execute f in the new context f(self); // restore recursive mapping to original p4 table p4_table[511].set(backup, PRESENT | WRITABLE); flush_tlb(); } temporary_page.unmap(self); } pub fn switch(&mut self, new_table: InactivePageTable) -> InactivePageTable { use x86::controlregs; let old_table = InactivePageTable { p4_frame: Frame::containing_address( unsafe { controlregs::cr3() } as usize), }; unsafe { controlregs::cr3_write(new_table.p4_frame.start_address() as u64); } old_table } } pub struct InactivePageTable { p4_frame: Frame, } /// Creates valid, inactive page tables that are zeroed and recursively mapped. impl InactivePageTable { pub fn new(frame: Frame, active_table: &mut ActivePageTable, temporary_page: &mut TemporaryPage) -> InactivePageTable { { // The 'active_table' and 'temporary_table' arguments needs to // be in a inner scope to ensure shadowing since the table // variable exclusively borrows temporary_page as long as it's alive let table = temporary_page.map_table_frame(frame.clone(), active_table); // Zeroing table is done here *duh* table.zero(); // Recursive mapping for the table table[511].set(frame.clone(), PRESENT | WRITABLE); } temporary_page.unmap(active_table); InactivePageTable {p4_frame: frame } } } /// Remaps the kernel sections by creating a temporary page. pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation, sdt_loc: &mut SDT_Loc) -> ActivePageTable where A: FrameAllocator{ use core::ops::Range; // Create a temporary page at some page number, in this case 0xcafebabe let mut temporary_page = TemporaryPage::new(Page { number: 0xcafebabe }, allocator); // Created by constructor let mut active_table = unsafe { ActivePageTable::new() }; // Created by constructor let mut new_table = { let frame = allocator.allocate_frame().expect("no more frames"); InactivePageTable::new(frame, &mut active_table, &mut temporary_page) }; active_table.with(&mut new_table, &mut temporary_page, |mapper| { let elf_sections_tag = boot_info.elf_sections_tag() .expect("Memory map tag required"); // Identity map the allocated kernel sections // Skip sections that are not loaded to memory. // We require pages to be aligned, see src/arch/x86_64/linker.ld for implementations for section in elf_sections_tag.sections() { if!section.is_allocated() { // section is not loaded to memory continue; } assert!(section.addr as usize % PAGE_SIZE == 0, "sections need to be page aligned"); // println!("mapping section at addr: {:#x}, size: {:#x}", // section.addr, // section.size); let flags = EntryFlags::from_elf_section_flags(section); let start_frame = Frame::containing_address(section.start_address()); let end_frame = Frame::containing_address(section.end_address() - 1); // 'range_inclusive' iterates over all frames on a section for frame in Frame::range_inclusive(start_frame, end_frame) { mapper.identity_map(frame, flags, allocator); } } // identity map the VGA text buffer let vga_buffer_frame = Frame::containing_address(0xb8000); mapper.identity_map(vga_buffer_frame, WRITABLE, allocator); // identity map the multiboot info structure let multiboot_start = Frame::containing_address(boot_info.start_address()); let multiboot_end = Frame::containing_address(boot_info.end_address() - 1); for frame in Frame::range_inclusive(multiboot_start, multiboot_end) { mapper.identity_map(frame, PRESENT, allocator); } for (start, end, next) in &mut sdt_loc.into_iter() { //println!("Allocating addresses {:x} to {:x} and {:x}", start, end, next); let start_addr = Frame::containing_address(start); let end_addr = Frame::containing_address(end); for frame in Frame::range_inclusive(start_addr, end_addr) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, PRESENT, allocator); } } if next!= 0 { let next_header_frame = Frame::containing_address(next); if mapper.is_unused(&next_header_frame, allocator)
} } let ioapic_start = Frame::containing_address(sdt_loc.ioapic_start); let ioapic_end = Frame::containing_address(sdt_loc.ioapic_end); for frame in Frame::range_inclusive(ioapic_start, ioapic_end) { if mapper.is_unused(&frame, allocator) { mapper.identity_map(frame, WRITABLE, allocator); } } let lapic_addr = Frame::containing_address(sdt_loc.lapic_ctrl); if mapper.is_unused(&lapic_addr, allocator) { mapper.identity_map(lapic_addr, WRITABLE, allocator); } }); // TODO: Delete when appropriate let old_table = active_table.switch(new_table); //println!("NEW TABLE!!!"); // TODO: Delete when appropriate let old_p4_page = Page::containing_address(old_table.p4_frame.start_address()); active_table.unmap(old_p4_page, allocator); //println!("guard page at {:#x}", old_p4_page.start_address()); active_table } /// Basic tresting of different page table levels and allocations as well as mapping specific bits in specific levels pub fn test_paging<A>(allocator: &mut A) where A: FrameAllocator { let mut page_table = unsafe { ActivePageTable::new() }; // test translate println!("Some = {:?}", page_table.translate(0)); // second P1 entry println!("Some = {:?}", page_table.translate(4096)); // second P2 entry println!("Some = {:?}", page_table.translate(512 * 4096)); // 300th P2 entry println!("Some = {:?}", page_table.translate(300 * 512 * 4096)); // second P3 entry println!("None = {:?}", page_table.translate(512 * 512 * 4096)); // last mapped byte println!("Some = {:?}", page_table.translate(512 * 512 * 4096 - 1)); // test map_to // 42th P3 entry let addr = 42 * 512 * 512 * 4096; let page = Page::containing_address(addr); let frame = allocator.allocate_frame().expect("no more frames"); println!("None = {:?}, map to {:?}", page_table.translate(addr), frame); page_table.map_to(page, frame, EntryFlags::empty(), allocator); println!("Some = {:?}", page_table.translate(addr)); println!("next free frame: {:?}", allocator.allocate_frame()); // test unmap println!("{:#x}", unsafe { *(Page::containing_address(addr).start_address() as *const u64) }); page_table.unmap(Page::containing_address(addr), allocator); println!("None = {:?}", page_table.translate(addr)); }
{ mapper.identity_map(next_header_frame, PRESENT, allocator); }
conditional_block
module.rs
display = "Cannot find method with pointer {:?}.", _0)] pub struct CannotFindMethod(language_server::MethodPointer); #[allow(missing_docs)] #[derive(Fail, Clone, Debug)] #[fail(display = "The definition with crumbs {:?} is not a direct child of the module.", _0)] pub struct NotDirectChild(ast::Crumbs); // ========== // === Id === // ========== /// The segments of module name. Allow finding module in the project. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Id { /// The last segment being a module name. For project's main module it should be equal /// to [`PROJECTS_MAIN_MODULE`]. pub name: ImString, /// The segments of all parent modules, from the top module to the direct parent. Does **not** /// include project name. pub parent_modules: Vec<ImString>, } impl Id { /// Create module id from list of segments. The list shall not contain the project name nor /// namespace. Fails if the list is empty (the module name is required). pub fn try_from_segments( segments: impl IntoIterator<Item: Into<ImString>>, ) -> FallibleResult<Self> { let mut segments = segments.into_iter().map(Into::into).collect_vec(); let name = segments.pop().ok_or(EmptySegments)?; Ok(Self { name, parent_modules: segments }) } /// Return the iterator over id's segments. pub fn segments(&self) -> impl Iterator<Item = &ImString> { self.parent_modules.iter().chain(iter::once(&self.name)) } } impl IntoIterator for Id { type Item = ImString; type IntoIter = impl Iterator<Item = Self::Item>; fn into_iter(self) -> Self::IntoIter { self.parent_modules.into_iter().chain(iter::once(self.name)) } } impl From<Id> for NamePath { fn from(id: Id) -> Self { id.into_iter().collect() } } impl Display for Id { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.segments().format(".")) } } // ============ // === Info === // ============ /// Wrapper allowing getting information about the module and updating it. #[derive(Clone, Debug)] pub struct Info { #[allow(missing_docs)] pub ast: known::Module, } impl Info { /// Generate a name for a definition that can be introduced without side-effects. /// /// The name shall be generated by appending number to the given base string. pub fn generate_name(&self, base: &str) -> FallibleResult<Identifier> { let used_names = self.used_names(); let used_names = used_names.iter().map(|name| name.item.as_str()); identifier::generate_name(base, used_names) } /// Identifiers introduced or referred to in the module's scope. /// /// Introducing identifier not included on this list should have no side-effects on the name /// resolution in the code in this graph. pub fn used_names(&self) -> Vec<Located<String>> { let usage = alias_analysis::analyze_crumbable(self.ast.shape()); usage.all_identifiers() } /// Iterate over all lines in module that contain an import declaration. pub fn enumerate_imports(&self) -> impl Iterator<Item = (ModuleCrumb, import::Info)> + '_ { let children = self.ast.shape().enumerate(); children.filter_map(|(crumb, ast)| Some((crumb, import::Info::from_ast(ast)?))) } /// Iterate over all import declarations in the module. /// /// If the caller wants to know *where* the declarations are, use `enumerate_imports`. pub fn iter_imports(&self) -> impl Iterator<Item = import::Info> + '_ { self.enumerate_imports().map(|(_, import)| import) } /// Check if module contains import with given id. pub fn contains_import(&self, id: import::Id) -> bool { self.iter_imports().any(|import| import.id() == id) } /// Add a new line to the module's block. /// /// Note that indices are the "module line" indices, which usually are quite different from text /// API line indices (because nested blocks doesn't count as separate "module lines"). pub fn add_line(&mut self, index: usize, ast: Option<Ast>) { let line = BlockLine::new(ast); self.ast.update_shape(|shape| shape.lines.insert(index, line)) } /// Remove line with given index. /// /// Returns removed line. Fails if the index is out of bounds. pub fn remove_line(&mut self, index: usize) -> FallibleResult<BlockLine<Option<Ast>>> { self.ast.update_shape(|shape| { shape.lines.try_remove(index).ok_or_else(|| LineIndexOutOfBounds.into()) }) } /// Remove a line that matches given import description. /// /// If there is more than one line matching, only the first one will be removed. /// Fails if there is no import matching given argument. pub fn remove_import(&mut self, to_remove: &import::Info) -> FallibleResult { let lookup_result = self.enumerate_imports().find(|(_, import)| import == to_remove); let (crumb, _) = lookup_result.ok_or_else(|| ImportNotFound(to_remove.to_string()))?; self.remove_line(crumb.line_index)?; Ok(()) } /// Remove a line that matches given import ID. /// /// If there is more than one line matching, only the first one will be removed. /// Fails if there is no import matching given argument. pub fn remove_import_by_id(&mut self, to_remove: import::Id) -> FallibleResult { let lookup_result = self.enumerate_imports().find(|(_, import)| import.id() == to_remove); let (crumb, _) = lookup_result.ok_or(ImportIdNotFound(to_remove))?; self.remove_line(crumb.line_index)?; Ok(()) } /// Add a new import declaration to a module. /// /// This function will try to keep imports in lexicographic order. It returns the index where /// import was added (index of import - an element on the list returned by `enumerate_imports`). // TODO [mwu] // Ideally we should not require parser but should use some sane way of generating AST from // the `ImportInfo` value. pub fn add_import(&mut self, parser: &parser::Parser, to_add: import::Info) -> usize { // Find last import that is not "after" the added one lexicographically. let previous_import = self.enumerate_imports().take_while(|(_, import)| &to_add > import).last(); let index_to_place_at = previous_import.map_or(0, |(crumb, _)| crumb.line_index + 1); let import_ast = parser.parse_line_ast(to_add.to_string()).unwrap(); self.add_line(index_to_place_at, Some(import_ast)); index_to_place_at } /// Add a new import declaration to a module. /// /// For more details the mechanics see [`add_import`] documentation. pub fn add_import_if_missing( &mut self, parser: &parser::Parser, to_add: import::Info, ) -> Option<usize> { (!self.contains_import(to_add.id())).then(|| self.add_import(parser, to_add)) } /// Place the line with given AST in the module's body. /// /// Unlike `add_line` (which is more low-level) will introduce empty lines around introduced /// line and describes the added line location in relation to other definitions. /// /// Typically used to place lines with definitions in the module. pub fn add_ast(&mut self, ast: Ast, location: Placement) -> FallibleResult { #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum BlankLinePlacement { Before, After, None, } let blank_line = match location { _ if self.ast.lines.is_empty() => BlankLinePlacement::None, Placement::Begin => BlankLinePlacement::After, Placement::End => BlankLinePlacement::Before, Placement::After(_) => BlankLinePlacement::Before, Placement::Before(_) => BlankLinePlacement::After, }; let mut index = match location { Placement::Begin => 0, Placement::End => self.ast.lines.len(), Placement::Before(next_def) => locate_line_with(&self.ast, &next_def)?.line_index, Placement::After(next_def) => locate_line_with(&self.ast, &next_def)?.line_index + 1, }; let mut add_line = |ast_opt: Option<Ast>| { self.add_line(index, ast_opt); index += 1; }; if blank_line == BlankLinePlacement::Before
add_line(Some(ast)); if blank_line == BlankLinePlacement::After { add_line(None); } Ok(()) } /// Add a new method definition to the module. pub fn add_method( &mut self, method: definition::ToAdd, location: Placement, parser: &parser::Parser, ) -> FallibleResult { let no_indent = 0; let definition_ast = method.ast(no_indent, parser)?; self.add_ast(definition_ast, location) } /// Updates the given definition using the passed invokable. pub fn update_definition( &mut self, id: &definition::Id, f: impl FnOnce(definition::DefinitionInfo) -> FallibleResult<definition::DefinitionInfo>, ) -> FallibleResult { let definition = locate(&self.ast, id)?; let new_definition = f(definition.item)?; let new_ast = new_definition.ast.into(); self.ast = self.ast.set_traversing(&definition.crumbs, new_ast)?; Ok(()) } #[cfg(test)] pub fn expect_code(&self, expected_code: impl AsRef<str>) { assert_eq!(self.ast.repr(), expected_code.as_ref()); } } impl From<known::Module> for Info { fn from(ast: known::Module) -> Self { Info { ast } } } // ================= // === Placement === // ================= /// Structure describing where to place something being added to the module. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Placement { /// Place at the beginning of the module. Begin, /// Place at the end of the module. End, /// Place after given definition; Before(definition::Crumb), /// Place before given definition; After(definition::Crumb), } // ======================= // === ChildDefinition === // ======================= /// Represents information about a definition being a direct child of this module, including its /// location. /// /// Internally it is `definition::ChildDefinition` with only a single `ModuleCrumb` as location. #[derive(Clone, Debug, Deref)] pub struct ChildDefinition(definition::ChildDefinition); impl ChildDefinition { fn try_retrieving_crumb(child: &definition::ChildDefinition) -> Option<ModuleCrumb> { match child.crumbs.as_slice() { [ast::crumbs::Crumb::Module(crumb)] => Some(*crumb), _ => None, } } /// Try constructing value from `definition::ChildDefinition`. Fails if it is not a direct child /// of a module. pub fn new(child: definition::ChildDefinition) -> Result<Self, NotDirectChild> { if Self::try_retrieving_crumb(&child).is_some() { Ok(Self(child)) } else { Err(NotDirectChild(child.crumbs)) } } /// The location of this definition child in the module. pub fn crumb(&self) -> ModuleCrumb { // Safe, because our only constructor checks that this works. This is the type's invariant. Self::try_retrieving_crumb(&self.0).unwrap() } } impl TryFrom<definition::ChildDefinition> for ChildDefinition { type Error = NotDirectChild; fn try_from(value: definition::ChildDefinition) -> Result<Self, Self::Error> { Self::new(value) } } // ======================== // === Module Utilities === // ======================== /// Looks up graph in the module. pub fn get_definition( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<definition::DefinitionInfo> { Ok(locate(ast, id)?.item) } /// Locate the line with given definition and return crumb that denotes it. /// /// Fails if there is no matching definition being a direct child of the module. pub fn locate_line_with( ast: &known::Module, crumb: &definition::Crumb, ) -> FallibleResult<ModuleCrumb> { locate_child(ast, crumb).map(|child| child.crumb()) } /// Locate the definition being the module's direct child. pub fn locate_child( ast: &known::Module, crumb: &definition::Crumb, ) -> FallibleResult<ChildDefinition> { let child = ast.def_iter().find_by_name(crumb)?; Ok(ChildDefinition::try_from(child)?) } /// Traverses the module's definition tree following the given Id crumbs, looking up the definition. pub fn locate( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<definition::ChildDefinition> { let mut crumbs_iter = id.crumbs.iter(); // Not exactly regular - we need special case for the first crumb as it is not a definition nor // a children. After this we can go just from one definition to another. let first_crumb = crumbs_iter.next().ok_or(EmptyDefinitionId)?; let mut child = ast.def_iter().find_by_name(first_crumb)?; for crumb in crumbs_iter { child = definition::resolve_single_name(child, crumb)?; } Ok(child) } /// Get a definition ID that points to a method matching given pointer. /// /// The module is assumed to be in the file identified by the `method.file` (for the purpose of /// desugaring implicit extensions methods for modules). /// /// The `module_name` parameter is the name of the module that contains `ast`. pub fn lookup_method( module_name: &QualifiedName, ast: &known::Module, method: &language_server::MethodPointer, ) -> FallibleResult<definition::Id> { let qualified_typename = QualifiedName::from_text(&method.defined_on_type)?; let defined_in_this_module = module_name == &qualified_typename; let method_module_name = QualifiedName::from_text(&method.module)?; let implicit_extension_allowed = method.defined_on_type == method_module_name.to_string(); for child in ast.def_iter() { let child_name = &child.name.item; let name_matches = child_name.name.item == method.name; let type_matches = match child_name.extended_target.as_slice() { [] => implicit_extension_allowed || defined_in_this_module, [typename] => typename.item == qualified_typename.name(), _ => child_name.explicitly_extends_type(&method.defined_on_type), }; if name_matches && type_matches { return Ok(definition::Id::new_single_crumb(child_name.clone())); } } Err(CannotFindMethod(method.clone()).into()) } /// Get a span in module's text representation where the given definition is located. pub fn definition_span( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<enso_text::Range<Byte>> { let location = locate(ast, id)?; ast.range_of_descendant_at(&location.crumbs) } impl DefinitionProvider for known::Module { fn indent(&self) -> usize { 0 } fn scope_kind(&self) -> definition::ScopeKind { definition::ScopeKind::Root } fn enumerate_asts<'a>(&'a self) -> Box<dyn Iterator<Item = ChildAst<'a>> + 'a> { self.ast().children() } } // ================ // === MethodId === // ================ /// A structure identifying a method. /// /// It is very similar to MethodPointer from language_server API, however it may point to the method /// outside the currently opened project. #[derive(Clone, Debug, serde::Deserialize, Eq, Hash, PartialEq, serde::Serialize)] #[allow(missing_docs)] pub struct MethodId { pub module: QualifiedName, pub defined_on_type: QualifiedName, pub name: String, } // ============ // === Test === // ============ #[cfg(test)] mod tests { use super::*; use crate::definition::DefinitionName; use engine_protocol::language_server::MethodPointer; #[test] fn import_listing() { let parser = parser::Parser::new(); let expect_imports = |code: &str, expected: &[&[&str]]| { let ast = parser.parse_module(code, default()).unwrap(); let info = Info { ast }; let imports = info.iter_imports().collect_vec(); assert_eq!(imports.len(), expected.len()); for (import, expected_segments) in imports.iter().zip(expected) { itertools::assert_equal(import.module.iter(), expected_segments.iter()); } }; // TODO [mwu] waiting for fix https://github.com/enso-org/enso/issues/1016 // expect_imports("import", &[&[]]); expect_imports("import Foo", &[&["Foo"]]); expect_imports("import Foo.Bar", &[&["Foo", "Bar"]]); expect_imports("foo = bar\nimport Foo.Bar", &[&["Foo", "Bar"]]); expect_imports("import Foo.Bar\nfoo=bar\nimport Foo.Bar", &[&["Foo", "Bar"], &[ "Foo", "Bar", ]]); } #[test] fn import_adding_and_removing() { let parser = parser::Parser::new(); let code = "import Foo.Bar.Baz"; let ast = parser.parse_module(code, default()).unwrap(); let mut info = Info { ast }; let import = |code| { let ast = parser.parse_line_ast(code).unwrap(); import::Info::from_ast(&ast).unwrap() }; info.add_import(&parser, import("import Bar.Gar")); info.expect_code("import Bar.Gar\nimport Foo.Bar.Baz"); info.add_import(&parser, import("import Gar.Bar")); info.expect_code("import Bar.Gar\nimport Foo.Bar.Baz\nimport Gar.Bar"); info.remove_import(&import("import Foo.Bar.Baz")).unwrap(); info.expect_code("import Bar.Gar\nimport Gar.Bar"); info.remove_import(&import("import Foo.Bar.Baz")).unwrap_err(); info.expect_code("import Bar.Gar\nimport Gar.Bar"); info.remove_import(&import("import Gar.Bar")).unwrap(); info.expect_code("import Bar.Gar"); info.remove_import(&import("import Bar.Gar")).unwrap(); info.expect_code(""); info.add_import(&parser, import("import Bar.Gar")); info.expect_code("import Bar.Gar"); } #[test] fn implicit_method_resolution() { let parser = parser::Parser::new(); let module_name = QualifiedName::from_all_segments(["local", "ProjectName", "Main"]).unwrap(); let expect_find = |method: &MethodPointer, code, expected: &definition::Id| { let module = parser.parse_module(code, default()).unwrap(); let result = lookup_method(&module_name, &module, method); assert_eq!(result.unwrap().to_string(), expected.to_string()); // TODO [mwu] // We should be able to use `assert_eq!(result.unwrap(),expected);` // But we can't, because definition::Id uses located fields and crumbs won't match. // Eventually we'll likely need to split definition names into located and unlocated // ones. Definition ID should not require any location info. }; let expect_not_found = |method: &MethodPointer, code| { let module = parser.parse_module(code, default()).unwrap(); lookup_method(&module_name, &module, method).expect_err("expected method not found"); }; // === Lookup the Main (local module type) extension method === let ptr = MethodPointer { defined_on_type: "local.ProjectName.Main".into(), module: "local.ProjectName.Main".into(), name: "foo".into(), }; // Implicit module extension method. let id = definition::Id::new_plain_name("foo"); expect_find(&ptr, "foo a b = a + b", &id); // Explicit module extension method. let id = definition::Id::new_single_crumb(DefinitionName::new_method("Main", "foo")); expect_find(&ptr, "Main.foo a b = a + b", &id); // Matching name but extending wrong type. expect_not_found(&ptr, "Number.foo a b = a + b"); // Mismatched name. expect_not_found(&ptr, "bar a b = a + b"); // === Lookup the Int (non-local type) extension method === let ptr = MethodPointer { defined_on_type: "std.Base.Main.Number".into(), module: "local.ProjectName.Main".into(), name: "foo".into(), }; expect_not_found(&ptr, "foo a b = a + b"); let id = definition::Id::new_single_crumb(DefinitionName::new_method("Number", "foo")); expect_find(&ptr, "Number.foo a b = a + b", &id); expect_not_found(&ptr, "Text.foo a b = a + b"); expect_not_found(&ptr, "bar a b = a + b"); } #[test] fn test_definition_location() { let code = r" some def = first line second line other def = first line second line nested def = nested body last line of other def last def = inline expression"; let parser = parser::Parser::new(); let module = parser.parse_module(code, default()).unwrap(); let module = Info { ast: module }; let id = definition::Id::new_plain_name("other"); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("last line of other def")); let id = definition::Id::new_plain_name("last"); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("inline expression")); let id = definition::Id::new_plain_names(["other", "nested"]); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("nested body")); } #[test] fn add_method() { let parser = parser::Parser::new(); let module = r#"Main.method1 arg = body main = Main.method1 10"#; let module = Info::from(parser.parse_module(module
{ add_line(None); }
conditional_block
module.rs
display = "Cannot find method with pointer {:?}.", _0)] pub struct CannotFindMethod(language_server::MethodPointer); #[allow(missing_docs)] #[derive(Fail, Clone, Debug)] #[fail(display = "The definition with crumbs {:?} is not a direct child of the module.", _0)] pub struct NotDirectChild(ast::Crumbs); // ========== // === Id === // ========== /// The segments of module name. Allow finding module in the project. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Id { /// The last segment being a module name. For project's main module it should be equal /// to [`PROJECTS_MAIN_MODULE`]. pub name: ImString, /// The segments of all parent modules, from the top module to the direct parent. Does **not** /// include project name. pub parent_modules: Vec<ImString>, } impl Id { /// Create module id from list of segments. The list shall not contain the project name nor /// namespace. Fails if the list is empty (the module name is required). pub fn try_from_segments( segments: impl IntoIterator<Item: Into<ImString>>, ) -> FallibleResult<Self> { let mut segments = segments.into_iter().map(Into::into).collect_vec(); let name = segments.pop().ok_or(EmptySegments)?; Ok(Self { name, parent_modules: segments }) } /// Return the iterator over id's segments. pub fn segments(&self) -> impl Iterator<Item = &ImString> { self.parent_modules.iter().chain(iter::once(&self.name)) } } impl IntoIterator for Id { type Item = ImString; type IntoIter = impl Iterator<Item = Self::Item>; fn into_iter(self) -> Self::IntoIter { self.parent_modules.into_iter().chain(iter::once(self.name)) } } impl From<Id> for NamePath { fn from(id: Id) -> Self { id.into_iter().collect() } } impl Display for Id { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.segments().format(".")) } } // ============ // === Info === // ============ /// Wrapper allowing getting information about the module and updating it. #[derive(Clone, Debug)] pub struct Info { #[allow(missing_docs)] pub ast: known::Module, } impl Info { /// Generate a name for a definition that can be introduced without side-effects. /// /// The name shall be generated by appending number to the given base string. pub fn generate_name(&self, base: &str) -> FallibleResult<Identifier> { let used_names = self.used_names(); let used_names = used_names.iter().map(|name| name.item.as_str()); identifier::generate_name(base, used_names) } /// Identifiers introduced or referred to in the module's scope. /// /// Introducing identifier not included on this list should have no side-effects on the name /// resolution in the code in this graph. pub fn used_names(&self) -> Vec<Located<String>> { let usage = alias_analysis::analyze_crumbable(self.ast.shape()); usage.all_identifiers() } /// Iterate over all lines in module that contain an import declaration. pub fn enumerate_imports(&self) -> impl Iterator<Item = (ModuleCrumb, import::Info)> + '_ { let children = self.ast.shape().enumerate(); children.filter_map(|(crumb, ast)| Some((crumb, import::Info::from_ast(ast)?))) } /// Iterate over all import declarations in the module. /// /// If the caller wants to know *where* the declarations are, use `enumerate_imports`. pub fn iter_imports(&self) -> impl Iterator<Item = import::Info> + '_ { self.enumerate_imports().map(|(_, import)| import) } /// Check if module contains import with given id. pub fn contains_import(&self, id: import::Id) -> bool { self.iter_imports().any(|import| import.id() == id) } /// Add a new line to the module's block. /// /// Note that indices are the "module line" indices, which usually are quite different from text /// API line indices (because nested blocks doesn't count as separate "module lines"). pub fn add_line(&mut self, index: usize, ast: Option<Ast>) { let line = BlockLine::new(ast); self.ast.update_shape(|shape| shape.lines.insert(index, line)) } /// Remove line with given index. /// /// Returns removed line. Fails if the index is out of bounds. pub fn remove_line(&mut self, index: usize) -> FallibleResult<BlockLine<Option<Ast>>> { self.ast.update_shape(|shape| { shape.lines.try_remove(index).ok_or_else(|| LineIndexOutOfBounds.into()) }) } /// Remove a line that matches given import description. /// /// If there is more than one line matching, only the first one will be removed. /// Fails if there is no import matching given argument. pub fn remove_import(&mut self, to_remove: &import::Info) -> FallibleResult { let lookup_result = self.enumerate_imports().find(|(_, import)| import == to_remove); let (crumb, _) = lookup_result.ok_or_else(|| ImportNotFound(to_remove.to_string()))?; self.remove_line(crumb.line_index)?; Ok(()) } /// Remove a line that matches given import ID. /// /// If there is more than one line matching, only the first one will be removed. /// Fails if there is no import matching given argument. pub fn remove_import_by_id(&mut self, to_remove: import::Id) -> FallibleResult { let lookup_result = self.enumerate_imports().find(|(_, import)| import.id() == to_remove); let (crumb, _) = lookup_result.ok_or(ImportIdNotFound(to_remove))?; self.remove_line(crumb.line_index)?; Ok(()) } /// Add a new import declaration to a module. /// /// This function will try to keep imports in lexicographic order. It returns the index where /// import was added (index of import - an element on the list returned by `enumerate_imports`). // TODO [mwu] // Ideally we should not require parser but should use some sane way of generating AST from // the `ImportInfo` value. pub fn add_import(&mut self, parser: &parser::Parser, to_add: import::Info) -> usize { // Find last import that is not "after" the added one lexicographically. let previous_import = self.enumerate_imports().take_while(|(_, import)| &to_add > import).last(); let index_to_place_at = previous_import.map_or(0, |(crumb, _)| crumb.line_index + 1); let import_ast = parser.parse_line_ast(to_add.to_string()).unwrap(); self.add_line(index_to_place_at, Some(import_ast)); index_to_place_at } /// Add a new import declaration to a module. /// /// For more details the mechanics see [`add_import`] documentation. pub fn
( &mut self, parser: &parser::Parser, to_add: import::Info, ) -> Option<usize> { (!self.contains_import(to_add.id())).then(|| self.add_import(parser, to_add)) } /// Place the line with given AST in the module's body. /// /// Unlike `add_line` (which is more low-level) will introduce empty lines around introduced /// line and describes the added line location in relation to other definitions. /// /// Typically used to place lines with definitions in the module. pub fn add_ast(&mut self, ast: Ast, location: Placement) -> FallibleResult { #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum BlankLinePlacement { Before, After, None, } let blank_line = match location { _ if self.ast.lines.is_empty() => BlankLinePlacement::None, Placement::Begin => BlankLinePlacement::After, Placement::End => BlankLinePlacement::Before, Placement::After(_) => BlankLinePlacement::Before, Placement::Before(_) => BlankLinePlacement::After, }; let mut index = match location { Placement::Begin => 0, Placement::End => self.ast.lines.len(), Placement::Before(next_def) => locate_line_with(&self.ast, &next_def)?.line_index, Placement::After(next_def) => locate_line_with(&self.ast, &next_def)?.line_index + 1, }; let mut add_line = |ast_opt: Option<Ast>| { self.add_line(index, ast_opt); index += 1; }; if blank_line == BlankLinePlacement::Before { add_line(None); } add_line(Some(ast)); if blank_line == BlankLinePlacement::After { add_line(None); } Ok(()) } /// Add a new method definition to the module. pub fn add_method( &mut self, method: definition::ToAdd, location: Placement, parser: &parser::Parser, ) -> FallibleResult { let no_indent = 0; let definition_ast = method.ast(no_indent, parser)?; self.add_ast(definition_ast, location) } /// Updates the given definition using the passed invokable. pub fn update_definition( &mut self, id: &definition::Id, f: impl FnOnce(definition::DefinitionInfo) -> FallibleResult<definition::DefinitionInfo>, ) -> FallibleResult { let definition = locate(&self.ast, id)?; let new_definition = f(definition.item)?; let new_ast = new_definition.ast.into(); self.ast = self.ast.set_traversing(&definition.crumbs, new_ast)?; Ok(()) } #[cfg(test)] pub fn expect_code(&self, expected_code: impl AsRef<str>) { assert_eq!(self.ast.repr(), expected_code.as_ref()); } } impl From<known::Module> for Info { fn from(ast: known::Module) -> Self { Info { ast } } } // ================= // === Placement === // ================= /// Structure describing where to place something being added to the module. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Placement { /// Place at the beginning of the module. Begin, /// Place at the end of the module. End, /// Place after given definition; Before(definition::Crumb), /// Place before given definition; After(definition::Crumb), } // ======================= // === ChildDefinition === // ======================= /// Represents information about a definition being a direct child of this module, including its /// location. /// /// Internally it is `definition::ChildDefinition` with only a single `ModuleCrumb` as location. #[derive(Clone, Debug, Deref)] pub struct ChildDefinition(definition::ChildDefinition); impl ChildDefinition { fn try_retrieving_crumb(child: &definition::ChildDefinition) -> Option<ModuleCrumb> { match child.crumbs.as_slice() { [ast::crumbs::Crumb::Module(crumb)] => Some(*crumb), _ => None, } } /// Try constructing value from `definition::ChildDefinition`. Fails if it is not a direct child /// of a module. pub fn new(child: definition::ChildDefinition) -> Result<Self, NotDirectChild> { if Self::try_retrieving_crumb(&child).is_some() { Ok(Self(child)) } else { Err(NotDirectChild(child.crumbs)) } } /// The location of this definition child in the module. pub fn crumb(&self) -> ModuleCrumb { // Safe, because our only constructor checks that this works. This is the type's invariant. Self::try_retrieving_crumb(&self.0).unwrap() } } impl TryFrom<definition::ChildDefinition> for ChildDefinition { type Error = NotDirectChild; fn try_from(value: definition::ChildDefinition) -> Result<Self, Self::Error> { Self::new(value) } } // ======================== // === Module Utilities === // ======================== /// Looks up graph in the module. pub fn get_definition( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<definition::DefinitionInfo> { Ok(locate(ast, id)?.item) } /// Locate the line with given definition and return crumb that denotes it. /// /// Fails if there is no matching definition being a direct child of the module. pub fn locate_line_with( ast: &known::Module, crumb: &definition::Crumb, ) -> FallibleResult<ModuleCrumb> { locate_child(ast, crumb).map(|child| child.crumb()) } /// Locate the definition being the module's direct child. pub fn locate_child( ast: &known::Module, crumb: &definition::Crumb, ) -> FallibleResult<ChildDefinition> { let child = ast.def_iter().find_by_name(crumb)?; Ok(ChildDefinition::try_from(child)?) } /// Traverses the module's definition tree following the given Id crumbs, looking up the definition. pub fn locate( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<definition::ChildDefinition> { let mut crumbs_iter = id.crumbs.iter(); // Not exactly regular - we need special case for the first crumb as it is not a definition nor // a children. After this we can go just from one definition to another. let first_crumb = crumbs_iter.next().ok_or(EmptyDefinitionId)?; let mut child = ast.def_iter().find_by_name(first_crumb)?; for crumb in crumbs_iter { child = definition::resolve_single_name(child, crumb)?; } Ok(child) } /// Get a definition ID that points to a method matching given pointer. /// /// The module is assumed to be in the file identified by the `method.file` (for the purpose of /// desugaring implicit extensions methods for modules). /// /// The `module_name` parameter is the name of the module that contains `ast`. pub fn lookup_method( module_name: &QualifiedName, ast: &known::Module, method: &language_server::MethodPointer, ) -> FallibleResult<definition::Id> { let qualified_typename = QualifiedName::from_text(&method.defined_on_type)?; let defined_in_this_module = module_name == &qualified_typename; let method_module_name = QualifiedName::from_text(&method.module)?; let implicit_extension_allowed = method.defined_on_type == method_module_name.to_string(); for child in ast.def_iter() { let child_name = &child.name.item; let name_matches = child_name.name.item == method.name; let type_matches = match child_name.extended_target.as_slice() { [] => implicit_extension_allowed || defined_in_this_module, [typename] => typename.item == qualified_typename.name(), _ => child_name.explicitly_extends_type(&method.defined_on_type), }; if name_matches && type_matches { return Ok(definition::Id::new_single_crumb(child_name.clone())); } } Err(CannotFindMethod(method.clone()).into()) } /// Get a span in module's text representation where the given definition is located. pub fn definition_span( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<enso_text::Range<Byte>> { let location = locate(ast, id)?; ast.range_of_descendant_at(&location.crumbs) } impl DefinitionProvider for known::Module { fn indent(&self) -> usize { 0 } fn scope_kind(&self) -> definition::ScopeKind { definition::ScopeKind::Root } fn enumerate_asts<'a>(&'a self) -> Box<dyn Iterator<Item = ChildAst<'a>> + 'a> { self.ast().children() } } // ================ // === MethodId === // ================ /// A structure identifying a method. /// /// It is very similar to MethodPointer from language_server API, however it may point to the method /// outside the currently opened project. #[derive(Clone, Debug, serde::Deserialize, Eq, Hash, PartialEq, serde::Serialize)] #[allow(missing_docs)] pub struct MethodId { pub module: QualifiedName, pub defined_on_type: QualifiedName, pub name: String, } // ============ // === Test === // ============ #[cfg(test)] mod tests { use super::*; use crate::definition::DefinitionName; use engine_protocol::language_server::MethodPointer; #[test] fn import_listing() { let parser = parser::Parser::new(); let expect_imports = |code: &str, expected: &[&[&str]]| { let ast = parser.parse_module(code, default()).unwrap(); let info = Info { ast }; let imports = info.iter_imports().collect_vec(); assert_eq!(imports.len(), expected.len()); for (import, expected_segments) in imports.iter().zip(expected) { itertools::assert_equal(import.module.iter(), expected_segments.iter()); } }; // TODO [mwu] waiting for fix https://github.com/enso-org/enso/issues/1016 // expect_imports("import", &[&[]]); expect_imports("import Foo", &[&["Foo"]]); expect_imports("import Foo.Bar", &[&["Foo", "Bar"]]); expect_imports("foo = bar\nimport Foo.Bar", &[&["Foo", "Bar"]]); expect_imports("import Foo.Bar\nfoo=bar\nimport Foo.Bar", &[&["Foo", "Bar"], &[ "Foo", "Bar", ]]); } #[test] fn import_adding_and_removing() { let parser = parser::Parser::new(); let code = "import Foo.Bar.Baz"; let ast = parser.parse_module(code, default()).unwrap(); let mut info = Info { ast }; let import = |code| { let ast = parser.parse_line_ast(code).unwrap(); import::Info::from_ast(&ast).unwrap() }; info.add_import(&parser, import("import Bar.Gar")); info.expect_code("import Bar.Gar\nimport Foo.Bar.Baz"); info.add_import(&parser, import("import Gar.Bar")); info.expect_code("import Bar.Gar\nimport Foo.Bar.Baz\nimport Gar.Bar"); info.remove_import(&import("import Foo.Bar.Baz")).unwrap(); info.expect_code("import Bar.Gar\nimport Gar.Bar"); info.remove_import(&import("import Foo.Bar.Baz")).unwrap_err(); info.expect_code("import Bar.Gar\nimport Gar.Bar"); info.remove_import(&import("import Gar.Bar")).unwrap(); info.expect_code("import Bar.Gar"); info.remove_import(&import("import Bar.Gar")).unwrap(); info.expect_code(""); info.add_import(&parser, import("import Bar.Gar")); info.expect_code("import Bar.Gar"); } #[test] fn implicit_method_resolution() { let parser = parser::Parser::new(); let module_name = QualifiedName::from_all_segments(["local", "ProjectName", "Main"]).unwrap(); let expect_find = |method: &MethodPointer, code, expected: &definition::Id| { let module = parser.parse_module(code, default()).unwrap(); let result = lookup_method(&module_name, &module, method); assert_eq!(result.unwrap().to_string(), expected.to_string()); // TODO [mwu] // We should be able to use `assert_eq!(result.unwrap(),expected);` // But we can't, because definition::Id uses located fields and crumbs won't match. // Eventually we'll likely need to split definition names into located and unlocated // ones. Definition ID should not require any location info. }; let expect_not_found = |method: &MethodPointer, code| { let module = parser.parse_module(code, default()).unwrap(); lookup_method(&module_name, &module, method).expect_err("expected method not found"); }; // === Lookup the Main (local module type) extension method === let ptr = MethodPointer { defined_on_type: "local.ProjectName.Main".into(), module: "local.ProjectName.Main".into(), name: "foo".into(), }; // Implicit module extension method. let id = definition::Id::new_plain_name("foo"); expect_find(&ptr, "foo a b = a + b", &id); // Explicit module extension method. let id = definition::Id::new_single_crumb(DefinitionName::new_method("Main", "foo")); expect_find(&ptr, "Main.foo a b = a + b", &id); // Matching name but extending wrong type. expect_not_found(&ptr, "Number.foo a b = a + b"); // Mismatched name. expect_not_found(&ptr, "bar a b = a + b"); // === Lookup the Int (non-local type) extension method === let ptr = MethodPointer { defined_on_type: "std.Base.Main.Number".into(), module: "local.ProjectName.Main".into(), name: "foo".into(), }; expect_not_found(&ptr, "foo a b = a + b"); let id = definition::Id::new_single_crumb(DefinitionName::new_method("Number", "foo")); expect_find(&ptr, "Number.foo a b = a + b", &id); expect_not_found(&ptr, "Text.foo a b = a + b"); expect_not_found(&ptr, "bar a b = a + b"); } #[test] fn test_definition_location() { let code = r" some def = first line second line other def = first line second line nested def = nested body last line of other def last def = inline expression"; let parser = parser::Parser::new(); let module = parser.parse_module(code, default()).unwrap(); let module = Info { ast: module }; let id = definition::Id::new_plain_name("other"); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("last line of other def")); let id = definition::Id::new_plain_name("last"); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("inline expression")); let id = definition::Id::new_plain_names(["other", "nested"]); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("nested body")); } #[test] fn add_method() { let parser = parser::Parser::new(); let module = r#"Main.method1 arg = body main = Main.method1 10"#; let module = Info::from(parser.parse_module(module
add_import_if_missing
identifier_name
module.rs
(display = "Cannot find method with pointer {:?}.", _0)] pub struct CannotFindMethod(language_server::MethodPointer); #[allow(missing_docs)] #[derive(Fail, Clone, Debug)] #[fail(display = "The definition with crumbs {:?} is not a direct child of the module.", _0)] pub struct NotDirectChild(ast::Crumbs); // ========== // === Id === // ========== /// The segments of module name. Allow finding module in the project. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// The segments of all parent modules, from the top module to the direct parent. Does **not** /// include project name. pub parent_modules: Vec<ImString>, } impl Id { /// Create module id from list of segments. The list shall not contain the project name nor /// namespace. Fails if the list is empty (the module name is required). pub fn try_from_segments( segments: impl IntoIterator<Item: Into<ImString>>, ) -> FallibleResult<Self> { let mut segments = segments.into_iter().map(Into::into).collect_vec(); let name = segments.pop().ok_or(EmptySegments)?; Ok(Self { name, parent_modules: segments }) } /// Return the iterator over id's segments. pub fn segments(&self) -> impl Iterator<Item = &ImString> { self.parent_modules.iter().chain(iter::once(&self.name)) } } impl IntoIterator for Id { type Item = ImString; type IntoIter = impl Iterator<Item = Self::Item>; fn into_iter(self) -> Self::IntoIter { self.parent_modules.into_iter().chain(iter::once(self.name)) } } impl From<Id> for NamePath { fn from(id: Id) -> Self { id.into_iter().collect() } } impl Display for Id { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.segments().format(".")) } } // ============ // === Info === // ============ /// Wrapper allowing getting information about the module and updating it. #[derive(Clone, Debug)] pub struct Info { #[allow(missing_docs)] pub ast: known::Module, } impl Info { /// Generate a name for a definition that can be introduced without side-effects. /// /// The name shall be generated by appending number to the given base string. pub fn generate_name(&self, base: &str) -> FallibleResult<Identifier> { let used_names = self.used_names(); let used_names = used_names.iter().map(|name| name.item.as_str()); identifier::generate_name(base, used_names) } /// Identifiers introduced or referred to in the module's scope. /// /// Introducing identifier not included on this list should have no side-effects on the name /// resolution in the code in this graph. pub fn used_names(&self) -> Vec<Located<String>> { let usage = alias_analysis::analyze_crumbable(self.ast.shape()); usage.all_identifiers() } /// Iterate over all lines in module that contain an import declaration. pub fn enumerate_imports(&self) -> impl Iterator<Item = (ModuleCrumb, import::Info)> + '_ { let children = self.ast.shape().enumerate(); children.filter_map(|(crumb, ast)| Some((crumb, import::Info::from_ast(ast)?))) } /// Iterate over all import declarations in the module. /// /// If the caller wants to know *where* the declarations are, use `enumerate_imports`. pub fn iter_imports(&self) -> impl Iterator<Item = import::Info> + '_ { self.enumerate_imports().map(|(_, import)| import) } /// Check if module contains import with given id. pub fn contains_import(&self, id: import::Id) -> bool { self.iter_imports().any(|import| import.id() == id) } /// Add a new line to the module's block. /// /// Note that indices are the "module line" indices, which usually are quite different from text /// API line indices (because nested blocks doesn't count as separate "module lines"). pub fn add_line(&mut self, index: usize, ast: Option<Ast>) { let line = BlockLine::new(ast); self.ast.update_shape(|shape| shape.lines.insert(index, line)) } /// Remove line with given index. /// /// Returns removed line. Fails if the index is out of bounds. pub fn remove_line(&mut self, index: usize) -> FallibleResult<BlockLine<Option<Ast>>> { self.ast.update_shape(|shape| { shape.lines.try_remove(index).ok_or_else(|| LineIndexOutOfBounds.into()) }) } /// Remove a line that matches given import description. /// /// If there is more than one line matching, only the first one will be removed. /// Fails if there is no import matching given argument. pub fn remove_import(&mut self, to_remove: &import::Info) -> FallibleResult { let lookup_result = self.enumerate_imports().find(|(_, import)| import == to_remove); let (crumb, _) = lookup_result.ok_or_else(|| ImportNotFound(to_remove.to_string()))?; self.remove_line(crumb.line_index)?; Ok(()) } /// Remove a line that matches given import ID. /// /// If there is more than one line matching, only the first one will be removed. /// Fails if there is no import matching given argument. pub fn remove_import_by_id(&mut self, to_remove: import::Id) -> FallibleResult { let lookup_result = self.enumerate_imports().find(|(_, import)| import.id() == to_remove); let (crumb, _) = lookup_result.ok_or(ImportIdNotFound(to_remove))?; self.remove_line(crumb.line_index)?; Ok(()) } /// Add a new import declaration to a module. /// /// This function will try to keep imports in lexicographic order. It returns the index where /// import was added (index of import - an element on the list returned by `enumerate_imports`). // TODO [mwu] // Ideally we should not require parser but should use some sane way of generating AST from // the `ImportInfo` value. pub fn add_import(&mut self, parser: &parser::Parser, to_add: import::Info) -> usize { // Find last import that is not "after" the added one lexicographically. let previous_import = self.enumerate_imports().take_while(|(_, import)| &to_add > import).last(); let index_to_place_at = previous_import.map_or(0, |(crumb, _)| crumb.line_index + 1); let import_ast = parser.parse_line_ast(to_add.to_string()).unwrap(); self.add_line(index_to_place_at, Some(import_ast)); index_to_place_at } /// Add a new import declaration to a module. /// /// For more details the mechanics see [`add_import`] documentation. pub fn add_import_if_missing( &mut self, parser: &parser::Parser, to_add: import::Info, ) -> Option<usize> { (!self.contains_import(to_add.id())).then(|| self.add_import(parser, to_add)) } /// Place the line with given AST in the module's body. /// /// Unlike `add_line` (which is more low-level) will introduce empty lines around introduced /// line and describes the added line location in relation to other definitions. /// /// Typically used to place lines with definitions in the module. pub fn add_ast(&mut self, ast: Ast, location: Placement) -> FallibleResult { #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum BlankLinePlacement { Before, After, None, } let blank_line = match location { _ if self.ast.lines.is_empty() => BlankLinePlacement::None, Placement::Begin => BlankLinePlacement::After, Placement::End => BlankLinePlacement::Before, Placement::After(_) => BlankLinePlacement::Before, Placement::Before(_) => BlankLinePlacement::After, }; let mut index = match location { Placement::Begin => 0, Placement::End => self.ast.lines.len(), Placement::Before(next_def) => locate_line_with(&self.ast, &next_def)?.line_index, Placement::After(next_def) => locate_line_with(&self.ast, &next_def)?.line_index + 1, }; let mut add_line = |ast_opt: Option<Ast>| { self.add_line(index, ast_opt); index += 1; }; if blank_line == BlankLinePlacement::Before { add_line(None); } add_line(Some(ast)); if blank_line == BlankLinePlacement::After { add_line(None); } Ok(()) } /// Add a new method definition to the module. pub fn add_method( &mut self, method: definition::ToAdd, location: Placement, parser: &parser::Parser, ) -> FallibleResult { let no_indent = 0; let definition_ast = method.ast(no_indent, parser)?; self.add_ast(definition_ast, location) } /// Updates the given definition using the passed invokable. pub fn update_definition( &mut self, id: &definition::Id, f: impl FnOnce(definition::DefinitionInfo) -> FallibleResult<definition::DefinitionInfo>, ) -> FallibleResult { let definition = locate(&self.ast, id)?; let new_definition = f(definition.item)?; let new_ast = new_definition.ast.into(); self.ast = self.ast.set_traversing(&definition.crumbs, new_ast)?; Ok(()) } #[cfg(test)] pub fn expect_code(&self, expected_code: impl AsRef<str>) { assert_eq!(self.ast.repr(), expected_code.as_ref()); } } impl From<known::Module> for Info { fn from(ast: known::Module) -> Self { Info { ast } } } // ================= // === Placement === // ================= /// Structure describing where to place something being added to the module. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Placement { /// Place at the beginning of the module. Begin, /// Place at the end of the module. End, /// Place after given definition; Before(definition::Crumb), /// Place before given definition; After(definition::Crumb), } // ======================= // === ChildDefinition === // ======================= /// Represents information about a definition being a direct child of this module, including its /// location. /// /// Internally it is `definition::ChildDefinition` with only a single `ModuleCrumb` as location. #[derive(Clone, Debug, Deref)] pub struct ChildDefinition(definition::ChildDefinition); impl ChildDefinition { fn try_retrieving_crumb(child: &definition::ChildDefinition) -> Option<ModuleCrumb> { match child.crumbs.as_slice() { [ast::crumbs::Crumb::Module(crumb)] => Some(*crumb), _ => None, } } /// Try constructing value from `definition::ChildDefinition`. Fails if it is not a direct child /// of a module. pub fn new(child: definition::ChildDefinition) -> Result<Self, NotDirectChild> { if Self::try_retrieving_crumb(&child).is_some() { Ok(Self(child)) } else { Err(NotDirectChild(child.crumbs)) } } /// The location of this definition child in the module. pub fn crumb(&self) -> ModuleCrumb { // Safe, because our only constructor checks that this works. This is the type's invariant. Self::try_retrieving_crumb(&self.0).unwrap() } } impl TryFrom<definition::ChildDefinition> for ChildDefinition { type Error = NotDirectChild; fn try_from(value: definition::ChildDefinition) -> Result<Self, Self::Error> { Self::new(value) } } // ======================== // === Module Utilities === // ======================== /// Looks up graph in the module. pub fn get_definition( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<definition::DefinitionInfo> { Ok(locate(ast, id)?.item) } /// Locate the line with given definition and return crumb that denotes it. /// /// Fails if there is no matching definition being a direct child of the module. pub fn locate_line_with( ast: &known::Module, crumb: &definition::Crumb, ) -> FallibleResult<ModuleCrumb> { locate_child(ast, crumb).map(|child| child.crumb()) } /// Locate the definition being the module's direct child. pub fn locate_child( ast: &known::Module, crumb: &definition::Crumb, ) -> FallibleResult<ChildDefinition> { let child = ast.def_iter().find_by_name(crumb)?; Ok(ChildDefinition::try_from(child)?) } /// Traverses the module's definition tree following the given Id crumbs, looking up the definition. pub fn locate( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<definition::ChildDefinition> { let mut crumbs_iter = id.crumbs.iter(); // Not exactly regular - we need special case for the first crumb as it is not a definition nor // a children. After this we can go just from one definition to another. let first_crumb = crumbs_iter.next().ok_or(EmptyDefinitionId)?; let mut child = ast.def_iter().find_by_name(first_crumb)?; for crumb in crumbs_iter { child = definition::resolve_single_name(child, crumb)?; } Ok(child) } /// Get a definition ID that points to a method matching given pointer. /// /// The module is assumed to be in the file identified by the `method.file` (for the purpose of /// desugaring implicit extensions methods for modules). /// /// The `module_name` parameter is the name of the module that contains `ast`. pub fn lookup_method( module_name: &QualifiedName, ast: &known::Module, method: &language_server::MethodPointer, ) -> FallibleResult<definition::Id> { let qualified_typename = QualifiedName::from_text(&method.defined_on_type)?; let defined_in_this_module = module_name == &qualified_typename; let method_module_name = QualifiedName::from_text(&method.module)?; let implicit_extension_allowed = method.defined_on_type == method_module_name.to_string(); for child in ast.def_iter() { let child_name = &child.name.item; let name_matches = child_name.name.item == method.name; let type_matches = match child_name.extended_target.as_slice() { [] => implicit_extension_allowed || defined_in_this_module, [typename] => typename.item == qualified_typename.name(), _ => child_name.explicitly_extends_type(&method.defined_on_type), }; if name_matches && type_matches { return Ok(definition::Id::new_single_crumb(child_name.clone())); } } Err(CannotFindMethod(method.clone()).into()) } /// Get a span in module's text representation where the given definition is located. pub fn definition_span( ast: &known::Module, id: &definition::Id, ) -> FallibleResult<enso_text::Range<Byte>> { let location = locate(ast, id)?; ast.range_of_descendant_at(&location.crumbs) } impl DefinitionProvider for known::Module { fn indent(&self) -> usize { 0 } fn scope_kind(&self) -> definition::ScopeKind { definition::ScopeKind::Root } fn enumerate_asts<'a>(&'a self) -> Box<dyn Iterator<Item = ChildAst<'a>> + 'a> { self.ast().children() } } // ================ // === MethodId === // ================ /// A structure identifying a method. /// /// It is very similar to MethodPointer from language_server API, however it may point to the method /// outside the currently opened project. #[derive(Clone, Debug, serde::Deserialize, Eq, Hash, PartialEq, serde::Serialize)] #[allow(missing_docs)] pub struct MethodId { pub module: QualifiedName, pub defined_on_type: QualifiedName, pub name: String, } // ============ // === Test === // ============ #[cfg(test)] mod tests { use super::*; use crate::definition::DefinitionName; use engine_protocol::language_server::MethodPointer; #[test] fn import_listing() { let parser = parser::Parser::new(); let expect_imports = |code: &str, expected: &[&[&str]]| { let ast = parser.parse_module(code, default()).unwrap(); let info = Info { ast }; let imports = info.iter_imports().collect_vec(); assert_eq!(imports.len(), expected.len()); for (import, expected_segments) in imports.iter().zip(expected) { itertools::assert_equal(import.module.iter(), expected_segments.iter()); } }; // TODO [mwu] waiting for fix https://github.com/enso-org/enso/issues/1016 // expect_imports("import", &[&[]]); expect_imports("import Foo", &[&["Foo"]]); expect_imports("import Foo.Bar", &[&["Foo", "Bar"]]); expect_imports("foo = bar\nimport Foo.Bar", &[&["Foo", "Bar"]]); expect_imports("import Foo.Bar\nfoo=bar\nimport Foo.Bar", &[&["Foo", "Bar"], &[ "Foo", "Bar", ]]); } #[test] fn import_adding_and_removing() { let parser = parser::Parser::new(); let code = "import Foo.Bar.Baz"; let ast = parser.parse_module(code, default()).unwrap(); let mut info = Info { ast }; let import = |code| { let ast = parser.parse_line_ast(code).unwrap(); import::Info::from_ast(&ast).unwrap() }; info.add_import(&parser, import("import Bar.Gar")); info.expect_code("import Bar.Gar\nimport Foo.Bar.Baz"); info.add_import(&parser, import("import Gar.Bar")); info.expect_code("import Bar.Gar\nimport Foo.Bar.Baz\nimport Gar.Bar"); info.remove_import(&import("import Foo.Bar.Baz")).unwrap(); info.expect_code("import Bar.Gar\nimport Gar.Bar"); info.remove_import(&import("import Foo.Bar.Baz")).unwrap_err(); info.expect_code("import Bar.Gar\nimport Gar.Bar"); info.remove_import(&import("import Gar.Bar")).unwrap(); info.expect_code("import Bar.Gar"); info.remove_import(&import("import Bar.Gar")).unwrap(); info.expect_code(""); info.add_import(&parser, import("import Bar.Gar")); info.expect_code("import Bar.Gar"); } #[test] fn implicit_method_resolution() { let parser = parser::Parser::new(); let module_name = QualifiedName::from_all_segments(["local", "ProjectName", "Main"]).unwrap(); let expect_find = |method: &MethodPointer, code, expected: &definition::Id| { let module = parser.parse_module(code, default()).unwrap(); let result = lookup_method(&module_name, &module, method); assert_eq!(result.unwrap().to_string(), expected.to_string()); // TODO [mwu] // We should be able to use `assert_eq!(result.unwrap(),expected);` // But we can't, because definition::Id uses located fields and crumbs won't match. // Eventually we'll likely need to split definition names into located and unlocated // ones. Definition ID should not require any location info. }; let expect_not_found = |method: &MethodPointer, code| { let module = parser.parse_module(code, default()).unwrap(); lookup_method(&module_name, &module, method).expect_err("expected method not found"); }; // === Lookup the Main (local module type) extension method === let ptr = MethodPointer { defined_on_type: "local.ProjectName.Main".into(), module: "local.ProjectName.Main".into(), name: "foo".into(), }; // Implicit module extension method. let id = definition::Id::new_plain_name("foo"); expect_find(&ptr, "foo a b = a + b", &id); // Explicit module extension method. let id = definition::Id::new_single_crumb(DefinitionName::new_method("Main", "foo")); expect_find(&ptr, "Main.foo a b = a + b", &id); // Matching name but extending wrong type. expect_not_found(&ptr, "Number.foo a b = a + b"); // Mismatched name. expect_not_found(&ptr, "bar a b = a + b"); // === Lookup the Int (non-local type) extension method === let ptr = MethodPointer { defined_on_type: "std.Base.Main.Number".into(), module: "local.ProjectName.Main".into(), name: "foo".into(), }; expect_not_found(&ptr, "foo a b = a + b"); let id = definition::Id::new_single_crumb(DefinitionName::new_method("Number", "foo")); expect_find(&ptr, "Number.foo a b = a + b", &id); expect_not_found(&ptr, "Text.foo a b = a + b"); expect_not_found(&ptr, "bar a b = a + b"); } #[test] fn test_definition_location() { let code = r" some def = first line second line other def = first line second line nested def = nested body last line of other def last def = inline expression"; let parser = parser::Parser::new(); let module = parser.parse_module(code, default()).unwrap(); let module = Info { ast: module }; let id = definition::Id::new_plain_name("other"); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("last line of other def")); let id = definition::Id::new_plain_name("last"); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("inline expression")); let id = definition::Id::new_plain_names(["other", "nested"]); let span = definition_span(&module.ast, &id).unwrap(); assert!(code[span].ends_with("nested body")); } #[test] fn add_method() { let parser = parser::Parser::new(); let module = r#"Main.method1 arg = body main = Main.method1 10"#; let module = Info::from(parser.parse_module(module, default
pub struct Id { /// The last segment being a module name. For project's main module it should be equal /// to [`PROJECTS_MAIN_MODULE`]. pub name: ImString,
random_line_split
init.rs
// Copyright (c) 2021 ESRLabs // // 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 super::{ clone::clone, fs::Mount, io::Fd, seccomp::AllowList, Checkpoint, Container, PipeRead, Start, SIGNAL_OFFSET, }; use nix::{ errno::Errno, libc::{self, c_int, c_ulong}, sched, sys::{ self, signal::{signal, sigprocmask, SigHandler, SigSet, SigmaskHow, Signal, SIGCHLD, SIGKILL}, }, unistd::{self, Uid}, }; use sched::CloneFlags; use std::{ collections::HashSet, env, ffi::CString, io::Read, os::unix::prelude::RawFd, process::exit, }; use sys::wait::{waitpid, WaitStatus}; // Init function. Pid 1. #[allow(clippy::too_many_arguments)] pub(super) fn init( container: &Container, init: &CString, argv: &[CString], env: &[CString], mounts: &[Mount], fds: &[(RawFd, Fd)], groups: &[u32], seccomp: Option<AllowList>, mut checkpoint: Checkpoint, tripwire: PipeRead, ) ->! { // Install a "default signal handler" that exits on any signal. This process is the "init" // process of this pid ns and therefore doesn't have any own signal handlers. This handler that just exits // is needed in case the container is signaled *before* the child is spawned that would otherwise receive the signal. // If the child is spawn when the signal is sent to this group it shall exit and the init returns from waitpid. set_init_signal_handlers(); // Become a session group leader setsid(); // Sync with parent checkpoint.wait(Start::Start); checkpoint.send(Start::Started); drop(checkpoint); pr_set_name_init(); // Become a subreaper for orphans in this namespace set_child_subreaper(true); let manifest = &container.manifest; let root = container .root .canonicalize() .expect("Failed to canonicalize root"); // Mount mount(&mounts); // Chroot unistd::chroot(&root).expect("Failed to chroot"); // Pwd env::set_current_dir("/").expect("Failed to set cwd to /"); // UID / GID setid(manifest.uid, manifest.gid); // Supplementary groups
set_no_new_privs(true); // Capabilities drop_capabilities(manifest.capabilities.as_ref()); // Close and dup fds file_descriptors(fds); // Clone match clone(CloneFlags::empty(), Some(SIGCHLD as i32)) { Ok(result) => match result { unistd::ForkResult::Parent { child } => { wait_for_parent_death(tripwire); reset_signal_handlers(); // Wait for the child to exit loop { match waitpid(Some(child), None) { Ok(WaitStatus::Exited(_pid, status)) => exit(status), Ok(WaitStatus::Signaled(_pid, status, _)) => { // Encode the signal number in the process exit status. It's not possible to raise a // a signal in this "init" process that is received by our parent let code = SIGNAL_OFFSET + status as i32; //debug!("Exiting with {} (signaled {})", code, status); exit(code); } Err(e) if e == nix::Error::Sys(Errno::EINTR) => continue, e => panic!("Failed to waitpid on {}: {:?}", child, e), } } } unistd::ForkResult::Child => { drop(tripwire); set_parent_death_signal(SIGKILL); // TODO: Post Linux 5.5 there's a nice clone flag that allows to reset the signal handler during the clone. reset_signal_handlers(); reset_signal_mask(); // Set seccomp filter if let Some(mut filter) = seccomp { filter.apply().expect("Failed to apply seccomp filter."); } panic!( "Execve: {:?} {:?}: {:?}", &init, &argv, unistd::execve(&init, &argv, &env) ) } }, Err(e) => panic!("Clone error: {}", e), } } /// Execute list of mount calls fn mount(mounts: &[Mount]) { for mount in mounts { mount.mount(); } } /// Apply file descriptor configuration fn file_descriptors(map: &[(RawFd, Fd)]) { for (fd, value) in map { match value { Fd::Close => { // Ignore close errors because the fd list contains the ReadDir fd and fds from other tasks. unistd::close(*fd).ok(); } Fd::Dup(n) => { unistd::dup2(*n, *fd).expect("Failed to dup2"); unistd::close(*n).expect("Failed to close"); } } } } fn set_child_subreaper(value: bool) { #[cfg(target_os = "android")] const PR_SET_CHILD_SUBREAPER: c_int = 36; #[cfg(not(target_os = "android"))] use libc::PR_SET_CHILD_SUBREAPER; let value = if value { 1u64 } else { 0u64 }; let result = unsafe { nix::libc::prctl(PR_SET_CHILD_SUBREAPER, value, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_CHILD_SUBREAPER"); } fn set_parent_death_signal(signal: Signal) { #[cfg(target_os = "android")] const PR_SET_PDEATHSIG: c_int = 1; #[cfg(not(target_os = "android"))] use libc::PR_SET_PDEATHSIG; let result = unsafe { nix::libc::prctl(PR_SET_PDEATHSIG, signal, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_PDEATHSIG"); } /// Wait in a separate thread for the parent (runtime) process to terminate. This should normally /// not happen. If it does, we (init) need to terminate ourselves or we will be adopted by system /// init. Setting PR_SET_PDEATHSIG is not an option here as we were spawned from a short lived tokio /// thread (not process) that would trigger the signal once the thread terminates. /// Performing this step before calling setgroups results in a SIGABRT. fn wait_for_parent_death(mut tripwire: PipeRead) { std::thread::spawn(move || { tripwire.read_exact(&mut [0u8, 1]).ok(); panic!("Runtime died"); }); } fn set_no_new_privs(value: bool) { #[cfg(target_os = "android")] pub const PR_SET_NO_NEW_PRIVS: c_int = 38; #[cfg(not(target_os = "android"))] use libc::PR_SET_NO_NEW_PRIVS; let result = unsafe { nix::libc::prctl(PR_SET_NO_NEW_PRIVS, value as c_ulong, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_NO_NEW_PRIVS") } #[cfg(target_os = "android")] pub const PR_SET_NAME: c_int = 15; #[cfg(not(target_os = "android"))] use libc::PR_SET_NAME; /// Set the name of the current process to "init" fn pr_set_name_init() { let cname = "init\0"; let result = unsafe { libc::prctl(PR_SET_NAME, cname.as_ptr() as c_ulong, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_NAME"); } /// Install default signal handler fn reset_signal_handlers() { Signal::iterator() .filter(|s| *s!= Signal::SIGCHLD) .filter(|s| *s!= Signal::SIGKILL) .filter(|s| *s!= Signal::SIGSTOP) .try_for_each(|s| unsafe { signal(s, SigHandler::SigDfl) }.map(drop)) .expect("failed to signal"); } fn reset_signal_mask() { sigprocmask(SigmaskHow::SIG_UNBLOCK, Some(&SigSet::all()), None) .expect("Failed to reset signal maks") } /// Install a signal handler that terminates the init process if the signal /// is received before the clone of the child. If this handler would not be /// installed the signal would be ignored (and not sent to the group) because /// the init processes in PID namespace do not have default signal handlers. fn set_init_signal_handlers() { extern "C" fn init_signal_handler(signal: c_int) { exit(SIGNAL_OFFSET + signal); } Signal::iterator() .filter(|s| *s!= Signal::SIGCHLD) .filter(|s| *s!= Signal::SIGKILL) .filter(|s| *s!= Signal::SIGSTOP) .try_for_each(|s| unsafe { signal(s, SigHandler::Handler(init_signal_handler)) }.map(drop)) .expect("Failed to set signal handler"); } // Reset effective caps to the most possible set fn reset_effective_caps() { caps::set(None, caps::CapSet::Effective, &caps::all()).expect("Failed to reset effective caps"); } /// Set uid/gid fn setid(uid: u16, gid: u16) { let rt_privileged = unistd::geteuid() == Uid::from_raw(0); // If running as uid 0 save our caps across the uid/gid drop if rt_privileged { caps::securebits::set_keepcaps(true).expect("Failed to set keep caps"); } let gid = unistd::Gid::from_raw(gid.into()); unistd::setresgid(gid, gid, gid).expect("Failed to set resgid"); let uid = unistd::Uid::from_raw(uid.into()); unistd::setresuid(uid, uid, uid).expect("Failed to set resuid"); if rt_privileged { reset_effective_caps(); caps::securebits::set_keepcaps(false).expect("Failed to set keep caps"); } } /// Become a session group leader fn setsid() { unistd::setsid().expect("Failed to call setsid"); } fn setgroups(groups: &[u32]) { let result = unsafe { nix::libc::setgroups(groups.len(), groups.as_ptr()) }; Errno::result(result) .map(drop) .expect("Failed to set supplementary groups"); } /// Drop capabilities fn drop_capabilities(cs: Option<&HashSet<caps::Capability>>) { let mut bounded = caps::read(None, caps::CapSet::Bounding).expect("Failed to read bounding caps"); if let Some(caps) = cs { bounded.retain(|c|!caps.contains(c)); } for cap in bounded { // caps::set cannot be called for bounded caps::drop(None, caps::CapSet::Bounding, cap).expect("Failed to drop bounding cap"); } if let Some(caps) = cs { caps::set(None, caps::CapSet::Effective, caps).expect("Failed to set effective caps"); caps::set(None, caps::CapSet::Permitted, caps).expect("Failed to set permitted caps"); caps::set(None, caps::CapSet::Inheritable, caps).expect("Failed to set inheritable caps"); caps::set(None, caps::CapSet::Ambient, caps).expect("Failed to set ambient caps"); } }
setgroups(groups); // No new privileges
random_line_split
init.rs
// Copyright (c) 2021 ESRLabs // // 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 super::{ clone::clone, fs::Mount, io::Fd, seccomp::AllowList, Checkpoint, Container, PipeRead, Start, SIGNAL_OFFSET, }; use nix::{ errno::Errno, libc::{self, c_int, c_ulong}, sched, sys::{ self, signal::{signal, sigprocmask, SigHandler, SigSet, SigmaskHow, Signal, SIGCHLD, SIGKILL}, }, unistd::{self, Uid}, }; use sched::CloneFlags; use std::{ collections::HashSet, env, ffi::CString, io::Read, os::unix::prelude::RawFd, process::exit, }; use sys::wait::{waitpid, WaitStatus}; // Init function. Pid 1. #[allow(clippy::too_many_arguments)] pub(super) fn init( container: &Container, init: &CString, argv: &[CString], env: &[CString], mounts: &[Mount], fds: &[(RawFd, Fd)], groups: &[u32], seccomp: Option<AllowList>, mut checkpoint: Checkpoint, tripwire: PipeRead, ) ->! { // Install a "default signal handler" that exits on any signal. This process is the "init" // process of this pid ns and therefore doesn't have any own signal handlers. This handler that just exits // is needed in case the container is signaled *before* the child is spawned that would otherwise receive the signal. // If the child is spawn when the signal is sent to this group it shall exit and the init returns from waitpid. set_init_signal_handlers(); // Become a session group leader setsid(); // Sync with parent checkpoint.wait(Start::Start); checkpoint.send(Start::Started); drop(checkpoint); pr_set_name_init(); // Become a subreaper for orphans in this namespace set_child_subreaper(true); let manifest = &container.manifest; let root = container .root .canonicalize() .expect("Failed to canonicalize root"); // Mount mount(&mounts); // Chroot unistd::chroot(&root).expect("Failed to chroot"); // Pwd env::set_current_dir("/").expect("Failed to set cwd to /"); // UID / GID setid(manifest.uid, manifest.gid); // Supplementary groups setgroups(groups); // No new privileges set_no_new_privs(true); // Capabilities drop_capabilities(manifest.capabilities.as_ref()); // Close and dup fds file_descriptors(fds); // Clone match clone(CloneFlags::empty(), Some(SIGCHLD as i32)) { Ok(result) => match result { unistd::ForkResult::Parent { child } => { wait_for_parent_death(tripwire); reset_signal_handlers(); // Wait for the child to exit loop { match waitpid(Some(child), None) { Ok(WaitStatus::Exited(_pid, status)) => exit(status), Ok(WaitStatus::Signaled(_pid, status, _)) => { // Encode the signal number in the process exit status. It's not possible to raise a // a signal in this "init" process that is received by our parent let code = SIGNAL_OFFSET + status as i32; //debug!("Exiting with {} (signaled {})", code, status); exit(code); } Err(e) if e == nix::Error::Sys(Errno::EINTR) => continue, e => panic!("Failed to waitpid on {}: {:?}", child, e), } } } unistd::ForkResult::Child => { drop(tripwire); set_parent_death_signal(SIGKILL); // TODO: Post Linux 5.5 there's a nice clone flag that allows to reset the signal handler during the clone. reset_signal_handlers(); reset_signal_mask(); // Set seccomp filter if let Some(mut filter) = seccomp { filter.apply().expect("Failed to apply seccomp filter."); } panic!( "Execve: {:?} {:?}: {:?}", &init, &argv, unistd::execve(&init, &argv, &env) ) } }, Err(e) => panic!("Clone error: {}", e), } } /// Execute list of mount calls fn mount(mounts: &[Mount]) { for mount in mounts { mount.mount(); } } /// Apply file descriptor configuration fn file_descriptors(map: &[(RawFd, Fd)]) { for (fd, value) in map { match value { Fd::Close => { // Ignore close errors because the fd list contains the ReadDir fd and fds from other tasks. unistd::close(*fd).ok(); } Fd::Dup(n) => { unistd::dup2(*n, *fd).expect("Failed to dup2"); unistd::close(*n).expect("Failed to close"); } } } } fn
(value: bool) { #[cfg(target_os = "android")] const PR_SET_CHILD_SUBREAPER: c_int = 36; #[cfg(not(target_os = "android"))] use libc::PR_SET_CHILD_SUBREAPER; let value = if value { 1u64 } else { 0u64 }; let result = unsafe { nix::libc::prctl(PR_SET_CHILD_SUBREAPER, value, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_CHILD_SUBREAPER"); } fn set_parent_death_signal(signal: Signal) { #[cfg(target_os = "android")] const PR_SET_PDEATHSIG: c_int = 1; #[cfg(not(target_os = "android"))] use libc::PR_SET_PDEATHSIG; let result = unsafe { nix::libc::prctl(PR_SET_PDEATHSIG, signal, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_PDEATHSIG"); } /// Wait in a separate thread for the parent (runtime) process to terminate. This should normally /// not happen. If it does, we (init) need to terminate ourselves or we will be adopted by system /// init. Setting PR_SET_PDEATHSIG is not an option here as we were spawned from a short lived tokio /// thread (not process) that would trigger the signal once the thread terminates. /// Performing this step before calling setgroups results in a SIGABRT. fn wait_for_parent_death(mut tripwire: PipeRead) { std::thread::spawn(move || { tripwire.read_exact(&mut [0u8, 1]).ok(); panic!("Runtime died"); }); } fn set_no_new_privs(value: bool) { #[cfg(target_os = "android")] pub const PR_SET_NO_NEW_PRIVS: c_int = 38; #[cfg(not(target_os = "android"))] use libc::PR_SET_NO_NEW_PRIVS; let result = unsafe { nix::libc::prctl(PR_SET_NO_NEW_PRIVS, value as c_ulong, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_NO_NEW_PRIVS") } #[cfg(target_os = "android")] pub const PR_SET_NAME: c_int = 15; #[cfg(not(target_os = "android"))] use libc::PR_SET_NAME; /// Set the name of the current process to "init" fn pr_set_name_init() { let cname = "init\0"; let result = unsafe { libc::prctl(PR_SET_NAME, cname.as_ptr() as c_ulong, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_NAME"); } /// Install default signal handler fn reset_signal_handlers() { Signal::iterator() .filter(|s| *s!= Signal::SIGCHLD) .filter(|s| *s!= Signal::SIGKILL) .filter(|s| *s!= Signal::SIGSTOP) .try_for_each(|s| unsafe { signal(s, SigHandler::SigDfl) }.map(drop)) .expect("failed to signal"); } fn reset_signal_mask() { sigprocmask(SigmaskHow::SIG_UNBLOCK, Some(&SigSet::all()), None) .expect("Failed to reset signal maks") } /// Install a signal handler that terminates the init process if the signal /// is received before the clone of the child. If this handler would not be /// installed the signal would be ignored (and not sent to the group) because /// the init processes in PID namespace do not have default signal handlers. fn set_init_signal_handlers() { extern "C" fn init_signal_handler(signal: c_int) { exit(SIGNAL_OFFSET + signal); } Signal::iterator() .filter(|s| *s!= Signal::SIGCHLD) .filter(|s| *s!= Signal::SIGKILL) .filter(|s| *s!= Signal::SIGSTOP) .try_for_each(|s| unsafe { signal(s, SigHandler::Handler(init_signal_handler)) }.map(drop)) .expect("Failed to set signal handler"); } // Reset effective caps to the most possible set fn reset_effective_caps() { caps::set(None, caps::CapSet::Effective, &caps::all()).expect("Failed to reset effective caps"); } /// Set uid/gid fn setid(uid: u16, gid: u16) { let rt_privileged = unistd::geteuid() == Uid::from_raw(0); // If running as uid 0 save our caps across the uid/gid drop if rt_privileged { caps::securebits::set_keepcaps(true).expect("Failed to set keep caps"); } let gid = unistd::Gid::from_raw(gid.into()); unistd::setresgid(gid, gid, gid).expect("Failed to set resgid"); let uid = unistd::Uid::from_raw(uid.into()); unistd::setresuid(uid, uid, uid).expect("Failed to set resuid"); if rt_privileged { reset_effective_caps(); caps::securebits::set_keepcaps(false).expect("Failed to set keep caps"); } } /// Become a session group leader fn setsid() { unistd::setsid().expect("Failed to call setsid"); } fn setgroups(groups: &[u32]) { let result = unsafe { nix::libc::setgroups(groups.len(), groups.as_ptr()) }; Errno::result(result) .map(drop) .expect("Failed to set supplementary groups"); } /// Drop capabilities fn drop_capabilities(cs: Option<&HashSet<caps::Capability>>) { let mut bounded = caps::read(None, caps::CapSet::Bounding).expect("Failed to read bounding caps"); if let Some(caps) = cs { bounded.retain(|c|!caps.contains(c)); } for cap in bounded { // caps::set cannot be called for bounded caps::drop(None, caps::CapSet::Bounding, cap).expect("Failed to drop bounding cap"); } if let Some(caps) = cs { caps::set(None, caps::CapSet::Effective, caps).expect("Failed to set effective caps"); caps::set(None, caps::CapSet::Permitted, caps).expect("Failed to set permitted caps"); caps::set(None, caps::CapSet::Inheritable, caps).expect("Failed to set inheritable caps"); caps::set(None, caps::CapSet::Ambient, caps).expect("Failed to set ambient caps"); } }
set_child_subreaper
identifier_name
init.rs
// Copyright (c) 2021 ESRLabs // // 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 super::{ clone::clone, fs::Mount, io::Fd, seccomp::AllowList, Checkpoint, Container, PipeRead, Start, SIGNAL_OFFSET, }; use nix::{ errno::Errno, libc::{self, c_int, c_ulong}, sched, sys::{ self, signal::{signal, sigprocmask, SigHandler, SigSet, SigmaskHow, Signal, SIGCHLD, SIGKILL}, }, unistd::{self, Uid}, }; use sched::CloneFlags; use std::{ collections::HashSet, env, ffi::CString, io::Read, os::unix::prelude::RawFd, process::exit, }; use sys::wait::{waitpid, WaitStatus}; // Init function. Pid 1. #[allow(clippy::too_many_arguments)] pub(super) fn init( container: &Container, init: &CString, argv: &[CString], env: &[CString], mounts: &[Mount], fds: &[(RawFd, Fd)], groups: &[u32], seccomp: Option<AllowList>, mut checkpoint: Checkpoint, tripwire: PipeRead, ) ->! { // Install a "default signal handler" that exits on any signal. This process is the "init" // process of this pid ns and therefore doesn't have any own signal handlers. This handler that just exits // is needed in case the container is signaled *before* the child is spawned that would otherwise receive the signal. // If the child is spawn when the signal is sent to this group it shall exit and the init returns from waitpid. set_init_signal_handlers(); // Become a session group leader setsid(); // Sync with parent checkpoint.wait(Start::Start); checkpoint.send(Start::Started); drop(checkpoint); pr_set_name_init(); // Become a subreaper for orphans in this namespace set_child_subreaper(true); let manifest = &container.manifest; let root = container .root .canonicalize() .expect("Failed to canonicalize root"); // Mount mount(&mounts); // Chroot unistd::chroot(&root).expect("Failed to chroot"); // Pwd env::set_current_dir("/").expect("Failed to set cwd to /"); // UID / GID setid(manifest.uid, manifest.gid); // Supplementary groups setgroups(groups); // No new privileges set_no_new_privs(true); // Capabilities drop_capabilities(manifest.capabilities.as_ref()); // Close and dup fds file_descriptors(fds); // Clone match clone(CloneFlags::empty(), Some(SIGCHLD as i32)) { Ok(result) => match result { unistd::ForkResult::Parent { child } => { wait_for_parent_death(tripwire); reset_signal_handlers(); // Wait for the child to exit loop { match waitpid(Some(child), None) { Ok(WaitStatus::Exited(_pid, status)) => exit(status), Ok(WaitStatus::Signaled(_pid, status, _)) => { // Encode the signal number in the process exit status. It's not possible to raise a // a signal in this "init" process that is received by our parent let code = SIGNAL_OFFSET + status as i32; //debug!("Exiting with {} (signaled {})", code, status); exit(code); } Err(e) if e == nix::Error::Sys(Errno::EINTR) => continue, e => panic!("Failed to waitpid on {}: {:?}", child, e), } } } unistd::ForkResult::Child => { drop(tripwire); set_parent_death_signal(SIGKILL); // TODO: Post Linux 5.5 there's a nice clone flag that allows to reset the signal handler during the clone. reset_signal_handlers(); reset_signal_mask(); // Set seccomp filter if let Some(mut filter) = seccomp { filter.apply().expect("Failed to apply seccomp filter."); } panic!( "Execve: {:?} {:?}: {:?}", &init, &argv, unistd::execve(&init, &argv, &env) ) } }, Err(e) => panic!("Clone error: {}", e), } } /// Execute list of mount calls fn mount(mounts: &[Mount]) { for mount in mounts { mount.mount(); } } /// Apply file descriptor configuration fn file_descriptors(map: &[(RawFd, Fd)]) { for (fd, value) in map { match value { Fd::Close => { // Ignore close errors because the fd list contains the ReadDir fd and fds from other tasks. unistd::close(*fd).ok(); } Fd::Dup(n) => { unistd::dup2(*n, *fd).expect("Failed to dup2"); unistd::close(*n).expect("Failed to close"); } } } } fn set_child_subreaper(value: bool) { #[cfg(target_os = "android")] const PR_SET_CHILD_SUBREAPER: c_int = 36; #[cfg(not(target_os = "android"))] use libc::PR_SET_CHILD_SUBREAPER; let value = if value { 1u64 } else { 0u64 }; let result = unsafe { nix::libc::prctl(PR_SET_CHILD_SUBREAPER, value, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_CHILD_SUBREAPER"); } fn set_parent_death_signal(signal: Signal) { #[cfg(target_os = "android")] const PR_SET_PDEATHSIG: c_int = 1; #[cfg(not(target_os = "android"))] use libc::PR_SET_PDEATHSIG; let result = unsafe { nix::libc::prctl(PR_SET_PDEATHSIG, signal, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_PDEATHSIG"); } /// Wait in a separate thread for the parent (runtime) process to terminate. This should normally /// not happen. If it does, we (init) need to terminate ourselves or we will be adopted by system /// init. Setting PR_SET_PDEATHSIG is not an option here as we were spawned from a short lived tokio /// thread (not process) that would trigger the signal once the thread terminates. /// Performing this step before calling setgroups results in a SIGABRT. fn wait_for_parent_death(mut tripwire: PipeRead) { std::thread::spawn(move || { tripwire.read_exact(&mut [0u8, 1]).ok(); panic!("Runtime died"); }); } fn set_no_new_privs(value: bool) { #[cfg(target_os = "android")] pub const PR_SET_NO_NEW_PRIVS: c_int = 38; #[cfg(not(target_os = "android"))] use libc::PR_SET_NO_NEW_PRIVS; let result = unsafe { nix::libc::prctl(PR_SET_NO_NEW_PRIVS, value as c_ulong, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_NO_NEW_PRIVS") } #[cfg(target_os = "android")] pub const PR_SET_NAME: c_int = 15; #[cfg(not(target_os = "android"))] use libc::PR_SET_NAME; /// Set the name of the current process to "init" fn pr_set_name_init() { let cname = "init\0"; let result = unsafe { libc::prctl(PR_SET_NAME, cname.as_ptr() as c_ulong, 0, 0, 0) }; Errno::result(result) .map(drop) .expect("Failed to set PR_SET_NAME"); } /// Install default signal handler fn reset_signal_handlers() { Signal::iterator() .filter(|s| *s!= Signal::SIGCHLD) .filter(|s| *s!= Signal::SIGKILL) .filter(|s| *s!= Signal::SIGSTOP) .try_for_each(|s| unsafe { signal(s, SigHandler::SigDfl) }.map(drop)) .expect("failed to signal"); } fn reset_signal_mask() { sigprocmask(SigmaskHow::SIG_UNBLOCK, Some(&SigSet::all()), None) .expect("Failed to reset signal maks") } /// Install a signal handler that terminates the init process if the signal /// is received before the clone of the child. If this handler would not be /// installed the signal would be ignored (and not sent to the group) because /// the init processes in PID namespace do not have default signal handlers. fn set_init_signal_handlers() { extern "C" fn init_signal_handler(signal: c_int) { exit(SIGNAL_OFFSET + signal); } Signal::iterator() .filter(|s| *s!= Signal::SIGCHLD) .filter(|s| *s!= Signal::SIGKILL) .filter(|s| *s!= Signal::SIGSTOP) .try_for_each(|s| unsafe { signal(s, SigHandler::Handler(init_signal_handler)) }.map(drop)) .expect("Failed to set signal handler"); } // Reset effective caps to the most possible set fn reset_effective_caps() { caps::set(None, caps::CapSet::Effective, &caps::all()).expect("Failed to reset effective caps"); } /// Set uid/gid fn setid(uid: u16, gid: u16) { let rt_privileged = unistd::geteuid() == Uid::from_raw(0); // If running as uid 0 save our caps across the uid/gid drop if rt_privileged { caps::securebits::set_keepcaps(true).expect("Failed to set keep caps"); } let gid = unistd::Gid::from_raw(gid.into()); unistd::setresgid(gid, gid, gid).expect("Failed to set resgid"); let uid = unistd::Uid::from_raw(uid.into()); unistd::setresuid(uid, uid, uid).expect("Failed to set resuid"); if rt_privileged { reset_effective_caps(); caps::securebits::set_keepcaps(false).expect("Failed to set keep caps"); } } /// Become a session group leader fn setsid()
fn setgroups(groups: &[u32]) { let result = unsafe { nix::libc::setgroups(groups.len(), groups.as_ptr()) }; Errno::result(result) .map(drop) .expect("Failed to set supplementary groups"); } /// Drop capabilities fn drop_capabilities(cs: Option<&HashSet<caps::Capability>>) { let mut bounded = caps::read(None, caps::CapSet::Bounding).expect("Failed to read bounding caps"); if let Some(caps) = cs { bounded.retain(|c|!caps.contains(c)); } for cap in bounded { // caps::set cannot be called for bounded caps::drop(None, caps::CapSet::Bounding, cap).expect("Failed to drop bounding cap"); } if let Some(caps) = cs { caps::set(None, caps::CapSet::Effective, caps).expect("Failed to set effective caps"); caps::set(None, caps::CapSet::Permitted, caps).expect("Failed to set permitted caps"); caps::set(None, caps::CapSet::Inheritable, caps).expect("Failed to set inheritable caps"); caps::set(None, caps::CapSet::Ambient, caps).expect("Failed to set ambient caps"); } }
{ unistd::setsid().expect("Failed to call setsid"); }
identifier_body
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_traits::Num; /// An error for OID parsing functions. #[derive(Debug)] pub enum OidParseError { TooShort, /// Signalizes that the first or second component is too large. /// The first must be within the range 0 to 6 (inclusive). /// The second component must be less than 40. FirstComponentsTooLarge, ParseIntError, } /// Object ID (OID) representation which can be relative or non-relative. /// An example for an OID in string representation is `"1.2.840.113549.1.1.5"`. /// /// For non-relative OIDs restrictions apply to the first two components. /// /// This library contains a procedural macro `oid` which can be used to /// create oids. For example `oid!(1.2.44.233)` or `oid!(rel 44.233)` /// for relative oids. See the [module documentation](index.html) for more information. #[derive(Hash, PartialEq, Eq, Clone)] pub struct Oid<'a> { asn1: Cow<'a, [u8]>, relative: bool, } impl<'a> TryFrom<Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: Any<'a>) -> Result<Self> { TryFrom::try_from(&any) } } impl<'a, 'b> TryFrom<&'b Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: &'b Any<'a>) -> Result<Self> { // check that any.data.last().unwrap() >> 7 == 0u8 let asn1 = Cow::Borrowed(any.data); Ok(Oid::new(asn1)) } } impl<'a> CheckDerConstraints for Oid<'a> { fn check_constraints(any: &Any) -> Result<()> { any.header.assert_primitive()?; any.header.length.assert_definite()?; Ok(()) } }
} #[cfg(feature = "std")] impl ToDer for Oid<'_> { fn to_der_len(&self) -> Result<usize> { // OID/REL-OID tag will not change header size, so we don't care here let header = Header::new( Class::Universal, false, Self::TAG, Length::Definite(self.asn1.len()), ); Ok(header.to_der_len()? + self.asn1.len()) } fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { let tag = if self.relative { Tag::RelativeOid } else { Tag::Oid }; let header = Header::new( Class::Universal, false, tag, Length::Definite(self.asn1.len()), ); header.write_der_header(writer).map_err(Into::into) } fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { writer.write(&self.asn1).map_err(Into::into) } } fn encode_relative(ids: &'_ [u64]) -> impl Iterator<Item = u8> + '_ { ids.iter().flat_map(|id| { let bit_count = 64 - id.leading_zeros(); let octets_needed = ((bit_count + 6) / 7).max(1); (0..octets_needed).map(move |i| { let flag = if i == octets_needed - 1 { 0 } else { 1 << 7 }; ((id >> (7 * (octets_needed - 1 - i))) & 0b111_1111) as u8 | flag }) }) } impl<'a> Oid<'a> { /// Create an OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create oids. pub const fn new(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: false, } } /// Create a relative OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create relative oids. pub const fn new_relative(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: true, } } /// Build an OID from an array of object identifier components. /// This method allocates memory on the heap. pub fn from(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.len() < 2 { if s.len() == 1 && s[0] == 0 { return Ok(Oid { asn1: Cow::Borrowed(&[0]), relative: false, }); } return Err(OidParseError::TooShort); } if s[0] >= 7 || s[1] >= 40 { return Err(OidParseError::FirstComponentsTooLarge); } let asn1_encoded: Vec<u8> = [(s[0] * 40 + s[1]) as u8] .iter() .copied() .chain(encode_relative(&s[2..])) .collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: false, }) } /// Build a relative OID from an array of object identifier components. pub fn from_relative(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.is_empty() { return Err(OidParseError::TooShort); } let asn1_encoded: Vec<u8> = encode_relative(s).collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: true, }) } /// Create a deep copy of the oid. /// /// This method allocates data on the heap. The returned oid /// can be used without keeping the ASN.1 representation around. /// /// Cloning the returned oid does again allocate data. pub fn to_owned(&self) -> Oid<'static> { Oid { asn1: Cow::from(self.asn1.to_vec()), relative: self.relative, } } /// Get the encoded oid without the header. #[inline] pub fn as_bytes(&self) -> &[u8] { self.asn1.as_ref() } /// Get the encoded oid without the header. #[deprecated(since = "0.2.0", note = "Use `as_bytes` instead")] #[inline] pub fn bytes(&self) -> &[u8] { self.as_bytes() } /// Get the bytes representation of the encoded oid pub fn into_cow(self) -> Cow<'a, [u8]> { self.asn1 } /// Convert the OID to a string representation. /// The string contains the IDs separated by dots, for ex: "1.2.840.113549.1.1.5" #[cfg(feature = "bigint")] pub fn to_id_string(&self) -> String { let ints: Vec<String> = self.iter_bigint().map(|i| i.to_string()).collect(); ints.join(".") } #[cfg(not(feature = "bigint"))] /// Convert the OID to a string representation. /// /// If every arc fits into a u64 a string like "1.2.840.113549.1.1.5" /// is returned, otherwise a hex representation. /// /// See also the "bigint" feature of this crate. pub fn to_id_string(&self) -> String { if let Some(arcs) = self.iter() { let ints: Vec<String> = arcs.map(|i| i.to_string()).collect(); ints.join(".") } else { let mut ret = String::with_capacity(self.asn1.len() * 3); for (i, o) in self.asn1.iter().enumerate() { ret.push_str(&format!("{:02x}", o)); if i + 1!= self.asn1.len() { ret.push(' '); } } ret } } /// Return an iterator over the sub-identifiers (arcs). #[cfg(feature = "bigint")] pub fn iter_bigint( &'_ self, ) -> impl Iterator<Item = BigUint> + FusedIterator + ExactSizeIterator + '_ { SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, } } /// Return an iterator over the sub-identifiers (arcs). /// Returns `None` if at least one arc does not fit into `u64`. pub fn iter( &'_ self, ) -> Option<impl Iterator<Item = u64> + FusedIterator + ExactSizeIterator + '_> { // Check that every arc fits into u64 let bytes = if self.relative { &self.asn1 } else if self.asn1.is_empty() { &[] } else { &self.asn1[1..] }; let max_bits = bytes .iter() .fold((0usize, 0usize), |(max, cur), c| { let is_end = (c >> 7) == 0u8; if is_end { (max.max(cur + 7), 0) } else { (max, cur + 7) } }) .0; if max_bits > 64 { return None; } Some(SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, }) } pub fn from_ber_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_ber(bytes)?; any.header.assert_primitive()?; any.header.assert_tag(Tag::RelativeOid)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } pub fn from_der_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_der(bytes)?; any.header.assert_tag(Tag::RelativeOid)?; Self::check_constraints(&any)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } /// Returns true if `needle` is a prefix of the OID. pub fn starts_with(&self, needle: &Oid) -> bool { self.asn1.len() >= needle.asn1.len() && self.asn1.starts_with(needle.as_bytes()) } } trait Repr: Num + Shl<usize, Output = Self> + From<u8> {} impl<N> Repr for N where N: Num + Shl<usize, Output = N> + From<u8> {} struct SubIdentifierIterator<'a, N: Repr> { oid: &'a Oid<'a>, pos: usize, first: bool, n: PhantomData<&'a N>, } impl<'a, N: Repr> Iterator for SubIdentifierIterator<'a, N> { type Item = N; fn next(&mut self) -> Option<Self::Item> { use num_traits::identities::Zero; if self.pos == self.oid.asn1.len() { return None; } if!self.oid.relative { if!self.first { debug_assert!(self.pos == 0); self.first = true; return Some((self.oid.asn1[0] / 40).into()); } else if self.pos == 0 { self.pos += 1; if self.oid.asn1[0] == 0 && self.oid.asn1.len() == 1 { return None; } return Some((self.oid.asn1[0] % 40).into()); } } // decode objet sub-identifier according to the asn.1 standard let mut res = <N as Zero>::zero(); for o in self.oid.asn1[self.pos..].iter() { self.pos += 1; res = (res << 7) + (o & 0b111_1111).into(); let flag = o >> 7; if flag == 0u8 { break; } } Some(res) } } impl<'a, N: Repr> FusedIterator for SubIdentifierIterator<'a, N> {} impl<'a, N: Repr> ExactSizeIterator for SubIdentifierIterator<'a, N> { fn len(&self) -> usize { if self.oid.relative { self.oid.asn1.iter().filter(|o| (*o >> 7) == 0u8).count() } else if self.oid.asn1.len() == 0 { 0 } else if self.oid.asn1.len() == 1 { if self.oid.asn1[0] == 0 { 1 } else { 2 } } else { 2 + self.oid.asn1[2..] .iter() .filter(|o| (*o >> 7) == 0u8) .count() } } #[cfg(feature = "exact_size_is_empty")] fn is_empty(&self) -> bool { self.oid.asn1.is_empty() } } impl<'a> fmt::Display for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.relative { f.write_str("rel. ")?; } f.write_str(&self.to_id_string()) } } impl<'a> fmt::Debug for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("OID(")?; <Oid as fmt::Display>::fmt(self, f)?; f.write_str(")") } } impl<'a> FromStr for Oid<'a> { type Err = OidParseError; fn from_str(s: &str) -> core::result::Result<Self, Self::Err> { let v: core::result::Result<Vec<_>, _> = s.split('.').map(|c| c.parse::<u64>()).collect(); v.map_err(|_| OidParseError::ParseIntError) .and_then(|v| Oid::from(&v)) } } /// Helper macro to declare integers at compile-time /// /// Since the DER encoded oids are not very readable we provide a /// procedural macro `oid!`. The macro can be used the following ways: /// /// - `oid!(1.4.42.23)`: Create a const expression for the corresponding `Oid<'static>` /// - `oid!(rel 42.23)`: Create a const expression for the corresponding relative `Oid<'static>` /// - `oid!(raw 1.4.42.23)`/`oid!(raw rel 42.23)`: Obtain the DER encoded form as a byte array. /// /// # Comparing oids /// /// Comparing a parsed oid to a static oid is probably the most common /// thing done with oids in your code. The `oid!` macro can be used in expression positions for /// this purpose. For example /// ``` /// use asn1_rs::{oid, Oid}; /// /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_STATIC_OID: Oid<'static> = oid!(1.2.456); /// assert_eq!(some_oid, SOME_STATIC_OID) /// ``` /// To get a relative Oid use `oid!(rel 1.2)`. /// /// Because of limitations for procedural macros ([rust issue](https://github.com/rust-lang/rust/issues/54727)) /// and constants used in patterns ([rust issue](https://github.com/rust-lang/rust/issues/31434)) /// the `oid` macro can not directly be used in patterns, also not through constants. /// You can do this, though: /// ``` /// # use asn1_rs::{oid, Oid}; /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_OID: Oid<'static> = oid!(1.2.456); /// if some_oid == SOME_OID || some_oid == oid!(1.2.456) { /// println!("match"); /// } /// /// // Alternatively, compare the DER encoded form directly: /// const SOME_OID_RAW: &[u8] = &oid!(raw 1.2.456); /// match some_oid.as_bytes() { /// SOME_OID_RAW => println!("match"), /// _ => panic!("no match"), /// } /// ``` /// *Attention*, be aware that the latter version might not handle the case of a relative oid correctly. An /// extra check might be necessary. #[macro_export] macro_rules! oid { (raw $( $item:literal ).*) => { $crate::exports::asn1_rs_impl::encode_oid!( $( $item ).* ) }; (raw $items:expr) => { $crate::exports::asn1_rs_impl::encode_oid!($items) }; (rel $($item:literal ).*) => { $crate::Oid::new_relative($crate::exports::borrow::Cow::Borrowed( &$crate::exports::asn1_rs_impl::encode_oid!(rel $( $item ).*), )) }; ($($item:literal ).*) => { $crate::Oid::new($crate::exports::borrow::Cow::Borrowed( &$crate::oid!(raw $( $item ).*), )) }; } #[cfg(test)] mod tests { use crate::{FromDer, Oid, ToDer}; use hex_literal::hex; #[test] fn declare_oid() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_string(), "1.2.840.113549.1"); } const OID_RSA_ENCRYPTION: &[u8] = &oid! {raw 1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: &[u8] = &oid! {raw 1.2.840.10045.2.1}; #[allow(clippy::match_like_matches_macro)] fn compare_oid(oid: &Oid) -> bool { match oid.as_bytes() { OID_RSA_ENCRYPTION => true, OID_EC_PUBLIC_KEY => true, _ => false, } } #[test] fn test_compare_oid() { let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert_eq!(oid, oid! {1.2.840.113549.1.1.1}); let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert!(compare_oid(&oid)); } #[test] fn oid_to_der() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_der_len(), Ok(9)); let v = oid.to_der_vec().expect("could not serialize"); assert_eq!(&v, &hex! {"06 07 2a 86 48 86 f7 0d 01"}); let (_, oid2) = Oid::from_der(&v).expect("could not re-parse"); assert_eq!(&oid, &oid2); } #[test] fn oid_starts_with() { const OID_RSA_ENCRYPTION: Oid = oid! {1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: Oid = oid! {1.2.840.10045.2.1}; let oid = super::oid! {1.2.840.113549.1}; assert!(OID_RSA_ENCRYPTION.starts_with(&oid)); assert!(!OID_EC_PUBLIC_KEY.starts_with(&oid)); } #[test] fn oid_macro_parameters() { // Code inspired from https://github.com/rusticata/der-parser/issues/68 macro_rules! foo { ($a:literal $b:literal $c:literal) => { super::oid!($a.$b.$c) }; } let oid = foo!(1 2 3); assert_eq!(oid, oid! {1.2.3}); } }
impl DerAutoDerive for Oid<'_> {} impl<'a> Tagged for Oid<'a> { const TAG: Tag = Tag::Oid;
random_line_split
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_traits::Num; /// An error for OID parsing functions. #[derive(Debug)] pub enum OidParseError { TooShort, /// Signalizes that the first or second component is too large. /// The first must be within the range 0 to 6 (inclusive). /// The second component must be less than 40. FirstComponentsTooLarge, ParseIntError, } /// Object ID (OID) representation which can be relative or non-relative. /// An example for an OID in string representation is `"1.2.840.113549.1.1.5"`. /// /// For non-relative OIDs restrictions apply to the first two components. /// /// This library contains a procedural macro `oid` which can be used to /// create oids. For example `oid!(1.2.44.233)` or `oid!(rel 44.233)` /// for relative oids. See the [module documentation](index.html) for more information. #[derive(Hash, PartialEq, Eq, Clone)] pub struct Oid<'a> { asn1: Cow<'a, [u8]>, relative: bool, } impl<'a> TryFrom<Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: Any<'a>) -> Result<Self> { TryFrom::try_from(&any) } } impl<'a, 'b> TryFrom<&'b Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: &'b Any<'a>) -> Result<Self> { // check that any.data.last().unwrap() >> 7 == 0u8 let asn1 = Cow::Borrowed(any.data); Ok(Oid::new(asn1)) } } impl<'a> CheckDerConstraints for Oid<'a> { fn check_constraints(any: &Any) -> Result<()> { any.header.assert_primitive()?; any.header.length.assert_definite()?; Ok(()) } } impl DerAutoDerive for Oid<'_> {} impl<'a> Tagged for Oid<'a> { const TAG: Tag = Tag::Oid; } #[cfg(feature = "std")] impl ToDer for Oid<'_> { fn to_der_len(&self) -> Result<usize> { // OID/REL-OID tag will not change header size, so we don't care here let header = Header::new( Class::Universal, false, Self::TAG, Length::Definite(self.asn1.len()), ); Ok(header.to_der_len()? + self.asn1.len()) } fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { let tag = if self.relative { Tag::RelativeOid } else { Tag::Oid }; let header = Header::new( Class::Universal, false, tag, Length::Definite(self.asn1.len()), ); header.write_der_header(writer).map_err(Into::into) } fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { writer.write(&self.asn1).map_err(Into::into) } } fn encode_relative(ids: &'_ [u64]) -> impl Iterator<Item = u8> + '_ { ids.iter().flat_map(|id| { let bit_count = 64 - id.leading_zeros(); let octets_needed = ((bit_count + 6) / 7).max(1); (0..octets_needed).map(move |i| { let flag = if i == octets_needed - 1 { 0 } else { 1 << 7 }; ((id >> (7 * (octets_needed - 1 - i))) & 0b111_1111) as u8 | flag }) }) } impl<'a> Oid<'a> { /// Create an OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create oids. pub const fn new(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: false, } } /// Create a relative OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create relative oids. pub const fn new_relative(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: true, } } /// Build an OID from an array of object identifier components. /// This method allocates memory on the heap. pub fn from(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.len() < 2 { if s.len() == 1 && s[0] == 0 { return Ok(Oid { asn1: Cow::Borrowed(&[0]), relative: false, }); } return Err(OidParseError::TooShort); } if s[0] >= 7 || s[1] >= 40 { return Err(OidParseError::FirstComponentsTooLarge); } let asn1_encoded: Vec<u8> = [(s[0] * 40 + s[1]) as u8] .iter() .copied() .chain(encode_relative(&s[2..])) .collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: false, }) } /// Build a relative OID from an array of object identifier components. pub fn from_relative(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.is_empty() { return Err(OidParseError::TooShort); } let asn1_encoded: Vec<u8> = encode_relative(s).collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: true, }) } /// Create a deep copy of the oid. /// /// This method allocates data on the heap. The returned oid /// can be used without keeping the ASN.1 representation around. /// /// Cloning the returned oid does again allocate data. pub fn to_owned(&self) -> Oid<'static> { Oid { asn1: Cow::from(self.asn1.to_vec()), relative: self.relative, } } /// Get the encoded oid without the header. #[inline] pub fn as_bytes(&self) -> &[u8] { self.asn1.as_ref() } /// Get the encoded oid without the header. #[deprecated(since = "0.2.0", note = "Use `as_bytes` instead")] #[inline] pub fn bytes(&self) -> &[u8] { self.as_bytes() } /// Get the bytes representation of the encoded oid pub fn into_cow(self) -> Cow<'a, [u8]> { self.asn1 } /// Convert the OID to a string representation. /// The string contains the IDs separated by dots, for ex: "1.2.840.113549.1.1.5" #[cfg(feature = "bigint")] pub fn to_id_string(&self) -> String { let ints: Vec<String> = self.iter_bigint().map(|i| i.to_string()).collect(); ints.join(".") } #[cfg(not(feature = "bigint"))] /// Convert the OID to a string representation. /// /// If every arc fits into a u64 a string like "1.2.840.113549.1.1.5" /// is returned, otherwise a hex representation. /// /// See also the "bigint" feature of this crate. pub fn to_id_string(&self) -> String { if let Some(arcs) = self.iter() { let ints: Vec<String> = arcs.map(|i| i.to_string()).collect(); ints.join(".") } else { let mut ret = String::with_capacity(self.asn1.len() * 3); for (i, o) in self.asn1.iter().enumerate() { ret.push_str(&format!("{:02x}", o)); if i + 1!= self.asn1.len() { ret.push(' '); } } ret } } /// Return an iterator over the sub-identifiers (arcs). #[cfg(feature = "bigint")] pub fn iter_bigint( &'_ self, ) -> impl Iterator<Item = BigUint> + FusedIterator + ExactSizeIterator + '_ { SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, } } /// Return an iterator over the sub-identifiers (arcs). /// Returns `None` if at least one arc does not fit into `u64`. pub fn iter( &'_ self, ) -> Option<impl Iterator<Item = u64> + FusedIterator + ExactSizeIterator + '_>
if max_bits > 64 { return None; } Some(SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, }) } pub fn from_ber_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_ber(bytes)?; any.header.assert_primitive()?; any.header.assert_tag(Tag::RelativeOid)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } pub fn from_der_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_der(bytes)?; any.header.assert_tag(Tag::RelativeOid)?; Self::check_constraints(&any)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } /// Returns true if `needle` is a prefix of the OID. pub fn starts_with(&self, needle: &Oid) -> bool { self.asn1.len() >= needle.asn1.len() && self.asn1.starts_with(needle.as_bytes()) } } trait Repr: Num + Shl<usize, Output = Self> + From<u8> {} impl<N> Repr for N where N: Num + Shl<usize, Output = N> + From<u8> {} struct SubIdentifierIterator<'a, N: Repr> { oid: &'a Oid<'a>, pos: usize, first: bool, n: PhantomData<&'a N>, } impl<'a, N: Repr> Iterator for SubIdentifierIterator<'a, N> { type Item = N; fn next(&mut self) -> Option<Self::Item> { use num_traits::identities::Zero; if self.pos == self.oid.asn1.len() { return None; } if!self.oid.relative { if!self.first { debug_assert!(self.pos == 0); self.first = true; return Some((self.oid.asn1[0] / 40).into()); } else if self.pos == 0 { self.pos += 1; if self.oid.asn1[0] == 0 && self.oid.asn1.len() == 1 { return None; } return Some((self.oid.asn1[0] % 40).into()); } } // decode objet sub-identifier according to the asn.1 standard let mut res = <N as Zero>::zero(); for o in self.oid.asn1[self.pos..].iter() { self.pos += 1; res = (res << 7) + (o & 0b111_1111).into(); let flag = o >> 7; if flag == 0u8 { break; } } Some(res) } } impl<'a, N: Repr> FusedIterator for SubIdentifierIterator<'a, N> {} impl<'a, N: Repr> ExactSizeIterator for SubIdentifierIterator<'a, N> { fn len(&self) -> usize { if self.oid.relative { self.oid.asn1.iter().filter(|o| (*o >> 7) == 0u8).count() } else if self.oid.asn1.len() == 0 { 0 } else if self.oid.asn1.len() == 1 { if self.oid.asn1[0] == 0 { 1 } else { 2 } } else { 2 + self.oid.asn1[2..] .iter() .filter(|o| (*o >> 7) == 0u8) .count() } } #[cfg(feature = "exact_size_is_empty")] fn is_empty(&self) -> bool { self.oid.asn1.is_empty() } } impl<'a> fmt::Display for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.relative { f.write_str("rel. ")?; } f.write_str(&self.to_id_string()) } } impl<'a> fmt::Debug for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("OID(")?; <Oid as fmt::Display>::fmt(self, f)?; f.write_str(")") } } impl<'a> FromStr for Oid<'a> { type Err = OidParseError; fn from_str(s: &str) -> core::result::Result<Self, Self::Err> { let v: core::result::Result<Vec<_>, _> = s.split('.').map(|c| c.parse::<u64>()).collect(); v.map_err(|_| OidParseError::ParseIntError) .and_then(|v| Oid::from(&v)) } } /// Helper macro to declare integers at compile-time /// /// Since the DER encoded oids are not very readable we provide a /// procedural macro `oid!`. The macro can be used the following ways: /// /// - `oid!(1.4.42.23)`: Create a const expression for the corresponding `Oid<'static>` /// - `oid!(rel 42.23)`: Create a const expression for the corresponding relative `Oid<'static>` /// - `oid!(raw 1.4.42.23)`/`oid!(raw rel 42.23)`: Obtain the DER encoded form as a byte array. /// /// # Comparing oids /// /// Comparing a parsed oid to a static oid is probably the most common /// thing done with oids in your code. The `oid!` macro can be used in expression positions for /// this purpose. For example /// ``` /// use asn1_rs::{oid, Oid}; /// /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_STATIC_OID: Oid<'static> = oid!(1.2.456); /// assert_eq!(some_oid, SOME_STATIC_OID) /// ``` /// To get a relative Oid use `oid!(rel 1.2)`. /// /// Because of limitations for procedural macros ([rust issue](https://github.com/rust-lang/rust/issues/54727)) /// and constants used in patterns ([rust issue](https://github.com/rust-lang/rust/issues/31434)) /// the `oid` macro can not directly be used in patterns, also not through constants. /// You can do this, though: /// ``` /// # use asn1_rs::{oid, Oid}; /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_OID: Oid<'static> = oid!(1.2.456); /// if some_oid == SOME_OID || some_oid == oid!(1.2.456) { /// println!("match"); /// } /// /// // Alternatively, compare the DER encoded form directly: /// const SOME_OID_RAW: &[u8] = &oid!(raw 1.2.456); /// match some_oid.as_bytes() { /// SOME_OID_RAW => println!("match"), /// _ => panic!("no match"), /// } /// ``` /// *Attention*, be aware that the latter version might not handle the case of a relative oid correctly. An /// extra check might be necessary. #[macro_export] macro_rules! oid { (raw $( $item:literal ).*) => { $crate::exports::asn1_rs_impl::encode_oid!( $( $item ).* ) }; (raw $items:expr) => { $crate::exports::asn1_rs_impl::encode_oid!($items) }; (rel $($item:literal ).*) => { $crate::Oid::new_relative($crate::exports::borrow::Cow::Borrowed( &$crate::exports::asn1_rs_impl::encode_oid!(rel $( $item ).*), )) }; ($($item:literal ).*) => { $crate::Oid::new($crate::exports::borrow::Cow::Borrowed( &$crate::oid!(raw $( $item ).*), )) }; } #[cfg(test)] mod tests { use crate::{FromDer, Oid, ToDer}; use hex_literal::hex; #[test] fn declare_oid() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_string(), "1.2.840.113549.1"); } const OID_RSA_ENCRYPTION: &[u8] = &oid! {raw 1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: &[u8] = &oid! {raw 1.2.840.10045.2.1}; #[allow(clippy::match_like_matches_macro)] fn compare_oid(oid: &Oid) -> bool { match oid.as_bytes() { OID_RSA_ENCRYPTION => true, OID_EC_PUBLIC_KEY => true, _ => false, } } #[test] fn test_compare_oid() { let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert_eq!(oid, oid! {1.2.840.113549.1.1.1}); let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert!(compare_oid(&oid)); } #[test] fn oid_to_der() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_der_len(), Ok(9)); let v = oid.to_der_vec().expect("could not serialize"); assert_eq!(&v, &hex! {"06 07 2a 86 48 86 f7 0d 01"}); let (_, oid2) = Oid::from_der(&v).expect("could not re-parse"); assert_eq!(&oid, &oid2); } #[test] fn oid_starts_with() { const OID_RSA_ENCRYPTION: Oid = oid! {1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: Oid = oid! {1.2.840.10045.2.1}; let oid = super::oid! {1.2.840.113549.1}; assert!(OID_RSA_ENCRYPTION.starts_with(&oid)); assert!(!OID_EC_PUBLIC_KEY.starts_with(&oid)); } #[test] fn oid_macro_parameters() { // Code inspired from https://github.com/rusticata/der-parser/issues/68 macro_rules! foo { ($a:literal $b:literal $c:literal) => { super::oid!($a.$b.$c) }; } let oid = foo!(1 2 3); assert_eq!(oid, oid! {1.2.3}); } }
{ // Check that every arc fits into u64 let bytes = if self.relative { &self.asn1 } else if self.asn1.is_empty() { &[] } else { &self.asn1[1..] }; let max_bits = bytes .iter() .fold((0usize, 0usize), |(max, cur), c| { let is_end = (c >> 7) == 0u8; if is_end { (max.max(cur + 7), 0) } else { (max, cur + 7) } }) .0;
identifier_body
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_traits::Num; /// An error for OID parsing functions. #[derive(Debug)] pub enum OidParseError { TooShort, /// Signalizes that the first or second component is too large. /// The first must be within the range 0 to 6 (inclusive). /// The second component must be less than 40. FirstComponentsTooLarge, ParseIntError, } /// Object ID (OID) representation which can be relative or non-relative. /// An example for an OID in string representation is `"1.2.840.113549.1.1.5"`. /// /// For non-relative OIDs restrictions apply to the first two components. /// /// This library contains a procedural macro `oid` which can be used to /// create oids. For example `oid!(1.2.44.233)` or `oid!(rel 44.233)` /// for relative oids. See the [module documentation](index.html) for more information. #[derive(Hash, PartialEq, Eq, Clone)] pub struct Oid<'a> { asn1: Cow<'a, [u8]>, relative: bool, } impl<'a> TryFrom<Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: Any<'a>) -> Result<Self> { TryFrom::try_from(&any) } } impl<'a, 'b> TryFrom<&'b Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: &'b Any<'a>) -> Result<Self> { // check that any.data.last().unwrap() >> 7 == 0u8 let asn1 = Cow::Borrowed(any.data); Ok(Oid::new(asn1)) } } impl<'a> CheckDerConstraints for Oid<'a> { fn check_constraints(any: &Any) -> Result<()> { any.header.assert_primitive()?; any.header.length.assert_definite()?; Ok(()) } } impl DerAutoDerive for Oid<'_> {} impl<'a> Tagged for Oid<'a> { const TAG: Tag = Tag::Oid; } #[cfg(feature = "std")] impl ToDer for Oid<'_> { fn to_der_len(&self) -> Result<usize> { // OID/REL-OID tag will not change header size, so we don't care here let header = Header::new( Class::Universal, false, Self::TAG, Length::Definite(self.asn1.len()), ); Ok(header.to_der_len()? + self.asn1.len()) } fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { let tag = if self.relative { Tag::RelativeOid } else { Tag::Oid }; let header = Header::new( Class::Universal, false, tag, Length::Definite(self.asn1.len()), ); header.write_der_header(writer).map_err(Into::into) } fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { writer.write(&self.asn1).map_err(Into::into) } } fn encode_relative(ids: &'_ [u64]) -> impl Iterator<Item = u8> + '_ { ids.iter().flat_map(|id| { let bit_count = 64 - id.leading_zeros(); let octets_needed = ((bit_count + 6) / 7).max(1); (0..octets_needed).map(move |i| { let flag = if i == octets_needed - 1 { 0 } else { 1 << 7 }; ((id >> (7 * (octets_needed - 1 - i))) & 0b111_1111) as u8 | flag }) }) } impl<'a> Oid<'a> { /// Create an OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create oids. pub const fn new(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: false, } } /// Create a relative OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create relative oids. pub const fn new_relative(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: true, } } /// Build an OID from an array of object identifier components. /// This method allocates memory on the heap. pub fn from(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.len() < 2 { if s.len() == 1 && s[0] == 0 { return Ok(Oid { asn1: Cow::Borrowed(&[0]), relative: false, }); } return Err(OidParseError::TooShort); } if s[0] >= 7 || s[1] >= 40 { return Err(OidParseError::FirstComponentsTooLarge); } let asn1_encoded: Vec<u8> = [(s[0] * 40 + s[1]) as u8] .iter() .copied() .chain(encode_relative(&s[2..])) .collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: false, }) } /// Build a relative OID from an array of object identifier components. pub fn from_relative(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.is_empty() { return Err(OidParseError::TooShort); } let asn1_encoded: Vec<u8> = encode_relative(s).collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: true, }) } /// Create a deep copy of the oid. /// /// This method allocates data on the heap. The returned oid /// can be used without keeping the ASN.1 representation around. /// /// Cloning the returned oid does again allocate data. pub fn to_owned(&self) -> Oid<'static> { Oid { asn1: Cow::from(self.asn1.to_vec()), relative: self.relative, } } /// Get the encoded oid without the header. #[inline] pub fn as_bytes(&self) -> &[u8] { self.asn1.as_ref() } /// Get the encoded oid without the header. #[deprecated(since = "0.2.0", note = "Use `as_bytes` instead")] #[inline] pub fn bytes(&self) -> &[u8] { self.as_bytes() } /// Get the bytes representation of the encoded oid pub fn into_cow(self) -> Cow<'a, [u8]> { self.asn1 } /// Convert the OID to a string representation. /// The string contains the IDs separated by dots, for ex: "1.2.840.113549.1.1.5" #[cfg(feature = "bigint")] pub fn to_id_string(&self) -> String { let ints: Vec<String> = self.iter_bigint().map(|i| i.to_string()).collect(); ints.join(".") } #[cfg(not(feature = "bigint"))] /// Convert the OID to a string representation. /// /// If every arc fits into a u64 a string like "1.2.840.113549.1.1.5" /// is returned, otherwise a hex representation. /// /// See also the "bigint" feature of this crate. pub fn to_id_string(&self) -> String { if let Some(arcs) = self.iter() { let ints: Vec<String> = arcs.map(|i| i.to_string()).collect(); ints.join(".") } else { let mut ret = String::with_capacity(self.asn1.len() * 3); for (i, o) in self.asn1.iter().enumerate() { ret.push_str(&format!("{:02x}", o)); if i + 1!= self.asn1.len() { ret.push(' '); } } ret } } /// Return an iterator over the sub-identifiers (arcs). #[cfg(feature = "bigint")] pub fn iter_bigint( &'_ self, ) -> impl Iterator<Item = BigUint> + FusedIterator + ExactSizeIterator + '_ { SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, } } /// Return an iterator over the sub-identifiers (arcs). /// Returns `None` if at least one arc does not fit into `u64`. pub fn iter( &'_ self, ) -> Option<impl Iterator<Item = u64> + FusedIterator + ExactSizeIterator + '_> { // Check that every arc fits into u64 let bytes = if self.relative { &self.asn1 } else if self.asn1.is_empty() { &[] } else { &self.asn1[1..] }; let max_bits = bytes .iter() .fold((0usize, 0usize), |(max, cur), c| { let is_end = (c >> 7) == 0u8; if is_end { (max.max(cur + 7), 0) } else { (max, cur + 7) } }) .0; if max_bits > 64 { return None; } Some(SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, }) } pub fn from_ber_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_ber(bytes)?; any.header.assert_primitive()?; any.header.assert_tag(Tag::RelativeOid)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } pub fn from_der_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_der(bytes)?; any.header.assert_tag(Tag::RelativeOid)?; Self::check_constraints(&any)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } /// Returns true if `needle` is a prefix of the OID. pub fn starts_with(&self, needle: &Oid) -> bool { self.asn1.len() >= needle.asn1.len() && self.asn1.starts_with(needle.as_bytes()) } } trait Repr: Num + Shl<usize, Output = Self> + From<u8> {} impl<N> Repr for N where N: Num + Shl<usize, Output = N> + From<u8> {} struct SubIdentifierIterator<'a, N: Repr> { oid: &'a Oid<'a>, pos: usize, first: bool, n: PhantomData<&'a N>, } impl<'a, N: Repr> Iterator for SubIdentifierIterator<'a, N> { type Item = N; fn next(&mut self) -> Option<Self::Item> { use num_traits::identities::Zero; if self.pos == self.oid.asn1.len() { return None; } if!self.oid.relative { if!self.first { debug_assert!(self.pos == 0); self.first = true; return Some((self.oid.asn1[0] / 40).into()); } else if self.pos == 0 { self.pos += 1; if self.oid.asn1[0] == 0 && self.oid.asn1.len() == 1 { return None; } return Some((self.oid.asn1[0] % 40).into()); } } // decode objet sub-identifier according to the asn.1 standard let mut res = <N as Zero>::zero(); for o in self.oid.asn1[self.pos..].iter() { self.pos += 1; res = (res << 7) + (o & 0b111_1111).into(); let flag = o >> 7; if flag == 0u8 { break; } } Some(res) } } impl<'a, N: Repr> FusedIterator for SubIdentifierIterator<'a, N> {} impl<'a, N: Repr> ExactSizeIterator for SubIdentifierIterator<'a, N> { fn len(&self) -> usize { if self.oid.relative { self.oid.asn1.iter().filter(|o| (*o >> 7) == 0u8).count() } else if self.oid.asn1.len() == 0 { 0 } else if self.oid.asn1.len() == 1 { if self.oid.asn1[0] == 0 { 1 } else { 2 } } else { 2 + self.oid.asn1[2..] .iter() .filter(|o| (*o >> 7) == 0u8) .count() } } #[cfg(feature = "exact_size_is_empty")] fn is_empty(&self) -> bool { self.oid.asn1.is_empty() } } impl<'a> fmt::Display for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.relative { f.write_str("rel. ")?; } f.write_str(&self.to_id_string()) } } impl<'a> fmt::Debug for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("OID(")?; <Oid as fmt::Display>::fmt(self, f)?; f.write_str(")") } } impl<'a> FromStr for Oid<'a> { type Err = OidParseError; fn from_str(s: &str) -> core::result::Result<Self, Self::Err> { let v: core::result::Result<Vec<_>, _> = s.split('.').map(|c| c.parse::<u64>()).collect(); v.map_err(|_| OidParseError::ParseIntError) .and_then(|v| Oid::from(&v)) } } /// Helper macro to declare integers at compile-time /// /// Since the DER encoded oids are not very readable we provide a /// procedural macro `oid!`. The macro can be used the following ways: /// /// - `oid!(1.4.42.23)`: Create a const expression for the corresponding `Oid<'static>` /// - `oid!(rel 42.23)`: Create a const expression for the corresponding relative `Oid<'static>` /// - `oid!(raw 1.4.42.23)`/`oid!(raw rel 42.23)`: Obtain the DER encoded form as a byte array. /// /// # Comparing oids /// /// Comparing a parsed oid to a static oid is probably the most common /// thing done with oids in your code. The `oid!` macro can be used in expression positions for /// this purpose. For example /// ``` /// use asn1_rs::{oid, Oid}; /// /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_STATIC_OID: Oid<'static> = oid!(1.2.456); /// assert_eq!(some_oid, SOME_STATIC_OID) /// ``` /// To get a relative Oid use `oid!(rel 1.2)`. /// /// Because of limitations for procedural macros ([rust issue](https://github.com/rust-lang/rust/issues/54727)) /// and constants used in patterns ([rust issue](https://github.com/rust-lang/rust/issues/31434)) /// the `oid` macro can not directly be used in patterns, also not through constants. /// You can do this, though: /// ``` /// # use asn1_rs::{oid, Oid}; /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_OID: Oid<'static> = oid!(1.2.456); /// if some_oid == SOME_OID || some_oid == oid!(1.2.456) { /// println!("match"); /// } /// /// // Alternatively, compare the DER encoded form directly: /// const SOME_OID_RAW: &[u8] = &oid!(raw 1.2.456); /// match some_oid.as_bytes() { /// SOME_OID_RAW => println!("match"), /// _ => panic!("no match"), /// } /// ``` /// *Attention*, be aware that the latter version might not handle the case of a relative oid correctly. An /// extra check might be necessary. #[macro_export] macro_rules! oid { (raw $( $item:literal ).*) => { $crate::exports::asn1_rs_impl::encode_oid!( $( $item ).* ) }; (raw $items:expr) => { $crate::exports::asn1_rs_impl::encode_oid!($items) }; (rel $($item:literal ).*) => { $crate::Oid::new_relative($crate::exports::borrow::Cow::Borrowed( &$crate::exports::asn1_rs_impl::encode_oid!(rel $( $item ).*), )) }; ($($item:literal ).*) => { $crate::Oid::new($crate::exports::borrow::Cow::Borrowed( &$crate::oid!(raw $( $item ).*), )) }; } #[cfg(test)] mod tests { use crate::{FromDer, Oid, ToDer}; use hex_literal::hex; #[test] fn declare_oid() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_string(), "1.2.840.113549.1"); } const OID_RSA_ENCRYPTION: &[u8] = &oid! {raw 1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: &[u8] = &oid! {raw 1.2.840.10045.2.1}; #[allow(clippy::match_like_matches_macro)] fn compare_oid(oid: &Oid) -> bool { match oid.as_bytes() { OID_RSA_ENCRYPTION => true, OID_EC_PUBLIC_KEY => true, _ => false, } } #[test] fn
() { let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert_eq!(oid, oid! {1.2.840.113549.1.1.1}); let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert!(compare_oid(&oid)); } #[test] fn oid_to_der() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_der_len(), Ok(9)); let v = oid.to_der_vec().expect("could not serialize"); assert_eq!(&v, &hex! {"06 07 2a 86 48 86 f7 0d 01"}); let (_, oid2) = Oid::from_der(&v).expect("could not re-parse"); assert_eq!(&oid, &oid2); } #[test] fn oid_starts_with() { const OID_RSA_ENCRYPTION: Oid = oid! {1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: Oid = oid! {1.2.840.10045.2.1}; let oid = super::oid! {1.2.840.113549.1}; assert!(OID_RSA_ENCRYPTION.starts_with(&oid)); assert!(!OID_EC_PUBLIC_KEY.starts_with(&oid)); } #[test] fn oid_macro_parameters() { // Code inspired from https://github.com/rusticata/der-parser/issues/68 macro_rules! foo { ($a:literal $b:literal $c:literal) => { super::oid!($a.$b.$c) }; } let oid = foo!(1 2 3); assert_eq!(oid, oid! {1.2.3}); } }
test_compare_oid
identifier_name
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_traits::Num; /// An error for OID parsing functions. #[derive(Debug)] pub enum OidParseError { TooShort, /// Signalizes that the first or second component is too large. /// The first must be within the range 0 to 6 (inclusive). /// The second component must be less than 40. FirstComponentsTooLarge, ParseIntError, } /// Object ID (OID) representation which can be relative or non-relative. /// An example for an OID in string representation is `"1.2.840.113549.1.1.5"`. /// /// For non-relative OIDs restrictions apply to the first two components. /// /// This library contains a procedural macro `oid` which can be used to /// create oids. For example `oid!(1.2.44.233)` or `oid!(rel 44.233)` /// for relative oids. See the [module documentation](index.html) for more information. #[derive(Hash, PartialEq, Eq, Clone)] pub struct Oid<'a> { asn1: Cow<'a, [u8]>, relative: bool, } impl<'a> TryFrom<Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: Any<'a>) -> Result<Self> { TryFrom::try_from(&any) } } impl<'a, 'b> TryFrom<&'b Any<'a>> for Oid<'a> { type Error = Error; fn try_from(any: &'b Any<'a>) -> Result<Self> { // check that any.data.last().unwrap() >> 7 == 0u8 let asn1 = Cow::Borrowed(any.data); Ok(Oid::new(asn1)) } } impl<'a> CheckDerConstraints for Oid<'a> { fn check_constraints(any: &Any) -> Result<()> { any.header.assert_primitive()?; any.header.length.assert_definite()?; Ok(()) } } impl DerAutoDerive for Oid<'_> {} impl<'a> Tagged for Oid<'a> { const TAG: Tag = Tag::Oid; } #[cfg(feature = "std")] impl ToDer for Oid<'_> { fn to_der_len(&self) -> Result<usize> { // OID/REL-OID tag will not change header size, so we don't care here let header = Header::new( Class::Universal, false, Self::TAG, Length::Definite(self.asn1.len()), ); Ok(header.to_der_len()? + self.asn1.len()) } fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { let tag = if self.relative { Tag::RelativeOid } else { Tag::Oid }; let header = Header::new( Class::Universal, false, tag, Length::Definite(self.asn1.len()), ); header.write_der_header(writer).map_err(Into::into) } fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> { writer.write(&self.asn1).map_err(Into::into) } } fn encode_relative(ids: &'_ [u64]) -> impl Iterator<Item = u8> + '_ { ids.iter().flat_map(|id| { let bit_count = 64 - id.leading_zeros(); let octets_needed = ((bit_count + 6) / 7).max(1); (0..octets_needed).map(move |i| { let flag = if i == octets_needed - 1 { 0 } else { 1 << 7 }; ((id >> (7 * (octets_needed - 1 - i))) & 0b111_1111) as u8 | flag }) }) } impl<'a> Oid<'a> { /// Create an OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create oids. pub const fn new(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: false, } } /// Create a relative OID from the ASN.1 DER encoded form. See the [module documentation](index.html) /// for other ways to create relative oids. pub const fn new_relative(asn1: Cow<'a, [u8]>) -> Oid { Oid { asn1, relative: true, } } /// Build an OID from an array of object identifier components. /// This method allocates memory on the heap. pub fn from(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.len() < 2 { if s.len() == 1 && s[0] == 0 { return Ok(Oid { asn1: Cow::Borrowed(&[0]), relative: false, }); } return Err(OidParseError::TooShort); } if s[0] >= 7 || s[1] >= 40 { return Err(OidParseError::FirstComponentsTooLarge); } let asn1_encoded: Vec<u8> = [(s[0] * 40 + s[1]) as u8] .iter() .copied() .chain(encode_relative(&s[2..])) .collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: false, }) } /// Build a relative OID from an array of object identifier components. pub fn from_relative(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> { if s.is_empty() { return Err(OidParseError::TooShort); } let asn1_encoded: Vec<u8> = encode_relative(s).collect(); Ok(Oid { asn1: Cow::from(asn1_encoded), relative: true, }) } /// Create a deep copy of the oid. /// /// This method allocates data on the heap. The returned oid /// can be used without keeping the ASN.1 representation around. /// /// Cloning the returned oid does again allocate data. pub fn to_owned(&self) -> Oid<'static> { Oid { asn1: Cow::from(self.asn1.to_vec()), relative: self.relative, } } /// Get the encoded oid without the header. #[inline] pub fn as_bytes(&self) -> &[u8] { self.asn1.as_ref() } /// Get the encoded oid without the header. #[deprecated(since = "0.2.0", note = "Use `as_bytes` instead")] #[inline] pub fn bytes(&self) -> &[u8] { self.as_bytes() } /// Get the bytes representation of the encoded oid pub fn into_cow(self) -> Cow<'a, [u8]> { self.asn1 } /// Convert the OID to a string representation. /// The string contains the IDs separated by dots, for ex: "1.2.840.113549.1.1.5" #[cfg(feature = "bigint")] pub fn to_id_string(&self) -> String { let ints: Vec<String> = self.iter_bigint().map(|i| i.to_string()).collect(); ints.join(".") } #[cfg(not(feature = "bigint"))] /// Convert the OID to a string representation. /// /// If every arc fits into a u64 a string like "1.2.840.113549.1.1.5" /// is returned, otherwise a hex representation. /// /// See also the "bigint" feature of this crate. pub fn to_id_string(&self) -> String { if let Some(arcs) = self.iter() { let ints: Vec<String> = arcs.map(|i| i.to_string()).collect(); ints.join(".") } else { let mut ret = String::with_capacity(self.asn1.len() * 3); for (i, o) in self.asn1.iter().enumerate() { ret.push_str(&format!("{:02x}", o)); if i + 1!= self.asn1.len() { ret.push(' '); } } ret } } /// Return an iterator over the sub-identifiers (arcs). #[cfg(feature = "bigint")] pub fn iter_bigint( &'_ self, ) -> impl Iterator<Item = BigUint> + FusedIterator + ExactSizeIterator + '_ { SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, } } /// Return an iterator over the sub-identifiers (arcs). /// Returns `None` if at least one arc does not fit into `u64`. pub fn iter( &'_ self, ) -> Option<impl Iterator<Item = u64> + FusedIterator + ExactSizeIterator + '_> { // Check that every arc fits into u64 let bytes = if self.relative { &self.asn1 } else if self.asn1.is_empty() { &[] } else { &self.asn1[1..] }; let max_bits = bytes .iter() .fold((0usize, 0usize), |(max, cur), c| { let is_end = (c >> 7) == 0u8; if is_end { (max.max(cur + 7), 0) } else { (max, cur + 7) } }) .0; if max_bits > 64 { return None; } Some(SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, }) } pub fn from_ber_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_ber(bytes)?; any.header.assert_primitive()?; any.header.assert_tag(Tag::RelativeOid)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } pub fn from_der_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::from_der(bytes)?; any.header.assert_tag(Tag::RelativeOid)?; Self::check_constraints(&any)?; let asn1 = Cow::Borrowed(any.data); Ok((rem, Oid::new_relative(asn1))) } /// Returns true if `needle` is a prefix of the OID. pub fn starts_with(&self, needle: &Oid) -> bool { self.asn1.len() >= needle.asn1.len() && self.asn1.starts_with(needle.as_bytes()) } } trait Repr: Num + Shl<usize, Output = Self> + From<u8> {} impl<N> Repr for N where N: Num + Shl<usize, Output = N> + From<u8> {} struct SubIdentifierIterator<'a, N: Repr> { oid: &'a Oid<'a>, pos: usize, first: bool, n: PhantomData<&'a N>, } impl<'a, N: Repr> Iterator for SubIdentifierIterator<'a, N> { type Item = N; fn next(&mut self) -> Option<Self::Item> { use num_traits::identities::Zero; if self.pos == self.oid.asn1.len() { return None; } if!self.oid.relative { if!self.first { debug_assert!(self.pos == 0); self.first = true; return Some((self.oid.asn1[0] / 40).into()); } else if self.pos == 0 { self.pos += 1; if self.oid.asn1[0] == 0 && self.oid.asn1.len() == 1 { return None; } return Some((self.oid.asn1[0] % 40).into()); } } // decode objet sub-identifier according to the asn.1 standard let mut res = <N as Zero>::zero(); for o in self.oid.asn1[self.pos..].iter() { self.pos += 1; res = (res << 7) + (o & 0b111_1111).into(); let flag = o >> 7; if flag == 0u8
} Some(res) } } impl<'a, N: Repr> FusedIterator for SubIdentifierIterator<'a, N> {} impl<'a, N: Repr> ExactSizeIterator for SubIdentifierIterator<'a, N> { fn len(&self) -> usize { if self.oid.relative { self.oid.asn1.iter().filter(|o| (*o >> 7) == 0u8).count() } else if self.oid.asn1.len() == 0 { 0 } else if self.oid.asn1.len() == 1 { if self.oid.asn1[0] == 0 { 1 } else { 2 } } else { 2 + self.oid.asn1[2..] .iter() .filter(|o| (*o >> 7) == 0u8) .count() } } #[cfg(feature = "exact_size_is_empty")] fn is_empty(&self) -> bool { self.oid.asn1.is_empty() } } impl<'a> fmt::Display for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.relative { f.write_str("rel. ")?; } f.write_str(&self.to_id_string()) } } impl<'a> fmt::Debug for Oid<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("OID(")?; <Oid as fmt::Display>::fmt(self, f)?; f.write_str(")") } } impl<'a> FromStr for Oid<'a> { type Err = OidParseError; fn from_str(s: &str) -> core::result::Result<Self, Self::Err> { let v: core::result::Result<Vec<_>, _> = s.split('.').map(|c| c.parse::<u64>()).collect(); v.map_err(|_| OidParseError::ParseIntError) .and_then(|v| Oid::from(&v)) } } /// Helper macro to declare integers at compile-time /// /// Since the DER encoded oids are not very readable we provide a /// procedural macro `oid!`. The macro can be used the following ways: /// /// - `oid!(1.4.42.23)`: Create a const expression for the corresponding `Oid<'static>` /// - `oid!(rel 42.23)`: Create a const expression for the corresponding relative `Oid<'static>` /// - `oid!(raw 1.4.42.23)`/`oid!(raw rel 42.23)`: Obtain the DER encoded form as a byte array. /// /// # Comparing oids /// /// Comparing a parsed oid to a static oid is probably the most common /// thing done with oids in your code. The `oid!` macro can be used in expression positions for /// this purpose. For example /// ``` /// use asn1_rs::{oid, Oid}; /// /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_STATIC_OID: Oid<'static> = oid!(1.2.456); /// assert_eq!(some_oid, SOME_STATIC_OID) /// ``` /// To get a relative Oid use `oid!(rel 1.2)`. /// /// Because of limitations for procedural macros ([rust issue](https://github.com/rust-lang/rust/issues/54727)) /// and constants used in patterns ([rust issue](https://github.com/rust-lang/rust/issues/31434)) /// the `oid` macro can not directly be used in patterns, also not through constants. /// You can do this, though: /// ``` /// # use asn1_rs::{oid, Oid}; /// # let some_oid: Oid<'static> = oid!(1.2.456); /// const SOME_OID: Oid<'static> = oid!(1.2.456); /// if some_oid == SOME_OID || some_oid == oid!(1.2.456) { /// println!("match"); /// } /// /// // Alternatively, compare the DER encoded form directly: /// const SOME_OID_RAW: &[u8] = &oid!(raw 1.2.456); /// match some_oid.as_bytes() { /// SOME_OID_RAW => println!("match"), /// _ => panic!("no match"), /// } /// ``` /// *Attention*, be aware that the latter version might not handle the case of a relative oid correctly. An /// extra check might be necessary. #[macro_export] macro_rules! oid { (raw $( $item:literal ).*) => { $crate::exports::asn1_rs_impl::encode_oid!( $( $item ).* ) }; (raw $items:expr) => { $crate::exports::asn1_rs_impl::encode_oid!($items) }; (rel $($item:literal ).*) => { $crate::Oid::new_relative($crate::exports::borrow::Cow::Borrowed( &$crate::exports::asn1_rs_impl::encode_oid!(rel $( $item ).*), )) }; ($($item:literal ).*) => { $crate::Oid::new($crate::exports::borrow::Cow::Borrowed( &$crate::oid!(raw $( $item ).*), )) }; } #[cfg(test)] mod tests { use crate::{FromDer, Oid, ToDer}; use hex_literal::hex; #[test] fn declare_oid() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_string(), "1.2.840.113549.1"); } const OID_RSA_ENCRYPTION: &[u8] = &oid! {raw 1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: &[u8] = &oid! {raw 1.2.840.10045.2.1}; #[allow(clippy::match_like_matches_macro)] fn compare_oid(oid: &Oid) -> bool { match oid.as_bytes() { OID_RSA_ENCRYPTION => true, OID_EC_PUBLIC_KEY => true, _ => false, } } #[test] fn test_compare_oid() { let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert_eq!(oid, oid! {1.2.840.113549.1.1.1}); let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert!(compare_oid(&oid)); } #[test] fn oid_to_der() { let oid = super::oid! {1.2.840.113549.1}; assert_eq!(oid.to_der_len(), Ok(9)); let v = oid.to_der_vec().expect("could not serialize"); assert_eq!(&v, &hex! {"06 07 2a 86 48 86 f7 0d 01"}); let (_, oid2) = Oid::from_der(&v).expect("could not re-parse"); assert_eq!(&oid, &oid2); } #[test] fn oid_starts_with() { const OID_RSA_ENCRYPTION: Oid = oid! {1.2.840.113549.1.1.1}; const OID_EC_PUBLIC_KEY: Oid = oid! {1.2.840.10045.2.1}; let oid = super::oid! {1.2.840.113549.1}; assert!(OID_RSA_ENCRYPTION.starts_with(&oid)); assert!(!OID_EC_PUBLIC_KEY.starts_with(&oid)); } #[test] fn oid_macro_parameters() { // Code inspired from https://github.com/rusticata/der-parser/issues/68 macro_rules! foo { ($a:literal $b:literal $c:literal) => { super::oid!($a.$b.$c) }; } let oid = foo!(1 2 3); assert_eq!(oid, oid! {1.2.3}); } }
{ break; }
conditional_block
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implement an iterator over the map //that will give the (x,y) coord of the tile and the tile itself impl Map { //We use i32's for the map's width / height because //easier intergration with libtcod //less wonky math when dealing with negatives pub fn new(width:i32, height:i32, default_tile:Tile) -> Self { assert!(width > 0, "width must be greater than 0!"); assert!(height > 0, "height must be greater than 0!"); Map { tiles: vec![default_tile; (height * width) as usize], width:width, height:height, out_of_bounds_tile: Tile::wall(), } } pub fn in_bounds(&self, x:i32, y:i32) -> bool { x >= 0 && y >= 0 && x < self.width() && y < self.height() } fn index_at(&self, x:i32, y:i32) -> usize { return (y * self.width() + x) as usize; } pub fn at(&self, x:i32, y:i32) -> &Tile { if!self.in_bounds(x,y) { return &self.out_of_bounds_tile; } &self.tiles[self.index_at(x,y)] } pub fn at_mut(&mut self, x:i32, y:i32) -> &mut Tile { let index = self.index_at(x,y); &mut self.tiles[index] } pub fn set(&mut self, x:i32, y:i32, tile:Tile){ let index = self.index_at(x,y); self.tiles[index] = tile; } pub fn width(&self) -> i32 { self.width } pub fn height(&self) -> i32 { self.height } fn create_room(&mut self, room: Rect, )
fn create_v_tunnel(&mut self, y1: i32, y2: i32, x: i32) { for y in cmp::min(y1, y2)..(cmp::max(y1, y2) + 1) { self.set(x,y, Tile::empty()); } } fn create_h_tunnel(&mut self, x1: i32, x2: i32, y: i32) { for x in cmp::min(x1, x2)..(cmp::max(x1, x2) + 1) { self.set(x,y, Tile::empty()); } } pub fn create_random_rooms(width:i32, height:i32, objects:&mut Vec<Object>) -> (Self, (i32,i32)){ const ROOM_MAX_SIZE: i32 = 10; const ROOM_MIN_SIZE: i32 = 6; const MAX_ROOMS: i32 = 40; //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); //our starting position will be in the first valid room's center. let mut starting_position = (0, 0); //Then "carve" the empty rooms out. let mut rooms = vec![]; //save local copy of thread_rng. Mostly for readability let mut rng = rand::thread_rng(); for _ in 0..MAX_ROOMS { // random width and height let w = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let h = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); // random position without going out of the boundaries of the map let x = rng.gen_range(0, map.width() - w); let y = rng.gen_range(0, map.height() - h); let new_room = Rect::new(x, y, w, h); // run through the other rooms and see if they intersect with this one let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room)); // this means there are no intersections, so this room is valid if!failed { // "carve" it to the map's tiles map.create_room(new_room); //TODO just for the hell of it make it so the player spawns randomly in the first room. let (new_x, new_y) = new_room.center(); Map::place_objects(new_room, objects); if rooms.is_empty() { //First room since there isnt any other rooms starting_position = (new_x, new_y); }else{ //Non first room. // all rooms after the first: // connect it to the previous room with a tunnel // center coordinates of the previous room let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); // draw a coin (random bool value -- either true or false) if rand::random() { // first move horizontally, then vertically map.create_h_tunnel(prev_x, new_x, prev_y); map.create_v_tunnel(prev_y, new_y, new_x); } else { // first move vertically, then horizontally map.create_v_tunnel(prev_y, new_y, prev_x); map.create_h_tunnel(prev_x, new_x, new_y); } } rooms.push(new_room); } } (map, starting_position) } pub fn place_objects(room: Rect, objects: &mut Vec<Object>) { let MAX_ROOM_MONSTERS = 3; // choose random number of monsters let num_monsters = rand::thread_rng().gen_range(0, MAX_ROOM_MONSTERS + 1); for _ in 0..num_monsters { // choose random spot for this monster let x = rand::thread_rng().gen_range(room.x1 + 1, room.x2); let y = rand::thread_rng().gen_range(room.y1 + 1, room.y2); let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); } } //followed //https://gamedevelopment.tutsplus.com/tutorials/generate-random-cave-levels-using-cellular-automata--gamedev-9664 pub fn create_caves(width:i32, height:i32, objects:&mut Vec<Object>) -> Self { //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); let mut rng = rand::thread_rng(); let chance_to_be_empty = 0.46; for tile in map.tiles.iter_mut(){ let chance = rng.gen::<f32>(); if chance < chance_to_be_empty { *tile = Tile::empty(); } } let sim_steps = 6; for _ in 0.. sim_steps { map.caves_sim_step(); } let max_spawn_chances = 200; let mut spawn_attempts = 0; let desired_monsters = 15; let mut spawn_amount = 0; while spawn_attempts < max_spawn_chances && spawn_amount <= desired_monsters { let x = rng.gen_range(0, map.width()); let y = rng.gen_range(0, map.height()); let tile_blocked = is_blocked(x,y, &map, objects); if!tile_blocked { let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); spawn_amount +=1; } spawn_attempts +=1; } println!("spawn amount: {} spawn_attempts: {}", spawn_amount, spawn_attempts); map } fn caves_sim_step(&mut self) { //We need to create a new map since updating the map in place will cause wonky behaviours. //TODO from a memory perspective we could just use boolean values to represent the walls //this will save memory from the map allocations //or... maybe just have 2 maps at a given time and free the last map once we are done with it. //arena allocator as well! let mut new_map = Map::new(self.width, self.height, Tile::wall()); let death_limit = 3; let birth_limit = 4; for x in 0.. self.width { for y in 0.. self.height { let empty_neighbor_count = self.count_empty_neighbours(x,y); //The new value is based on our simulation rules //First, if a cell is empty but has too few neighbours, fill if!self.at(x,y).is_wall() { if empty_neighbor_count < death_limit { new_map.set(x,y, Tile::wall()); } else{ new_map.set(x,y, Tile::empty()); } } else{ //Otherwise, if the cell is filled now, check if it has the right number of neighbours to be cleared if empty_neighbor_count > birth_limit { new_map.set(x,y, Tile::empty()); } else{ new_map.set(x,y, Tile::wall()); } } } } *self = new_map; } //We should create a unit test for this.. pub fn count_empty_neighbours(&self, x:i32, y:i32) -> i32{ let mut count = 0; for i in -1.. 2 { for j in -1.. 2 { let neighbour_x = x + i; let neighbour_y = y + j; //if we're looking at the middle point do nothing if i == 0 && j == 0 {} else if neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= self.width() || neighbour_y >= self.height() { //Out of bounds. Count as a neighbor? count += 1; }else if!self.at(neighbour_x, neighbour_y).is_wall() { count += 1; } } } count } }
{ for x in (room.x1 + 1) .. room.x2 { for y in (room.y1 + 1) .. room.y2 { self.set(x,y,Tile::empty()); } } }
identifier_body
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implement an iterator over the map //that will give the (x,y) coord of the tile and the tile itself impl Map { //We use i32's for the map's width / height because //easier intergration with libtcod //less wonky math when dealing with negatives pub fn new(width:i32, height:i32, default_tile:Tile) -> Self { assert!(width > 0, "width must be greater than 0!"); assert!(height > 0, "height must be greater than 0!"); Map { tiles: vec![default_tile; (height * width) as usize], width:width, height:height, out_of_bounds_tile: Tile::wall(), } } pub fn in_bounds(&self, x:i32, y:i32) -> bool { x >= 0 && y >= 0 && x < self.width() && y < self.height() } fn index_at(&self, x:i32, y:i32) -> usize { return (y * self.width() + x) as usize; } pub fn at(&self, x:i32, y:i32) -> &Tile { if!self.in_bounds(x,y) { return &self.out_of_bounds_tile; } &self.tiles[self.index_at(x,y)] } pub fn at_mut(&mut self, x:i32, y:i32) -> &mut Tile { let index = self.index_at(x,y); &mut self.tiles[index] } pub fn set(&mut self, x:i32, y:i32, tile:Tile){ let index = self.index_at(x,y); self.tiles[index] = tile; } pub fn width(&self) -> i32 { self.width } pub fn height(&self) -> i32 { self.height } fn create_room(&mut self, room: Rect, ) { for x in (room.x1 + 1).. room.x2 { for y in (room.y1 + 1).. room.y2 { self.set(x,y,Tile::empty()); } } } fn create_v_tunnel(&mut self, y1: i32, y2: i32, x: i32) { for y in cmp::min(y1, y2)..(cmp::max(y1, y2) + 1) { self.set(x,y, Tile::empty()); } } fn create_h_tunnel(&mut self, x1: i32, x2: i32, y: i32) { for x in cmp::min(x1, x2)..(cmp::max(x1, x2) + 1) { self.set(x,y, Tile::empty()); } } pub fn create_random_rooms(width:i32, height:i32, objects:&mut Vec<Object>) -> (Self, (i32,i32)){ const ROOM_MAX_SIZE: i32 = 10; const ROOM_MIN_SIZE: i32 = 6; const MAX_ROOMS: i32 = 40; //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); //our starting position will be in the first valid room's center. let mut starting_position = (0, 0); //Then "carve" the empty rooms out. let mut rooms = vec![]; //save local copy of thread_rng. Mostly for readability let mut rng = rand::thread_rng(); for _ in 0..MAX_ROOMS { // random width and height let w = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let h = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); // random position without going out of the boundaries of the map let x = rng.gen_range(0, map.width() - w); let y = rng.gen_range(0, map.height() - h); let new_room = Rect::new(x, y, w, h); // run through the other rooms and see if they intersect with this one let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room)); // this means there are no intersections, so this room is valid if!failed { // "carve" it to the map's tiles map.create_room(new_room); //TODO just for the hell of it make it so the player spawns randomly in the first room. let (new_x, new_y) = new_room.center(); Map::place_objects(new_room, objects); if rooms.is_empty() { //First room since there isnt any other rooms starting_position = (new_x, new_y); }else{ //Non first room. // all rooms after the first: // connect it to the previous room with a tunnel // center coordinates of the previous room let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); // draw a coin (random bool value -- either true or false) if rand::random() { // first move horizontally, then vertically map.create_h_tunnel(prev_x, new_x, prev_y); map.create_v_tunnel(prev_y, new_y, new_x); } else { // first move vertically, then horizontally map.create_v_tunnel(prev_y, new_y, prev_x); map.create_h_tunnel(prev_x, new_x, new_y); } } rooms.push(new_room); } } (map, starting_position) } pub fn place_objects(room: Rect, objects: &mut Vec<Object>) { let MAX_ROOM_MONSTERS = 3; // choose random number of monsters let num_monsters = rand::thread_rng().gen_range(0, MAX_ROOM_MONSTERS + 1); for _ in 0..num_monsters { // choose random spot for this monster let x = rand::thread_rng().gen_range(room.x1 + 1, room.x2); let y = rand::thread_rng().gen_range(room.y1 + 1, room.y2); let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); } } //followed //https://gamedevelopment.tutsplus.com/tutorials/generate-random-cave-levels-using-cellular-automata--gamedev-9664 pub fn create_caves(width:i32, height:i32, objects:&mut Vec<Object>) -> Self { //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); let mut rng = rand::thread_rng(); let chance_to_be_empty = 0.46; for tile in map.tiles.iter_mut(){ let chance = rng.gen::<f32>(); if chance < chance_to_be_empty { *tile = Tile::empty(); } } let sim_steps = 6; for _ in 0.. sim_steps { map.caves_sim_step(); } let max_spawn_chances = 200; let mut spawn_attempts = 0; let desired_monsters = 15; let mut spawn_amount = 0; while spawn_attempts < max_spawn_chances && spawn_amount <= desired_monsters { let x = rng.gen_range(0, map.width());
let y = rng.gen_range(0, map.height()); let tile_blocked = is_blocked(x,y, &map, objects); if!tile_blocked { let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); spawn_amount +=1; } spawn_attempts +=1; } println!("spawn amount: {} spawn_attempts: {}", spawn_amount, spawn_attempts); map } fn caves_sim_step(&mut self) { //We need to create a new map since updating the map in place will cause wonky behaviours. //TODO from a memory perspective we could just use boolean values to represent the walls //this will save memory from the map allocations //or... maybe just have 2 maps at a given time and free the last map once we are done with it. //arena allocator as well! let mut new_map = Map::new(self.width, self.height, Tile::wall()); let death_limit = 3; let birth_limit = 4; for x in 0.. self.width { for y in 0.. self.height { let empty_neighbor_count = self.count_empty_neighbours(x,y); //The new value is based on our simulation rules //First, if a cell is empty but has too few neighbours, fill if!self.at(x,y).is_wall() { if empty_neighbor_count < death_limit { new_map.set(x,y, Tile::wall()); } else{ new_map.set(x,y, Tile::empty()); } } else{ //Otherwise, if the cell is filled now, check if it has the right number of neighbours to be cleared if empty_neighbor_count > birth_limit { new_map.set(x,y, Tile::empty()); } else{ new_map.set(x,y, Tile::wall()); } } } } *self = new_map; } //We should create a unit test for this.. pub fn count_empty_neighbours(&self, x:i32, y:i32) -> i32{ let mut count = 0; for i in -1.. 2 { for j in -1.. 2 { let neighbour_x = x + i; let neighbour_y = y + j; //if we're looking at the middle point do nothing if i == 0 && j == 0 {} else if neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= self.width() || neighbour_y >= self.height() { //Out of bounds. Count as a neighbor? count += 1; }else if!self.at(neighbour_x, neighbour_y).is_wall() { count += 1; } } } count } }
random_line_split
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implement an iterator over the map //that will give the (x,y) coord of the tile and the tile itself impl Map { //We use i32's for the map's width / height because //easier intergration with libtcod //less wonky math when dealing with negatives pub fn new(width:i32, height:i32, default_tile:Tile) -> Self { assert!(width > 0, "width must be greater than 0!"); assert!(height > 0, "height must be greater than 0!"); Map { tiles: vec![default_tile; (height * width) as usize], width:width, height:height, out_of_bounds_tile: Tile::wall(), } } pub fn in_bounds(&self, x:i32, y:i32) -> bool { x >= 0 && y >= 0 && x < self.width() && y < self.height() } fn index_at(&self, x:i32, y:i32) -> usize { return (y * self.width() + x) as usize; } pub fn at(&self, x:i32, y:i32) -> &Tile { if!self.in_bounds(x,y) { return &self.out_of_bounds_tile; } &self.tiles[self.index_at(x,y)] } pub fn at_mut(&mut self, x:i32, y:i32) -> &mut Tile { let index = self.index_at(x,y); &mut self.tiles[index] } pub fn set(&mut self, x:i32, y:i32, tile:Tile){ let index = self.index_at(x,y); self.tiles[index] = tile; } pub fn width(&self) -> i32 { self.width } pub fn height(&self) -> i32 { self.height } fn create_room(&mut self, room: Rect, ) { for x in (room.x1 + 1).. room.x2 { for y in (room.y1 + 1).. room.y2 { self.set(x,y,Tile::empty()); } } } fn create_v_tunnel(&mut self, y1: i32, y2: i32, x: i32) { for y in cmp::min(y1, y2)..(cmp::max(y1, y2) + 1) { self.set(x,y, Tile::empty()); } } fn create_h_tunnel(&mut self, x1: i32, x2: i32, y: i32) { for x in cmp::min(x1, x2)..(cmp::max(x1, x2) + 1) { self.set(x,y, Tile::empty()); } } pub fn create_random_rooms(width:i32, height:i32, objects:&mut Vec<Object>) -> (Self, (i32,i32)){ const ROOM_MAX_SIZE: i32 = 10; const ROOM_MIN_SIZE: i32 = 6; const MAX_ROOMS: i32 = 40; //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); //our starting position will be in the first valid room's center. let mut starting_position = (0, 0); //Then "carve" the empty rooms out. let mut rooms = vec![]; //save local copy of thread_rng. Mostly for readability let mut rng = rand::thread_rng(); for _ in 0..MAX_ROOMS { // random width and height let w = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let h = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); // random position without going out of the boundaries of the map let x = rng.gen_range(0, map.width() - w); let y = rng.gen_range(0, map.height() - h); let new_room = Rect::new(x, y, w, h); // run through the other rooms and see if they intersect with this one let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room)); // this means there are no intersections, so this room is valid if!failed { // "carve" it to the map's tiles map.create_room(new_room); //TODO just for the hell of it make it so the player spawns randomly in the first room. let (new_x, new_y) = new_room.center(); Map::place_objects(new_room, objects); if rooms.is_empty() { //First room since there isnt any other rooms starting_position = (new_x, new_y); }else{ //Non first room. // all rooms after the first: // connect it to the previous room with a tunnel // center coordinates of the previous room let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); // draw a coin (random bool value -- either true or false) if rand::random() { // first move horizontally, then vertically map.create_h_tunnel(prev_x, new_x, prev_y); map.create_v_tunnel(prev_y, new_y, new_x); } else { // first move vertically, then horizontally map.create_v_tunnel(prev_y, new_y, prev_x); map.create_h_tunnel(prev_x, new_x, new_y); } } rooms.push(new_room); } } (map, starting_position) } pub fn place_objects(room: Rect, objects: &mut Vec<Object>) { let MAX_ROOM_MONSTERS = 3; // choose random number of monsters let num_monsters = rand::thread_rng().gen_range(0, MAX_ROOM_MONSTERS + 1); for _ in 0..num_monsters { // choose random spot for this monster let x = rand::thread_rng().gen_range(room.x1 + 1, room.x2); let y = rand::thread_rng().gen_range(room.y1 + 1, room.y2); let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); } } //followed //https://gamedevelopment.tutsplus.com/tutorials/generate-random-cave-levels-using-cellular-automata--gamedev-9664 pub fn create_caves(width:i32, height:i32, objects:&mut Vec<Object>) -> Self { //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); let mut rng = rand::thread_rng(); let chance_to_be_empty = 0.46; for tile in map.tiles.iter_mut(){ let chance = rng.gen::<f32>(); if chance < chance_to_be_empty
} let sim_steps = 6; for _ in 0.. sim_steps { map.caves_sim_step(); } let max_spawn_chances = 200; let mut spawn_attempts = 0; let desired_monsters = 15; let mut spawn_amount = 0; while spawn_attempts < max_spawn_chances && spawn_amount <= desired_monsters { let x = rng.gen_range(0, map.width()); let y = rng.gen_range(0, map.height()); let tile_blocked = is_blocked(x,y, &map, objects); if!tile_blocked { let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); spawn_amount +=1; } spawn_attempts +=1; } println!("spawn amount: {} spawn_attempts: {}", spawn_amount, spawn_attempts); map } fn caves_sim_step(&mut self) { //We need to create a new map since updating the map in place will cause wonky behaviours. //TODO from a memory perspective we could just use boolean values to represent the walls //this will save memory from the map allocations //or... maybe just have 2 maps at a given time and free the last map once we are done with it. //arena allocator as well! let mut new_map = Map::new(self.width, self.height, Tile::wall()); let death_limit = 3; let birth_limit = 4; for x in 0.. self.width { for y in 0.. self.height { let empty_neighbor_count = self.count_empty_neighbours(x,y); //The new value is based on our simulation rules //First, if a cell is empty but has too few neighbours, fill if!self.at(x,y).is_wall() { if empty_neighbor_count < death_limit { new_map.set(x,y, Tile::wall()); } else{ new_map.set(x,y, Tile::empty()); } } else{ //Otherwise, if the cell is filled now, check if it has the right number of neighbours to be cleared if empty_neighbor_count > birth_limit { new_map.set(x,y, Tile::empty()); } else{ new_map.set(x,y, Tile::wall()); } } } } *self = new_map; } //We should create a unit test for this.. pub fn count_empty_neighbours(&self, x:i32, y:i32) -> i32{ let mut count = 0; for i in -1.. 2 { for j in -1.. 2 { let neighbour_x = x + i; let neighbour_y = y + j; //if we're looking at the middle point do nothing if i == 0 && j == 0 {} else if neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= self.width() || neighbour_y >= self.height() { //Out of bounds. Count as a neighbor? count += 1; }else if!self.at(neighbour_x, neighbour_y).is_wall() { count += 1; } } } count } }
{ *tile = Tile::empty(); }
conditional_block
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implement an iterator over the map //that will give the (x,y) coord of the tile and the tile itself impl Map { //We use i32's for the map's width / height because //easier intergration with libtcod //less wonky math when dealing with negatives pub fn
(width:i32, height:i32, default_tile:Tile) -> Self { assert!(width > 0, "width must be greater than 0!"); assert!(height > 0, "height must be greater than 0!"); Map { tiles: vec![default_tile; (height * width) as usize], width:width, height:height, out_of_bounds_tile: Tile::wall(), } } pub fn in_bounds(&self, x:i32, y:i32) -> bool { x >= 0 && y >= 0 && x < self.width() && y < self.height() } fn index_at(&self, x:i32, y:i32) -> usize { return (y * self.width() + x) as usize; } pub fn at(&self, x:i32, y:i32) -> &Tile { if!self.in_bounds(x,y) { return &self.out_of_bounds_tile; } &self.tiles[self.index_at(x,y)] } pub fn at_mut(&mut self, x:i32, y:i32) -> &mut Tile { let index = self.index_at(x,y); &mut self.tiles[index] } pub fn set(&mut self, x:i32, y:i32, tile:Tile){ let index = self.index_at(x,y); self.tiles[index] = tile; } pub fn width(&self) -> i32 { self.width } pub fn height(&self) -> i32 { self.height } fn create_room(&mut self, room: Rect, ) { for x in (room.x1 + 1).. room.x2 { for y in (room.y1 + 1).. room.y2 { self.set(x,y,Tile::empty()); } } } fn create_v_tunnel(&mut self, y1: i32, y2: i32, x: i32) { for y in cmp::min(y1, y2)..(cmp::max(y1, y2) + 1) { self.set(x,y, Tile::empty()); } } fn create_h_tunnel(&mut self, x1: i32, x2: i32, y: i32) { for x in cmp::min(x1, x2)..(cmp::max(x1, x2) + 1) { self.set(x,y, Tile::empty()); } } pub fn create_random_rooms(width:i32, height:i32, objects:&mut Vec<Object>) -> (Self, (i32,i32)){ const ROOM_MAX_SIZE: i32 = 10; const ROOM_MIN_SIZE: i32 = 6; const MAX_ROOMS: i32 = 40; //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); //our starting position will be in the first valid room's center. let mut starting_position = (0, 0); //Then "carve" the empty rooms out. let mut rooms = vec![]; //save local copy of thread_rng. Mostly for readability let mut rng = rand::thread_rng(); for _ in 0..MAX_ROOMS { // random width and height let w = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let h = rng.gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); // random position without going out of the boundaries of the map let x = rng.gen_range(0, map.width() - w); let y = rng.gen_range(0, map.height() - h); let new_room = Rect::new(x, y, w, h); // run through the other rooms and see if they intersect with this one let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room)); // this means there are no intersections, so this room is valid if!failed { // "carve" it to the map's tiles map.create_room(new_room); //TODO just for the hell of it make it so the player spawns randomly in the first room. let (new_x, new_y) = new_room.center(); Map::place_objects(new_room, objects); if rooms.is_empty() { //First room since there isnt any other rooms starting_position = (new_x, new_y); }else{ //Non first room. // all rooms after the first: // connect it to the previous room with a tunnel // center coordinates of the previous room let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); // draw a coin (random bool value -- either true or false) if rand::random() { // first move horizontally, then vertically map.create_h_tunnel(prev_x, new_x, prev_y); map.create_v_tunnel(prev_y, new_y, new_x); } else { // first move vertically, then horizontally map.create_v_tunnel(prev_y, new_y, prev_x); map.create_h_tunnel(prev_x, new_x, new_y); } } rooms.push(new_room); } } (map, starting_position) } pub fn place_objects(room: Rect, objects: &mut Vec<Object>) { let MAX_ROOM_MONSTERS = 3; // choose random number of monsters let num_monsters = rand::thread_rng().gen_range(0, MAX_ROOM_MONSTERS + 1); for _ in 0..num_monsters { // choose random spot for this monster let x = rand::thread_rng().gen_range(room.x1 + 1, room.x2); let y = rand::thread_rng().gen_range(room.y1 + 1, room.y2); let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); } } //followed //https://gamedevelopment.tutsplus.com/tutorials/generate-random-cave-levels-using-cellular-automata--gamedev-9664 pub fn create_caves(width:i32, height:i32, objects:&mut Vec<Object>) -> Self { //set everything to a wall first. let mut map = Map::new(width,height, Tile::wall()); let mut rng = rand::thread_rng(); let chance_to_be_empty = 0.46; for tile in map.tiles.iter_mut(){ let chance = rng.gen::<f32>(); if chance < chance_to_be_empty { *tile = Tile::empty(); } } let sim_steps = 6; for _ in 0.. sim_steps { map.caves_sim_step(); } let max_spawn_chances = 200; let mut spawn_attempts = 0; let desired_monsters = 15; let mut spawn_amount = 0; while spawn_attempts < max_spawn_chances && spawn_amount <= desired_monsters { let x = rng.gen_range(0, map.width()); let y = rng.gen_range(0, map.height()); let tile_blocked = is_blocked(x,y, &map, objects); if!tile_blocked { let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Object::new(x, y, ascii::orc, *tileset::orc,"orc", true) } else { Object::new(x, y, ascii::troll, *tileset::troll,"troll", true) }; monster.alive = true; objects.push(monster); spawn_amount +=1; } spawn_attempts +=1; } println!("spawn amount: {} spawn_attempts: {}", spawn_amount, spawn_attempts); map } fn caves_sim_step(&mut self) { //We need to create a new map since updating the map in place will cause wonky behaviours. //TODO from a memory perspective we could just use boolean values to represent the walls //this will save memory from the map allocations //or... maybe just have 2 maps at a given time and free the last map once we are done with it. //arena allocator as well! let mut new_map = Map::new(self.width, self.height, Tile::wall()); let death_limit = 3; let birth_limit = 4; for x in 0.. self.width { for y in 0.. self.height { let empty_neighbor_count = self.count_empty_neighbours(x,y); //The new value is based on our simulation rules //First, if a cell is empty but has too few neighbours, fill if!self.at(x,y).is_wall() { if empty_neighbor_count < death_limit { new_map.set(x,y, Tile::wall()); } else{ new_map.set(x,y, Tile::empty()); } } else{ //Otherwise, if the cell is filled now, check if it has the right number of neighbours to be cleared if empty_neighbor_count > birth_limit { new_map.set(x,y, Tile::empty()); } else{ new_map.set(x,y, Tile::wall()); } } } } *self = new_map; } //We should create a unit test for this.. pub fn count_empty_neighbours(&self, x:i32, y:i32) -> i32{ let mut count = 0; for i in -1.. 2 { for j in -1.. 2 { let neighbour_x = x + i; let neighbour_y = y + j; //if we're looking at the middle point do nothing if i == 0 && j == 0 {} else if neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= self.width() || neighbour_y >= self.height() { //Out of bounds. Count as a neighbor? count += 1; }else if!self.at(neighbour_x, neighbour_y).is_wall() { count += 1; } } } count } }
new
identifier_name
encode.rs
use super::constants::{CR, DEFAULT_LINE_SIZE, DOT, ESCAPE, LF, NUL}; use super::errors::EncodeError; use std::fs::File; use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write}; use std::path::Path; /// Options for encoding. /// The entry point for encoding a file (part) /// to a file or (TCP) stream. #[derive(Debug)] pub struct EncodeOptions { line_length: u8, parts: u32, part: u32, begin: u64, end: u64, } impl Default for EncodeOptions { /// Constructs a new EncodeOptions instance, with the following defaults: /// line_length = 128. /// parts = 1, /// part = begin = end = 0 fn default() -> Self { EncodeOptions { line_length: DEFAULT_LINE_SIZE, parts: 1, part: 0, begin: 0, end: 0, } } } impl EncodeOptions { /// Constructs a new EncodeOptions with defaults, see Default impl. pub fn new() -> EncodeOptions { Default::default() } /// Sets the maximum line length. pub fn line_length(mut self, line_length: u8) -> EncodeOptions { self.line_length = line_length; self } /// Sets the number of parts (default=1). /// When the number of parts is 1, no '=ypart' line will be written /// in the ouput. pub fn parts(mut self, parts: u32) -> EncodeOptions { self.parts = parts; self } /// Sets the part number. /// Only used when `parts > 1`. /// The part number count starts at 1. pub fn part(mut self, part: u32) -> EncodeOptions { self.part = part; self } /// Sets the begin (which is the file offset + 1). /// Only used when `parts > 1`. /// The size of the part is `end - begin + 1`. pub fn begin(mut self, begin: u64) -> EncodeOptions { self.begin = begin; self } /// Sets the end. /// Only used when `parts > 1`. /// The size of the part is `end - begin + 1`. /// `end` should be larger than `begin`, otherwise an overflow error occurrs. pub fn end(mut self, end: u64) -> EncodeOptions { self.end = end; self } /// Encodes the input file and writes it to the writer. For multi-part encoding, only /// one part is encoded. In case of multipart, the part number, begin and end offset need /// to be specified in the `EncodeOptions`. When directly encoding to an NNTP stream, the /// caller needs to take care of the message header and end of multi-line block (`".\r\n"`). /// /// # Example /// ```rust,no_run /// let encode_options = yenc::EncodeOptions::default() /// .parts(2) /// .part(1) /// .begin(1) /// .end(38400); /// let mut output_file = std::fs::File::create("test1.bin.yenc.001").unwrap(); /// encode_options.encode_file("test1.bin", &mut output_file).unwrap(); /// ``` /// # Errors /// - when the output file already exists /// pub fn encode_file<P, W>(&self, input_path: P, output: W) -> Result<(), EncodeError> where P: AsRef<Path>, W: Write, { let input_filename = input_path.as_ref().file_name(); let input_filename = match input_filename { Some(s) => s.to_str().unwrap_or(""), None => "", }; let input_file = File::open(&input_path)?; let length = input_file.metadata()?.len(); self.encode_stream(input_file, output, length, input_filename) } /// Checks the options. Returns Ok(()) if all options are ok. /// # Return /// - EncodeError::PartNumberMissing /// - EncodeError::PartBeginOffsetMissing /// - EncodeError::PartEndOffsetMissing /// - EncodeError::PartOffsetsInvalidRange pub fn check_options(&self) -> Result<(), EncodeError> { if self.parts > 1 && self.part == 0 { return Err(EncodeError::PartNumberMissing); } if self.parts > 1 && self.begin == 0 { return Err(EncodeError::PartBeginOffsetMissing); } if self.parts > 1 && self.end == 0 { return Err(EncodeError::PartEndOffsetMissing); } if self.parts > 1 && self.begin > self.end { return Err(EncodeError::PartOffsetsInvalidRange); } Ok(()) } /// Encodes the date from input from stream and writes the encoded data to the output stream. /// The input stream does not need to be a file, therefore, size and input_filename /// must be specified. The input_filename ends up as the filename in the yenc header. #[allow(clippy::write_with_newline)] pub fn encode_stream<R, W>( &self, input: R, output: W, length: u64, input_filename: &str, ) -> Result<(), EncodeError> where R: Read + Seek, W: Write, { let mut rdr = BufReader::new(input); let mut checksum = crc32fast::Hasher::new(); let mut buffer = [0u8; 8192]; let mut col = 0; let mut num_bytes = 0; let mut output = BufWriter::new(output); self.check_options()?; if self.parts == 1 { write!( output, "=ybegin line={} size={} name={}\r\n", self.line_length, length, input_filename )?; } else { write!( output, "=ybegin part={} line={} size={} name={}\r\n", self.part, self.line_length, length, input_filename )?; } if self.parts > 1 { write!(output, "=ypart begin={} end={}\r\n", self.begin, self.end)?; } rdr.seek(SeekFrom::Start(self.begin - 1))?; let mut remainder = (self.end - self.begin + 1) as usize; while remainder > 0 { let buf_slice = if remainder > buffer.len() { &mut buffer[..] } else { &mut buffer[0..remainder] }; rdr.read_exact(buf_slice)?; checksum.update(buf_slice); num_bytes += buf_slice.len(); col = encode_buffer(buf_slice, col, self.line_length, &mut output)?; remainder -= buf_slice.len(); } if self.parts > 1 { write!( output, "\r\n=yend size={} part={} pcrc32={:08x}\r\n", num_bytes, self.part, checksum.finalize() )?; } else { write!( output, "\r\n=yend size={} crc32={:08x}\r\n", num_bytes, checksum.finalize() )?; } Ok(()) } } /// Encodes the input buffer and writes it to the writer. /// /// Lines are wrapped with a maximum of `line_length` characters per line. /// Does not include the header and footer lines. /// Only `encode_stream` and `encode_file` produce the headers in the output. /// The `col` parameter is the starting offset in the row. The result contains the new offset. pub fn encode_buffer<W>( input: &[u8], col: u8, line_length: u8, writer: W, ) -> Result<u8, EncodeError> where W: Write, { let mut col = col; let mut writer = writer; let mut v = Vec::<u8>::with_capacity(((input.len() as f64) * 1.04) as usize); input.iter().for_each(|&b| { let encoded = encode_byte(b); v.push(encoded.0); col += match encoded.0 { ESCAPE => { v.push(encoded.1); 2 } DOT if col == 0 => { v.push(DOT); 2 } _ => 1, }; if col >= line_length { v.push(CR); v.push(LF); col = 0; } }); writer.write_all(&v)?; Ok(col) } #[inline(always)] fn encode_byte(input_byte: u8) -> (u8, u8) { let mut output = (0, 0); let output_byte = input_byte.overflowing_add(42).0; match output_byte { LF | CR | NUL | ESCAPE => { output.0 = ESCAPE; output.1 = output_byte.overflowing_add(64).0; } _ => { output.0 = output_byte; } }; output } #[cfg(test)] mod tests { use super::super::constants::{CR, ESCAPE, LF, NUL}; use super::{encode_buffer, encode_byte, EncodeOptions}; #[test] fn escape_null() { assert_eq!((ESCAPE, 0x40), encode_byte(214)); } /* #[test] fn escape_tab() { let mut output = [0u8; 2]; assert_eq!(2, encode_byte(214 + TAB, &mut output)); assert_eq!(vec![ESCAPE, 0x49], output); } */ #[test] fn escape_lf() { assert_eq!((ESCAPE, 0x4A), encode_byte(214 + LF)); } #[test] fn escape_cr() { assert_eq!((ESCAPE, 0x4D), encode_byte(214 + CR)); } /* #[test] fn escape_space() { let mut output = [0u8; 2]; assert_eq!(2, encode_byte(214 + SPACE, &mut output)); assert_eq!(vec![ESCAPE, 0x60], output); } */ #[test] fn escape_equal_sign() { assert_eq!((ESCAPE, 0x7D), encode_byte(ESCAPE - 42)); } #[test] fn non_escaped() { for x in 0..256u16 { let encoded = (x as u8).overflowing_add(42).0; if encoded!= NUL && encoded!= CR && encoded!= LF && encoded!= ESCAPE { assert_eq!((encoded, 0), encode_byte(x as u8)); } } } #[test] fn test_encode_buffer() { let buffer = (0..256u16).map(|c| c as u8).collect::<Vec<u8>>(); #[rustfmt::skip] const EXPECTED: [u8; 264] = [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 125, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
211, 212, 213, 214, 215, 216,217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 61, 64, 1, 2, 3, 4, 5, 6, 7, 8, 9, 61, 74, 11, 12, 61, 77, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 13, 10, 38, 39, 40, 41]; let mut encoded = Vec::<u8>::new(); let result = encode_buffer(&buffer, 0, 128, &mut encoded); assert!(result.is_ok()); assert_eq!(encoded.as_slice(), &EXPECTED[..]); } #[test] fn encode_options_invalid_parts() { let encode_options = EncodeOptions::new().parts(2).begin(1).end(38400); let vr = encode_options.check_options(); assert!(vr.is_err()); } #[test] fn encode_options_invalid_begin() { let encode_options = EncodeOptions::new().parts(2).part(1).end(38400); let vr = encode_options.check_options(); assert!(vr.is_err()); } #[test] fn encode_options_invalid_end() { let encode_options = EncodeOptions::new().parts(2).part(1).begin(1); let vr = encode_options.check_options(); assert!(vr.is_err()); } #[test] fn encode_options_invalid_range() { let encode_options = EncodeOptions::new().parts(2).part(1).begin(38400).end(1); let vr = encode_options.check_options(); assert!(vr.is_err()); } }
133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 13, 10, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
random_line_split