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
to_twos_complement_limbs.rs
use malachite_base::num::arithmetic::traits::WrappingNegAssign; use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place; use malachite_nz::natural::logic::not::limbs_not_in_place; use malachite_nz::platform::Limb; pub fn limbs_twos_complement_in_place_alt_1(limbs: &mut [Limb]) -> bool { let i = limbs.iter().cloned().take_while(|&x| x == 0).count(); let len = limbs.len(); if i == len { return true; } limbs[i].wrapping_neg_assign(); let j = i + 1; if j!= len { limbs_not_in_place(&mut limbs[j..]); } false } pub fn limbs_twos_complement_in_place_alt_2(limbs: &mut [Limb]) -> bool { let carry = limbs_sub_limb_in_place(limbs, 1); limbs_not_in_place(limbs); carry
}
random_line_split
to_twos_complement_limbs.rs
use malachite_base::num::arithmetic::traits::WrappingNegAssign; use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place; use malachite_nz::natural::logic::not::limbs_not_in_place; use malachite_nz::platform::Limb; pub fn
(limbs: &mut [Limb]) -> bool { let i = limbs.iter().cloned().take_while(|&x| x == 0).count(); let len = limbs.len(); if i == len { return true; } limbs[i].wrapping_neg_assign(); let j = i + 1; if j!= len { limbs_not_in_place(&mut limbs[j..]); } false } pub fn limbs_twos_complement_in_place_alt_2(limbs: &mut [Limb]) -> bool { let carry = limbs_sub_limb_in_place(limbs, 1); limbs_not_in_place(limbs); carry }
limbs_twos_complement_in_place_alt_1
identifier_name
to_twos_complement_limbs.rs
use malachite_base::num::arithmetic::traits::WrappingNegAssign; use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place; use malachite_nz::natural::logic::not::limbs_not_in_place; use malachite_nz::platform::Limb; pub fn limbs_twos_complement_in_place_alt_1(limbs: &mut [Limb]) -> bool { let i = limbs.iter().cloned().take_while(|&x| x == 0).count(); let len = limbs.len(); if i == len { return true; } limbs[i].wrapping_neg_assign(); let j = i + 1; if j!= len { limbs_not_in_place(&mut limbs[j..]); } false } pub fn limbs_twos_complement_in_place_alt_2(limbs: &mut [Limb]) -> bool
{ let carry = limbs_sub_limb_in_place(limbs, 1); limbs_not_in_place(limbs); carry }
identifier_body
packed-struct-layout.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(dead_code)] use std::mem; #[repr(packed)] struct S4 { a: u8, b: [u8; 3], } #[repr(packed)] struct S5 {
pub fn main() { unsafe { let s4 = S4 { a: 1, b: [2,3,4] }; let transd : [u8; 4] = mem::transmute(s4); assert_eq!(transd, [1, 2, 3, 4]); let s5 = S5 { a: 1, b: 0xff_00_00_ff }; let transd : [u8; 5] = mem::transmute(s5); // Don't worry about endianness, the u32 is palindromic. assert_eq!(transd, [1, 0xff, 0, 0, 0xff]); } }
a: u8, b: u32 }
random_line_split
packed-struct-layout.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(dead_code)] use std::mem; #[repr(packed)] struct S4 { a: u8, b: [u8; 3], } #[repr(packed)] struct S5 { a: u8, b: u32 } pub fn
() { unsafe { let s4 = S4 { a: 1, b: [2,3,4] }; let transd : [u8; 4] = mem::transmute(s4); assert_eq!(transd, [1, 2, 3, 4]); let s5 = S5 { a: 1, b: 0xff_00_00_ff }; let transd : [u8; 5] = mem::transmute(s5); // Don't worry about endianness, the u32 is palindromic. assert_eq!(transd, [1, 0xff, 0, 0, 0xff]); } }
main
identifier_name
light.rs
use ::types::Vec3f; use ::types::Color; pub trait Light { /// Light direction /// v: Point to illuminate /// Returns the direction of light rays pointing from v fn direction(&self, v: Vec3f) -> Vec3f; /// Light illumincation /// v: Point to illuminate /// Returns the color of the light at the pointi v fn illumination(&self, v: Vec3f) -> Color; /// Light shadow
} pub struct PointLight { position: Vec3f, color: Color, } impl PointLight { pub fn new(position: Vec3f, color: Color) -> Self { Self { position, color } } pub fn set_position(&mut self, position: Vec3f) { self.position = position; } fn position(&self) -> &Vec3f { &self.position } } impl Light for PointLight { fn direction(&self, v: Vec3f) -> Vec3f { self.position - v } fn illumination(&self, v: Vec3f) -> Color { self.color } fn shadow(&self, t: f64) -> bool { t < 1.0 } }
/// Line index of the closest shadow ray intesection /// Where the point is in shadow fn shadow(&self, t: f64) -> bool;
random_line_split
light.rs
use ::types::Vec3f; use ::types::Color; pub trait Light { /// Light direction /// v: Point to illuminate /// Returns the direction of light rays pointing from v fn direction(&self, v: Vec3f) -> Vec3f; /// Light illumincation /// v: Point to illuminate /// Returns the color of the light at the pointi v fn illumination(&self, v: Vec3f) -> Color; /// Light shadow /// Line index of the closest shadow ray intesection /// Where the point is in shadow fn shadow(&self, t: f64) -> bool; } pub struct PointLight { position: Vec3f, color: Color, } impl PointLight { pub fn new(position: Vec3f, color: Color) -> Self { Self { position, color } } pub fn set_position(&mut self, position: Vec3f) { self.position = position; } fn position(&self) -> &Vec3f { &self.position } } impl Light for PointLight { fn direction(&self, v: Vec3f) -> Vec3f { self.position - v } fn illumination(&self, v: Vec3f) -> Color { self.color } fn
(&self, t: f64) -> bool { t < 1.0 } }
shadow
identifier_name
light.rs
use ::types::Vec3f; use ::types::Color; pub trait Light { /// Light direction /// v: Point to illuminate /// Returns the direction of light rays pointing from v fn direction(&self, v: Vec3f) -> Vec3f; /// Light illumincation /// v: Point to illuminate /// Returns the color of the light at the pointi v fn illumination(&self, v: Vec3f) -> Color; /// Light shadow /// Line index of the closest shadow ray intesection /// Where the point is in shadow fn shadow(&self, t: f64) -> bool; } pub struct PointLight { position: Vec3f, color: Color, } impl PointLight { pub fn new(position: Vec3f, color: Color) -> Self { Self { position, color } } pub fn set_position(&mut self, position: Vec3f)
fn position(&self) -> &Vec3f { &self.position } } impl Light for PointLight { fn direction(&self, v: Vec3f) -> Vec3f { self.position - v } fn illumination(&self, v: Vec3f) -> Color { self.color } fn shadow(&self, t: f64) -> bool { t < 1.0 } }
{ self.position = position; }
identifier_body
encoding.rs
// Copyright 2013-2014 Simon Sapin. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Abstraction that conditionally compiles either to rust-encoding, //! or to only support UTF-8. #[cfg(feature = "query_encoding")] extern crate encoding; use std::borrow::Cow; #[cfg(feature = "query_encoding")] use self::encoding::types::{DecoderTrap, EncoderTrap}; #[cfg(feature = "query_encoding")] use self::encoding::label::encoding_from_whatwg_label; #[cfg(feature = "query_encoding")] pub use self::encoding::types::EncodingRef; #[cfg(feature = "query_encoding")] #[derive(Copy)] pub struct EncodingOverride { /// `None` means UTF-8. encoding: Option<EncodingRef> } #[cfg(feature = "query_encoding")] impl EncodingOverride { pub fn from_opt_encoding(encoding: Option<EncodingRef>) -> EncodingOverride { encoding.map(EncodingOverride::from_encoding).unwrap_or_else(EncodingOverride::utf8) } pub fn from_encoding(encoding: EncodingRef) -> EncodingOverride { EncodingOverride { encoding: if encoding.name() == "utf-8" { None } else { Some(encoding) } } } pub fn utf8() -> EncodingOverride { EncodingOverride { encoding: None } } pub fn lookup(label: &[u8]) -> Option<EncodingOverride> { ::std::str::from_utf8(label) .ok()
.and_then(encoding_from_whatwg_label) .map(EncodingOverride::from_encoding) } pub fn is_utf8(&self) -> bool { self.encoding.is_none() } pub fn decode(&self, input: &[u8]) -> String { match self.encoding { Some(encoding) => encoding.decode(input, DecoderTrap::Replace).unwrap(), None => String::from_utf8_lossy(input).to_string(), } } pub fn encode<'a>(&self, input: &'a str) -> Cow<'a, Vec<u8>, [u8]> { match self.encoding { Some(encoding) => Cow::Owned( encoding.encode(input, EncoderTrap::NcrEscape).unwrap()), None => Cow::Borrowed(input.as_bytes()), // UTF-8 } } } #[cfg(not(feature = "query_encoding"))] #[derive(Copy)] pub struct EncodingOverride; #[cfg(not(feature = "query_encoding"))] impl EncodingOverride { pub fn utf8() -> EncodingOverride { EncodingOverride } pub fn lookup(_label: &[u8]) -> Option<EncodingOverride> { None } pub fn is_utf8(&self) -> bool { true } pub fn decode(&self, input: &[u8]) -> String { String::from_utf8_lossy(input).into_owned() } pub fn encode<'a>(&self, input: &'a str) -> Cow<'a, Vec<u8>, [u8]> { Cow::Borrowed(input.as_bytes()) } }
random_line_split
encoding.rs
// Copyright 2013-2014 Simon Sapin. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Abstraction that conditionally compiles either to rust-encoding, //! or to only support UTF-8. #[cfg(feature = "query_encoding")] extern crate encoding; use std::borrow::Cow; #[cfg(feature = "query_encoding")] use self::encoding::types::{DecoderTrap, EncoderTrap}; #[cfg(feature = "query_encoding")] use self::encoding::label::encoding_from_whatwg_label; #[cfg(feature = "query_encoding")] pub use self::encoding::types::EncodingRef; #[cfg(feature = "query_encoding")] #[derive(Copy)] pub struct EncodingOverride { /// `None` means UTF-8. encoding: Option<EncodingRef> } #[cfg(feature = "query_encoding")] impl EncodingOverride { pub fn from_opt_encoding(encoding: Option<EncodingRef>) -> EncodingOverride { encoding.map(EncodingOverride::from_encoding).unwrap_or_else(EncodingOverride::utf8) } pub fn from_encoding(encoding: EncodingRef) -> EncodingOverride { EncodingOverride { encoding: if encoding.name() == "utf-8" { None } else { Some(encoding) } } } pub fn utf8() -> EncodingOverride { EncodingOverride { encoding: None } } pub fn lookup(label: &[u8]) -> Option<EncodingOverride> { ::std::str::from_utf8(label) .ok() .and_then(encoding_from_whatwg_label) .map(EncodingOverride::from_encoding) } pub fn is_utf8(&self) -> bool { self.encoding.is_none() } pub fn decode(&self, input: &[u8]) -> String { match self.encoding { Some(encoding) => encoding.decode(input, DecoderTrap::Replace).unwrap(), None => String::from_utf8_lossy(input).to_string(), } } pub fn encode<'a>(&self, input: &'a str) -> Cow<'a, Vec<u8>, [u8]> { match self.encoding { Some(encoding) => Cow::Owned( encoding.encode(input, EncoderTrap::NcrEscape).unwrap()), None => Cow::Borrowed(input.as_bytes()), // UTF-8 } } } #[cfg(not(feature = "query_encoding"))] #[derive(Copy)] pub struct
; #[cfg(not(feature = "query_encoding"))] impl EncodingOverride { pub fn utf8() -> EncodingOverride { EncodingOverride } pub fn lookup(_label: &[u8]) -> Option<EncodingOverride> { None } pub fn is_utf8(&self) -> bool { true } pub fn decode(&self, input: &[u8]) -> String { String::from_utf8_lossy(input).into_owned() } pub fn encode<'a>(&self, input: &'a str) -> Cow<'a, Vec<u8>, [u8]> { Cow::Borrowed(input.as_bytes()) } }
EncodingOverride
identifier_name
fullscreen.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use std::io; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cfg(feature = "window")] fn
() { // enumerating monitors let monitor = { for (num, monitor) in glutin::get_available_monitors().enumerate() { println!("Monitor #{}: {:?}", num, monitor.get_name()); } print!("Please write the number of the monitor to use: "); let mut num = String::new(); io::stdin().read_line(&mut num).unwrap(); let num = num.trim().parse().ok().expect("Please enter a number"); let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID"); println!("Using {:?}", monitor.get_name()); monitor }; let window = glutin::WindowBuilder::new() .with_title("Hello world!".to_string()) .with_fullscreen(monitor) .build() .unwrap(); unsafe { window.make_current() }; let context = support::load(&window); for event in window.wait_events() { context.draw_frame((0.0, 1.0, 0.0, 1.0)); window.swap_buffers(); println!("{:?}", event); match event { glutin::Event::Closed => break, _ => () } } }
main
identifier_name
fullscreen.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use std::io; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main()
#[cfg(feature = "window")] fn main() { // enumerating monitors let monitor = { for (num, monitor) in glutin::get_available_monitors().enumerate() { println!("Monitor #{}: {:?}", num, monitor.get_name()); } print!("Please write the number of the monitor to use: "); let mut num = String::new(); io::stdin().read_line(&mut num).unwrap(); let num = num.trim().parse().ok().expect("Please enter a number"); let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID"); println!("Using {:?}", monitor.get_name()); monitor }; let window = glutin::WindowBuilder::new() .with_title("Hello world!".to_string()) .with_fullscreen(monitor) .build() .unwrap(); unsafe { window.make_current() }; let context = support::load(&window); for event in window.wait_events() { context.draw_frame((0.0, 1.0, 0.0, 1.0)); window.swap_buffers(); println!("{:?}", event); match event { glutin::Event::Closed => break, _ => () } } }
{ println!("This example requires glutin to be compiled with the `window` feature"); }
identifier_body
fullscreen.rs
#[cfg(target_os = "android")] #[macro_use]
extern crate glutin; use std::io; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cfg(feature = "window")] fn main() { // enumerating monitors let monitor = { for (num, monitor) in glutin::get_available_monitors().enumerate() { println!("Monitor #{}: {:?}", num, monitor.get_name()); } print!("Please write the number of the monitor to use: "); let mut num = String::new(); io::stdin().read_line(&mut num).unwrap(); let num = num.trim().parse().ok().expect("Please enter a number"); let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID"); println!("Using {:?}", monitor.get_name()); monitor }; let window = glutin::WindowBuilder::new() .with_title("Hello world!".to_string()) .with_fullscreen(monitor) .build() .unwrap(); unsafe { window.make_current() }; let context = support::load(&window); for event in window.wait_events() { context.draw_frame((0.0, 1.0, 0.0, 1.0)); window.swap_buffers(); println!("{:?}", event); match event { glutin::Event::Closed => break, _ => () } } }
extern crate android_glue;
random_line_split
user.rs
import_controller_generic_requeriments!(); use dal::models::user::{User, UpdateUser}; use dal::models::post::{Post}; pub fn get(req: &mut Request) -> IronResult<Response>{ let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let user_data = some_or_return!( User::get_by_id(user_id, &connection, &logger), response_not_found("User not found") ); response_ok(&user_data) } pub fn get_me(req: &mut Request) -> IronResult<Response> { response_ok(&req.get_user_data()) } pub fn delete(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let quatity_deleted = ok_or_return!( User::delete(user_id, &connection, &logger), response_internal_server_error("Error deleting the user") ); info!(logger, "Deleted users"; "quatity_deleted" => quatity_deleted); response_ok(&json!({"quantity": quatity_deleted})) } pub fn update(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let user = get_body_as!(UpdateUser, req, response_bad_request); let user = ok_or_return!( User::update(&user, user_id, &connection, &logger), response_internal_server_error("Error deleting the user") ); response_ok(&user) } pub fn get_user_posts(req: &mut Request) -> IronResult<Response>
{ let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = req.get_user_data().id; let posts = Post::get_post_from_user(user_id, &connection, &logger); response_ok(&posts) }
identifier_body
user.rs
import_controller_generic_requeriments!(); use dal::models::user::{User, UpdateUser}; use dal::models::post::{Post}; pub fn get(req: &mut Request) -> IronResult<Response>{ let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let user_data = some_or_return!( User::get_by_id(user_id, &connection, &logger), response_not_found("User not found") ); response_ok(&user_data) } pub fn
(req: &mut Request) -> IronResult<Response> { response_ok(&req.get_user_data()) } pub fn delete(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let quatity_deleted = ok_or_return!( User::delete(user_id, &connection, &logger), response_internal_server_error("Error deleting the user") ); info!(logger, "Deleted users"; "quatity_deleted" => quatity_deleted); response_ok(&json!({"quantity": quatity_deleted})) } pub fn update(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let user = get_body_as!(UpdateUser, req, response_bad_request); let user = ok_or_return!( User::update(&user, user_id, &connection, &logger), response_internal_server_error("Error deleting the user") ); response_ok(&user) } pub fn get_user_posts(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = req.get_user_data().id; let posts = Post::get_post_from_user(user_id, &connection, &logger); response_ok(&posts) }
get_me
identifier_name
user.rs
import_controller_generic_requeriments!(); use dal::models::user::{User, UpdateUser};
pub fn get(req: &mut Request) -> IronResult<Response>{ let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let user_data = some_or_return!( User::get_by_id(user_id, &connection, &logger), response_not_found("User not found") ); response_ok(&user_data) } pub fn get_me(req: &mut Request) -> IronResult<Response> { response_ok(&req.get_user_data()) } pub fn delete(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let quatity_deleted = ok_or_return!( User::delete(user_id, &connection, &logger), response_internal_server_error("Error deleting the user") ); info!(logger, "Deleted users"; "quatity_deleted" => quatity_deleted); response_ok(&json!({"quantity": quatity_deleted})) } pub fn update(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found")); let user = get_body_as!(UpdateUser, req, response_bad_request); let user = ok_or_return!( User::update(&user, user_id, &connection, &logger), response_internal_server_error("Error deleting the user") ); response_ok(&user) } pub fn get_user_posts(req: &mut Request) -> IronResult<Response> { let connection = req.get_db_conn(); let logger = req.get_logger(); let user_id = req.get_user_data().id; let posts = Post::get_post_from_user(user_id, &connection, &logger); response_ok(&posts) }
use dal::models::post::{Post};
random_line_split
dyn.rs
use rstest::*; #[fixture] fn dyn_box() -> Box<dyn Iterator<Item=i32>> { Box::new(std::iter::once(42)) } #[fixture] fn dyn_ref() -> &'static dyn ToString { &42 } #[fixture] fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 { dyn_box.next().unwrap() } #[fixture] fn dyn_ref_resolve(dyn_ref: &dyn ToString) -> String { dyn_ref.to_string() } #[rstest] fn test_dyn_box(mut dyn_box: Box<dyn Iterator<Item=i32>>) { assert_eq!(42, dyn_box.next().unwrap()) } #[rstest] fn test_dyn_ref(dyn_ref: &dyn ToString)
#[rstest] fn test_dyn_box_resolve(dyn_box_resolve: i32) { assert_eq!(42, dyn_box_resolve) } #[rstest] fn test_dyn_ref_resolve(dyn_ref_resolve: String) { assert_eq!("42", dyn_ref_resolve) }
{ assert_eq!("42", dyn_ref.to_string()) }
identifier_body
dyn.rs
use rstest::*; #[fixture] fn dyn_box() -> Box<dyn Iterator<Item=i32>> { Box::new(std::iter::once(42)) } #[fixture] fn dyn_ref() -> &'static dyn ToString { &42 } #[fixture] fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 { dyn_box.next().unwrap() } #[fixture] fn dyn_ref_resolve(dyn_ref: &dyn ToString) -> String { dyn_ref.to_string() } #[rstest] fn test_dyn_box(mut dyn_box: Box<dyn Iterator<Item=i32>>) { assert_eq!(42, dyn_box.next().unwrap()) } #[rstest] fn test_dyn_ref(dyn_ref: &dyn ToString) { assert_eq!("42", dyn_ref.to_string()) } #[rstest] fn
(dyn_box_resolve: i32) { assert_eq!(42, dyn_box_resolve) } #[rstest] fn test_dyn_ref_resolve(dyn_ref_resolve: String) { assert_eq!("42", dyn_ref_resolve) }
test_dyn_box_resolve
identifier_name
dyn.rs
use rstest::*; #[fixture] fn dyn_box() -> Box<dyn Iterator<Item=i32>> { Box::new(std::iter::once(42)) } #[fixture] fn dyn_ref() -> &'static dyn ToString { &42 } #[fixture] fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 { dyn_box.next().unwrap() } #[fixture] fn dyn_ref_resolve(dyn_ref: &dyn ToString) -> String { dyn_ref.to_string() } #[rstest] fn test_dyn_box(mut dyn_box: Box<dyn Iterator<Item=i32>>) { assert_eq!(42, dyn_box.next().unwrap()) } #[rstest] fn test_dyn_ref(dyn_ref: &dyn ToString) { assert_eq!("42", dyn_ref.to_string()) } #[rstest] fn test_dyn_box_resolve(dyn_box_resolve: i32) { assert_eq!(42, dyn_box_resolve) } #[rstest] fn test_dyn_ref_resolve(dyn_ref_resolve: String) {
}
assert_eq!("42", dyn_ref_resolve)
random_line_split
mod.rs
//! Provide helpers for making ioctl system calls //! //! Currently supports Linux on all architectures. Other platforms welcome! //! //! This library is pretty low-level and messy. `ioctl` is not fun. //! //! What is an `ioctl`? //! =================== //! //! The `ioctl` syscall is the grab-bag syscall on POSIX systems. Don't want //! to add a new syscall? Make it an `ioctl`! `ioctl` refers to both the syscall, //! and the commands that can be send with it. `ioctl` stands for "IO control", //! and the commands are always sent to a file descriptor. //! //! It is common to see `ioctl`s used for the following purposes: //! //! * Provide read/write access to out-of-band data related //! to a device such as configuration (for instance, setting //! serial port options) //! * Provide a mechanism for performing full-duplex data //! transfers (for instance, xfer on SPI devices). //! * Provide access to control functions on a device (for example, //! on Linux you can send commands like pause, resume, and eject //! to the CDROM device. //! * Do whatever else the device driver creator thought made most sense. //! //! `ioctl`s are synchronous system calls and are similar to read and //! write calls in that regard. //! //! What does this module support? //! =============================== //! //! This library provides the `ioctl!` macro, for binding `ioctl`s. It also tries //! to bind every `ioctl` supported by the system with said macro, but //! some `ioctl`s requires some amount of manual work (usually by //! providing `struct` declaration) that this library does not support yet. //! //! Additionally, in `etc`, there are scripts for scraping system headers for //! `ioctl` definitions, and generating calls to `ioctl!` corresponding to them. //! //! How do I get the magic numbers? //! =============================== //! //! For Linux, look at your system's headers. For example, `/usr/include/linxu/input.h` has a lot //! of lines defining macros which use `_IOR`, `_IOW`, `_IOC`, and `_IORW`. These macros //! correspond to the `ior!`, `iow!`, `ioc!`, and `iorw!` macros defined in this crate. //! Additionally, there is the `ioctl!` macro for creating a wrapper around `ioctl` that is //! somewhat more type-safe. //! //! Most `ioctl`s have no or little documentation. You'll need to scrounge through //! the source to figure out what they do and how they should be used. //! //! # Interface Overview //! //! This ioctl module seeks to tame the ioctl beast by providing a set of safer (although not safe) //! functions implementing the most common ioctl access patterns. //! //! The most common access patterns for ioctls are as follows: //! //! 1. `read`: A pointer is provided to the kernel which is populated //! with a value containing the "result" of the operation. The //! result may be an integer or structure. The kernel may also //! read values from the provided pointer (usually a structure). //! 2. `write`: A pointer is provided to the kernel containing values //! that the kernel will read in order to perform the operation. //! 3. `execute`: The operation is passed to the kernel but no //! additional pointer is passed. The operation is enough //! and it either succeeds or results in an error. //! //! Where appropriate, versions of these interface function are provided //! taking either refernces or pointers. The pointer versions are //! necessary for cases (notably slices) where a reference cannot //! be generically cast to a pointer. #[cfg(any(target_os = "linux", target_os = "android"))] #[path = "platform/linux.rs"] #[macro_use] mod platform; #[cfg(target_os = "macos")] #[path = "platform/macos.rs"] #[macro_use] mod platform; #[cfg(target_os = "ios")] #[path = "platform/ios.rs"] #[macro_use] mod platform; #[cfg(target_os = "freebsd")] #[path = "platform/freebsd.rs"] #[macro_use] mod platform; #[cfg(target_os = "openbsd")] #[path = "platform/openbsd.rs"] #[macro_use] mod platform; #[cfg(target_os = "dragonfly")]
mod platform; pub use self::platform::*; // liblibc has the wrong decl for linux :| hack until #26809 lands. extern "C" { #[doc(hidden)] pub fn ioctl(fd: libc::c_int, req: libc::c_ulong,...) -> libc::c_int; } /// A hack to get the macros to work nicely. #[doc(hidden)] pub use ::libc as libc;
#[path = "platform/dragonfly.rs"] #[macro_use]
random_line_split
tournament.rs
#![feature(slice_patterns)] #![feature(convert)] use std::fs::File; use std::path::Path; use std::io::Read; extern crate tournament; fn file_equal(output_file: &str, expected_file: &str) { let output = match File::open(&Path::new(output_file)) { Err(e) => panic!("Couldn't open {}: {}", output_file, e), Ok(mut f) => { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", output_file, e), Ok(_) => buf } } }; let expected = match File::open(&Path::new(expected_file)) { Err(e) => panic!("Couldn't open {}: {}", expected_file, e), Ok(mut f) => { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", expected_file, e), Ok(_) => buf } } }; assert_eq!("\n".to_string() + output.as_ref(), "\n".to_string() + expected.as_ref()); } #[test] #[ignore] fn test_good() { assert_eq!(tournament::tally(&Path::new("tests/input1.txt"), &Path::new("tests/output1.txt")), Ok(6)); file_equal("tests/output1.txt", "tests/expected1.txt"); } #[test] #[ignore] fn test_ignore_bad_lines() { assert_eq!(tournament::tally(&Path::new("tests/input2.txt"), &Path::new("tests/output2.txt")), Ok(6)); file_equal("tests/output2.txt", "tests/expected2.txt"); } #[test] #[ignore] fn test_incomplete_competition()
{ assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4)); file_equal("tests/output3.txt", "tests/expected3.txt"); }
identifier_body
tournament.rs
#![feature(slice_patterns)] #![feature(convert)] use std::fs::File; use std::path::Path; use std::io::Read; extern crate tournament; fn file_equal(output_file: &str, expected_file: &str) { let output = match File::open(&Path::new(output_file)) { Err(e) => panic!("Couldn't open {}: {}", output_file, e), Ok(mut f) => { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", output_file, e), Ok(_) => buf } } }; let expected = match File::open(&Path::new(expected_file)) { Err(e) => panic!("Couldn't open {}: {}", expected_file, e), Ok(mut f) => { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", expected_file, e), Ok(_) => buf } } }; assert_eq!("\n".to_string() + output.as_ref(), "\n".to_string() + expected.as_ref()); } #[test] #[ignore] fn test_good() { assert_eq!(tournament::tally(&Path::new("tests/input1.txt"), &Path::new("tests/output1.txt")), Ok(6)); file_equal("tests/output1.txt", "tests/expected1.txt"); } #[test] #[ignore] fn test_ignore_bad_lines() { assert_eq!(tournament::tally(&Path::new("tests/input2.txt"), &Path::new("tests/output2.txt")), Ok(6)); file_equal("tests/output2.txt", "tests/expected2.txt"); } #[test] #[ignore] fn
() { assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4)); file_equal("tests/output3.txt", "tests/expected3.txt"); }
test_incomplete_competition
identifier_name
tournament.rs
#![feature(slice_patterns)] #![feature(convert)] use std::fs::File; use std::path::Path; use std::io::Read; extern crate tournament; fn file_equal(output_file: &str, expected_file: &str) { let output = match File::open(&Path::new(output_file)) { Err(e) => panic!("Couldn't open {}: {}", output_file, e), Ok(mut f) => { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", output_file, e), Ok(_) => buf } } }; let expected = match File::open(&Path::new(expected_file)) { Err(e) => panic!("Couldn't open {}: {}", expected_file, e), Ok(mut f) => { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", expected_file, e), Ok(_) => buf } } }; assert_eq!("\n".to_string() + output.as_ref(), "\n".to_string() + expected.as_ref()); } #[test] #[ignore] fn test_good() { assert_eq!(tournament::tally(&Path::new("tests/input1.txt"), &Path::new("tests/output1.txt")), Ok(6)); file_equal("tests/output1.txt", "tests/expected1.txt"); } #[test] #[ignore] fn test_ignore_bad_lines() { assert_eq!(tournament::tally(&Path::new("tests/input2.txt"), &Path::new("tests/output2.txt")), Ok(6)); file_equal("tests/output2.txt", "tests/expected2.txt"); } #[test] #[ignore]
file_equal("tests/output3.txt", "tests/expected3.txt"); }
fn test_incomplete_competition() { assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4));
random_line_split
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Syntax extension to create floating point literals from hexadecimal strings Once loaded, hexfloat!() is called with a string containing the hexadecimal floating-point literal, and an optional type (f32 or f64). If the type is omitted, the literal is treated the same as a normal unsuffixed literal. # Examples To load the extension and use it: ```rust,ignore #[phase(plugin)] extern crate hexfloat; fn main() { let val = hexfloat!("0x1.ffffb4", f32); } ``` # References * [ExploringBinary: hexadecimal floating point constants] (http://www.exploringbinary.com/hexadecimal-floating-point-constants/) */ #![crate_name = "hexfloat"] #![deprecated = "This is now a cargo package located at: \ https://github.com/rust-lang/hexfloat"] #![allow(deprecated)] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(plugin_registrar)] extern crate syntax; extern crate rustc; use syntax::ast; use syntax::codemap::{Span, mk_sp}; use syntax::ext::base; use syntax::ext::base::{ExtCtxt, MacExpr}; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::ptr::P; use rustc::plugin::Registry; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("hexfloat", expand_syntax_ext); } //Check if the literal is valid (as LLVM expects), //and return a descriptive error if not. fn hex_float_lit_err(s: &str) -> Option<(uint, String)> { let mut chars = s.chars().peekable(); let mut i = 0; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } if chars.next()!= Some('0') { return Some((i, "Expected '0'".to_string())); } i+=1; if chars.next()!= Some('x') { return Some((i, "Expected 'x'".to_string())); } i+=1; let mut d_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;} if chars.next()!= Some('.') { return Some((i, "Expected '.'".to_string())); } i+=1; let mut f_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;} if d_len == 0 && f_len == 0 { return Some((i, "Expected digits before or after decimal \ point".to_string())); } if chars.next()!= Some('p') { return Some((i, "Expected 'p'".to_string())); } i+=1; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } let mut e_len = 0i; for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1} if e_len == 0 { return Some((i, "Expected exponent digits".to_string())); } match chars.next() { None => None, Some(_) => Some((i, "Expected end of string".to_string())) } } pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let (expr, ty_lit) = parse_tts(cx, tts); let ty = match ty_lit { None => None, Some(Ident{ident, span}) => match token::get_ident(ident).get() { "f32" => Some(ast::TyF32), "f64" => Some(ast::TyF64), _ =>
} }; let s = match expr.node { // expression is a literal ast::ExprLit(ref lit) => match lit.node { // string literal ast::LitStr(ref s, _) => { s.clone() } _ => { cx.span_err(expr.span, "unsupported literal in hexfloat!"); return base::DummyResult::expr(sp); } }, _ => { cx.span_err(expr.span, "non-literal in hexfloat!"); return base::DummyResult::expr(sp); } }; { let err = hex_float_lit_err(s.get()); match err { Some((err_pos, err_str)) => { let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1); let span = syntax::codemap::mk_sp(pos,pos); cx.span_err(span, format!("invalid hex float literal in hexfloat!: \ {}", err_str).as_slice()); return base::DummyResult::expr(sp); } _ => () } } let lit = match ty { None => ast::LitFloatUnsuffixed(s), Some (ty) => ast::LitFloat(s, ty) }; MacExpr::new(cx.expr_lit(sp, lit)) } struct Ident { ident: ast::Ident, span: Span } fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (P<ast::Expr>, Option<Ident>) { let p = &mut cx.new_parser_from_tts(tts); let ex = p.parse_expr(); let id = if p.token == token::EOF { None } else { p.expect(&token::COMMA); let lo = p.span.lo; let ident = p.parse_ident(); let hi = p.last_span.hi; Some(Ident{ident: ident, span: mk_sp(lo, hi)}) }; if p.token!= token::EOF { p.unexpected(); } (ex, id) } // FIXME (10872): This is required to prevent an LLVM assert on Windows #[test] fn dummy_test() { }
{ cx.span_err(span, "invalid floating point type in hexfloat!"); None }
conditional_block
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Syntax extension to create floating point literals from hexadecimal strings Once loaded, hexfloat!() is called with a string containing the hexadecimal floating-point literal, and an optional type (f32 or f64). If the type is omitted, the literal is treated the same as a normal unsuffixed literal. # Examples To load the extension and use it: ```rust,ignore #[phase(plugin)] extern crate hexfloat; fn main() { let val = hexfloat!("0x1.ffffb4", f32); } ``` # References * [ExploringBinary: hexadecimal floating point constants] (http://www.exploringbinary.com/hexadecimal-floating-point-constants/) */ #![crate_name = "hexfloat"] #![deprecated = "This is now a cargo package located at: \ https://github.com/rust-lang/hexfloat"] #![allow(deprecated)] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(plugin_registrar)] extern crate syntax; extern crate rustc; use syntax::ast; use syntax::codemap::{Span, mk_sp}; use syntax::ext::base; use syntax::ext::base::{ExtCtxt, MacExpr}; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::ptr::P; use rustc::plugin::Registry; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("hexfloat", expand_syntax_ext); } //Check if the literal is valid (as LLVM expects), //and return a descriptive error if not. fn hex_float_lit_err(s: &str) -> Option<(uint, String)> { let mut chars = s.chars().peekable(); let mut i = 0; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } if chars.next()!= Some('0') { return Some((i, "Expected '0'".to_string())); } i+=1; if chars.next()!= Some('x') { return Some((i, "Expected 'x'".to_string())); } i+=1; let mut d_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;} if chars.next()!= Some('.') { return Some((i, "Expected '.'".to_string())); } i+=1; let mut f_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;} if d_len == 0 && f_len == 0 { return Some((i, "Expected digits before or after decimal \ point".to_string())); } if chars.next()!= Some('p') { return Some((i, "Expected 'p'".to_string())); } i+=1; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } let mut e_len = 0i; for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1} if e_len == 0 { return Some((i, "Expected exponent digits".to_string())); } match chars.next() { None => None, Some(_) => Some((i, "Expected end of string".to_string())) } } pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let (expr, ty_lit) = parse_tts(cx, tts); let ty = match ty_lit { None => None, Some(Ident{ident, span}) => match token::get_ident(ident).get() { "f32" => Some(ast::TyF32), "f64" => Some(ast::TyF64), _ => { cx.span_err(span, "invalid floating point type in hexfloat!"); None } } }; let s = match expr.node { // expression is a literal ast::ExprLit(ref lit) => match lit.node { // string literal ast::LitStr(ref s, _) => { s.clone() } _ => { cx.span_err(expr.span, "unsupported literal in hexfloat!"); return base::DummyResult::expr(sp); } }, _ => { cx.span_err(expr.span, "non-literal in hexfloat!"); return base::DummyResult::expr(sp); } }; { let err = hex_float_lit_err(s.get()); match err { Some((err_pos, err_str)) => { let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1); let span = syntax::codemap::mk_sp(pos,pos); cx.span_err(span, format!("invalid hex float literal in hexfloat!: \ {}", err_str).as_slice()); return base::DummyResult::expr(sp); } _ => () } } let lit = match ty { None => ast::LitFloatUnsuffixed(s), Some (ty) => ast::LitFloat(s, ty) }; MacExpr::new(cx.expr_lit(sp, lit)) } struct Ident { ident: ast::Ident, span: Span } fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (P<ast::Expr>, Option<Ident>) { let p = &mut cx.new_parser_from_tts(tts); let ex = p.parse_expr(); let id = if p.token == token::EOF { None } else { p.expect(&token::COMMA); let lo = p.span.lo; let ident = p.parse_ident(); let hi = p.last_span.hi; Some(Ident{ident: ident, span: mk_sp(lo, hi)}) }; if p.token!= token::EOF { p.unexpected(); } (ex, id) } // FIXME (10872): This is required to prevent an LLVM assert on Windows #[test] fn
() { }
dummy_test
identifier_name
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Syntax extension to create floating point literals from hexadecimal strings Once loaded, hexfloat!() is called with a string containing the hexadecimal floating-point literal, and an optional type (f32 or f64). If the type is omitted, the literal is treated the same as a normal unsuffixed literal. # Examples To load the extension and use it: ```rust,ignore #[phase(plugin)] extern crate hexfloat; fn main() { let val = hexfloat!("0x1.ffffb4", f32); } ``` # References * [ExploringBinary: hexadecimal floating point constants] (http://www.exploringbinary.com/hexadecimal-floating-point-constants/) */ #![crate_name = "hexfloat"] #![deprecated = "This is now a cargo package located at: \ https://github.com/rust-lang/hexfloat"] #![allow(deprecated)] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(plugin_registrar)] extern crate syntax; extern crate rustc; use syntax::ast; use syntax::codemap::{Span, mk_sp}; use syntax::ext::base; use syntax::ext::base::{ExtCtxt, MacExpr}; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::ptr::P; use rustc::plugin::Registry; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry)
//Check if the literal is valid (as LLVM expects), //and return a descriptive error if not. fn hex_float_lit_err(s: &str) -> Option<(uint, String)> { let mut chars = s.chars().peekable(); let mut i = 0; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } if chars.next()!= Some('0') { return Some((i, "Expected '0'".to_string())); } i+=1; if chars.next()!= Some('x') { return Some((i, "Expected 'x'".to_string())); } i+=1; let mut d_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;} if chars.next()!= Some('.') { return Some((i, "Expected '.'".to_string())); } i+=1; let mut f_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;} if d_len == 0 && f_len == 0 { return Some((i, "Expected digits before or after decimal \ point".to_string())); } if chars.next()!= Some('p') { return Some((i, "Expected 'p'".to_string())); } i+=1; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } let mut e_len = 0i; for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1} if e_len == 0 { return Some((i, "Expected exponent digits".to_string())); } match chars.next() { None => None, Some(_) => Some((i, "Expected end of string".to_string())) } } pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let (expr, ty_lit) = parse_tts(cx, tts); let ty = match ty_lit { None => None, Some(Ident{ident, span}) => match token::get_ident(ident).get() { "f32" => Some(ast::TyF32), "f64" => Some(ast::TyF64), _ => { cx.span_err(span, "invalid floating point type in hexfloat!"); None } } }; let s = match expr.node { // expression is a literal ast::ExprLit(ref lit) => match lit.node { // string literal ast::LitStr(ref s, _) => { s.clone() } _ => { cx.span_err(expr.span, "unsupported literal in hexfloat!"); return base::DummyResult::expr(sp); } }, _ => { cx.span_err(expr.span, "non-literal in hexfloat!"); return base::DummyResult::expr(sp); } }; { let err = hex_float_lit_err(s.get()); match err { Some((err_pos, err_str)) => { let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1); let span = syntax::codemap::mk_sp(pos,pos); cx.span_err(span, format!("invalid hex float literal in hexfloat!: \ {}", err_str).as_slice()); return base::DummyResult::expr(sp); } _ => () } } let lit = match ty { None => ast::LitFloatUnsuffixed(s), Some (ty) => ast::LitFloat(s, ty) }; MacExpr::new(cx.expr_lit(sp, lit)) } struct Ident { ident: ast::Ident, span: Span } fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (P<ast::Expr>, Option<Ident>) { let p = &mut cx.new_parser_from_tts(tts); let ex = p.parse_expr(); let id = if p.token == token::EOF { None } else { p.expect(&token::COMMA); let lo = p.span.lo; let ident = p.parse_ident(); let hi = p.last_span.hi; Some(Ident{ident: ident, span: mk_sp(lo, hi)}) }; if p.token!= token::EOF { p.unexpected(); } (ex, id) } // FIXME (10872): This is required to prevent an LLVM assert on Windows #[test] fn dummy_test() { }
{ reg.register_macro("hexfloat", expand_syntax_ext); }
identifier_body
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Syntax extension to create floating point literals from hexadecimal strings Once loaded, hexfloat!() is called with a string containing the hexadecimal floating-point literal, and an optional type (f32 or f64). If the type is omitted, the literal is treated the same as a normal unsuffixed literal. # Examples To load the extension and use it: ```rust,ignore #[phase(plugin)] extern crate hexfloat; fn main() { let val = hexfloat!("0x1.ffffb4", f32); } ``` # References * [ExploringBinary: hexadecimal floating point constants] (http://www.exploringbinary.com/hexadecimal-floating-point-constants/) */ #![crate_name = "hexfloat"] #![deprecated = "This is now a cargo package located at: \ https://github.com/rust-lang/hexfloat"] #![allow(deprecated)] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(plugin_registrar)] extern crate syntax; extern crate rustc; use syntax::ast; use syntax::codemap::{Span, mk_sp}; use syntax::ext::base; use syntax::ext::base::{ExtCtxt, MacExpr}; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::ptr::P; use rustc::plugin::Registry; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("hexfloat", expand_syntax_ext); } //Check if the literal is valid (as LLVM expects), //and return a descriptive error if not. fn hex_float_lit_err(s: &str) -> Option<(uint, String)> { let mut chars = s.chars().peekable(); let mut i = 0; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } if chars.next()!= Some('0') { return Some((i, "Expected '0'".to_string())); } i+=1; if chars.next()!= Some('x') { return Some((i, "Expected 'x'".to_string())); } i+=1; let mut d_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;} if chars.next()!= Some('.') { return Some((i, "Expected '.'".to_string())); } i+=1; let mut f_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;} if d_len == 0 && f_len == 0 { return Some((i, "Expected digits before or after decimal \ point".to_string())); } if chars.next()!= Some('p') { return Some((i, "Expected 'p'".to_string())); } i+=1; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } let mut e_len = 0i; for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1} if e_len == 0 { return Some((i, "Expected exponent digits".to_string())); } match chars.next() { None => None, Some(_) => Some((i, "Expected end of string".to_string())) } } pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let (expr, ty_lit) = parse_tts(cx, tts);
"f32" => Some(ast::TyF32), "f64" => Some(ast::TyF64), _ => { cx.span_err(span, "invalid floating point type in hexfloat!"); None } } }; let s = match expr.node { // expression is a literal ast::ExprLit(ref lit) => match lit.node { // string literal ast::LitStr(ref s, _) => { s.clone() } _ => { cx.span_err(expr.span, "unsupported literal in hexfloat!"); return base::DummyResult::expr(sp); } }, _ => { cx.span_err(expr.span, "non-literal in hexfloat!"); return base::DummyResult::expr(sp); } }; { let err = hex_float_lit_err(s.get()); match err { Some((err_pos, err_str)) => { let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1); let span = syntax::codemap::mk_sp(pos,pos); cx.span_err(span, format!("invalid hex float literal in hexfloat!: \ {}", err_str).as_slice()); return base::DummyResult::expr(sp); } _ => () } } let lit = match ty { None => ast::LitFloatUnsuffixed(s), Some (ty) => ast::LitFloat(s, ty) }; MacExpr::new(cx.expr_lit(sp, lit)) } struct Ident { ident: ast::Ident, span: Span } fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (P<ast::Expr>, Option<Ident>) { let p = &mut cx.new_parser_from_tts(tts); let ex = p.parse_expr(); let id = if p.token == token::EOF { None } else { p.expect(&token::COMMA); let lo = p.span.lo; let ident = p.parse_ident(); let hi = p.last_span.hi; Some(Ident{ident: ident, span: mk_sp(lo, hi)}) }; if p.token!= token::EOF { p.unexpected(); } (ex, id) } // FIXME (10872): This is required to prevent an LLVM assert on Windows #[test] fn dummy_test() { }
let ty = match ty_lit { None => None, Some(Ident{ident, span}) => match token::get_ident(ident).get() {
random_line_split
function-arguments.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -C no-prepopulate-passes #![feature(allocator)] pub struct S { _field: [i64; 4], } pub struct UnsafeInner { _field: std::cell::UnsafeCell<i16>, } // CHECK: zeroext i1 @boolean(i1 zeroext) #[no_mangle] pub fn boolean(x: bool) -> bool { x } // CHECK: @readonly_borrow(i32* noalias readonly dereferenceable(4)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn readonly_borrow(_: &i32) { } // CHECK: @static_borrow(i32* noalias readonly dereferenceable(4)) // static borrow may be captured #[no_mangle] pub fn static_borrow(_: &'static i32) { } // CHECK: @named_borrow(i32* noalias readonly dereferenceable(4)) // borrow with named lifetime may be captured #[no_mangle] pub fn named_borrow<'r>(_: &'r i32) { } // CHECK: @unsafe_borrow(%UnsafeInner* dereferenceable(2)) // unsafe interior means this isn't actually readonly and there may be aliases... #[no_mangle] pub fn unsafe_borrow(_: &UnsafeInner)
// CHECK: @mutable_unsafe_borrow(%UnsafeInner* noalias dereferenceable(2)) //... unless this is a mutable borrow, those never alias #[no_mangle] pub fn mutable_unsafe_borrow(_: &mut UnsafeInner) { } // CHECK: @mutable_borrow(i32* noalias dereferenceable(4)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn mutable_borrow(_: &mut i32) { } // CHECK: @indirect_struct(%S* noalias nocapture dereferenceable(32)) #[no_mangle] pub fn indirect_struct(_: S) { } // CHECK: @borrowed_struct(%S* noalias readonly dereferenceable(32)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn borrowed_struct(_: &S) { } // CHECK: noalias dereferenceable(4) i32* @_box(i32* noalias dereferenceable(4)) #[no_mangle] pub fn _box(x: Box<i32>) -> Box<i32> { x } // CHECK: @struct_return(%S* noalias nocapture sret dereferenceable(32)) #[no_mangle] pub fn struct_return() -> S { S { _field: [0, 0, 0, 0] } } // CHECK: noalias i8* @allocator() #[no_mangle] #[allocator] pub fn allocator() -> *const i8 { std::ptr::null() }
{ }
identifier_body
function-arguments.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -C no-prepopulate-passes #![feature(allocator)] pub struct S { _field: [i64; 4], } pub struct UnsafeInner { _field: std::cell::UnsafeCell<i16>, } // CHECK: zeroext i1 @boolean(i1 zeroext) #[no_mangle] pub fn boolean(x: bool) -> bool { x } // CHECK: @readonly_borrow(i32* noalias readonly dereferenceable(4)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn readonly_borrow(_: &i32) { } // CHECK: @static_borrow(i32* noalias readonly dereferenceable(4)) // static borrow may be captured #[no_mangle] pub fn static_borrow(_: &'static i32) { } // CHECK: @named_borrow(i32* noalias readonly dereferenceable(4)) // borrow with named lifetime may be captured #[no_mangle] pub fn named_borrow<'r>(_: &'r i32) { } // CHECK: @unsafe_borrow(%UnsafeInner* dereferenceable(2)) // unsafe interior means this isn't actually readonly and there may be aliases... #[no_mangle] pub fn unsafe_borrow(_: &UnsafeInner) { } // CHECK: @mutable_unsafe_borrow(%UnsafeInner* noalias dereferenceable(2)) //... unless this is a mutable borrow, those never alias #[no_mangle] pub fn mutable_unsafe_borrow(_: &mut UnsafeInner) { } // CHECK: @mutable_borrow(i32* noalias dereferenceable(4)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn mutable_borrow(_: &mut i32) { } // CHECK: @indirect_struct(%S* noalias nocapture dereferenceable(32)) #[no_mangle] pub fn indirect_struct(_: S) { } // CHECK: @borrowed_struct(%S* noalias readonly dereferenceable(32)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn borrowed_struct(_: &S) { } // CHECK: noalias dereferenceable(4) i32* @_box(i32* noalias dereferenceable(4)) #[no_mangle] pub fn _box(x: Box<i32>) -> Box<i32> { x } // CHECK: @struct_return(%S* noalias nocapture sret dereferenceable(32)) #[no_mangle] pub fn
() -> S { S { _field: [0, 0, 0, 0] } } // CHECK: noalias i8* @allocator() #[no_mangle] #[allocator] pub fn allocator() -> *const i8 { std::ptr::null() }
struct_return
identifier_name
function-arguments.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -C no-prepopulate-passes #![feature(allocator)] pub struct S { _field: [i64; 4], } pub struct UnsafeInner { _field: std::cell::UnsafeCell<i16>, } // CHECK: zeroext i1 @boolean(i1 zeroext) #[no_mangle] pub fn boolean(x: bool) -> bool { x } // CHECK: @readonly_borrow(i32* noalias readonly dereferenceable(4)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn readonly_borrow(_: &i32) { } // CHECK: @static_borrow(i32* noalias readonly dereferenceable(4)) // static borrow may be captured #[no_mangle] pub fn static_borrow(_: &'static i32) { } // CHECK: @named_borrow(i32* noalias readonly dereferenceable(4)) // borrow with named lifetime may be captured #[no_mangle] pub fn named_borrow<'r>(_: &'r i32) { } // CHECK: @unsafe_borrow(%UnsafeInner* dereferenceable(2)) // unsafe interior means this isn't actually readonly and there may be aliases... #[no_mangle] pub fn unsafe_borrow(_: &UnsafeInner) { } // CHECK: @mutable_unsafe_borrow(%UnsafeInner* noalias dereferenceable(2)) //... unless this is a mutable borrow, those never alias #[no_mangle] pub fn mutable_unsafe_borrow(_: &mut UnsafeInner) { } // CHECK: @mutable_borrow(i32* noalias dereferenceable(4)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn mutable_borrow(_: &mut i32) { } // CHECK: @indirect_struct(%S* noalias nocapture dereferenceable(32)) #[no_mangle] pub fn indirect_struct(_: S) { } // CHECK: @borrowed_struct(%S* noalias readonly dereferenceable(32)) // FIXME #25759 This should also have `nocapture` #[no_mangle] pub fn borrowed_struct(_: &S) { } // CHECK: noalias dereferenceable(4) i32* @_box(i32* noalias dereferenceable(4)) #[no_mangle] pub fn _box(x: Box<i32>) -> Box<i32> { x }
} } // CHECK: noalias i8* @allocator() #[no_mangle] #[allocator] pub fn allocator() -> *const i8 { std::ptr::null() }
// CHECK: @struct_return(%S* noalias nocapture sret dereferenceable(32)) #[no_mangle] pub fn struct_return() -> S { S { _field: [0, 0, 0, 0]
random_line_split
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast type compare<T> = extern "Rust" fn(T, T) -> bool; fn test_generic<T:Clone>(expected: T, eq: compare<T>) { let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") }; assert!((eq(expected, actual))); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); } #[deriving(Clone)] struct Pair { a: int, b: int, } fn test_rec()
pub fn main() { test_bool(); test_rec(); }
{ fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec); }
identifier_body
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast type compare<T> = extern "Rust" fn(T, T) -> bool; fn test_generic<T:Clone>(expected: T, eq: compare<T>) { let actual: T = match true { true =>
, _ => fail!("wat") }; assert!((eq(expected, actual))); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); } #[deriving(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec); } pub fn main() { test_bool(); test_rec(); }
{ expected.clone() }
conditional_block
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast type compare<T> = extern "Rust" fn(T, T) -> bool; fn
<T:Clone>(expected: T, eq: compare<T>) { let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") }; assert!((eq(expected, actual))); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); } #[deriving(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec); } pub fn main() { test_bool(); test_rec(); }
test_generic
identifier_name
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast type compare<T> = extern "Rust" fn(T, T) -> bool; fn test_generic<T:Clone>(expected: T, eq: compare<T>) { let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") }; assert!((eq(expected, actual))); }
#[deriving(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec); } pub fn main() { test_bool(); test_rec(); }
fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); }
random_line_split
upload.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::str::{self, FromStr}; use anyhow::{Context, Error}; use bytes::Bytes; use futures::{ channel::mpsc::{self, channel}, SinkExt, Stream, StreamExt, TryStreamExt, }; use futures_util::try_join; use gotham::state::{FromState, State}; use gotham_derive::{StateData, StaticResponseExtender}; use http::header::CONTENT_LENGTH; use hyper::{Body, Request}; use serde::Deserialize; use stats::prelude::*; use filestore::{self, Alias, FetchKey, StoreRequest}; use gotham_ext::{ error::HttpError, middleware::{HttpScubaKey, ScubaMiddlewareState}, response::{EmptyBody, TryIntoResponse}, }; use lfs_protocol::{ ObjectAction, ObjectStatus, Operation, RequestBatch, RequestObject, ResponseBatch, Sha256 as LfsSha256, Transfer, }; use mononoke_types::hash::Sha256; use crate::errors::ErrorKind; use crate::lfs_server_context::RepositoryRequestContext; use crate::middleware::LfsMethod; use crate::scuba::LfsScubaKey; use crate::util::read_header_value; define_stats! { prefix ="mononoke.lfs.upload"; upstream_uploads: timeseries(Rate, Sum), upstream_success: timeseries(Rate, Sum), internal_uploads: timeseries(Rate, Sum), internal_success: timeseries(Rate, Sum), size_bytes: histogram(1_500_000, 0, 150_000_000, Average, Sum, Count; P 5; P 25; P 50; P 75; P 95; P 97; P 99), } // Small buffers for Filestore & Dewey const BUFFER_SIZE: usize = 5; mod closeable_sender { use pin_project::pin_project; use futures::{ channel::mpsc::{SendError, Sender}, sink::Sink, task::{Context, Poll}, }; use std::pin::Pin; #[pin_project] pub struct CloseableSender<T> { #[pin] inner: Sender<T>, } impl<T> CloseableSender<T> { pub fn new(inner: Sender<T>) -> Self { Self { inner } } } impl<T> Sink<T> for CloseableSender<T> { type Error = SendError; fn poll_ready( self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { match self.project().inner.poll_ready(ctx) { Poll::Ready(Err(e)) if e.is_disconnected() => Poll::Ready(Ok(())), x => x, } } fn start_send(self: Pin<&mut Self>, msg: T) -> Result<(), Self::Error> { match self.project().inner.start_send(msg) { Err(e) if e.is_disconnected() => Ok(()), x => x, } } fn poll_flush( self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { self.project().inner.poll_flush(ctx) } fn poll_close( self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { self.project().inner.poll_close(ctx) } } } use closeable_sender::CloseableSender; // NOTE: We don't deserialize things beyond a String form, in order to report errors in our // controller, not in routing. #[derive(Deserialize, StateData, StaticResponseExtender)] pub struct UploadParams { repository: String, oid: String, size: String, } fn find_actions( batch: ResponseBatch, object: &RequestObject, ) -> Result<HashMap<Operation, ObjectAction>, Error> { let ResponseBatch { transfer, objects } = batch; match transfer { Transfer::Basic => objects .into_iter() .find(|o| o.object == *object) .ok_or(ErrorKind::UpstreamMissingObject(*object).into()) .and_then(|o| match o.status { ObjectStatus::Ok { authenticated: false, actions, } => Ok(actions), _ => Err(ErrorKind::UpstreamInvalidObject(o).into()), }), Transfer::Unknown => Err(ErrorKind::UpstreamInvalidTransfer.into()), } } async fn internal_upload<S>( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, data: S, ) -> Result<(), Error> where S: Stream<Item = Result<Bytes, Error>> + Unpin + Send +'static, { STATS::internal_uploads.add_value(1); let res = filestore::store( ctx.repo.blobstore(), ctx.repo.filestore_config(), &ctx.ctx, &StoreRequest::with_sha256(size, oid), data, ) .await .context(ErrorKind::FilestoreWriteFailure) .map_err(Error::from); if!res.is_err() { STATS::internal_success.add_value(1); } Ok(()) } async fn upstream_upload<S>( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, data: S, ) -> Result<(), Error> where S: Stream<Item = Result<Bytes, Error>> + Unpin + Send +'static, { let object = RequestObject { oid: LfsSha256(oid.into_inner()), size, }; let batch = RequestBatch { operation: Operation::Upload, r#ref: None, transfers: vec![Transfer::Basic], objects: vec![object], }; let res = ctx .upstream_batch(&batch) .await .context(ErrorKind::UpstreamBatchError)?; let batch = match res { Some(res) => res, None => { // We have no upstream: discard this copy. return Ok(()); } }; let action = find_actions(batch, &object)?.remove(&Operation::Upload); if let Some(action) = action { // TODO: We are discarding expiry and headers here. We probably shouldn't. // TODO: We are discarding verify actions. STATS::upstream_uploads.add_value(1); let ObjectAction { href,.. } = action; // TODO: Fix this after updating Hyper: https://github.com/hyperium/hyper/pull/2187 let (sender, receiver) = mpsc::channel(0); tokio::spawn(data.map(Ok).forward(sender)); let body = Body::wrap_stream(receiver); let req = Request::put(href) .header("Content-Length", &size.to_string()) .body(body.into())?; // NOTE: We read the response body here, otherwise Hyper will not allow this connection to // be reused. ctx.dispatch(req) .await .context(ErrorKind::UpstreamUploadError)? .discard() .await?; STATS::upstream_success.add_value(1); return Ok(()); } Ok(()) } async fn upload_from_client<S>( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, body: S, scuba: &mut Option<&mut ScubaMiddlewareState>, ) -> Result<(), Error> where S: Stream<Item = Result<Bytes, ()>> + Unpin + Send +'static, { let (internal_send, internal_recv) = channel::<Result<Bytes, ()>>(BUFFER_SIZE); let (upstream_send, upstream_recv) = channel::<Result<Bytes, ()>>(BUFFER_SIZE); // CloseableSender lets us allow a stream to close without breaking the sender. This is useful // if e.g. upstream already has the data we want to send, so we decide not to send it. This // gives us better error messages, since if one of our uploads fail, we're guaranteed that the // consume_stream future isn't the one that'll return an error. let internal_send = CloseableSender::new(internal_send); let upstream_send = CloseableSender::new(upstream_send); let mut sink = internal_send.fanout(upstream_send); let internal_recv = internal_recv .map_err(|()| ErrorKind::ClientCancelled) .err_into(); let upstream_recv = upstream_recv .map_err(|()| ErrorKind::ClientCancelled) .err_into(); let internal_upload = internal_upload(&ctx, oid, size, internal_recv); let upstream_upload = upstream_upload(&ctx, oid, size, upstream_recv); let mut received: usize = 0; let mut data = body .map_ok(|chunk| { received += chunk.len(); chunk }) .map(Ok); // Note: this closure simply creates a single future that sends all data then closes the sink. // It needs to be a single future because all 3 futures below need to make progress // concurrently for the upload to succeed (if the destinations aren't making progress, we'll // deadlock, if the source isn't making progress, we'll deadlock too, and if the sink doesn't // close, we'll never finish the uploads). let consume_stream = async { sink.send_all(&mut data) .await .map_err(|_| ErrorKind::ClientCancelled) .map_err(Error::from)?; sink.close().await?; Ok(()) }; let res = try_join!(internal_upload, upstream_upload, consume_stream); ScubaMiddlewareState::maybe_add(scuba, HttpScubaKey::RequestBytesReceived, received); res.map(|_| ()) } async fn sync_internal_and_upstream( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, scuba: &mut Option<&mut ScubaMiddlewareState>, ) -> Result<(), Error> { let key = FetchKey::Aliased(Alias::Sha256(oid)); let res = filestore::fetch(ctx.repo.get_blobstore(), ctx.ctx.clone(), &key).await?; match res { Some(stream) => { // We have the data, so presumably upstream does not have it. ScubaMiddlewareState::maybe_add(scuba, LfsScubaKey::UploadSync, "internal_to_upstream"); upstream_upload(ctx, oid, size, stream).await?; } None => { // We do not have the data. Get it from upstream. ScubaMiddlewareState::maybe_add(scuba, LfsScubaKey::UploadSync, "upstream_to_internal"); let object = RequestObject { oid: LfsSha256(oid.into_inner()), size, }; let batch = RequestBatch { operation: Operation::Download, r#ref: None, transfers: vec![Transfer::Basic], objects: vec![object], }; let batch = ctx .upstream_batch(&batch) .await .context(ErrorKind::UpstreamBatchError)? .ok_or_else(|| ErrorKind::ObjectCannotBeSynced(object))?; let action = find_actions(batch, &object)? .remove(&Operation::Download) .ok_or_else(|| ErrorKind::ObjectCannotBeSynced(object))?; let req = Request::get(action.href).body(Body::empty())?; let stream = ctx .dispatch(req) .await .context(ErrorKind::ObjectCannotBeSynced(object))? .into_inner(); internal_upload(ctx, oid, size, stream).await?; } } Ok(()) } pub async fn upload(state: &mut State) -> Result<impl TryIntoResponse, HttpError> { let UploadParams { repository, oid, size,
let oid = Sha256::from_str(&oid).map_err(HttpError::e400)?; let size = size.parse().map_err(Error::from).map_err(HttpError::e400)?; let content_length: Option<u64> = read_header_value(state, CONTENT_LENGTH) .transpose() .map_err(HttpError::e400)?; if let Some(content_length) = content_length { ScubaMiddlewareState::try_borrow_add( state, HttpScubaKey::RequestContentLength, content_length, ); } STATS::size_bytes.add_value(size as i64); if let Some(max_upload_size) = ctx.max_upload_size() { if size > max_upload_size { Err(HttpError::e400(ErrorKind::UploadTooLarge( size, max_upload_size, )))?; } } // The key invariant of our proxy design is that if you upload to this LFS server, then the // content will be present in both this LFS server and its upstream. To do so, we've // historically asked the client to upload whatever data either server is missing. However, // this only works if the client has the data, but it doesn't always. Indeed, if the client // only holds a LFS pointer (but knows the data is available on the server), then we can find // ourselves in a situation where the client needs to upload to us, but cannot (because it does // not have the data). However, the client still needs a mechanism to assert that the data is // in both this LFS server and its upstream. So, to support this mechanism, we let the client // send an empty request when uploading. When this happens, we assume we must have the content // somewhere, and try to sync it as necessary (to upstream if we have it internally, and to // internal if we don't). match content_length { Some(0) if size > 0 => { let mut scuba = state.try_borrow_mut::<ScubaMiddlewareState>(); sync_internal_and_upstream(&ctx, oid, size, &mut scuba) .await .map_err(HttpError::e500)?; } _ => { // TODO: More appropriate status codes here let body = Body::take_from(state).map_err(|_| ()); let mut scuba = state.try_borrow_mut::<ScubaMiddlewareState>(); upload_from_client(&ctx, oid, size, body, &mut scuba) .await .map_err(HttpError::e500)?; } } Ok(EmptyBody::new()) } #[cfg(test)] mod test { use super::*; use fbinit::FacebookInit; use futures::{future, stream}; #[fbinit::test] async fn test_upload_from_client_discard_upstream(fb: FacebookInit) -> Result<(), Error> { let ctx = RepositoryRequestContext::test_builder(fb)? .upstream_uri(None) .build()?; let body = stream::once(future::ready(Ok(Bytes::from("foobar")))); let oid = Sha256::from_str("c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2")?; let size = 6; upload_from_client(&ctx, oid, size, body, &mut None).await?; Ok(()) } }
} = state.take(); let ctx = RepositoryRequestContext::instantiate(state, repository.clone(), LfsMethod::Upload).await?;
random_line_split
upload.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::str::{self, FromStr}; use anyhow::{Context, Error}; use bytes::Bytes; use futures::{ channel::mpsc::{self, channel}, SinkExt, Stream, StreamExt, TryStreamExt, }; use futures_util::try_join; use gotham::state::{FromState, State}; use gotham_derive::{StateData, StaticResponseExtender}; use http::header::CONTENT_LENGTH; use hyper::{Body, Request}; use serde::Deserialize; use stats::prelude::*; use filestore::{self, Alias, FetchKey, StoreRequest}; use gotham_ext::{ error::HttpError, middleware::{HttpScubaKey, ScubaMiddlewareState}, response::{EmptyBody, TryIntoResponse}, }; use lfs_protocol::{ ObjectAction, ObjectStatus, Operation, RequestBatch, RequestObject, ResponseBatch, Sha256 as LfsSha256, Transfer, }; use mononoke_types::hash::Sha256; use crate::errors::ErrorKind; use crate::lfs_server_context::RepositoryRequestContext; use crate::middleware::LfsMethod; use crate::scuba::LfsScubaKey; use crate::util::read_header_value; define_stats! { prefix ="mononoke.lfs.upload"; upstream_uploads: timeseries(Rate, Sum), upstream_success: timeseries(Rate, Sum), internal_uploads: timeseries(Rate, Sum), internal_success: timeseries(Rate, Sum), size_bytes: histogram(1_500_000, 0, 150_000_000, Average, Sum, Count; P 5; P 25; P 50; P 75; P 95; P 97; P 99), } // Small buffers for Filestore & Dewey const BUFFER_SIZE: usize = 5; mod closeable_sender { use pin_project::pin_project; use futures::{ channel::mpsc::{SendError, Sender}, sink::Sink, task::{Context, Poll}, }; use std::pin::Pin; #[pin_project] pub struct CloseableSender<T> { #[pin] inner: Sender<T>, } impl<T> CloseableSender<T> { pub fn new(inner: Sender<T>) -> Self { Self { inner } } } impl<T> Sink<T> for CloseableSender<T> { type Error = SendError; fn poll_ready( self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { match self.project().inner.poll_ready(ctx) { Poll::Ready(Err(e)) if e.is_disconnected() => Poll::Ready(Ok(())), x => x, } } fn start_send(self: Pin<&mut Self>, msg: T) -> Result<(), Self::Error> { match self.project().inner.start_send(msg) { Err(e) if e.is_disconnected() => Ok(()), x => x, } } fn poll_flush( self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { self.project().inner.poll_flush(ctx) } fn poll_close( self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { self.project().inner.poll_close(ctx) } } } use closeable_sender::CloseableSender; // NOTE: We don't deserialize things beyond a String form, in order to report errors in our // controller, not in routing. #[derive(Deserialize, StateData, StaticResponseExtender)] pub struct UploadParams { repository: String, oid: String, size: String, } fn find_actions( batch: ResponseBatch, object: &RequestObject, ) -> Result<HashMap<Operation, ObjectAction>, Error> { let ResponseBatch { transfer, objects } = batch; match transfer { Transfer::Basic => objects .into_iter() .find(|o| o.object == *object) .ok_or(ErrorKind::UpstreamMissingObject(*object).into()) .and_then(|o| match o.status { ObjectStatus::Ok { authenticated: false, actions, } => Ok(actions), _ => Err(ErrorKind::UpstreamInvalidObject(o).into()), }), Transfer::Unknown => Err(ErrorKind::UpstreamInvalidTransfer.into()), } } async fn internal_upload<S>( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, data: S, ) -> Result<(), Error> where S: Stream<Item = Result<Bytes, Error>> + Unpin + Send +'static, { STATS::internal_uploads.add_value(1); let res = filestore::store( ctx.repo.blobstore(), ctx.repo.filestore_config(), &ctx.ctx, &StoreRequest::with_sha256(size, oid), data, ) .await .context(ErrorKind::FilestoreWriteFailure) .map_err(Error::from); if!res.is_err() { STATS::internal_success.add_value(1); } Ok(()) } async fn upstream_upload<S>( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, data: S, ) -> Result<(), Error> where S: Stream<Item = Result<Bytes, Error>> + Unpin + Send +'static, { let object = RequestObject { oid: LfsSha256(oid.into_inner()), size, }; let batch = RequestBatch { operation: Operation::Upload, r#ref: None, transfers: vec![Transfer::Basic], objects: vec![object], }; let res = ctx .upstream_batch(&batch) .await .context(ErrorKind::UpstreamBatchError)?; let batch = match res { Some(res) => res, None => { // We have no upstream: discard this copy. return Ok(()); } }; let action = find_actions(batch, &object)?.remove(&Operation::Upload); if let Some(action) = action { // TODO: We are discarding expiry and headers here. We probably shouldn't. // TODO: We are discarding verify actions. STATS::upstream_uploads.add_value(1); let ObjectAction { href,.. } = action; // TODO: Fix this after updating Hyper: https://github.com/hyperium/hyper/pull/2187 let (sender, receiver) = mpsc::channel(0); tokio::spawn(data.map(Ok).forward(sender)); let body = Body::wrap_stream(receiver); let req = Request::put(href) .header("Content-Length", &size.to_string()) .body(body.into())?; // NOTE: We read the response body here, otherwise Hyper will not allow this connection to // be reused. ctx.dispatch(req) .await .context(ErrorKind::UpstreamUploadError)? .discard() .await?; STATS::upstream_success.add_value(1); return Ok(()); } Ok(()) } async fn
<S>( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, body: S, scuba: &mut Option<&mut ScubaMiddlewareState>, ) -> Result<(), Error> where S: Stream<Item = Result<Bytes, ()>> + Unpin + Send +'static, { let (internal_send, internal_recv) = channel::<Result<Bytes, ()>>(BUFFER_SIZE); let (upstream_send, upstream_recv) = channel::<Result<Bytes, ()>>(BUFFER_SIZE); // CloseableSender lets us allow a stream to close without breaking the sender. This is useful // if e.g. upstream already has the data we want to send, so we decide not to send it. This // gives us better error messages, since if one of our uploads fail, we're guaranteed that the // consume_stream future isn't the one that'll return an error. let internal_send = CloseableSender::new(internal_send); let upstream_send = CloseableSender::new(upstream_send); let mut sink = internal_send.fanout(upstream_send); let internal_recv = internal_recv .map_err(|()| ErrorKind::ClientCancelled) .err_into(); let upstream_recv = upstream_recv .map_err(|()| ErrorKind::ClientCancelled) .err_into(); let internal_upload = internal_upload(&ctx, oid, size, internal_recv); let upstream_upload = upstream_upload(&ctx, oid, size, upstream_recv); let mut received: usize = 0; let mut data = body .map_ok(|chunk| { received += chunk.len(); chunk }) .map(Ok); // Note: this closure simply creates a single future that sends all data then closes the sink. // It needs to be a single future because all 3 futures below need to make progress // concurrently for the upload to succeed (if the destinations aren't making progress, we'll // deadlock, if the source isn't making progress, we'll deadlock too, and if the sink doesn't // close, we'll never finish the uploads). let consume_stream = async { sink.send_all(&mut data) .await .map_err(|_| ErrorKind::ClientCancelled) .map_err(Error::from)?; sink.close().await?; Ok(()) }; let res = try_join!(internal_upload, upstream_upload, consume_stream); ScubaMiddlewareState::maybe_add(scuba, HttpScubaKey::RequestBytesReceived, received); res.map(|_| ()) } async fn sync_internal_and_upstream( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, scuba: &mut Option<&mut ScubaMiddlewareState>, ) -> Result<(), Error> { let key = FetchKey::Aliased(Alias::Sha256(oid)); let res = filestore::fetch(ctx.repo.get_blobstore(), ctx.ctx.clone(), &key).await?; match res { Some(stream) => { // We have the data, so presumably upstream does not have it. ScubaMiddlewareState::maybe_add(scuba, LfsScubaKey::UploadSync, "internal_to_upstream"); upstream_upload(ctx, oid, size, stream).await?; } None => { // We do not have the data. Get it from upstream. ScubaMiddlewareState::maybe_add(scuba, LfsScubaKey::UploadSync, "upstream_to_internal"); let object = RequestObject { oid: LfsSha256(oid.into_inner()), size, }; let batch = RequestBatch { operation: Operation::Download, r#ref: None, transfers: vec![Transfer::Basic], objects: vec![object], }; let batch = ctx .upstream_batch(&batch) .await .context(ErrorKind::UpstreamBatchError)? .ok_or_else(|| ErrorKind::ObjectCannotBeSynced(object))?; let action = find_actions(batch, &object)? .remove(&Operation::Download) .ok_or_else(|| ErrorKind::ObjectCannotBeSynced(object))?; let req = Request::get(action.href).body(Body::empty())?; let stream = ctx .dispatch(req) .await .context(ErrorKind::ObjectCannotBeSynced(object))? .into_inner(); internal_upload(ctx, oid, size, stream).await?; } } Ok(()) } pub async fn upload(state: &mut State) -> Result<impl TryIntoResponse, HttpError> { let UploadParams { repository, oid, size, } = state.take(); let ctx = RepositoryRequestContext::instantiate(state, repository.clone(), LfsMethod::Upload).await?; let oid = Sha256::from_str(&oid).map_err(HttpError::e400)?; let size = size.parse().map_err(Error::from).map_err(HttpError::e400)?; let content_length: Option<u64> = read_header_value(state, CONTENT_LENGTH) .transpose() .map_err(HttpError::e400)?; if let Some(content_length) = content_length { ScubaMiddlewareState::try_borrow_add( state, HttpScubaKey::RequestContentLength, content_length, ); } STATS::size_bytes.add_value(size as i64); if let Some(max_upload_size) = ctx.max_upload_size() { if size > max_upload_size { Err(HttpError::e400(ErrorKind::UploadTooLarge( size, max_upload_size, )))?; } } // The key invariant of our proxy design is that if you upload to this LFS server, then the // content will be present in both this LFS server and its upstream. To do so, we've // historically asked the client to upload whatever data either server is missing. However, // this only works if the client has the data, but it doesn't always. Indeed, if the client // only holds a LFS pointer (but knows the data is available on the server), then we can find // ourselves in a situation where the client needs to upload to us, but cannot (because it does // not have the data). However, the client still needs a mechanism to assert that the data is // in both this LFS server and its upstream. So, to support this mechanism, we let the client // send an empty request when uploading. When this happens, we assume we must have the content // somewhere, and try to sync it as necessary (to upstream if we have it internally, and to // internal if we don't). match content_length { Some(0) if size > 0 => { let mut scuba = state.try_borrow_mut::<ScubaMiddlewareState>(); sync_internal_and_upstream(&ctx, oid, size, &mut scuba) .await .map_err(HttpError::e500)?; } _ => { // TODO: More appropriate status codes here let body = Body::take_from(state).map_err(|_| ()); let mut scuba = state.try_borrow_mut::<ScubaMiddlewareState>(); upload_from_client(&ctx, oid, size, body, &mut scuba) .await .map_err(HttpError::e500)?; } } Ok(EmptyBody::new()) } #[cfg(test)] mod test { use super::*; use fbinit::FacebookInit; use futures::{future, stream}; #[fbinit::test] async fn test_upload_from_client_discard_upstream(fb: FacebookInit) -> Result<(), Error> { let ctx = RepositoryRequestContext::test_builder(fb)? .upstream_uri(None) .build()?; let body = stream::once(future::ready(Ok(Bytes::from("foobar")))); let oid = Sha256::from_str("c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2")?; let size = 6; upload_from_client(&ctx, oid, size, body, &mut None).await?; Ok(()) } }
upload_from_client
identifier_name
example-uncommented.rs
#![feature(custom_attribute,plugin)] #![plugin(tag_safe)] #![allow(dead_code)] /// RAII primitive spinlock struct Spinlock; /// Handle to said spinlock struct HeldSpinlock(&'static Spinlock); /// RAII IRQ hold struct IRQLock; /// Spinlock that also disables IRQs struct
(Spinlock); static S_NON_IRQ_SPINLOCK: Spinlock = Spinlock; static S_IRQ_SPINLOCK: IrqSpinlock = IrqSpinlock(Spinlock); #[deny(not_tagged_safe)] // Make the lint an error #[req_safe(irq)] // Require this method be IRQ safe fn irq_handler() { let _lock = acquire_non_irq_spinlock(&S_NON_IRQ_SPINLOCK); //~^ ERROR Calling irq-unsafe method from } // This method handles IRQ safety internally, and hence makes // this lint allowable. #[is_safe(irq)] fn acquire_irq_spinlock(l: &'static IrqSpinlock) -> (IRQLock,HeldSpinlock) { // Prevent IRQs from firing let irql = hold_irqs(); // and acquire the spinlock (irql, acquire_non_irq_spinlock(&l.0)) } // Stop IRQs from firing until the returned value is dropped #[is_safe(irq)] fn hold_irqs() -> IRQLock { IRQLock } // Not safe to call in an IRQ without protection (as that can lead to a uniprocessor deadlock) #[not_safe(irq)] fn acquire_non_irq_spinlock(l: &'static Spinlock) -> HeldSpinlock { HeldSpinlock(l) } fn main() { irq_handler(); } // vim: ts=4 sw=4 expandtab
IrqSpinlock
identifier_name
example-uncommented.rs
#![feature(custom_attribute,plugin)] #![plugin(tag_safe)] #![allow(dead_code)] /// RAII primitive spinlock struct Spinlock; /// Handle to said spinlock struct HeldSpinlock(&'static Spinlock); /// RAII IRQ hold struct IRQLock; /// Spinlock that also disables IRQs struct IrqSpinlock(Spinlock); static S_NON_IRQ_SPINLOCK: Spinlock = Spinlock; static S_IRQ_SPINLOCK: IrqSpinlock = IrqSpinlock(Spinlock); #[deny(not_tagged_safe)] // Make the lint an error #[req_safe(irq)] // Require this method be IRQ safe fn irq_handler() { let _lock = acquire_non_irq_spinlock(&S_NON_IRQ_SPINLOCK); //~^ ERROR Calling irq-unsafe method from } // This method handles IRQ safety internally, and hence makes // this lint allowable. #[is_safe(irq)] fn acquire_irq_spinlock(l: &'static IrqSpinlock) -> (IRQLock,HeldSpinlock) { // Prevent IRQs from firing let irql = hold_irqs(); // and acquire the spinlock (irql, acquire_non_irq_spinlock(&l.0)) } // Stop IRQs from firing until the returned value is dropped #[is_safe(irq)] fn hold_irqs() -> IRQLock { IRQLock } // Not safe to call in an IRQ without protection (as that can lead to a uniprocessor deadlock) #[not_safe(irq)] fn acquire_non_irq_spinlock(l: &'static Spinlock) -> HeldSpinlock { HeldSpinlock(l) } fn main()
// vim: ts=4 sw=4 expandtab
{ irq_handler(); }
identifier_body
example-uncommented.rs
#![feature(custom_attribute,plugin)] #![plugin(tag_safe)] #![allow(dead_code)] /// RAII primitive spinlock struct Spinlock; /// Handle to said spinlock struct HeldSpinlock(&'static Spinlock); /// RAII IRQ hold struct IRQLock; /// Spinlock that also disables IRQs struct IrqSpinlock(Spinlock); static S_NON_IRQ_SPINLOCK: Spinlock = Spinlock; static S_IRQ_SPINLOCK: IrqSpinlock = IrqSpinlock(Spinlock); #[deny(not_tagged_safe)] // Make the lint an error #[req_safe(irq)] // Require this method be IRQ safe fn irq_handler() { let _lock = acquire_non_irq_spinlock(&S_NON_IRQ_SPINLOCK); //~^ ERROR Calling irq-unsafe method from } // This method handles IRQ safety internally, and hence makes // this lint allowable. #[is_safe(irq)] fn acquire_irq_spinlock(l: &'static IrqSpinlock) -> (IRQLock,HeldSpinlock) { // Prevent IRQs from firing let irql = hold_irqs(); // and acquire the spinlock (irql, acquire_non_irq_spinlock(&l.0)) } // Stop IRQs from firing until the returned value is dropped #[is_safe(irq)] fn hold_irqs() -> IRQLock { IRQLock } // Not safe to call in an IRQ without protection (as that can lead to a uniprocessor deadlock) #[not_safe(irq)] fn acquire_non_irq_spinlock(l: &'static Spinlock) -> HeldSpinlock
irq_handler(); } // vim: ts=4 sw=4 expandtab
{ HeldSpinlock(l) } fn main() {
random_line_split
reader.rs
//! This module allows you to read from a CDB. use helpers::{hash, unpack}; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use types::{Error, Result}; use writer::Writer; /// Allows you to read from CDB. /// /// #Example /// /// Given a file stored at `filename` with the following contents: /// /// ```text /// { /// "key": "value", /// } /// ``` /// /// this is how you can read the stored value: /// /// ``` /// # use galvanize::Result; /// # use galvanize::Writer; /// use galvanize::Reader; /// use std::fs::File; /// /// # // Doing this to get around the fact that you can't have `try!` in `main`. /// # fn main() { /// # let _ = do_try(); /// # } /// # /// # fn do_try() -> Result<()> { /// # let filename = "reader_example.cdb"; /// let key = "key".as_bytes(); /// # { /// # let mut f = File::create(filename)?; /// # let mut cdb_writer = Writer::new(&mut f)?; /// # cdb_writer.put(key, "value".as_bytes()); /// # } /// /// let mut f = File::open(filename)?; /// let mut cdb_reader = Reader::new(&mut f)?; /// let stored_vals = cdb_reader.get(key); /// assert_eq!(stored_vals.len(), 1); /// assert_eq!(&stored_vals[0][..], &"value".as_bytes()[..]); /// /// // The CDB contains only one entry: /// assert_eq!(cdb_reader.len(), 1); /// /// // Accessing a key that isn't in the CDB: /// let non_existing_key = "non_existing_key".as_bytes(); /// let empty = cdb_reader.get(non_existing_key); /// assert_eq!(empty.len(), 0); /// /// assert!(cdb_reader.get_first(non_existing_key).is_err()); /// # /// # Ok(()) /// # } /// ``` #[derive(Debug)] pub struct Reader<'a, F: Read + Seek + 'a> { /// Opened file to read values from. file: &'a mut F, /// Index for the contents of the CDB. index: Vec<(u32, u32)>, /// Position in the file where the hash table starts. table_start: usize, /// How many elements are there in the CDB. length: usize, } /// Iterator struct for Key, Values in a CDB. pub struct ItemIterator<'a, 'file: 'a, F: Read + Seek + 'file> { reader: &'a mut Reader<'file, F>, } /// Iterate over (Key, Values) in a CDB until the end of file. impl<'a, 'file: 'a, F: Read + Seek + 'file> Iterator for ItemIterator<'a, 'file, F> { /// A single `key`, `value` pair. type Item = (Vec<u8>, Vec<u8>); /// Fetch the next (`key`, `value`) pair, if any. fn next(&mut self) -> Option<Self::Item> { match self.reader.file.seek(SeekFrom::Current(0)) { Ok(pos) => { if pos >= self.reader.table_start as u64 { return None; } } Err(_) => return None, } // We're in the Footer/Hash Table of the file, no more items. let mut buf: [u8; 8] = [0; 8]; { let mut chunk = self.reader.file.take(8); let _ = chunk.read(&mut buf); } let k = unpack([buf[0], buf[1], buf[2], buf[3]]); // Key length let v = unpack([buf[4], buf[5], buf[6], buf[7]]); // Value length let mut key: Vec<u8> = vec![]; { let mut chunk = self.reader.file.take(k as u64); let _ = chunk.read_to_end(&mut key); } let mut val: Vec<u8> = vec![]; { let mut chunk = self.reader.file.take(v as u64); let _ = chunk.read_to_end(&mut val); } Some((key, val)) } } /// Convert a [`Reader`]() CDB into an `Iterator`. /// /// One use of this, is using Rust's `for` loop syntax. /// #Example /// ``` /// # use galvanize::Reader; /// # use std::fs::File; /// # let filename = "tests/testdata/top250pws.cdb"; /// let mut f = File::open(filename).unwrap(); /// /// let mut cdb_reader = Reader::new(&mut f).ok().unwrap(); /// let len = cdb_reader.len(); /// /// # let mut i = 0; /// for (k, v) in cdb_reader.into_iter() { /// // Consume the (k, v) pair. /// # let _ = k; /// # i += 1; /// # let s = &i.to_string(); /// # let val = s.as_bytes(); /// # assert_eq!(&v[..], &val[..]); /// } /// # assert_eq!(len, i); /// # /// # // Do it again to make sure the iterator doesn't consume and lifetimes /// # // work as expected. /// # i = 0; /// # for (_, v) in cdb_reader.into_iter() { /// # i += 1; /// # let s = &i.to_string(); /// # let val = s.as_bytes(); /// # assert_eq!(&v[..], &val[..]); /// # } /// # assert_eq!(len, i); /// ``` impl<'a, 'file: 'a, F: Read + Seek + 'file> IntoIterator for &'a mut Reader<'file, F> { /// A single `key`, `value` pair. type Item = (Vec<u8>, Vec<u8>); /// The [`ItemIterator`](struct.ItemIterator.html) type this will convert /// into. type IntoIter = ItemIterator<'a, 'file, F>; fn into_iter(self) -> Self::IntoIter { let _ = self.file.seek(SeekFrom::Start(2048)); ItemIterator { reader: self } } } impl<'a, F: Read + Seek + 'a> Reader<'a, F> { /// Creates a new `Reader` consuming the provided `file`. pub fn new(file: &'a mut F) -> Result<Reader<'a, F>> { match file.seek(SeekFrom::End(0)) { Err(e) => return Err(Error::IOError(e)), Ok(n) => { if n < 2048 { return Err(Error::CDBTooSmall); } } }; // Using u32 instead of usize as standard CDBs can only be 4GB in size. let mut index: Vec<(u32, u32)> = vec![]; let mut sum: u32 = 0; let mut buf: Vec<u8> = vec![]; { file.seek(SeekFrom::Start(0))?; let mut chunk = file.take(2048); chunk.read_to_end(&mut buf)?; } for ix in 0..2048 / 8 { let i = ix * 8; let k = unpack([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]); let v = unpack([buf[i + 4], buf[i + 5], buf[i + 6], buf[i + 7]]); sum = sum + (v >> 1); index.push((k, v)); } let table_start = index.iter().map(|item| item.0).min().unwrap(); Ok(Reader { file: file, index: index, table_start: table_start as usize, length: sum as usize, }) } /// How many `(key, value)` pairs are there in this Read Only CDB. pub fn len(&self) -> usize { self.length } /// Return a `Vec` of all the values under the given `key`. pub fn get(&mut self, key: &[u8]) -> Vec<Vec<u8>> { let mut i = 0; let mut values: Vec<Vec<u8>> = vec![]; loop { match self.get_from_pos(key, i) { Ok(v) => values.push(v), Err(_) => break, } i += 1; } values } /// Return a `Vec` of all the keys in this Read Only CDB. /// /// Keep in mind that if there're duplicated keys, they will appear /// multiple times in the resulting `Vec`. pub fn keys(&mut self) -> Vec<Vec<u8>> { let mut keys: Vec<Vec<u8>> = vec![]; for item in self.into_iter() { keys.push(item.0); } keys } /// Pull the `value` bytes for the first occurence of the given `key` in /// this CDB. pub fn get_first(&mut self, key: &[u8]) -> Result<Vec<u8>> { self.get_from_pos(key, 0) } /// Pull the `value` bytes for the `index`st occurence of the given `key` /// in this CDB. pub fn get_from_pos(&mut self, key: &[u8], index: u32) -> Result<Vec<u8>> { // Truncate to 32 bits and remove sign. let h = hash(key) & 0xffffffff; let (start, nslots) = self.index[(h & 0xff) as usize]; if nslots > index { // Bucket has keys. let end = start + (nslots << 3); let slot_off = start + (((h >> 8) % nslots) << 3); let mut counter = 0; // Every 8 bytes from the slot offset to the end, and then from the // end to the slot_offset. for pos in (slot_off..end) .chain(start..slot_off) .enumerate() .filter(|item| item.0 % 8 == 0) .map(|item| item.1) { let mut buf: [u8; 8] = [0; 8]; { self.file.seek(SeekFrom::Start(pos as u64))?; let mut chunk = self.file.take(8); chunk.read(&mut buf)?; } let rec_h = unpack([buf[0], buf[1], buf[2], buf[3]]); let rec_pos = unpack([buf[4], buf[5], buf[6], buf[7]]); if rec_h == 0 { // Key not in file. return Err(Error::KeyNotInCDB); } else if rec_h == h { // Hash of key found in file. { self.file.seek(SeekFrom::Start(rec_pos as u64))?; let mut chunk = self.file.take(8); chunk.read(&mut buf)?; } let klen = unpack([buf[0], buf[1], buf[2], buf[3]]); let dlen = unpack([buf[4], buf[5], buf[6], buf[7]]); let mut buf: Vec<u8> = vec![]; { let mut chunk = self.file.take(klen as u64); chunk.read_to_end(&mut buf)?; } { if buf == key { // Found key in file buf.clear(); let mut chunk = self.file.take(dlen as u64); chunk.read_to_end(&mut buf)?; if counter == index { return Ok(buf); } counter = counter + 1; } } } } } Err(Error::KeyNotInCDB) } } // Needs to be a file to `truncate` at the end. impl<'a> Reader<'a, File> { /// Transform this `Reader` into a `Writer` using the same underlying /// `file`. /// /// The underlying file will have its hash table `truncate`d. This will be /// regenerated on `Writer` drop. pub fn
(mut self) -> Result<Writer<'a, File>> { match self.file.seek(SeekFrom::Start(self.table_start as u64)) { Ok(_) => { let mut index: Vec<Vec<(u32, u32)>> = vec![Vec::new(); 256]; let mut buf = &mut [0 as u8; 8]; // Read hash table until end of file to recreate Writer index. while let Ok(s) = self.file.read(buf) { if s == 0 { // EOF break; } let h = unpack([buf[0], buf[1], buf[2], buf[3]]); let pos = unpack([buf[4], buf[5], buf[6], buf[7]]); index[(h & 0xff) as usize].push((h, pos)); } // Clear the hash table at the end of the file. It'll be // recreated on `Drop` of the `Writer`. match self.file.set_len(self.table_start as u64) { Ok(_) => (), Err(e) => return Err(Error::IOError(e)), } Writer::new_with_index(self.file, index) } Err(e) => Err(Error::IOError(e)), } } }
as_writer
identifier_name
reader.rs
//! This module allows you to read from a CDB. use helpers::{hash, unpack}; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use types::{Error, Result}; use writer::Writer; /// Allows you to read from CDB. /// /// #Example /// /// Given a file stored at `filename` with the following contents: /// /// ```text /// { /// "key": "value", /// } /// ``` /// /// this is how you can read the stored value: /// /// ``` /// # use galvanize::Result; /// # use galvanize::Writer; /// use galvanize::Reader; /// use std::fs::File; /// /// # // Doing this to get around the fact that you can't have `try!` in `main`. /// # fn main() { /// # let _ = do_try(); /// # } /// # /// # fn do_try() -> Result<()> { /// # let filename = "reader_example.cdb"; /// let key = "key".as_bytes(); /// # { /// # let mut f = File::create(filename)?; /// # let mut cdb_writer = Writer::new(&mut f)?; /// # cdb_writer.put(key, "value".as_bytes()); /// # } /// /// let mut f = File::open(filename)?; /// let mut cdb_reader = Reader::new(&mut f)?; /// let stored_vals = cdb_reader.get(key); /// assert_eq!(stored_vals.len(), 1); /// assert_eq!(&stored_vals[0][..], &"value".as_bytes()[..]); /// /// // The CDB contains only one entry: /// assert_eq!(cdb_reader.len(), 1); /// /// // Accessing a key that isn't in the CDB: /// let non_existing_key = "non_existing_key".as_bytes(); /// let empty = cdb_reader.get(non_existing_key); /// assert_eq!(empty.len(), 0); /// /// assert!(cdb_reader.get_first(non_existing_key).is_err()); /// # /// # Ok(()) /// # } /// ``` #[derive(Debug)] pub struct Reader<'a, F: Read + Seek + 'a> { /// Opened file to read values from. file: &'a mut F, /// Index for the contents of the CDB. index: Vec<(u32, u32)>, /// Position in the file where the hash table starts. table_start: usize, /// How many elements are there in the CDB. length: usize, } /// Iterator struct for Key, Values in a CDB. pub struct ItemIterator<'a, 'file: 'a, F: Read + Seek + 'file> { reader: &'a mut Reader<'file, F>, } /// Iterate over (Key, Values) in a CDB until the end of file. impl<'a, 'file: 'a, F: Read + Seek + 'file> Iterator for ItemIterator<'a, 'file, F> { /// A single `key`, `value` pair. type Item = (Vec<u8>, Vec<u8>); /// Fetch the next (`key`, `value`) pair, if any. fn next(&mut self) -> Option<Self::Item> { match self.reader.file.seek(SeekFrom::Current(0)) { Ok(pos) => { if pos >= self.reader.table_start as u64 { return None; } } Err(_) => return None, } // We're in the Footer/Hash Table of the file, no more items. let mut buf: [u8; 8] = [0; 8]; { let mut chunk = self.reader.file.take(8); let _ = chunk.read(&mut buf); } let k = unpack([buf[0], buf[1], buf[2], buf[3]]); // Key length let v = unpack([buf[4], buf[5], buf[6], buf[7]]); // Value length let mut key: Vec<u8> = vec![]; { let mut chunk = self.reader.file.take(k as u64); let _ = chunk.read_to_end(&mut key); } let mut val: Vec<u8> = vec![]; { let mut chunk = self.reader.file.take(v as u64); let _ = chunk.read_to_end(&mut val); } Some((key, val)) } } /// Convert a [`Reader`]() CDB into an `Iterator`. /// /// One use of this, is using Rust's `for` loop syntax. /// #Example /// ``` /// # use galvanize::Reader; /// # use std::fs::File; /// # let filename = "tests/testdata/top250pws.cdb"; /// let mut f = File::open(filename).unwrap(); /// /// let mut cdb_reader = Reader::new(&mut f).ok().unwrap(); /// let len = cdb_reader.len(); /// /// # let mut i = 0; /// for (k, v) in cdb_reader.into_iter() { /// // Consume the (k, v) pair. /// # let _ = k; /// # i += 1; /// # let s = &i.to_string(); /// # let val = s.as_bytes(); /// # assert_eq!(&v[..], &val[..]); /// }
/// # // Do it again to make sure the iterator doesn't consume and lifetimes /// # // work as expected. /// # i = 0; /// # for (_, v) in cdb_reader.into_iter() { /// # i += 1; /// # let s = &i.to_string(); /// # let val = s.as_bytes(); /// # assert_eq!(&v[..], &val[..]); /// # } /// # assert_eq!(len, i); /// ``` impl<'a, 'file: 'a, F: Read + Seek + 'file> IntoIterator for &'a mut Reader<'file, F> { /// A single `key`, `value` pair. type Item = (Vec<u8>, Vec<u8>); /// The [`ItemIterator`](struct.ItemIterator.html) type this will convert /// into. type IntoIter = ItemIterator<'a, 'file, F>; fn into_iter(self) -> Self::IntoIter { let _ = self.file.seek(SeekFrom::Start(2048)); ItemIterator { reader: self } } } impl<'a, F: Read + Seek + 'a> Reader<'a, F> { /// Creates a new `Reader` consuming the provided `file`. pub fn new(file: &'a mut F) -> Result<Reader<'a, F>> { match file.seek(SeekFrom::End(0)) { Err(e) => return Err(Error::IOError(e)), Ok(n) => { if n < 2048 { return Err(Error::CDBTooSmall); } } }; // Using u32 instead of usize as standard CDBs can only be 4GB in size. let mut index: Vec<(u32, u32)> = vec![]; let mut sum: u32 = 0; let mut buf: Vec<u8> = vec![]; { file.seek(SeekFrom::Start(0))?; let mut chunk = file.take(2048); chunk.read_to_end(&mut buf)?; } for ix in 0..2048 / 8 { let i = ix * 8; let k = unpack([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]); let v = unpack([buf[i + 4], buf[i + 5], buf[i + 6], buf[i + 7]]); sum = sum + (v >> 1); index.push((k, v)); } let table_start = index.iter().map(|item| item.0).min().unwrap(); Ok(Reader { file: file, index: index, table_start: table_start as usize, length: sum as usize, }) } /// How many `(key, value)` pairs are there in this Read Only CDB. pub fn len(&self) -> usize { self.length } /// Return a `Vec` of all the values under the given `key`. pub fn get(&mut self, key: &[u8]) -> Vec<Vec<u8>> { let mut i = 0; let mut values: Vec<Vec<u8>> = vec![]; loop { match self.get_from_pos(key, i) { Ok(v) => values.push(v), Err(_) => break, } i += 1; } values } /// Return a `Vec` of all the keys in this Read Only CDB. /// /// Keep in mind that if there're duplicated keys, they will appear /// multiple times in the resulting `Vec`. pub fn keys(&mut self) -> Vec<Vec<u8>> { let mut keys: Vec<Vec<u8>> = vec![]; for item in self.into_iter() { keys.push(item.0); } keys } /// Pull the `value` bytes for the first occurence of the given `key` in /// this CDB. pub fn get_first(&mut self, key: &[u8]) -> Result<Vec<u8>> { self.get_from_pos(key, 0) } /// Pull the `value` bytes for the `index`st occurence of the given `key` /// in this CDB. pub fn get_from_pos(&mut self, key: &[u8], index: u32) -> Result<Vec<u8>> { // Truncate to 32 bits and remove sign. let h = hash(key) & 0xffffffff; let (start, nslots) = self.index[(h & 0xff) as usize]; if nslots > index { // Bucket has keys. let end = start + (nslots << 3); let slot_off = start + (((h >> 8) % nslots) << 3); let mut counter = 0; // Every 8 bytes from the slot offset to the end, and then from the // end to the slot_offset. for pos in (slot_off..end) .chain(start..slot_off) .enumerate() .filter(|item| item.0 % 8 == 0) .map(|item| item.1) { let mut buf: [u8; 8] = [0; 8]; { self.file.seek(SeekFrom::Start(pos as u64))?; let mut chunk = self.file.take(8); chunk.read(&mut buf)?; } let rec_h = unpack([buf[0], buf[1], buf[2], buf[3]]); let rec_pos = unpack([buf[4], buf[5], buf[6], buf[7]]); if rec_h == 0 { // Key not in file. return Err(Error::KeyNotInCDB); } else if rec_h == h { // Hash of key found in file. { self.file.seek(SeekFrom::Start(rec_pos as u64))?; let mut chunk = self.file.take(8); chunk.read(&mut buf)?; } let klen = unpack([buf[0], buf[1], buf[2], buf[3]]); let dlen = unpack([buf[4], buf[5], buf[6], buf[7]]); let mut buf: Vec<u8> = vec![]; { let mut chunk = self.file.take(klen as u64); chunk.read_to_end(&mut buf)?; } { if buf == key { // Found key in file buf.clear(); let mut chunk = self.file.take(dlen as u64); chunk.read_to_end(&mut buf)?; if counter == index { return Ok(buf); } counter = counter + 1; } } } } } Err(Error::KeyNotInCDB) } } // Needs to be a file to `truncate` at the end. impl<'a> Reader<'a, File> { /// Transform this `Reader` into a `Writer` using the same underlying /// `file`. /// /// The underlying file will have its hash table `truncate`d. This will be /// regenerated on `Writer` drop. pub fn as_writer(mut self) -> Result<Writer<'a, File>> { match self.file.seek(SeekFrom::Start(self.table_start as u64)) { Ok(_) => { let mut index: Vec<Vec<(u32, u32)>> = vec![Vec::new(); 256]; let mut buf = &mut [0 as u8; 8]; // Read hash table until end of file to recreate Writer index. while let Ok(s) = self.file.read(buf) { if s == 0 { // EOF break; } let h = unpack([buf[0], buf[1], buf[2], buf[3]]); let pos = unpack([buf[4], buf[5], buf[6], buf[7]]); index[(h & 0xff) as usize].push((h, pos)); } // Clear the hash table at the end of the file. It'll be // recreated on `Drop` of the `Writer`. match self.file.set_len(self.table_start as u64) { Ok(_) => (), Err(e) => return Err(Error::IOError(e)), } Writer::new_with_index(self.file, index) } Err(e) => Err(Error::IOError(e)), } } }
/// # assert_eq!(len, i); /// #
random_line_split
reader.rs
//! This module allows you to read from a CDB. use helpers::{hash, unpack}; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use types::{Error, Result}; use writer::Writer; /// Allows you to read from CDB. /// /// #Example /// /// Given a file stored at `filename` with the following contents: /// /// ```text /// { /// "key": "value", /// } /// ``` /// /// this is how you can read the stored value: /// /// ``` /// # use galvanize::Result; /// # use galvanize::Writer; /// use galvanize::Reader; /// use std::fs::File; /// /// # // Doing this to get around the fact that you can't have `try!` in `main`. /// # fn main() { /// # let _ = do_try(); /// # } /// # /// # fn do_try() -> Result<()> { /// # let filename = "reader_example.cdb"; /// let key = "key".as_bytes(); /// # { /// # let mut f = File::create(filename)?; /// # let mut cdb_writer = Writer::new(&mut f)?; /// # cdb_writer.put(key, "value".as_bytes()); /// # } /// /// let mut f = File::open(filename)?; /// let mut cdb_reader = Reader::new(&mut f)?; /// let stored_vals = cdb_reader.get(key); /// assert_eq!(stored_vals.len(), 1); /// assert_eq!(&stored_vals[0][..], &"value".as_bytes()[..]); /// /// // The CDB contains only one entry: /// assert_eq!(cdb_reader.len(), 1); /// /// // Accessing a key that isn't in the CDB: /// let non_existing_key = "non_existing_key".as_bytes(); /// let empty = cdb_reader.get(non_existing_key); /// assert_eq!(empty.len(), 0); /// /// assert!(cdb_reader.get_first(non_existing_key).is_err()); /// # /// # Ok(()) /// # } /// ``` #[derive(Debug)] pub struct Reader<'a, F: Read + Seek + 'a> { /// Opened file to read values from. file: &'a mut F, /// Index for the contents of the CDB. index: Vec<(u32, u32)>, /// Position in the file where the hash table starts. table_start: usize, /// How many elements are there in the CDB. length: usize, } /// Iterator struct for Key, Values in a CDB. pub struct ItemIterator<'a, 'file: 'a, F: Read + Seek + 'file> { reader: &'a mut Reader<'file, F>, } /// Iterate over (Key, Values) in a CDB until the end of file. impl<'a, 'file: 'a, F: Read + Seek + 'file> Iterator for ItemIterator<'a, 'file, F> { /// A single `key`, `value` pair. type Item = (Vec<u8>, Vec<u8>); /// Fetch the next (`key`, `value`) pair, if any. fn next(&mut self) -> Option<Self::Item> { match self.reader.file.seek(SeekFrom::Current(0)) { Ok(pos) => { if pos >= self.reader.table_start as u64 { return None; } } Err(_) => return None, } // We're in the Footer/Hash Table of the file, no more items. let mut buf: [u8; 8] = [0; 8]; { let mut chunk = self.reader.file.take(8); let _ = chunk.read(&mut buf); } let k = unpack([buf[0], buf[1], buf[2], buf[3]]); // Key length let v = unpack([buf[4], buf[5], buf[6], buf[7]]); // Value length let mut key: Vec<u8> = vec![]; { let mut chunk = self.reader.file.take(k as u64); let _ = chunk.read_to_end(&mut key); } let mut val: Vec<u8> = vec![]; { let mut chunk = self.reader.file.take(v as u64); let _ = chunk.read_to_end(&mut val); } Some((key, val)) } } /// Convert a [`Reader`]() CDB into an `Iterator`. /// /// One use of this, is using Rust's `for` loop syntax. /// #Example /// ``` /// # use galvanize::Reader; /// # use std::fs::File; /// # let filename = "tests/testdata/top250pws.cdb"; /// let mut f = File::open(filename).unwrap(); /// /// let mut cdb_reader = Reader::new(&mut f).ok().unwrap(); /// let len = cdb_reader.len(); /// /// # let mut i = 0; /// for (k, v) in cdb_reader.into_iter() { /// // Consume the (k, v) pair. /// # let _ = k; /// # i += 1; /// # let s = &i.to_string(); /// # let val = s.as_bytes(); /// # assert_eq!(&v[..], &val[..]); /// } /// # assert_eq!(len, i); /// # /// # // Do it again to make sure the iterator doesn't consume and lifetimes /// # // work as expected. /// # i = 0; /// # for (_, v) in cdb_reader.into_iter() { /// # i += 1; /// # let s = &i.to_string(); /// # let val = s.as_bytes(); /// # assert_eq!(&v[..], &val[..]); /// # } /// # assert_eq!(len, i); /// ``` impl<'a, 'file: 'a, F: Read + Seek + 'file> IntoIterator for &'a mut Reader<'file, F> { /// A single `key`, `value` pair. type Item = (Vec<u8>, Vec<u8>); /// The [`ItemIterator`](struct.ItemIterator.html) type this will convert /// into. type IntoIter = ItemIterator<'a, 'file, F>; fn into_iter(self) -> Self::IntoIter { let _ = self.file.seek(SeekFrom::Start(2048)); ItemIterator { reader: self } } } impl<'a, F: Read + Seek + 'a> Reader<'a, F> { /// Creates a new `Reader` consuming the provided `file`. pub fn new(file: &'a mut F) -> Result<Reader<'a, F>> { match file.seek(SeekFrom::End(0)) { Err(e) => return Err(Error::IOError(e)), Ok(n) => { if n < 2048 { return Err(Error::CDBTooSmall); } } }; // Using u32 instead of usize as standard CDBs can only be 4GB in size. let mut index: Vec<(u32, u32)> = vec![]; let mut sum: u32 = 0; let mut buf: Vec<u8> = vec![]; { file.seek(SeekFrom::Start(0))?; let mut chunk = file.take(2048); chunk.read_to_end(&mut buf)?; } for ix in 0..2048 / 8 { let i = ix * 8; let k = unpack([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]); let v = unpack([buf[i + 4], buf[i + 5], buf[i + 6], buf[i + 7]]); sum = sum + (v >> 1); index.push((k, v)); } let table_start = index.iter().map(|item| item.0).min().unwrap(); Ok(Reader { file: file, index: index, table_start: table_start as usize, length: sum as usize, }) } /// How many `(key, value)` pairs are there in this Read Only CDB. pub fn len(&self) -> usize { self.length } /// Return a `Vec` of all the values under the given `key`. pub fn get(&mut self, key: &[u8]) -> Vec<Vec<u8>>
/// Return a `Vec` of all the keys in this Read Only CDB. /// /// Keep in mind that if there're duplicated keys, they will appear /// multiple times in the resulting `Vec`. pub fn keys(&mut self) -> Vec<Vec<u8>> { let mut keys: Vec<Vec<u8>> = vec![]; for item in self.into_iter() { keys.push(item.0); } keys } /// Pull the `value` bytes for the first occurence of the given `key` in /// this CDB. pub fn get_first(&mut self, key: &[u8]) -> Result<Vec<u8>> { self.get_from_pos(key, 0) } /// Pull the `value` bytes for the `index`st occurence of the given `key` /// in this CDB. pub fn get_from_pos(&mut self, key: &[u8], index: u32) -> Result<Vec<u8>> { // Truncate to 32 bits and remove sign. let h = hash(key) & 0xffffffff; let (start, nslots) = self.index[(h & 0xff) as usize]; if nslots > index { // Bucket has keys. let end = start + (nslots << 3); let slot_off = start + (((h >> 8) % nslots) << 3); let mut counter = 0; // Every 8 bytes from the slot offset to the end, and then from the // end to the slot_offset. for pos in (slot_off..end) .chain(start..slot_off) .enumerate() .filter(|item| item.0 % 8 == 0) .map(|item| item.1) { let mut buf: [u8; 8] = [0; 8]; { self.file.seek(SeekFrom::Start(pos as u64))?; let mut chunk = self.file.take(8); chunk.read(&mut buf)?; } let rec_h = unpack([buf[0], buf[1], buf[2], buf[3]]); let rec_pos = unpack([buf[4], buf[5], buf[6], buf[7]]); if rec_h == 0 { // Key not in file. return Err(Error::KeyNotInCDB); } else if rec_h == h { // Hash of key found in file. { self.file.seek(SeekFrom::Start(rec_pos as u64))?; let mut chunk = self.file.take(8); chunk.read(&mut buf)?; } let klen = unpack([buf[0], buf[1], buf[2], buf[3]]); let dlen = unpack([buf[4], buf[5], buf[6], buf[7]]); let mut buf: Vec<u8> = vec![]; { let mut chunk = self.file.take(klen as u64); chunk.read_to_end(&mut buf)?; } { if buf == key { // Found key in file buf.clear(); let mut chunk = self.file.take(dlen as u64); chunk.read_to_end(&mut buf)?; if counter == index { return Ok(buf); } counter = counter + 1; } } } } } Err(Error::KeyNotInCDB) } } // Needs to be a file to `truncate` at the end. impl<'a> Reader<'a, File> { /// Transform this `Reader` into a `Writer` using the same underlying /// `file`. /// /// The underlying file will have its hash table `truncate`d. This will be /// regenerated on `Writer` drop. pub fn as_writer(mut self) -> Result<Writer<'a, File>> { match self.file.seek(SeekFrom::Start(self.table_start as u64)) { Ok(_) => { let mut index: Vec<Vec<(u32, u32)>> = vec![Vec::new(); 256]; let mut buf = &mut [0 as u8; 8]; // Read hash table until end of file to recreate Writer index. while let Ok(s) = self.file.read(buf) { if s == 0 { // EOF break; } let h = unpack([buf[0], buf[1], buf[2], buf[3]]); let pos = unpack([buf[4], buf[5], buf[6], buf[7]]); index[(h & 0xff) as usize].push((h, pos)); } // Clear the hash table at the end of the file. It'll be // recreated on `Drop` of the `Writer`. match self.file.set_len(self.table_start as u64) { Ok(_) => (), Err(e) => return Err(Error::IOError(e)), } Writer::new_with_index(self.file, index) } Err(e) => Err(Error::IOError(e)), } } }
{ let mut i = 0; let mut values: Vec<Vec<u8>> = vec![]; loop { match self.get_from_pos(key, i) { Ok(v) => values.push(v), Err(_) => break, } i += 1; } values }
identifier_body
path.rs
use ::inflector::Inflector; use ::regex::Regex; use ::syn::Ident; use ::quote::Tokens; use ::yaml_rust::Yaml; use infer::method; use infer::TokensResult; fn mod_ident(path: &str) -> Ident { let rustified = path.replace('/', " ").trim().to_snake_case(); let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap(); let ident = re.replace_all(rustified.as_str(), "_${resource}_"); Ident::new(ident) } pub(super) fn infer_v3(path: &str, schema: &Yaml) -> TokensResult { let path_mod = mod_ident(path); let method_schemata = schema.as_hash().expect("Path must be a map."); let mut method_impls: Vec<Tokens> = Vec::new(); let mut path_level_structs = quote!(); for (method, method_schema) in method_schemata { let method = method.as_str().expect("Method must be a string."); let (method_impl, maybe_param_structs) = method::infer_v3(&method, &method_schema)?; method_impls.push(method_impl); if let Some(param_structs) = maybe_param_structs { path_level_structs = param_structs; } } Ok(quote! { #[allow(non_snake_case)] pub mod #path_mod { #[allow(unused_imports)] use ::tapioca::Body; use ::tapioca::Client; use ::tapioca::Url; use ::tapioca::header; use ::tapioca::response::Response; #[allow(unused_imports)] use ::tapioca::query::QueryString; #[allow(unused_imports)] use super::auth_scheme; #[allow(unused_imports)] use super::schema_ref; use super::API_URL; #[allow(unused_imports)] use super::ServerAuth; const API_PATH: &'static str = #path; #path_level_structs
#(#method_impls)* } }) } #[cfg(tests)] mod tests { use super::*; #[test] fn leading_slash() { assert_eq!(mod_ident("/foo"), Ident::new("foo")); } #[test] fn both_slash() { assert_eq!(mod_ident("/foo/"), Ident::new("foo")); } #[test] fn no_slash() { assert_eq!(mod_ident("foo"), Ident::new("foo")); } #[test] fn trailing_slash() { assert_eq!(mod_ident("foo/"), Ident::new("foo")); } #[test] fn multipart() { assert_eq!(mod_ident("/foo/bar"), Ident::new("foo_bar")); } #[test] fn resource() { assert_eq!(mod_ident("/foo/{id}"), Ident::new("foo__id_")); } #[test] fn multi_resource() { assert_eq!(mod_ident("/foo/{id}/{bar}"), Ident::new("foo__id___bar_")); } #[test] fn multipart_resource() { assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar")); } #[test] fn multipart_multiresource() { assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_")); } }
random_line_split
path.rs
use ::inflector::Inflector; use ::regex::Regex; use ::syn::Ident; use ::quote::Tokens; use ::yaml_rust::Yaml; use infer::method; use infer::TokensResult; fn mod_ident(path: &str) -> Ident { let rustified = path.replace('/', " ").trim().to_snake_case(); let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap(); let ident = re.replace_all(rustified.as_str(), "_${resource}_"); Ident::new(ident) } pub(super) fn infer_v3(path: &str, schema: &Yaml) -> TokensResult { let path_mod = mod_ident(path); let method_schemata = schema.as_hash().expect("Path must be a map."); let mut method_impls: Vec<Tokens> = Vec::new(); let mut path_level_structs = quote!(); for (method, method_schema) in method_schemata { let method = method.as_str().expect("Method must be a string."); let (method_impl, maybe_param_structs) = method::infer_v3(&method, &method_schema)?; method_impls.push(method_impl); if let Some(param_structs) = maybe_param_structs
} Ok(quote! { #[allow(non_snake_case)] pub mod #path_mod { #[allow(unused_imports)] use ::tapioca::Body; use ::tapioca::Client; use ::tapioca::Url; use ::tapioca::header; use ::tapioca::response::Response; #[allow(unused_imports)] use ::tapioca::query::QueryString; #[allow(unused_imports)] use super::auth_scheme; #[allow(unused_imports)] use super::schema_ref; use super::API_URL; #[allow(unused_imports)] use super::ServerAuth; const API_PATH: &'static str = #path; #path_level_structs #(#method_impls)* } }) } #[cfg(tests)] mod tests { use super::*; #[test] fn leading_slash() { assert_eq!(mod_ident("/foo"), Ident::new("foo")); } #[test] fn both_slash() { assert_eq!(mod_ident("/foo/"), Ident::new("foo")); } #[test] fn no_slash() { assert_eq!(mod_ident("foo"), Ident::new("foo")); } #[test] fn trailing_slash() { assert_eq!(mod_ident("foo/"), Ident::new("foo")); } #[test] fn multipart() { assert_eq!(mod_ident("/foo/bar"), Ident::new("foo_bar")); } #[test] fn resource() { assert_eq!(mod_ident("/foo/{id}"), Ident::new("foo__id_")); } #[test] fn multi_resource() { assert_eq!(mod_ident("/foo/{id}/{bar}"), Ident::new("foo__id___bar_")); } #[test] fn multipart_resource() { assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar")); } #[test] fn multipart_multiresource() { assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_")); } }
{ path_level_structs = param_structs; }
conditional_block
path.rs
use ::inflector::Inflector; use ::regex::Regex; use ::syn::Ident; use ::quote::Tokens; use ::yaml_rust::Yaml; use infer::method; use infer::TokensResult; fn mod_ident(path: &str) -> Ident { let rustified = path.replace('/', " ").trim().to_snake_case(); let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap(); let ident = re.replace_all(rustified.as_str(), "_${resource}_"); Ident::new(ident) } pub(super) fn infer_v3(path: &str, schema: &Yaml) -> TokensResult { let path_mod = mod_ident(path); let method_schemata = schema.as_hash().expect("Path must be a map."); let mut method_impls: Vec<Tokens> = Vec::new(); let mut path_level_structs = quote!(); for (method, method_schema) in method_schemata { let method = method.as_str().expect("Method must be a string."); let (method_impl, maybe_param_structs) = method::infer_v3(&method, &method_schema)?; method_impls.push(method_impl); if let Some(param_structs) = maybe_param_structs { path_level_structs = param_structs; } } Ok(quote! { #[allow(non_snake_case)] pub mod #path_mod { #[allow(unused_imports)] use ::tapioca::Body; use ::tapioca::Client; use ::tapioca::Url; use ::tapioca::header; use ::tapioca::response::Response; #[allow(unused_imports)] use ::tapioca::query::QueryString; #[allow(unused_imports)] use super::auth_scheme; #[allow(unused_imports)] use super::schema_ref; use super::API_URL; #[allow(unused_imports)] use super::ServerAuth; const API_PATH: &'static str = #path; #path_level_structs #(#method_impls)* } }) } #[cfg(tests)] mod tests { use super::*; #[test] fn leading_slash() { assert_eq!(mod_ident("/foo"), Ident::new("foo")); } #[test] fn both_slash() { assert_eq!(mod_ident("/foo/"), Ident::new("foo")); } #[test] fn no_slash() { assert_eq!(mod_ident("foo"), Ident::new("foo")); } #[test] fn trailing_slash() { assert_eq!(mod_ident("foo/"), Ident::new("foo")); } #[test] fn multipart() { assert_eq!(mod_ident("/foo/bar"), Ident::new("foo_bar")); } #[test] fn resource() { assert_eq!(mod_ident("/foo/{id}"), Ident::new("foo__id_")); } #[test] fn multi_resource() { assert_eq!(mod_ident("/foo/{id}/{bar}"), Ident::new("foo__id___bar_")); } #[test] fn multipart_resource()
#[test] fn multipart_multiresource() { assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_")); } }
{ assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar")); }
identifier_body
path.rs
use ::inflector::Inflector; use ::regex::Regex; use ::syn::Ident; use ::quote::Tokens; use ::yaml_rust::Yaml; use infer::method; use infer::TokensResult; fn mod_ident(path: &str) -> Ident { let rustified = path.replace('/', " ").trim().to_snake_case(); let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap(); let ident = re.replace_all(rustified.as_str(), "_${resource}_"); Ident::new(ident) } pub(super) fn infer_v3(path: &str, schema: &Yaml) -> TokensResult { let path_mod = mod_ident(path); let method_schemata = schema.as_hash().expect("Path must be a map."); let mut method_impls: Vec<Tokens> = Vec::new(); let mut path_level_structs = quote!(); for (method, method_schema) in method_schemata { let method = method.as_str().expect("Method must be a string."); let (method_impl, maybe_param_structs) = method::infer_v3(&method, &method_schema)?; method_impls.push(method_impl); if let Some(param_structs) = maybe_param_structs { path_level_structs = param_structs; } } Ok(quote! { #[allow(non_snake_case)] pub mod #path_mod { #[allow(unused_imports)] use ::tapioca::Body; use ::tapioca::Client; use ::tapioca::Url; use ::tapioca::header; use ::tapioca::response::Response; #[allow(unused_imports)] use ::tapioca::query::QueryString; #[allow(unused_imports)] use super::auth_scheme; #[allow(unused_imports)] use super::schema_ref; use super::API_URL; #[allow(unused_imports)] use super::ServerAuth; const API_PATH: &'static str = #path; #path_level_structs #(#method_impls)* } }) } #[cfg(tests)] mod tests { use super::*; #[test] fn leading_slash() { assert_eq!(mod_ident("/foo"), Ident::new("foo")); } #[test] fn both_slash() { assert_eq!(mod_ident("/foo/"), Ident::new("foo")); } #[test] fn no_slash() { assert_eq!(mod_ident("foo"), Ident::new("foo")); } #[test] fn trailing_slash() { assert_eq!(mod_ident("foo/"), Ident::new("foo")); } #[test] fn multipart() { assert_eq!(mod_ident("/foo/bar"), Ident::new("foo_bar")); } #[test] fn resource() { assert_eq!(mod_ident("/foo/{id}"), Ident::new("foo__id_")); } #[test] fn multi_resource() { assert_eq!(mod_ident("/foo/{id}/{bar}"), Ident::new("foo__id___bar_")); } #[test] fn
() { assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar")); } #[test] fn multipart_multiresource() { assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_")); } }
multipart_resource
identifier_name
where-clauses.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass trait Equal { fn equal(&self, other: &Self) -> bool; fn equals<T,U>(&self, this: &T, that: &T, x: &U, y: &U) -> bool where T: Eq, U: Eq; } impl<T> Equal for T where T: Eq { fn
(&self, other: &T) -> bool { self == other } fn equals<U,X>(&self, this: &U, other: &U, x: &X, y: &X) -> bool where U: Eq, X: Eq { this == other && x == y } } fn equal<T>(x: &T, y: &T) -> bool where T: Eq { x == y } fn main() { println!("{}", equal(&1, &2)); println!("{}", equal(&1, &1)); println!("{}", "hello".equal(&"hello")); println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar")); }
equal
identifier_name
where-clauses.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass trait Equal { fn equal(&self, other: &Self) -> bool; fn equals<T,U>(&self, this: &T, that: &T, x: &U, y: &U) -> bool where T: Eq, U: Eq; } impl<T> Equal for T where T: Eq { fn equal(&self, other: &T) -> bool { self == other } fn equals<U,X>(&self, this: &U, other: &U, x: &X, y: &X) -> bool where U: Eq, X: Eq { this == other && x == y } } fn equal<T>(x: &T, y: &T) -> bool where T: Eq { x == y } fn main()
{ println!("{}", equal(&1, &2)); println!("{}", equal(&1, &1)); println!("{}", "hello".equal(&"hello")); println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar")); }
identifier_body
where-clauses.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass trait Equal { fn equal(&self, other: &Self) -> bool; fn equals<T,U>(&self, this: &T, that: &T, x: &U, y: &U) -> bool where T: Eq, U: Eq;
impl<T> Equal for T where T: Eq { fn equal(&self, other: &T) -> bool { self == other } fn equals<U,X>(&self, this: &U, other: &U, x: &X, y: &X) -> bool where U: Eq, X: Eq { this == other && x == y } } fn equal<T>(x: &T, y: &T) -> bool where T: Eq { x == y } fn main() { println!("{}", equal(&1, &2)); println!("{}", equal(&1, &1)); println!("{}", "hello".equal(&"hello")); println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar")); }
}
random_line_split
completion.rs
//! Completion API use std::borrow::Cow::{self, Borrowed, Owned}; use std::fs; use std::path::{self, Path}; use super::Result; use line_buffer::LineBuffer; use memchr::memchr; // TODO: let the implementers choose/find word boudaries??? // (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion // ("select t.na| from tbl as t") // TODO: make &self &mut self??? /// A completion candidate. pub trait Candidate { /// Text to display when listing alternatives. fn display(&self) -> &str; /// Text to insert in line. fn replacement(&self) -> &str; } impl Candidate for String { fn display(&self) -> &str { self.as_str() } fn replacement(&self) -> &str { self.as_str() } } pub struct Pair { pub display: String, pub replacement: String, } impl Candidate for Pair { fn display(&self) -> &str { self.display.as_str() } fn replacement(&self) -> &str { self.replacement.as_str() } } /// To be called for tab-completion. pub trait Completer { type Candidate: Candidate; /// Takes the currently edited `line` with the cursor `pos`ition and /// returns the start position and the completion candidates for the /// partial word to be completed. /// /// ("ls /usr/loc", 11) => Ok((3, vec!["/usr/local/"])) fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)>; /// Updates the edited `line` with the `elected` candidate. fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { let end = line.pos(); line.replace(start..end, elected) } } impl Completer for () { type Candidate = String; fn complete(&self, _line: &str, _pos: usize) -> Result<(usize, Vec<String>)> { Ok((0, Vec::with_capacity(0))) } fn update(&self, _line: &mut LineBuffer, _start: usize, _elected: &str) { unreachable!() } } impl<'c, C:?Sized + Completer> Completer for &'c C { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } macro_rules! box_completer { ($($id: ident)*) => { $( impl<C:?Sized + Completer> Completer for $id<C> { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } )* } } use std::rc::Rc; use std::sync::Arc; box_completer! { Box Rc Arc } /// A `Completer` for file and folder names. pub struct FilenameCompleter { break_chars: &'static [u8], double_quotes_special_chars: &'static [u8], } static DOUBLE_QUOTES_ESCAPE_CHAR: Option<char> = Some('\\'); // rl_basic_word_break_characters, rl_completer_word_break_characters #[cfg(unix)] static DEFAULT_BREAK_CHARS: [u8; 18] = [ b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(unix)] static ESCAPE_CHAR: Option<char> = Some('\\'); // Remove \ to make file completion works on windows #[cfg(windows)] static DEFAULT_BREAK_CHARS: [u8; 17] = [ b' ', b'\t', b'\n', b'"', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(windows)] static ESCAPE_CHAR: Option<char> = None; // In double quotes, not all break_chars need to be escaped // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html #[cfg(unix)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 4] = [b'"', b'$', b'\\', b'`']; #[cfg(windows)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 1] = [b'"']; // TODO Validate: only '"'? #[derive(Clone, Copy, Debug, PartialEq)] pub enum Quote { Double, Single, None, } impl FilenameCompleter { pub fn new() -> FilenameCompleter { FilenameCompleter { break_chars: &DEFAULT_BREAK_CHARS, double_quotes_special_chars: &DOUBLE_QUOTES_SPECIAL_CHARS, } } } impl Default for FilenameCompleter { fn default() -> FilenameCompleter { FilenameCompleter::new() } } impl Completer for FilenameCompleter { type Candidate = Pair; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Pair>)> { let (start, path, esc_char, break_chars, quote) = if let Some((idx, quote)) = find_unclosed_quote(&line[..pos]) { let start = idx + 1; if quote == Quote::Double { ( start, unescape(&line[start..pos], DOUBLE_QUOTES_ESCAPE_CHAR), DOUBLE_QUOTES_ESCAPE_CHAR, &self.double_quotes_special_chars, quote, ) } else { ( start, Borrowed(&line[start..pos]), None, &self.break_chars, quote, ) } } else { let (start, path) = extract_word(line, pos, ESCAPE_CHAR, &self.break_chars); let path = unescape(path, ESCAPE_CHAR); (start, path, ESCAPE_CHAR, &self.break_chars, Quote::None) }; let matches = try!(filename_complete(&path, esc_char, break_chars, quote)); Ok((start, matches)) } } /// Remove escape char pub fn unescape(input: &str, esc_char: Option<char>) -> Cow<str> { if esc_char.is_none() { return Borrowed(input); } let esc_char = esc_char.unwrap(); if!input.chars().any(|c| c == esc_char) { return Borrowed(input); } let mut result = String::with_capacity(input.len()); let mut chars = input.chars(); while let Some(ch) = chars.next() { if ch == esc_char { if let Some(ch) = chars.next() { if cfg!(windows) && ch!= '"' { // TODO Validate: only '"'? result.push(esc_char); } result.push(ch); } else if cfg!(windows) { result.push(ch); } } else { result.push(ch); } } Owned(result) } /// Escape any `break_chars` in `input` string with `esc_char`. /// For example, '/User Information' becomes '/User\ Information' /// when space is a breaking char and '\\' the escape char. pub fn
( mut input: String, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> String { if quote == Quote::Single { return input; // no escape in single quotes } let n = input .bytes() .filter(|b| memchr(*b, break_chars).is_some()) .count(); if n == 0 { return input; // no need to escape } if esc_char.is_none() { if cfg!(windows) && quote == Quote::None { input.insert(0, '"'); // force double quote return input; } return input; } let esc_char = esc_char.unwrap(); let mut result = String::with_capacity(input.len() + n); for c in input.chars() { if c.is_ascii() && memchr(c as u8, break_chars).is_some() { result.push(esc_char); } result.push(c); } result } fn filename_complete( path: &str, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> Result<Vec<Pair>> { use dirs::home_dir; use std::env::current_dir; let sep = path::MAIN_SEPARATOR; let (dir_name, file_name) = match path.rfind(sep) { Some(idx) => path.split_at(idx + sep.len_utf8()), None => ("", path), }; let dir_path = Path::new(dir_name); let dir = if dir_path.starts_with("~") { // ~[/...] if let Some(home) = home_dir() { match dir_path.strip_prefix("~") { Ok(rel_path) => home.join(rel_path), _ => home, } } else { dir_path.to_path_buf() } } else if dir_path.is_relative() { // TODO ~user[/...] (https://crates.io/crates/users) if let Ok(cwd) = current_dir() { cwd.join(dir_path) } else { dir_path.to_path_buf() } } else { dir_path.to_path_buf() }; let mut entries: Vec<Pair> = Vec::new(); for entry in try!(dir.read_dir()) { let entry = try!(entry); if let Some(s) = entry.file_name().to_str() { if s.starts_with(file_name) { if let Ok(metadata) = fs::metadata(entry.path()) { let mut path = String::from(dir_name) + s; if metadata.is_dir() { path.push(sep); } entries.push(Pair { display: String::from(s), replacement: escape(path, esc_char, break_chars, quote), }); } // else ignore PermissionDenied } } } Ok(entries) } /// Given a `line` and a cursor `pos`ition, /// try to find backward the start of a word. /// Return (0, `line[..pos]`) if no break char has been found. /// Return the word and its start position (idx, `line[idx..pos]`) otherwise. pub fn extract_word<'l>( line: &'l str, pos: usize, esc_char: Option<char>, break_chars: &[u8], ) -> (usize, &'l str) { let line = &line[..pos]; if line.is_empty() { return (0, line); } let mut start = None; for (i, c) in line.char_indices().rev() { if esc_char.is_some() && start.is_some() { if esc_char.unwrap() == c { // escaped break char start = None; continue; } else { break; } } if c.is_ascii() && memchr(c as u8, break_chars).is_some() { start = Some(i + c.len_utf8()); if esc_char.is_none() { break; } // else maybe escaped... } } match start { Some(start) => (start, &line[start..]), None => (0, line), } } pub fn longest_common_prefix<C: Candidate>(candidates: &[C]) -> Option<&str> { if candidates.is_empty() { return None; } else if candidates.len() == 1 { return Some(&candidates[0].replacement()); } let mut longest_common_prefix = 0; 'o: loop { for (i, c1) in candidates.iter().enumerate().take(candidates.len() - 1) { let b1 = c1.replacement().as_bytes(); let b2 = candidates[i + 1].replacement().as_bytes(); if b1.len() <= longest_common_prefix || b2.len() <= longest_common_prefix || b1[longest_common_prefix]!= b2[longest_common_prefix] { break 'o; } } longest_common_prefix += 1; } let candidate = candidates[0].replacement(); while!candidate.is_char_boundary(longest_common_prefix) { longest_common_prefix -= 1; } if longest_common_prefix == 0 { return None; } Some(&candidate[0..longest_common_prefix]) } #[derive(PartialEq)] enum ScanMode { DoubleQuote, Escape, EscapeInDoubleQuote, Normal, SingleQuote, } /// try to find an unclosed single/double quote in `s`. /// Return `None` if no unclosed quote is found. /// Return the unclosed quote position and if it is a double quote. fn find_unclosed_quote(s: &str) -> Option<(usize, Quote)> { let char_indices = s.char_indices(); let mut mode = ScanMode::Normal; let mut quote_index = 0; for (index, char) in char_indices { match mode { ScanMode::DoubleQuote => { if char == '"' { mode = ScanMode::Normal; } else if char == '\\' { // both windows and unix support escape in double quote mode = ScanMode::EscapeInDoubleQuote; } } ScanMode::Escape => { mode = ScanMode::Normal; } ScanMode::EscapeInDoubleQuote => { mode = ScanMode::DoubleQuote; } ScanMode::Normal => { if char == '"' { mode = ScanMode::DoubleQuote; quote_index = index; } else if char == '\\' && cfg!(not(windows)) { mode = ScanMode::Escape; } else if char == '\'' && cfg!(not(windows)) { mode = ScanMode::SingleQuote; quote_index = index; } } ScanMode::SingleQuote => { if char == '\'' { mode = ScanMode::Normal; } // no escape in single quotes } }; } if ScanMode::DoubleQuote == mode || ScanMode::EscapeInDoubleQuote == mode { return Some((quote_index, Quote::Double)); } else if ScanMode::SingleQuote == mode { return Some((quote_index, Quote::Single)); } None } #[cfg(test)] mod tests { #[test] pub fn extract_word() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let line = "ls '/usr/local/b"; assert_eq!( (4, "/usr/local/b"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); let line = "ls /User\\ Information"; assert_eq!( (3, "/User\\ Information"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); } #[test] pub fn unescape() { use std::borrow::Cow::{self, Borrowed, Owned}; let input = "/usr/local/b"; assert_eq!(Borrowed(input), super::unescape(input, Some('\\'))); if cfg!(windows) { let input = "c:\\users\\All Users\\"; let result: Cow<str> = Borrowed(input); assert_eq!(result, super::unescape(input, Some('\\'))); } else { let input = "/User\\ Information"; let result: Cow<str> = Owned(String::from("/User Information")); assert_eq!(result, super::unescape(input, Some('\\'))); } } #[test] pub fn escape() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let input = String::from("/usr/local/b"); assert_eq!( input.clone(), super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); let input = String::from("/User Information"); let result = String::from("/User\\ Information"); assert_eq!( result, super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); } #[test] pub fn longest_common_prefix() { let mut candidates = vec![]; { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let s = "User"; let c1 = String::from(s); candidates.push(c1.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c2 = String::from("Users"); candidates.push(c2.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c3 = String::from(""); candidates.push(c3.clone()); { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let candidates = vec![String::from("fée"), String::from("fête")]; let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some("f"), lcp); } #[test] pub fn find_unclosed_quote() { assert_eq!(None, super::find_unclosed_quote("ls /etc")); assert_eq!( Some((3, super::Quote::Double)), super::find_unclosed_quote("ls \"User Information") ); assert_eq!( None, super::find_unclosed_quote("ls \"/User Information\" /etc") ); assert_eq!( Some((0, super::Quote::Double)), super::find_unclosed_quote("\"c:\\users\\All Users\\") ) } }
escape
identifier_name
completion.rs
//! Completion API use std::borrow::Cow::{self, Borrowed, Owned}; use std::fs; use std::path::{self, Path}; use super::Result; use line_buffer::LineBuffer; use memchr::memchr; // TODO: let the implementers choose/find word boudaries??? // (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion // ("select t.na| from tbl as t") // TODO: make &self &mut self??? /// A completion candidate. pub trait Candidate { /// Text to display when listing alternatives. fn display(&self) -> &str; /// Text to insert in line. fn replacement(&self) -> &str; } impl Candidate for String { fn display(&self) -> &str { self.as_str() } fn replacement(&self) -> &str { self.as_str() } } pub struct Pair { pub display: String, pub replacement: String, } impl Candidate for Pair { fn display(&self) -> &str { self.display.as_str() } fn replacement(&self) -> &str { self.replacement.as_str() } } /// To be called for tab-completion. pub trait Completer { type Candidate: Candidate; /// Takes the currently edited `line` with the cursor `pos`ition and /// returns the start position and the completion candidates for the /// partial word to be completed. /// /// ("ls /usr/loc", 11) => Ok((3, vec!["/usr/local/"])) fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)>; /// Updates the edited `line` with the `elected` candidate. fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { let end = line.pos(); line.replace(start..end, elected) } } impl Completer for () { type Candidate = String; fn complete(&self, _line: &str, _pos: usize) -> Result<(usize, Vec<String>)> { Ok((0, Vec::with_capacity(0))) } fn update(&self, _line: &mut LineBuffer, _start: usize, _elected: &str) { unreachable!() } } impl<'c, C:?Sized + Completer> Completer for &'c C { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } macro_rules! box_completer { ($($id: ident)*) => { $( impl<C:?Sized + Completer> Completer for $id<C> { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } )* } } use std::rc::Rc; use std::sync::Arc; box_completer! { Box Rc Arc } /// A `Completer` for file and folder names. pub struct FilenameCompleter { break_chars: &'static [u8], double_quotes_special_chars: &'static [u8], } static DOUBLE_QUOTES_ESCAPE_CHAR: Option<char> = Some('\\'); // rl_basic_word_break_characters, rl_completer_word_break_characters #[cfg(unix)] static DEFAULT_BREAK_CHARS: [u8; 18] = [ b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(unix)] static ESCAPE_CHAR: Option<char> = Some('\\'); // Remove \ to make file completion works on windows #[cfg(windows)] static DEFAULT_BREAK_CHARS: [u8; 17] = [ b' ', b'\t', b'\n', b'"', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(windows)] static ESCAPE_CHAR: Option<char> = None; // In double quotes, not all break_chars need to be escaped // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html #[cfg(unix)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 4] = [b'"', b'$', b'\\', b'`']; #[cfg(windows)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 1] = [b'"']; // TODO Validate: only '"'? #[derive(Clone, Copy, Debug, PartialEq)] pub enum Quote { Double, Single, None, } impl FilenameCompleter { pub fn new() -> FilenameCompleter { FilenameCompleter { break_chars: &DEFAULT_BREAK_CHARS, double_quotes_special_chars: &DOUBLE_QUOTES_SPECIAL_CHARS, } } } impl Default for FilenameCompleter { fn default() -> FilenameCompleter { FilenameCompleter::new() } } impl Completer for FilenameCompleter { type Candidate = Pair; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Pair>)> { let (start, path, esc_char, break_chars, quote) = if let Some((idx, quote)) = find_unclosed_quote(&line[..pos]) { let start = idx + 1; if quote == Quote::Double { ( start, unescape(&line[start..pos], DOUBLE_QUOTES_ESCAPE_CHAR), DOUBLE_QUOTES_ESCAPE_CHAR, &self.double_quotes_special_chars, quote, ) } else { ( start, Borrowed(&line[start..pos]), None, &self.break_chars, quote, ) } } else { let (start, path) = extract_word(line, pos, ESCAPE_CHAR, &self.break_chars); let path = unescape(path, ESCAPE_CHAR); (start, path, ESCAPE_CHAR, &self.break_chars, Quote::None) }; let matches = try!(filename_complete(&path, esc_char, break_chars, quote)); Ok((start, matches)) } } /// Remove escape char pub fn unescape(input: &str, esc_char: Option<char>) -> Cow<str> { if esc_char.is_none() { return Borrowed(input); } let esc_char = esc_char.unwrap(); if!input.chars().any(|c| c == esc_char) { return Borrowed(input); } let mut result = String::with_capacity(input.len()); let mut chars = input.chars(); while let Some(ch) = chars.next() { if ch == esc_char { if let Some(ch) = chars.next() { if cfg!(windows) && ch!= '"' { // TODO Validate: only '"'? result.push(esc_char); } result.push(ch); } else if cfg!(windows) { result.push(ch); } } else { result.push(ch); } } Owned(result) } /// Escape any `break_chars` in `input` string with `esc_char`. /// For example, '/User Information' becomes '/User\ Information' /// when space is a breaking char and '\\' the escape char. pub fn escape( mut input: String, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> String { if quote == Quote::Single { return input; // no escape in single quotes } let n = input .bytes() .filter(|b| memchr(*b, break_chars).is_some()) .count(); if n == 0 { return input; // no need to escape } if esc_char.is_none() { if cfg!(windows) && quote == Quote::None { input.insert(0, '"'); // force double quote return input; } return input; } let esc_char = esc_char.unwrap(); let mut result = String::with_capacity(input.len() + n); for c in input.chars() { if c.is_ascii() && memchr(c as u8, break_chars).is_some() { result.push(esc_char); } result.push(c); } result } fn filename_complete( path: &str, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> Result<Vec<Pair>> { use dirs::home_dir; use std::env::current_dir; let sep = path::MAIN_SEPARATOR; let (dir_name, file_name) = match path.rfind(sep) { Some(idx) => path.split_at(idx + sep.len_utf8()), None => ("", path), }; let dir_path = Path::new(dir_name); let dir = if dir_path.starts_with("~") { // ~[/...] if let Some(home) = home_dir() { match dir_path.strip_prefix("~") { Ok(rel_path) => home.join(rel_path), _ => home, } } else { dir_path.to_path_buf() } } else if dir_path.is_relative() { // TODO ~user[/...] (https://crates.io/crates/users) if let Ok(cwd) = current_dir() { cwd.join(dir_path) } else { dir_path.to_path_buf() } } else { dir_path.to_path_buf() }; let mut entries: Vec<Pair> = Vec::new(); for entry in try!(dir.read_dir()) { let entry = try!(entry); if let Some(s) = entry.file_name().to_str() { if s.starts_with(file_name) { if let Ok(metadata) = fs::metadata(entry.path()) { let mut path = String::from(dir_name) + s; if metadata.is_dir() { path.push(sep); } entries.push(Pair { display: String::from(s), replacement: escape(path, esc_char, break_chars, quote), }); } // else ignore PermissionDenied } } } Ok(entries) } /// Given a `line` and a cursor `pos`ition, /// try to find backward the start of a word. /// Return (0, `line[..pos]`) if no break char has been found. /// Return the word and its start position (idx, `line[idx..pos]`) otherwise. pub fn extract_word<'l>( line: &'l str, pos: usize, esc_char: Option<char>, break_chars: &[u8], ) -> (usize, &'l str) { let line = &line[..pos]; if line.is_empty() { return (0, line); } let mut start = None; for (i, c) in line.char_indices().rev() { if esc_char.is_some() && start.is_some() { if esc_char.unwrap() == c { // escaped break char start = None; continue; } else { break; } } if c.is_ascii() && memchr(c as u8, break_chars).is_some() { start = Some(i + c.len_utf8()); if esc_char.is_none() { break; } // else maybe escaped... } } match start { Some(start) => (start, &line[start..]), None => (0, line), } } pub fn longest_common_prefix<C: Candidate>(candidates: &[C]) -> Option<&str> { if candidates.is_empty() { return None; } else if candidates.len() == 1 { return Some(&candidates[0].replacement()); } let mut longest_common_prefix = 0; 'o: loop { for (i, c1) in candidates.iter().enumerate().take(candidates.len() - 1) { let b1 = c1.replacement().as_bytes(); let b2 = candidates[i + 1].replacement().as_bytes(); if b1.len() <= longest_common_prefix || b2.len() <= longest_common_prefix || b1[longest_common_prefix]!= b2[longest_common_prefix] { break 'o; } } longest_common_prefix += 1; } let candidate = candidates[0].replacement(); while!candidate.is_char_boundary(longest_common_prefix) { longest_common_prefix -= 1; } if longest_common_prefix == 0 { return None; } Some(&candidate[0..longest_common_prefix]) } #[derive(PartialEq)] enum ScanMode { DoubleQuote, Escape, EscapeInDoubleQuote, Normal, SingleQuote, } /// try to find an unclosed single/double quote in `s`. /// Return `None` if no unclosed quote is found. /// Return the unclosed quote position and if it is a double quote. fn find_unclosed_quote(s: &str) -> Option<(usize, Quote)> { let char_indices = s.char_indices(); let mut mode = ScanMode::Normal; let mut quote_index = 0; for (index, char) in char_indices { match mode { ScanMode::DoubleQuote => { if char == '"' { mode = ScanMode::Normal; } else if char == '\\' { // both windows and unix support escape in double quote mode = ScanMode::EscapeInDoubleQuote; } } ScanMode::Escape => { mode = ScanMode::Normal; } ScanMode::EscapeInDoubleQuote => { mode = ScanMode::DoubleQuote; } ScanMode::Normal => { if char == '"' { mode = ScanMode::DoubleQuote; quote_index = index; } else if char == '\\' && cfg!(not(windows)) { mode = ScanMode::Escape; } else if char == '\'' && cfg!(not(windows)) { mode = ScanMode::SingleQuote; quote_index = index; } } ScanMode::SingleQuote => { if char == '\'' { mode = ScanMode::Normal; } // no escape in single quotes } }; } if ScanMode::DoubleQuote == mode || ScanMode::EscapeInDoubleQuote == mode { return Some((quote_index, Quote::Double)); } else if ScanMode::SingleQuote == mode { return Some((quote_index, Quote::Single)); } None } #[cfg(test)] mod tests { #[test] pub fn extract_word() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let line = "ls '/usr/local/b"; assert_eq!( (4, "/usr/local/b"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); let line = "ls /User\\ Information"; assert_eq!( (3, "/User\\ Information"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); } #[test] pub fn unescape() { use std::borrow::Cow::{self, Borrowed, Owned}; let input = "/usr/local/b"; assert_eq!(Borrowed(input), super::unescape(input, Some('\\'))); if cfg!(windows) { let input = "c:\\users\\All Users\\"; let result: Cow<str> = Borrowed(input); assert_eq!(result, super::unescape(input, Some('\\'))); } else { let input = "/User\\ Information"; let result: Cow<str> = Owned(String::from("/User Information")); assert_eq!(result, super::unescape(input, Some('\\'))); } } #[test] pub fn escape() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let input = String::from("/usr/local/b"); assert_eq!( input.clone(), super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); let input = String::from("/User Information"); let result = String::from("/User\\ Information"); assert_eq!( result, super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); } #[test] pub fn longest_common_prefix() { let mut candidates = vec![]; { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let s = "User"; let c1 = String::from(s); candidates.push(c1.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c2 = String::from("Users"); candidates.push(c2.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c3 = String::from(""); candidates.push(c3.clone()); { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let candidates = vec![String::from("fée"), String::from("fête")]; let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some("f"), lcp); } #[test] pub fn find_unclosed_quote() { assert_eq!(None, super::find_unclosed_quote("ls /etc")); assert_eq!( Some((3, super::Quote::Double)), super::find_unclosed_quote("ls \"User Information") ); assert_eq!( None, super::find_unclosed_quote("ls \"/User Information\" /etc")
); assert_eq!( Some((0, super::Quote::Double)), super::find_unclosed_quote("\"c:\\users\\All Users\\") ) } }
random_line_split
completion.rs
//! Completion API use std::borrow::Cow::{self, Borrowed, Owned}; use std::fs; use std::path::{self, Path}; use super::Result; use line_buffer::LineBuffer; use memchr::memchr; // TODO: let the implementers choose/find word boudaries??? // (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion // ("select t.na| from tbl as t") // TODO: make &self &mut self??? /// A completion candidate. pub trait Candidate { /// Text to display when listing alternatives. fn display(&self) -> &str; /// Text to insert in line. fn replacement(&self) -> &str; } impl Candidate for String { fn display(&self) -> &str { self.as_str() } fn replacement(&self) -> &str { self.as_str() } } pub struct Pair { pub display: String, pub replacement: String, } impl Candidate for Pair { fn display(&self) -> &str { self.display.as_str() } fn replacement(&self) -> &str { self.replacement.as_str() } } /// To be called for tab-completion. pub trait Completer { type Candidate: Candidate; /// Takes the currently edited `line` with the cursor `pos`ition and /// returns the start position and the completion candidates for the /// partial word to be completed. /// /// ("ls /usr/loc", 11) => Ok((3, vec!["/usr/local/"])) fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)>; /// Updates the edited `line` with the `elected` candidate. fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { let end = line.pos(); line.replace(start..end, elected) } } impl Completer for () { type Candidate = String; fn complete(&self, _line: &str, _pos: usize) -> Result<(usize, Vec<String>)> { Ok((0, Vec::with_capacity(0))) } fn update(&self, _line: &mut LineBuffer, _start: usize, _elected: &str)
} impl<'c, C:?Sized + Completer> Completer for &'c C { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } macro_rules! box_completer { ($($id: ident)*) => { $( impl<C:?Sized + Completer> Completer for $id<C> { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } )* } } use std::rc::Rc; use std::sync::Arc; box_completer! { Box Rc Arc } /// A `Completer` for file and folder names. pub struct FilenameCompleter { break_chars: &'static [u8], double_quotes_special_chars: &'static [u8], } static DOUBLE_QUOTES_ESCAPE_CHAR: Option<char> = Some('\\'); // rl_basic_word_break_characters, rl_completer_word_break_characters #[cfg(unix)] static DEFAULT_BREAK_CHARS: [u8; 18] = [ b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(unix)] static ESCAPE_CHAR: Option<char> = Some('\\'); // Remove \ to make file completion works on windows #[cfg(windows)] static DEFAULT_BREAK_CHARS: [u8; 17] = [ b' ', b'\t', b'\n', b'"', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(windows)] static ESCAPE_CHAR: Option<char> = None; // In double quotes, not all break_chars need to be escaped // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html #[cfg(unix)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 4] = [b'"', b'$', b'\\', b'`']; #[cfg(windows)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 1] = [b'"']; // TODO Validate: only '"'? #[derive(Clone, Copy, Debug, PartialEq)] pub enum Quote { Double, Single, None, } impl FilenameCompleter { pub fn new() -> FilenameCompleter { FilenameCompleter { break_chars: &DEFAULT_BREAK_CHARS, double_quotes_special_chars: &DOUBLE_QUOTES_SPECIAL_CHARS, } } } impl Default for FilenameCompleter { fn default() -> FilenameCompleter { FilenameCompleter::new() } } impl Completer for FilenameCompleter { type Candidate = Pair; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Pair>)> { let (start, path, esc_char, break_chars, quote) = if let Some((idx, quote)) = find_unclosed_quote(&line[..pos]) { let start = idx + 1; if quote == Quote::Double { ( start, unescape(&line[start..pos], DOUBLE_QUOTES_ESCAPE_CHAR), DOUBLE_QUOTES_ESCAPE_CHAR, &self.double_quotes_special_chars, quote, ) } else { ( start, Borrowed(&line[start..pos]), None, &self.break_chars, quote, ) } } else { let (start, path) = extract_word(line, pos, ESCAPE_CHAR, &self.break_chars); let path = unescape(path, ESCAPE_CHAR); (start, path, ESCAPE_CHAR, &self.break_chars, Quote::None) }; let matches = try!(filename_complete(&path, esc_char, break_chars, quote)); Ok((start, matches)) } } /// Remove escape char pub fn unescape(input: &str, esc_char: Option<char>) -> Cow<str> { if esc_char.is_none() { return Borrowed(input); } let esc_char = esc_char.unwrap(); if!input.chars().any(|c| c == esc_char) { return Borrowed(input); } let mut result = String::with_capacity(input.len()); let mut chars = input.chars(); while let Some(ch) = chars.next() { if ch == esc_char { if let Some(ch) = chars.next() { if cfg!(windows) && ch!= '"' { // TODO Validate: only '"'? result.push(esc_char); } result.push(ch); } else if cfg!(windows) { result.push(ch); } } else { result.push(ch); } } Owned(result) } /// Escape any `break_chars` in `input` string with `esc_char`. /// For example, '/User Information' becomes '/User\ Information' /// when space is a breaking char and '\\' the escape char. pub fn escape( mut input: String, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> String { if quote == Quote::Single { return input; // no escape in single quotes } let n = input .bytes() .filter(|b| memchr(*b, break_chars).is_some()) .count(); if n == 0 { return input; // no need to escape } if esc_char.is_none() { if cfg!(windows) && quote == Quote::None { input.insert(0, '"'); // force double quote return input; } return input; } let esc_char = esc_char.unwrap(); let mut result = String::with_capacity(input.len() + n); for c in input.chars() { if c.is_ascii() && memchr(c as u8, break_chars).is_some() { result.push(esc_char); } result.push(c); } result } fn filename_complete( path: &str, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> Result<Vec<Pair>> { use dirs::home_dir; use std::env::current_dir; let sep = path::MAIN_SEPARATOR; let (dir_name, file_name) = match path.rfind(sep) { Some(idx) => path.split_at(idx + sep.len_utf8()), None => ("", path), }; let dir_path = Path::new(dir_name); let dir = if dir_path.starts_with("~") { // ~[/...] if let Some(home) = home_dir() { match dir_path.strip_prefix("~") { Ok(rel_path) => home.join(rel_path), _ => home, } } else { dir_path.to_path_buf() } } else if dir_path.is_relative() { // TODO ~user[/...] (https://crates.io/crates/users) if let Ok(cwd) = current_dir() { cwd.join(dir_path) } else { dir_path.to_path_buf() } } else { dir_path.to_path_buf() }; let mut entries: Vec<Pair> = Vec::new(); for entry in try!(dir.read_dir()) { let entry = try!(entry); if let Some(s) = entry.file_name().to_str() { if s.starts_with(file_name) { if let Ok(metadata) = fs::metadata(entry.path()) { let mut path = String::from(dir_name) + s; if metadata.is_dir() { path.push(sep); } entries.push(Pair { display: String::from(s), replacement: escape(path, esc_char, break_chars, quote), }); } // else ignore PermissionDenied } } } Ok(entries) } /// Given a `line` and a cursor `pos`ition, /// try to find backward the start of a word. /// Return (0, `line[..pos]`) if no break char has been found. /// Return the word and its start position (idx, `line[idx..pos]`) otherwise. pub fn extract_word<'l>( line: &'l str, pos: usize, esc_char: Option<char>, break_chars: &[u8], ) -> (usize, &'l str) { let line = &line[..pos]; if line.is_empty() { return (0, line); } let mut start = None; for (i, c) in line.char_indices().rev() { if esc_char.is_some() && start.is_some() { if esc_char.unwrap() == c { // escaped break char start = None; continue; } else { break; } } if c.is_ascii() && memchr(c as u8, break_chars).is_some() { start = Some(i + c.len_utf8()); if esc_char.is_none() { break; } // else maybe escaped... } } match start { Some(start) => (start, &line[start..]), None => (0, line), } } pub fn longest_common_prefix<C: Candidate>(candidates: &[C]) -> Option<&str> { if candidates.is_empty() { return None; } else if candidates.len() == 1 { return Some(&candidates[0].replacement()); } let mut longest_common_prefix = 0; 'o: loop { for (i, c1) in candidates.iter().enumerate().take(candidates.len() - 1) { let b1 = c1.replacement().as_bytes(); let b2 = candidates[i + 1].replacement().as_bytes(); if b1.len() <= longest_common_prefix || b2.len() <= longest_common_prefix || b1[longest_common_prefix]!= b2[longest_common_prefix] { break 'o; } } longest_common_prefix += 1; } let candidate = candidates[0].replacement(); while!candidate.is_char_boundary(longest_common_prefix) { longest_common_prefix -= 1; } if longest_common_prefix == 0 { return None; } Some(&candidate[0..longest_common_prefix]) } #[derive(PartialEq)] enum ScanMode { DoubleQuote, Escape, EscapeInDoubleQuote, Normal, SingleQuote, } /// try to find an unclosed single/double quote in `s`. /// Return `None` if no unclosed quote is found. /// Return the unclosed quote position and if it is a double quote. fn find_unclosed_quote(s: &str) -> Option<(usize, Quote)> { let char_indices = s.char_indices(); let mut mode = ScanMode::Normal; let mut quote_index = 0; for (index, char) in char_indices { match mode { ScanMode::DoubleQuote => { if char == '"' { mode = ScanMode::Normal; } else if char == '\\' { // both windows and unix support escape in double quote mode = ScanMode::EscapeInDoubleQuote; } } ScanMode::Escape => { mode = ScanMode::Normal; } ScanMode::EscapeInDoubleQuote => { mode = ScanMode::DoubleQuote; } ScanMode::Normal => { if char == '"' { mode = ScanMode::DoubleQuote; quote_index = index; } else if char == '\\' && cfg!(not(windows)) { mode = ScanMode::Escape; } else if char == '\'' && cfg!(not(windows)) { mode = ScanMode::SingleQuote; quote_index = index; } } ScanMode::SingleQuote => { if char == '\'' { mode = ScanMode::Normal; } // no escape in single quotes } }; } if ScanMode::DoubleQuote == mode || ScanMode::EscapeInDoubleQuote == mode { return Some((quote_index, Quote::Double)); } else if ScanMode::SingleQuote == mode { return Some((quote_index, Quote::Single)); } None } #[cfg(test)] mod tests { #[test] pub fn extract_word() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let line = "ls '/usr/local/b"; assert_eq!( (4, "/usr/local/b"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); let line = "ls /User\\ Information"; assert_eq!( (3, "/User\\ Information"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); } #[test] pub fn unescape() { use std::borrow::Cow::{self, Borrowed, Owned}; let input = "/usr/local/b"; assert_eq!(Borrowed(input), super::unescape(input, Some('\\'))); if cfg!(windows) { let input = "c:\\users\\All Users\\"; let result: Cow<str> = Borrowed(input); assert_eq!(result, super::unescape(input, Some('\\'))); } else { let input = "/User\\ Information"; let result: Cow<str> = Owned(String::from("/User Information")); assert_eq!(result, super::unescape(input, Some('\\'))); } } #[test] pub fn escape() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let input = String::from("/usr/local/b"); assert_eq!( input.clone(), super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); let input = String::from("/User Information"); let result = String::from("/User\\ Information"); assert_eq!( result, super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); } #[test] pub fn longest_common_prefix() { let mut candidates = vec![]; { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let s = "User"; let c1 = String::from(s); candidates.push(c1.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c2 = String::from("Users"); candidates.push(c2.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c3 = String::from(""); candidates.push(c3.clone()); { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let candidates = vec![String::from("fée"), String::from("fête")]; let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some("f"), lcp); } #[test] pub fn find_unclosed_quote() { assert_eq!(None, super::find_unclosed_quote("ls /etc")); assert_eq!( Some((3, super::Quote::Double)), super::find_unclosed_quote("ls \"User Information") ); assert_eq!( None, super::find_unclosed_quote("ls \"/User Information\" /etc") ); assert_eq!( Some((0, super::Quote::Double)), super::find_unclosed_quote("\"c:\\users\\All Users\\") ) } }
{ unreachable!() }
identifier_body
completion.rs
//! Completion API use std::borrow::Cow::{self, Borrowed, Owned}; use std::fs; use std::path::{self, Path}; use super::Result; use line_buffer::LineBuffer; use memchr::memchr; // TODO: let the implementers choose/find word boudaries??? // (line, pos) is like (rl_line_buffer, rl_point) to make contextual completion // ("select t.na| from tbl as t") // TODO: make &self &mut self??? /// A completion candidate. pub trait Candidate { /// Text to display when listing alternatives. fn display(&self) -> &str; /// Text to insert in line. fn replacement(&self) -> &str; } impl Candidate for String { fn display(&self) -> &str { self.as_str() } fn replacement(&self) -> &str { self.as_str() } } pub struct Pair { pub display: String, pub replacement: String, } impl Candidate for Pair { fn display(&self) -> &str { self.display.as_str() } fn replacement(&self) -> &str { self.replacement.as_str() } } /// To be called for tab-completion. pub trait Completer { type Candidate: Candidate; /// Takes the currently edited `line` with the cursor `pos`ition and /// returns the start position and the completion candidates for the /// partial word to be completed. /// /// ("ls /usr/loc", 11) => Ok((3, vec!["/usr/local/"])) fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)>; /// Updates the edited `line` with the `elected` candidate. fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { let end = line.pos(); line.replace(start..end, elected) } } impl Completer for () { type Candidate = String; fn complete(&self, _line: &str, _pos: usize) -> Result<(usize, Vec<String>)> { Ok((0, Vec::with_capacity(0))) } fn update(&self, _line: &mut LineBuffer, _start: usize, _elected: &str) { unreachable!() } } impl<'c, C:?Sized + Completer> Completer for &'c C { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } macro_rules! box_completer { ($($id: ident)*) => { $( impl<C:?Sized + Completer> Completer for $id<C> { type Candidate = C::Candidate; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> { (**self).complete(line, pos) } fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) { (**self).update(line, start, elected) } } )* } } use std::rc::Rc; use std::sync::Arc; box_completer! { Box Rc Arc } /// A `Completer` for file and folder names. pub struct FilenameCompleter { break_chars: &'static [u8], double_quotes_special_chars: &'static [u8], } static DOUBLE_QUOTES_ESCAPE_CHAR: Option<char> = Some('\\'); // rl_basic_word_break_characters, rl_completer_word_break_characters #[cfg(unix)] static DEFAULT_BREAK_CHARS: [u8; 18] = [ b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(unix)] static ESCAPE_CHAR: Option<char> = Some('\\'); // Remove \ to make file completion works on windows #[cfg(windows)] static DEFAULT_BREAK_CHARS: [u8; 17] = [ b' ', b'\t', b'\n', b'"', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(windows)] static ESCAPE_CHAR: Option<char> = None; // In double quotes, not all break_chars need to be escaped // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html #[cfg(unix)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 4] = [b'"', b'$', b'\\', b'`']; #[cfg(windows)] static DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 1] = [b'"']; // TODO Validate: only '"'? #[derive(Clone, Copy, Debug, PartialEq)] pub enum Quote { Double, Single, None, } impl FilenameCompleter { pub fn new() -> FilenameCompleter { FilenameCompleter { break_chars: &DEFAULT_BREAK_CHARS, double_quotes_special_chars: &DOUBLE_QUOTES_SPECIAL_CHARS, } } } impl Default for FilenameCompleter { fn default() -> FilenameCompleter { FilenameCompleter::new() } } impl Completer for FilenameCompleter { type Candidate = Pair; fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Pair>)> { let (start, path, esc_char, break_chars, quote) = if let Some((idx, quote)) = find_unclosed_quote(&line[..pos]) { let start = idx + 1; if quote == Quote::Double { ( start, unescape(&line[start..pos], DOUBLE_QUOTES_ESCAPE_CHAR), DOUBLE_QUOTES_ESCAPE_CHAR, &self.double_quotes_special_chars, quote, ) } else { ( start, Borrowed(&line[start..pos]), None, &self.break_chars, quote, ) } } else { let (start, path) = extract_word(line, pos, ESCAPE_CHAR, &self.break_chars); let path = unescape(path, ESCAPE_CHAR); (start, path, ESCAPE_CHAR, &self.break_chars, Quote::None) }; let matches = try!(filename_complete(&path, esc_char, break_chars, quote)); Ok((start, matches)) } } /// Remove escape char pub fn unescape(input: &str, esc_char: Option<char>) -> Cow<str> { if esc_char.is_none() { return Borrowed(input); } let esc_char = esc_char.unwrap(); if!input.chars().any(|c| c == esc_char) { return Borrowed(input); } let mut result = String::with_capacity(input.len()); let mut chars = input.chars(); while let Some(ch) = chars.next() { if ch == esc_char { if let Some(ch) = chars.next() { if cfg!(windows) && ch!= '"' { // TODO Validate: only '"'? result.push(esc_char); } result.push(ch); } else if cfg!(windows) { result.push(ch); } } else { result.push(ch); } } Owned(result) } /// Escape any `break_chars` in `input` string with `esc_char`. /// For example, '/User Information' becomes '/User\ Information' /// when space is a breaking char and '\\' the escape char. pub fn escape( mut input: String, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> String { if quote == Quote::Single { return input; // no escape in single quotes } let n = input .bytes() .filter(|b| memchr(*b, break_chars).is_some()) .count(); if n == 0 { return input; // no need to escape } if esc_char.is_none() { if cfg!(windows) && quote == Quote::None { input.insert(0, '"'); // force double quote return input; } return input; } let esc_char = esc_char.unwrap(); let mut result = String::with_capacity(input.len() + n); for c in input.chars() { if c.is_ascii() && memchr(c as u8, break_chars).is_some() { result.push(esc_char); } result.push(c); } result } fn filename_complete( path: &str, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> Result<Vec<Pair>> { use dirs::home_dir; use std::env::current_dir; let sep = path::MAIN_SEPARATOR; let (dir_name, file_name) = match path.rfind(sep) { Some(idx) => path.split_at(idx + sep.len_utf8()), None => ("", path), }; let dir_path = Path::new(dir_name); let dir = if dir_path.starts_with("~") { // ~[/...] if let Some(home) = home_dir() { match dir_path.strip_prefix("~") { Ok(rel_path) => home.join(rel_path), _ => home, } } else { dir_path.to_path_buf() } } else if dir_path.is_relative() { // TODO ~user[/...] (https://crates.io/crates/users) if let Ok(cwd) = current_dir() { cwd.join(dir_path) } else { dir_path.to_path_buf() } } else { dir_path.to_path_buf() }; let mut entries: Vec<Pair> = Vec::new(); for entry in try!(dir.read_dir()) { let entry = try!(entry); if let Some(s) = entry.file_name().to_str() { if s.starts_with(file_name) { if let Ok(metadata) = fs::metadata(entry.path()) { let mut path = String::from(dir_name) + s; if metadata.is_dir() { path.push(sep); } entries.push(Pair { display: String::from(s), replacement: escape(path, esc_char, break_chars, quote), }); } // else ignore PermissionDenied } } } Ok(entries) } /// Given a `line` and a cursor `pos`ition, /// try to find backward the start of a word. /// Return (0, `line[..pos]`) if no break char has been found. /// Return the word and its start position (idx, `line[idx..pos]`) otherwise. pub fn extract_word<'l>( line: &'l str, pos: usize, esc_char: Option<char>, break_chars: &[u8], ) -> (usize, &'l str) { let line = &line[..pos]; if line.is_empty() { return (0, line); } let mut start = None; for (i, c) in line.char_indices().rev() { if esc_char.is_some() && start.is_some() { if esc_char.unwrap() == c { // escaped break char start = None; continue; } else { break; } } if c.is_ascii() && memchr(c as u8, break_chars).is_some() { start = Some(i + c.len_utf8()); if esc_char.is_none() { break; } // else maybe escaped... } } match start { Some(start) => (start, &line[start..]), None => (0, line), } } pub fn longest_common_prefix<C: Candidate>(candidates: &[C]) -> Option<&str> { if candidates.is_empty() { return None; } else if candidates.len() == 1 { return Some(&candidates[0].replacement()); } let mut longest_common_prefix = 0; 'o: loop { for (i, c1) in candidates.iter().enumerate().take(candidates.len() - 1) { let b1 = c1.replacement().as_bytes(); let b2 = candidates[i + 1].replacement().as_bytes(); if b1.len() <= longest_common_prefix || b2.len() <= longest_common_prefix || b1[longest_common_prefix]!= b2[longest_common_prefix] { break 'o; } } longest_common_prefix += 1; } let candidate = candidates[0].replacement(); while!candidate.is_char_boundary(longest_common_prefix) { longest_common_prefix -= 1; } if longest_common_prefix == 0
Some(&candidate[0..longest_common_prefix]) } #[derive(PartialEq)] enum ScanMode { DoubleQuote, Escape, EscapeInDoubleQuote, Normal, SingleQuote, } /// try to find an unclosed single/double quote in `s`. /// Return `None` if no unclosed quote is found. /// Return the unclosed quote position and if it is a double quote. fn find_unclosed_quote(s: &str) -> Option<(usize, Quote)> { let char_indices = s.char_indices(); let mut mode = ScanMode::Normal; let mut quote_index = 0; for (index, char) in char_indices { match mode { ScanMode::DoubleQuote => { if char == '"' { mode = ScanMode::Normal; } else if char == '\\' { // both windows and unix support escape in double quote mode = ScanMode::EscapeInDoubleQuote; } } ScanMode::Escape => { mode = ScanMode::Normal; } ScanMode::EscapeInDoubleQuote => { mode = ScanMode::DoubleQuote; } ScanMode::Normal => { if char == '"' { mode = ScanMode::DoubleQuote; quote_index = index; } else if char == '\\' && cfg!(not(windows)) { mode = ScanMode::Escape; } else if char == '\'' && cfg!(not(windows)) { mode = ScanMode::SingleQuote; quote_index = index; } } ScanMode::SingleQuote => { if char == '\'' { mode = ScanMode::Normal; } // no escape in single quotes } }; } if ScanMode::DoubleQuote == mode || ScanMode::EscapeInDoubleQuote == mode { return Some((quote_index, Quote::Double)); } else if ScanMode::SingleQuote == mode { return Some((quote_index, Quote::Single)); } None } #[cfg(test)] mod tests { #[test] pub fn extract_word() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let line = "ls '/usr/local/b"; assert_eq!( (4, "/usr/local/b"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); let line = "ls /User\\ Information"; assert_eq!( (3, "/User\\ Information"), super::extract_word(line, line.len(), Some('\\'), &break_chars) ); } #[test] pub fn unescape() { use std::borrow::Cow::{self, Borrowed, Owned}; let input = "/usr/local/b"; assert_eq!(Borrowed(input), super::unescape(input, Some('\\'))); if cfg!(windows) { let input = "c:\\users\\All Users\\"; let result: Cow<str> = Borrowed(input); assert_eq!(result, super::unescape(input, Some('\\'))); } else { let input = "/User\\ Information"; let result: Cow<str> = Owned(String::from("/User Information")); assert_eq!(result, super::unescape(input, Some('\\'))); } } #[test] pub fn escape() { let break_chars: &[u8] = &super::DEFAULT_BREAK_CHARS; let input = String::from("/usr/local/b"); assert_eq!( input.clone(), super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); let input = String::from("/User Information"); let result = String::from("/User\\ Information"); assert_eq!( result, super::escape(input, Some('\\'), &break_chars, super::Quote::None) ); } #[test] pub fn longest_common_prefix() { let mut candidates = vec![]; { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let s = "User"; let c1 = String::from(s); candidates.push(c1.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c2 = String::from("Users"); candidates.push(c2.clone()); { let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some(s), lcp); } let c3 = String::from(""); candidates.push(c3.clone()); { let lcp = super::longest_common_prefix(&candidates); assert!(lcp.is_none()); } let candidates = vec![String::from("fée"), String::from("fête")]; let lcp = super::longest_common_prefix(&candidates); assert_eq!(Some("f"), lcp); } #[test] pub fn find_unclosed_quote() { assert_eq!(None, super::find_unclosed_quote("ls /etc")); assert_eq!( Some((3, super::Quote::Double)), super::find_unclosed_quote("ls \"User Information") ); assert_eq!( None, super::find_unclosed_quote("ls \"/User Information\" /etc") ); assert_eq!( Some((0, super::Quote::Double)), super::find_unclosed_quote("\"c:\\users\\All Users\\") ) } }
{ return None; }
conditional_block
event_pad_axis.rs
// Copyright 2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use gdk_sys; use glib::translate::*; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EventPadAxis(::Event); event_wrapper!(EventPadAxis, GdkEventPadAxis); event_subtype!(EventPadAxis, gdk_sys::GDK_PAD_RING | gdk_sys::GDK_PAD_STRIP); impl EventPadAxis { pub fn get_time(&self) -> u32 { self.as_ref().time } pub fn get_group(&self) -> u32 { self.as_ref().group } pub fn get_index(&self) -> u32
pub fn get_mode(&self) -> u32 { self.as_ref().mode } pub fn get_value(&self) -> f64 { self.as_ref().value } }
{ self.as_ref().index }
identifier_body
event_pad_axis.rs
// Copyright 2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use gdk_sys; use glib::translate::*; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EventPadAxis(::Event); event_wrapper!(EventPadAxis, GdkEventPadAxis); event_subtype!(EventPadAxis, gdk_sys::GDK_PAD_RING | gdk_sys::GDK_PAD_STRIP); impl EventPadAxis { pub fn get_time(&self) -> u32 { self.as_ref().time } pub fn
(&self) -> u32 { self.as_ref().group } pub fn get_index(&self) -> u32 { self.as_ref().index } pub fn get_mode(&self) -> u32 { self.as_ref().mode } pub fn get_value(&self) -> f64 { self.as_ref().value } }
get_group
identifier_name
event_pad_axis.rs
// Copyright 2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use gdk_sys; use glib::translate::*; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EventPadAxis(::Event); event_wrapper!(EventPadAxis, GdkEventPadAxis); event_subtype!(EventPadAxis, gdk_sys::GDK_PAD_RING | gdk_sys::GDK_PAD_STRIP); impl EventPadAxis { pub fn get_time(&self) -> u32 { self.as_ref().time } pub fn get_group(&self) -> u32 { self.as_ref().group } pub fn get_index(&self) -> u32 { self.as_ref().index }
} pub fn get_value(&self) -> f64 { self.as_ref().value } }
pub fn get_mode(&self) -> u32 { self.as_ref().mode
random_line_split
mod.rs
mod serialize; /// Handle to a dock #[derive(Debug, PartialEq, Clone, Copy)] pub struct DockHandle(pub u64); /// Holds information about the plugin view, data and handle #[derive(Debug, Clone)] pub struct Dock { pub handle: DockHandle, pub plugin_name: String, pub plugin_data: Option<Vec<String>>, } impl Dock { pub fn new(dock_handle: DockHandle, plugin_name: &str) -> Dock
} #[cfg(test)] mod test { extern crate serde_json; use super::{Dock, DockHandle}; #[test] fn test_dockhandle_serialize() { let handle_in = DockHandle(0x1337); let serialized = serde_json::to_string(&handle_in).unwrap(); let handle_out: DockHandle = serde_json::from_str(&serialized).unwrap(); assert_eq!(handle_in, handle_out); } #[test] fn test_dock_serialize_0() { let dock_in = Dock { handle: DockHandle(1), plugin_name: "disassembly".to_owned(), plugin_data: None, }; let serialized = serde_json::to_string(&dock_in).unwrap(); let dock_out: Dock = serde_json::from_str(&serialized).unwrap(); assert_eq!(dock_in.handle, dock_out.handle); assert_eq!(dock_in.plugin_name, dock_out.plugin_name); assert_eq!(dock_in.plugin_data, dock_out.plugin_data); } #[test] fn test_dock_serialize_1() { let dock_in = Dock { handle: DockHandle(1), plugin_name: "registers".to_owned(), plugin_data: Some(vec!["some_data".to_owned(), "more_data".to_owned()]), }; let serialized = serde_json::to_string(&dock_in).unwrap(); let dock_out: Dock = serde_json::from_str(&serialized).unwrap(); assert_eq!(dock_in.handle, dock_out.handle); assert_eq!(dock_in.plugin_name, dock_out.plugin_name); assert_eq!(dock_in.plugin_data, dock_out.plugin_data); let plugin_data = dock_out.plugin_data.as_ref().unwrap(); assert_eq!(plugin_data.len(), 2); assert_eq!(plugin_data[0], "some_data"); assert_eq!(plugin_data[1], "more_data"); } }
{ Dock { handle: dock_handle, plugin_name: plugin_name.to_owned(), plugin_data: None, } }
identifier_body
mod.rs
mod serialize; /// Handle to a dock #[derive(Debug, PartialEq, Clone, Copy)] pub struct DockHandle(pub u64); /// Holds information about the plugin view, data and handle #[derive(Debug, Clone)] pub struct Dock { pub handle: DockHandle, pub plugin_name: String, pub plugin_data: Option<Vec<String>>, } impl Dock { pub fn new(dock_handle: DockHandle, plugin_name: &str) -> Dock { Dock { handle: dock_handle, plugin_name: plugin_name.to_owned(), plugin_data: None, } } } #[cfg(test)] mod test { extern crate serde_json; use super::{Dock, DockHandle}; #[test] fn test_dockhandle_serialize() { let handle_in = DockHandle(0x1337); let serialized = serde_json::to_string(&handle_in).unwrap(); let handle_out: DockHandle = serde_json::from_str(&serialized).unwrap(); assert_eq!(handle_in, handle_out); }
let dock_in = Dock { handle: DockHandle(1), plugin_name: "disassembly".to_owned(), plugin_data: None, }; let serialized = serde_json::to_string(&dock_in).unwrap(); let dock_out: Dock = serde_json::from_str(&serialized).unwrap(); assert_eq!(dock_in.handle, dock_out.handle); assert_eq!(dock_in.plugin_name, dock_out.plugin_name); assert_eq!(dock_in.plugin_data, dock_out.plugin_data); } #[test] fn test_dock_serialize_1() { let dock_in = Dock { handle: DockHandle(1), plugin_name: "registers".to_owned(), plugin_data: Some(vec!["some_data".to_owned(), "more_data".to_owned()]), }; let serialized = serde_json::to_string(&dock_in).unwrap(); let dock_out: Dock = serde_json::from_str(&serialized).unwrap(); assert_eq!(dock_in.handle, dock_out.handle); assert_eq!(dock_in.plugin_name, dock_out.plugin_name); assert_eq!(dock_in.plugin_data, dock_out.plugin_data); let plugin_data = dock_out.plugin_data.as_ref().unwrap(); assert_eq!(plugin_data.len(), 2); assert_eq!(plugin_data[0], "some_data"); assert_eq!(plugin_data[1], "more_data"); } }
#[test] fn test_dock_serialize_0() {
random_line_split
mod.rs
mod serialize; /// Handle to a dock #[derive(Debug, PartialEq, Clone, Copy)] pub struct DockHandle(pub u64); /// Holds information about the plugin view, data and handle #[derive(Debug, Clone)] pub struct Dock { pub handle: DockHandle, pub plugin_name: String, pub plugin_data: Option<Vec<String>>, } impl Dock { pub fn new(dock_handle: DockHandle, plugin_name: &str) -> Dock { Dock { handle: dock_handle, plugin_name: plugin_name.to_owned(), plugin_data: None, } } } #[cfg(test)] mod test { extern crate serde_json; use super::{Dock, DockHandle}; #[test] fn test_dockhandle_serialize() { let handle_in = DockHandle(0x1337); let serialized = serde_json::to_string(&handle_in).unwrap(); let handle_out: DockHandle = serde_json::from_str(&serialized).unwrap(); assert_eq!(handle_in, handle_out); } #[test] fn test_dock_serialize_0() { let dock_in = Dock { handle: DockHandle(1), plugin_name: "disassembly".to_owned(), plugin_data: None, }; let serialized = serde_json::to_string(&dock_in).unwrap(); let dock_out: Dock = serde_json::from_str(&serialized).unwrap(); assert_eq!(dock_in.handle, dock_out.handle); assert_eq!(dock_in.plugin_name, dock_out.plugin_name); assert_eq!(dock_in.plugin_data, dock_out.plugin_data); } #[test] fn
() { let dock_in = Dock { handle: DockHandle(1), plugin_name: "registers".to_owned(), plugin_data: Some(vec!["some_data".to_owned(), "more_data".to_owned()]), }; let serialized = serde_json::to_string(&dock_in).unwrap(); let dock_out: Dock = serde_json::from_str(&serialized).unwrap(); assert_eq!(dock_in.handle, dock_out.handle); assert_eq!(dock_in.plugin_name, dock_out.plugin_name); assert_eq!(dock_in.plugin_data, dock_out.plugin_data); let plugin_data = dock_out.plugin_data.as_ref().unwrap(); assert_eq!(plugin_data.len(), 2); assert_eq!(plugin_data[0], "some_data"); assert_eq!(plugin_data[1], "more_data"); } }
test_dock_serialize_1
identifier_name
smoke.rs
use futures::StreamExt; use opentelemetry::global::shutdown_tracer_provider; use opentelemetry::trace::{Span, SpanKind, Tracer}; use opentelemetry_otlp::WithExportConfig; use opentelemetry_proto::tonic::collector::trace::v1::{ trace_service_server::{TraceService, TraceServiceServer}, ExportTraceServiceRequest, ExportTraceServiceResponse, }; use std::{net::SocketAddr, sync::Mutex}; use tokio::sync::mpsc; use tokio_stream::wrappers::TcpListenerStream; struct MockServer { tx: Mutex<mpsc::Sender<ExportTraceServiceRequest>>, } impl MockServer { pub fn new(tx: mpsc::Sender<ExportTraceServiceRequest>) -> Self { Self { tx: Mutex::new(tx) } } } #[tonic::async_trait] impl TraceService for MockServer { async fn export( &self, request: tonic::Request<ExportTraceServiceRequest>, ) -> Result<tonic::Response<ExportTraceServiceResponse>, tonic::Status> { println!("Sending request into channel..."); // assert we have required metadata key assert_eq!( request.metadata().get("x-header-key"), Some(&("header-value".parse().unwrap())) ); self.tx .lock() .unwrap() .try_send(request.into_inner()) .expect("Channel full"); Ok(tonic::Response::new(ExportTraceServiceResponse {})) } } async fn setup() -> (SocketAddr, mpsc::Receiver<ExportTraceServiceRequest>) { let addr: SocketAddr = "[::1]:0".parse().unwrap(); let listener = tokio::net::TcpListener::bind(addr) .await .expect("failed to bind"); let addr = listener.local_addr().unwrap(); let stream = TcpListenerStream::new(listener).map(|s| { if let Ok(ref s) = s { println!("Got new conn at {}", s.peer_addr().unwrap()); } s }); let (req_tx, req_rx) = mpsc::channel(10); let service = TraceServiceServer::new(MockServer::new(req_tx)); tokio::task::spawn(async move { tonic::transport::Server::builder() .add_service(service) .serve_with_incoming(stream) .await .expect("Server failed"); }); (addr, req_rx) } #[tokio::test(flavor = "multi_thread")] async fn
() { println!("Starting server setup..."); let (addr, mut req_rx) = setup().await; { println!("Installing tracer..."); let mut metadata = tonic::metadata::MetadataMap::new(); metadata.insert("x-header-key", "header-value".parse().unwrap()); let tracer = opentelemetry_otlp::new_pipeline() .tracing() .with_exporter( opentelemetry_otlp::new_exporter() .tonic() .with_endpoint(format!("http://{}", addr)) .with_metadata(metadata), ) .install_batch(opentelemetry::runtime::Tokio) .expect("failed to install"); println!("Sending span..."); let mut span = tracer .span_builder("my-test-span") .with_kind(SpanKind::Server) .start(&tracer); span.add_event("my-test-event", vec![]); span.end(); shutdown_tracer_provider(); } println!("Waiting for request..."); let req = req_rx.recv().await.expect("missing export request"); let first_span = req .resource_spans .get(0) .unwrap() .instrumentation_library_spans .get(0) .unwrap() .spans .get(0) .unwrap(); assert_eq!("my-test-span", first_span.name); let first_event = first_span.events.get(0).unwrap(); assert_eq!("my-test-event", first_event.name); }
smoke_tracer
identifier_name
smoke.rs
use futures::StreamExt; use opentelemetry::global::shutdown_tracer_provider; use opentelemetry::trace::{Span, SpanKind, Tracer}; use opentelemetry_otlp::WithExportConfig; use opentelemetry_proto::tonic::collector::trace::v1::{ trace_service_server::{TraceService, TraceServiceServer}, ExportTraceServiceRequest, ExportTraceServiceResponse, }; use std::{net::SocketAddr, sync::Mutex}; use tokio::sync::mpsc; use tokio_stream::wrappers::TcpListenerStream; struct MockServer { tx: Mutex<mpsc::Sender<ExportTraceServiceRequest>>, } impl MockServer { pub fn new(tx: mpsc::Sender<ExportTraceServiceRequest>) -> Self { Self { tx: Mutex::new(tx) } } } #[tonic::async_trait] impl TraceService for MockServer { async fn export( &self, request: tonic::Request<ExportTraceServiceRequest>, ) -> Result<tonic::Response<ExportTraceServiceResponse>, tonic::Status> { println!("Sending request into channel..."); // assert we have required metadata key assert_eq!( request.metadata().get("x-header-key"), Some(&("header-value".parse().unwrap())) ); self.tx .lock() .unwrap() .try_send(request.into_inner()) .expect("Channel full"); Ok(tonic::Response::new(ExportTraceServiceResponse {})) } } async fn setup() -> (SocketAddr, mpsc::Receiver<ExportTraceServiceRequest>) { let addr: SocketAddr = "[::1]:0".parse().unwrap(); let listener = tokio::net::TcpListener::bind(addr) .await .expect("failed to bind"); let addr = listener.local_addr().unwrap(); let stream = TcpListenerStream::new(listener).map(|s| { if let Ok(ref s) = s
s }); let (req_tx, req_rx) = mpsc::channel(10); let service = TraceServiceServer::new(MockServer::new(req_tx)); tokio::task::spawn(async move { tonic::transport::Server::builder() .add_service(service) .serve_with_incoming(stream) .await .expect("Server failed"); }); (addr, req_rx) } #[tokio::test(flavor = "multi_thread")] async fn smoke_tracer() { println!("Starting server setup..."); let (addr, mut req_rx) = setup().await; { println!("Installing tracer..."); let mut metadata = tonic::metadata::MetadataMap::new(); metadata.insert("x-header-key", "header-value".parse().unwrap()); let tracer = opentelemetry_otlp::new_pipeline() .tracing() .with_exporter( opentelemetry_otlp::new_exporter() .tonic() .with_endpoint(format!("http://{}", addr)) .with_metadata(metadata), ) .install_batch(opentelemetry::runtime::Tokio) .expect("failed to install"); println!("Sending span..."); let mut span = tracer .span_builder("my-test-span") .with_kind(SpanKind::Server) .start(&tracer); span.add_event("my-test-event", vec![]); span.end(); shutdown_tracer_provider(); } println!("Waiting for request..."); let req = req_rx.recv().await.expect("missing export request"); let first_span = req .resource_spans .get(0) .unwrap() .instrumentation_library_spans .get(0) .unwrap() .spans .get(0) .unwrap(); assert_eq!("my-test-span", first_span.name); let first_event = first_span.events.get(0).unwrap(); assert_eq!("my-test-event", first_event.name); }
{ println!("Got new conn at {}", s.peer_addr().unwrap()); }
conditional_block
smoke.rs
use futures::StreamExt; use opentelemetry::global::shutdown_tracer_provider; use opentelemetry::trace::{Span, SpanKind, Tracer}; use opentelemetry_otlp::WithExportConfig; use opentelemetry_proto::tonic::collector::trace::v1::{ trace_service_server::{TraceService, TraceServiceServer}, ExportTraceServiceRequest, ExportTraceServiceResponse, }; use std::{net::SocketAddr, sync::Mutex}; use tokio::sync::mpsc; use tokio_stream::wrappers::TcpListenerStream; struct MockServer { tx: Mutex<mpsc::Sender<ExportTraceServiceRequest>>, } impl MockServer { pub fn new(tx: mpsc::Sender<ExportTraceServiceRequest>) -> Self { Self { tx: Mutex::new(tx) } } } #[tonic::async_trait] impl TraceService for MockServer { async fn export( &self, request: tonic::Request<ExportTraceServiceRequest>, ) -> Result<tonic::Response<ExportTraceServiceResponse>, tonic::Status> { println!("Sending request into channel..."); // assert we have required metadata key assert_eq!( request.metadata().get("x-header-key"), Some(&("header-value".parse().unwrap())) ); self.tx .lock() .unwrap() .try_send(request.into_inner()) .expect("Channel full"); Ok(tonic::Response::new(ExportTraceServiceResponse {})) } } async fn setup() -> (SocketAddr, mpsc::Receiver<ExportTraceServiceRequest>) { let addr: SocketAddr = "[::1]:0".parse().unwrap(); let listener = tokio::net::TcpListener::bind(addr) .await .expect("failed to bind"); let addr = listener.local_addr().unwrap(); let stream = TcpListenerStream::new(listener).map(|s| { if let Ok(ref s) = s { println!("Got new conn at {}", s.peer_addr().unwrap()); } s }); let (req_tx, req_rx) = mpsc::channel(10); let service = TraceServiceServer::new(MockServer::new(req_tx)); tokio::task::spawn(async move { tonic::transport::Server::builder() .add_service(service) .serve_with_incoming(stream) .await .expect("Server failed"); }); (addr, req_rx) } #[tokio::test(flavor = "multi_thread")] async fn smoke_tracer() { println!("Starting server setup..."); let (addr, mut req_rx) = setup().await; { println!("Installing tracer..."); let mut metadata = tonic::metadata::MetadataMap::new(); metadata.insert("x-header-key", "header-value".parse().unwrap()); let tracer = opentelemetry_otlp::new_pipeline() .tracing() .with_exporter( opentelemetry_otlp::new_exporter() .tonic() .with_endpoint(format!("http://{}", addr))
.with_metadata(metadata), ) .install_batch(opentelemetry::runtime::Tokio) .expect("failed to install"); println!("Sending span..."); let mut span = tracer .span_builder("my-test-span") .with_kind(SpanKind::Server) .start(&tracer); span.add_event("my-test-event", vec![]); span.end(); shutdown_tracer_provider(); } println!("Waiting for request..."); let req = req_rx.recv().await.expect("missing export request"); let first_span = req .resource_spans .get(0) .unwrap() .instrumentation_library_spans .get(0) .unwrap() .spans .get(0) .unwrap(); assert_eq!("my-test-span", first_span.name); let first_event = first_span.events.get(0).unwrap(); assert_eq!("my-test-event", first_event.name); }
random_line_split
smoke.rs
use futures::StreamExt; use opentelemetry::global::shutdown_tracer_provider; use opentelemetry::trace::{Span, SpanKind, Tracer}; use opentelemetry_otlp::WithExportConfig; use opentelemetry_proto::tonic::collector::trace::v1::{ trace_service_server::{TraceService, TraceServiceServer}, ExportTraceServiceRequest, ExportTraceServiceResponse, }; use std::{net::SocketAddr, sync::Mutex}; use tokio::sync::mpsc; use tokio_stream::wrappers::TcpListenerStream; struct MockServer { tx: Mutex<mpsc::Sender<ExportTraceServiceRequest>>, } impl MockServer { pub fn new(tx: mpsc::Sender<ExportTraceServiceRequest>) -> Self { Self { tx: Mutex::new(tx) } } } #[tonic::async_trait] impl TraceService for MockServer { async fn export( &self, request: tonic::Request<ExportTraceServiceRequest>, ) -> Result<tonic::Response<ExportTraceServiceResponse>, tonic::Status> { println!("Sending request into channel..."); // assert we have required metadata key assert_eq!( request.metadata().get("x-header-key"), Some(&("header-value".parse().unwrap())) ); self.tx .lock() .unwrap() .try_send(request.into_inner()) .expect("Channel full"); Ok(tonic::Response::new(ExportTraceServiceResponse {})) } } async fn setup() -> (SocketAddr, mpsc::Receiver<ExportTraceServiceRequest>) { let addr: SocketAddr = "[::1]:0".parse().unwrap(); let listener = tokio::net::TcpListener::bind(addr) .await .expect("failed to bind"); let addr = listener.local_addr().unwrap(); let stream = TcpListenerStream::new(listener).map(|s| { if let Ok(ref s) = s { println!("Got new conn at {}", s.peer_addr().unwrap()); } s }); let (req_tx, req_rx) = mpsc::channel(10); let service = TraceServiceServer::new(MockServer::new(req_tx)); tokio::task::spawn(async move { tonic::transport::Server::builder() .add_service(service) .serve_with_incoming(stream) .await .expect("Server failed"); }); (addr, req_rx) } #[tokio::test(flavor = "multi_thread")] async fn smoke_tracer()
let mut span = tracer .span_builder("my-test-span") .with_kind(SpanKind::Server) .start(&tracer); span.add_event("my-test-event", vec![]); span.end(); shutdown_tracer_provider(); } println!("Waiting for request..."); let req = req_rx.recv().await.expect("missing export request"); let first_span = req .resource_spans .get(0) .unwrap() .instrumentation_library_spans .get(0) .unwrap() .spans .get(0) .unwrap(); assert_eq!("my-test-span", first_span.name); let first_event = first_span.events.get(0).unwrap(); assert_eq!("my-test-event", first_event.name); }
{ println!("Starting server setup..."); let (addr, mut req_rx) = setup().await; { println!("Installing tracer..."); let mut metadata = tonic::metadata::MetadataMap::new(); metadata.insert("x-header-key", "header-value".parse().unwrap()); let tracer = opentelemetry_otlp::new_pipeline() .tracing() .with_exporter( opentelemetry_otlp::new_exporter() .tonic() .with_endpoint(format!("http://{}", addr)) .with_metadata(metadata), ) .install_batch(opentelemetry::runtime::Tokio) .expect("failed to install"); println!("Sending span...");
identifier_body
main.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-windows // ignore-tidy-linelength // compile-flags: -g -C no-prepopulate-passes --remap-path-prefix={{cwd}}=/the/cwd --remap-path-prefix={{src-base}}=/the/src // aux-build:remap_path_prefix_aux.rs extern crate remap_path_prefix_aux; // Here we check that submodules and include files are found using the path without // remapping. This test requires that rustc is called with an absolute path. mod aux_mod; include!("aux_mod.rs"); // Here we check that the expansion of the file!() macro is mapped. // CHECK: @0 = private unnamed_addr constant <{ [34 x i8] }> <{ [34 x i8] c"/the/src/remap_path_prefix/main.rs" }>, align 1 pub static FILE_PATH: &'static str = file!(); fn
() { remap_path_prefix_aux::some_aux_function(); aux_mod::some_aux_mod_function(); some_aux_mod_function(); } // Here we check that local debuginfo is mapped correctly. // CHECK:!DIFile(filename: "/the/src/remap_path_prefix/main.rs", directory: "/the/cwd/") // And here that debuginfo from other crates are expanded to absolute paths. // CHECK:!DIFile(filename: "/the/aux-src/remap_path_prefix_aux.rs", directory: "")
main
identifier_name
main.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-windows // ignore-tidy-linelength // compile-flags: -g -C no-prepopulate-passes --remap-path-prefix={{cwd}}=/the/cwd --remap-path-prefix={{src-base}}=/the/src // aux-build:remap_path_prefix_aux.rs extern crate remap_path_prefix_aux;
include!("aux_mod.rs"); // Here we check that the expansion of the file!() macro is mapped. // CHECK: @0 = private unnamed_addr constant <{ [34 x i8] }> <{ [34 x i8] c"/the/src/remap_path_prefix/main.rs" }>, align 1 pub static FILE_PATH: &'static str = file!(); fn main() { remap_path_prefix_aux::some_aux_function(); aux_mod::some_aux_mod_function(); some_aux_mod_function(); } // Here we check that local debuginfo is mapped correctly. // CHECK:!DIFile(filename: "/the/src/remap_path_prefix/main.rs", directory: "/the/cwd/") // And here that debuginfo from other crates are expanded to absolute paths. // CHECK:!DIFile(filename: "/the/aux-src/remap_path_prefix_aux.rs", directory: "")
// Here we check that submodules and include files are found using the path without // remapping. This test requires that rustc is called with an absolute path. mod aux_mod;
random_line_split
main.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-windows // ignore-tidy-linelength // compile-flags: -g -C no-prepopulate-passes --remap-path-prefix={{cwd}}=/the/cwd --remap-path-prefix={{src-base}}=/the/src // aux-build:remap_path_prefix_aux.rs extern crate remap_path_prefix_aux; // Here we check that submodules and include files are found using the path without // remapping. This test requires that rustc is called with an absolute path. mod aux_mod; include!("aux_mod.rs"); // Here we check that the expansion of the file!() macro is mapped. // CHECK: @0 = private unnamed_addr constant <{ [34 x i8] }> <{ [34 x i8] c"/the/src/remap_path_prefix/main.rs" }>, align 1 pub static FILE_PATH: &'static str = file!(); fn main()
// Here we check that local debuginfo is mapped correctly. // CHECK:!DIFile(filename: "/the/src/remap_path_prefix/main.rs", directory: "/the/cwd/") // And here that debuginfo from other crates are expanded to absolute paths. // CHECK:!DIFile(filename: "/the/aux-src/remap_path_prefix_aux.rs", directory: "")
{ remap_path_prefix_aux::some_aux_function(); aux_mod::some_aux_mod_function(); some_aux_mod_function(); }
identifier_body
p011.rs
#![feature(core)] use euler::*; mod euler; #[no_mangle] pub extern "C" fn solution() -> EulerType { let g = [ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8], [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0], [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65], [52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91], [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80], [24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50], [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70], [67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21], [24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72], [21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95], [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92], [16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57], [86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58], [19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40], [4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66], [88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69], [4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36], [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16], [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54], [1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48u64], ]; EulerU( (0.. 20).map(|j| (0.. 20 - 4).map(|i| max( (0.. 4).map(|k| g[j][i + k]).product(), (0.. 4).map(|k| g[i + k][j]).product() ) ).max().unwrap() ).chain((0.. 20 - 4).map(|i| (0.. 20 - 4).map(|j| max( (0.. 4).map(|k| g[j + k][i + k]).product(), (0.. 4).map(|k| g[j + 4 - k][i + k]).product() ) ).max().unwrap() )).max().unwrap() ) } fn
() { print_euler(solution()) }
main
identifier_name
p011.rs
#![feature(core)] use euler::*; mod euler; #[no_mangle]
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0], [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65], [52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91], [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80], [24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50], [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70], [67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21], [24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72], [21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95], [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92], [16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57], [86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58], [19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40], [4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66], [88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69], [4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36], [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16], [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54], [1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48u64], ]; EulerU( (0.. 20).map(|j| (0.. 20 - 4).map(|i| max( (0.. 4).map(|k| g[j][i + k]).product(), (0.. 4).map(|k| g[i + k][j]).product() ) ).max().unwrap() ).chain((0.. 20 - 4).map(|i| (0.. 20 - 4).map(|j| max( (0.. 4).map(|k| g[j + k][i + k]).product(), (0.. 4).map(|k| g[j + 4 - k][i + k]).product() ) ).max().unwrap() )).max().unwrap() ) } fn main() { print_euler(solution()) }
pub extern "C" fn solution() -> EulerType { let g = [ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
random_line_split
p011.rs
#![feature(core)] use euler::*; mod euler; #[no_mangle] pub extern "C" fn solution() -> EulerType
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54], [1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48u64], ]; EulerU( (0.. 20).map(|j| (0.. 20 - 4).map(|i| max( (0.. 4).map(|k| g[j][i + k]).product(), (0.. 4).map(|k| g[i + k][j]).product() ) ).max().unwrap() ).chain((0.. 20 - 4).map(|i| (0.. 20 - 4).map(|j| max( (0.. 4).map(|k| g[j + k][i + k]).product(), (0.. 4).map(|k| g[j + 4 - k][i + k]).product() ) ).max().unwrap() )).max().unwrap() ) } fn main() { print_euler(solution()) }
{ let g = [ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8], [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0], [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65], [52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91], [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80], [24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50], [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70], [67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21], [24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72], [21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95], [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92], [16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57], [86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58], [19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40], [4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66], [88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69], [4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36], [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
identifier_body
regions-close-over-type-parameter-multiple.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] // Various tests where we over type parameters with multiple lifetime // bounds. trait SomeTrait { fn get(&self) -> isize; } fn make_object_good1<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'a>
fn make_object_good2<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'b> { // A outlives 'a AND 'b... box v as Box<SomeTrait+'b> //...hence this type is safe. } fn make_object_bad<'a,'b,'c,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'c> { // A outlives 'a AND 'b...but not 'c. box v as Box<SomeTrait+'a> //~ ERROR cannot infer an appropriate lifetime } fn main() { }
{ // A outlives 'a AND 'b... box v as Box<SomeTrait+'a> // ...hence this type is safe. }
identifier_body
regions-close-over-type-parameter-multiple.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] // Various tests where we over type parameters with multiple lifetime // bounds.
// A outlives 'a AND 'b... box v as Box<SomeTrait+'a> //...hence this type is safe. } fn make_object_good2<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'b> { // A outlives 'a AND 'b... box v as Box<SomeTrait+'b> //...hence this type is safe. } fn make_object_bad<'a,'b,'c,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'c> { // A outlives 'a AND 'b...but not 'c. box v as Box<SomeTrait+'a> //~ ERROR cannot infer an appropriate lifetime } fn main() { }
trait SomeTrait { fn get(&self) -> isize; } fn make_object_good1<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'a> {
random_line_split
regions-close-over-type-parameter-multiple.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] // Various tests where we over type parameters with multiple lifetime // bounds. trait SomeTrait { fn get(&self) -> isize; } fn make_object_good1<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'a> { // A outlives 'a AND 'b... box v as Box<SomeTrait+'a> //...hence this type is safe. } fn make_object_good2<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'b> { // A outlives 'a AND 'b... box v as Box<SomeTrait+'b> //...hence this type is safe. } fn
<'a,'b,'c,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'c> { // A outlives 'a AND 'b...but not 'c. box v as Box<SomeTrait+'a> //~ ERROR cannot infer an appropriate lifetime } fn main() { }
make_object_bad
identifier_name
generators.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, generators, generator_trait, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete use std::marker::Unpin; use std::ops::{Generator, GeneratorState}; use std::pin::Pin; enum YieldOrReturn<Y, R> { Yield(Y), Return(R), } fn finish<T, Y, R>(mut t: T) -> Vec<YieldOrReturn<Y, R>> where T: Generator<(), Yield = Y, Return = R> + Unpin, { let mut results = Vec::new(); loop { match Pin::new(&mut t).resume(()) { GeneratorState::Yielded(yielded) => results.push(YieldOrReturn::Yield(yielded)), GeneratorState::Complete(returned) => { results.push(YieldOrReturn::Return(returned)); return results; } } } } // This test checks that the polymorphization analysis functions on generators. #[rustc_polymorphize_error] pub fn
<T>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { //~^ ERROR item has unused generic parameters || { //~^ ERROR item has unused generic parameters yield 1; 2 } } #[rustc_polymorphize_error] pub fn used_type_in_yield<Y: Default>() -> impl Generator<(), Yield = Y, Return = u32> + Unpin { || { yield Y::default(); 2 } } #[rustc_polymorphize_error] pub fn used_type_in_return<R: Default>() -> impl Generator<(), Yield = u32, Return = R> + Unpin { || { yield 3; R::default() } } #[rustc_polymorphize_error] pub fn unused_const<const T: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { //~^ ERROR item has unused generic parameters || { //~^ ERROR item has unused generic parameters yield 1; 2 } } #[rustc_polymorphize_error] pub fn used_const_in_yield<const Y: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { || { yield Y; 2 } } #[rustc_polymorphize_error] pub fn used_const_in_return<const R: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { || { yield 4; R } } fn main() { finish(unused_type::<u32>()); finish(used_type_in_yield::<u32>()); finish(used_type_in_return::<u32>()); finish(unused_const::<1u32>()); finish(used_const_in_yield::<1u32>()); finish(used_const_in_return::<1u32>()); }
unused_type
identifier_name
generators.rs
// build-fail // compile-flags:-Zpolymorphize=on #![feature(generic_const_exprs, generators, generator_trait, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete use std::marker::Unpin; use std::ops::{Generator, GeneratorState}; use std::pin::Pin; enum YieldOrReturn<Y, R> { Yield(Y), Return(R), } fn finish<T, Y, R>(mut t: T) -> Vec<YieldOrReturn<Y, R>> where T: Generator<(), Yield = Y, Return = R> + Unpin, { let mut results = Vec::new(); loop { match Pin::new(&mut t).resume(()) { GeneratorState::Yielded(yielded) => results.push(YieldOrReturn::Yield(yielded)), GeneratorState::Complete(returned) => { results.push(YieldOrReturn::Return(returned)); return results; } } } } // This test checks that the polymorphization analysis functions on generators. #[rustc_polymorphize_error] pub fn unused_type<T>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { //~^ ERROR item has unused generic parameters || { //~^ ERROR item has unused generic parameters yield 1; 2 } } #[rustc_polymorphize_error] pub fn used_type_in_yield<Y: Default>() -> impl Generator<(), Yield = Y, Return = u32> + Unpin { || { yield Y::default(); 2 }
} #[rustc_polymorphize_error] pub fn used_type_in_return<R: Default>() -> impl Generator<(), Yield = u32, Return = R> + Unpin { || { yield 3; R::default() } } #[rustc_polymorphize_error] pub fn unused_const<const T: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { //~^ ERROR item has unused generic parameters || { //~^ ERROR item has unused generic parameters yield 1; 2 } } #[rustc_polymorphize_error] pub fn used_const_in_yield<const Y: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { || { yield Y; 2 } } #[rustc_polymorphize_error] pub fn used_const_in_return<const R: u32>() -> impl Generator<(), Yield = u32, Return = u32> + Unpin { || { yield 4; R } } fn main() { finish(unused_type::<u32>()); finish(used_type_in_yield::<u32>()); finish(used_type_in_return::<u32>()); finish(unused_const::<1u32>()); finish(used_const_in_yield::<1u32>()); finish(used_const_in_return::<1u32>()); }
random_line_split
env.rs
use std::process::Command; use std::str; static PROGNAME: &'static str = "./env"; #[test] fn test_single_name_value_pair() { let po = Command::new(PROGNAME) .arg("FOO=bar") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert!(out.lines_any().any(|line| line == "FOO=bar")); } #[test] fn test_multiple_name_value_pairs() { let po = Command::new(PROGNAME) .arg("FOO=bar") .arg("ABC=xyz") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out.lines_any().filter(|&line| line == "FOO=bar" || line == "ABC=xyz").count(), 2); } #[test] fn test_ignore_environment() { let po = Command::new(PROGNAME) .arg("-i") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, ""); let po = Command::new(PROGNAME) .arg("-") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, ""); } #[test] fn test_null_delimiter()
#[test] fn test_unset_variable() { // This test depends on the HOME variable being pre-defined by the // default shell let po = Command::new(PROGNAME) .arg("-u") .arg("HOME") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out.lines_any().any(|line| line.starts_with("HOME=")), false); }
{ let po = Command::new(PROGNAME) .arg("-i") .arg("--null") .arg("FOO=bar") .arg("ABC=xyz") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, "FOO=bar\0ABC=xyz\0"); }
identifier_body
env.rs
use std::process::Command; use std::str; static PROGNAME: &'static str = "./env"; #[test] fn test_single_name_value_pair() { let po = Command::new(PROGNAME) .arg("FOO=bar") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert!(out.lines_any().any(|line| line == "FOO=bar")); } #[test] fn test_multiple_name_value_pairs() { let po = Command::new(PROGNAME) .arg("FOO=bar") .arg("ABC=xyz") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out.lines_any().filter(|&line| line == "FOO=bar" || line == "ABC=xyz").count(), 2); } #[test] fn test_ignore_environment() { let po = Command::new(PROGNAME) .arg("-i") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, ""); let po = Command::new(PROGNAME) .arg("-") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, ""); } #[test] fn test_null_delimiter() { let po = Command::new(PROGNAME) .arg("-i") .arg("--null") .arg("FOO=bar") .arg("ABC=xyz") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, "FOO=bar\0ABC=xyz\0"); } #[test] fn
() { // This test depends on the HOME variable being pre-defined by the // default shell let po = Command::new(PROGNAME) .arg("-u") .arg("HOME") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out.lines_any().any(|line| line.starts_with("HOME=")), false); }
test_unset_variable
identifier_name
env.rs
use std::str; static PROGNAME: &'static str = "./env"; #[test] fn test_single_name_value_pair() { let po = Command::new(PROGNAME) .arg("FOO=bar") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert!(out.lines_any().any(|line| line == "FOO=bar")); } #[test] fn test_multiple_name_value_pairs() { let po = Command::new(PROGNAME) .arg("FOO=bar") .arg("ABC=xyz") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out.lines_any().filter(|&line| line == "FOO=bar" || line == "ABC=xyz").count(), 2); } #[test] fn test_ignore_environment() { let po = Command::new(PROGNAME) .arg("-i") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, ""); let po = Command::new(PROGNAME) .arg("-") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, ""); } #[test] fn test_null_delimiter() { let po = Command::new(PROGNAME) .arg("-i") .arg("--null") .arg("FOO=bar") .arg("ABC=xyz") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out, "FOO=bar\0ABC=xyz\0"); } #[test] fn test_unset_variable() { // This test depends on the HOME variable being pre-defined by the // default shell let po = Command::new(PROGNAME) .arg("-u") .arg("HOME") .output() .unwrap_or_else(|err| panic!("{}", err)); let out = str::from_utf8(&po.stdout[..]).unwrap(); assert_eq!(out.lines_any().any(|line| line.starts_with("HOME=")), false); }
use std::process::Command;
random_line_split
name.rs
/* * Copyright (C) 2015 Benjamin Fry <[email protected]> * * 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. */ //! Record type for all cname like records. //! //! A generic struct for all {*}NAME pointer RData records, CNAME, NS, and PTR. Here is the text for //! CNAME from RFC 1035, Domain Implementation and Specification, November 1987: //! //! [RFC 1035, DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987](https://tools.ietf.org/html/rfc1035) //! //! ```text //! 3.3.1. CNAME RDATA format //! //! +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ //! / CNAME / //! / / //! +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ //! //! where: //! //! CNAME A <domain-name> which specifies the canonical or primary //! name for the owner. The owner name is an alias. //! //! CNAME RRs cause no additional section processing, but name servers may //! choose to restart the query at the canonical name in certain cases. See //! the description of name server logic in [RFC-1034] for details. //! ``` use crate::error::*; use crate::rr::domain::Name; use crate::serialize::binary::*; /// Read the RData from the given Decoder pub fn read(decoder: &mut BinDecoder) -> ProtoResult<Name> { Name::read(decoder) } /// [RFC 4034](https://tools.ietf.org/html/rfc4034#section-6), DNSSEC Resource Records, March 2005 /// /// This is accurate for all currently known name records. /// /// ```text /// 6.2. Canonical RR Form /// /// For the purposes of DNS security, the canonical form of an RR is the /// wire format of the RR where: /// /// ... /// /// 3. if the type of the RR is NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR, /// HINFO, MINFO, MX, HINFO, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX, /// SRV, DNAME, A6, RRSIG, or (rfc6840 removes NSEC), all uppercase /// US-ASCII letters in the DNS names contained within the RDATA are replaced /// by the corresponding lowercase US-ASCII letters; /// ``` pub fn emit(encoder: &mut BinEncoder, name_data: &Name) -> ProtoResult<()> { let is_canonical_names = encoder.is_canonical_names(); name_data.emit_with_lowercase(encoder, is_canonical_names)?; Ok(()) } #[test] pub fn test()
{ #![allow(clippy::dbg_macro, clippy::print_stdout)] let rdata = Name::from_ascii("WWW.example.com.").unwrap(); let mut bytes = Vec::new(); let mut encoder: BinEncoder = BinEncoder::new(&mut bytes); assert!(emit(&mut encoder, &rdata).is_ok()); let bytes = encoder.into_bytes(); println!("bytes: {:?}", bytes); let mut decoder: BinDecoder = BinDecoder::new(bytes); let read_rdata = read(&mut decoder).expect("Decoding error"); assert_eq!(rdata, read_rdata); }
identifier_body
name.rs
/* * Copyright (C) 2015 Benjamin Fry <[email protected]> * * 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. */ //! Record type for all cname like records. //! //! A generic struct for all {*}NAME pointer RData records, CNAME, NS, and PTR. Here is the text for //! CNAME from RFC 1035, Domain Implementation and Specification, November 1987: //! //! [RFC 1035, DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987](https://tools.ietf.org/html/rfc1035) //! //! ```text //! 3.3.1. CNAME RDATA format //! //! +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ //! / CNAME / //! / / //! +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ //! //! where: //! //! CNAME A <domain-name> which specifies the canonical or primary //! name for the owner. The owner name is an alias. //! //! CNAME RRs cause no additional section processing, but name servers may //! choose to restart the query at the canonical name in certain cases. See //! the description of name server logic in [RFC-1034] for details. //! ``` use crate::error::*; use crate::rr::domain::Name; use crate::serialize::binary::*; /// Read the RData from the given Decoder pub fn read(decoder: &mut BinDecoder) -> ProtoResult<Name> { Name::read(decoder) } /// [RFC 4034](https://tools.ietf.org/html/rfc4034#section-6), DNSSEC Resource Records, March 2005 /// /// This is accurate for all currently known name records. /// /// ```text /// 6.2. Canonical RR Form /// /// For the purposes of DNS security, the canonical form of an RR is the /// wire format of the RR where: /// /// ... /// /// 3. if the type of the RR is NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR, /// HINFO, MINFO, MX, HINFO, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX, /// SRV, DNAME, A6, RRSIG, or (rfc6840 removes NSEC), all uppercase /// US-ASCII letters in the DNS names contained within the RDATA are replaced
/// by the corresponding lowercase US-ASCII letters; /// ``` pub fn emit(encoder: &mut BinEncoder, name_data: &Name) -> ProtoResult<()> { let is_canonical_names = encoder.is_canonical_names(); name_data.emit_with_lowercase(encoder, is_canonical_names)?; Ok(()) } #[test] pub fn test() { #![allow(clippy::dbg_macro, clippy::print_stdout)] let rdata = Name::from_ascii("WWW.example.com.").unwrap(); let mut bytes = Vec::new(); let mut encoder: BinEncoder = BinEncoder::new(&mut bytes); assert!(emit(&mut encoder, &rdata).is_ok()); let bytes = encoder.into_bytes(); println!("bytes: {:?}", bytes); let mut decoder: BinDecoder = BinDecoder::new(bytes); let read_rdata = read(&mut decoder).expect("Decoding error"); assert_eq!(rdata, read_rdata); }
random_line_split
name.rs
/* * Copyright (C) 2015 Benjamin Fry <[email protected]> * * 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. */ //! Record type for all cname like records. //! //! A generic struct for all {*}NAME pointer RData records, CNAME, NS, and PTR. Here is the text for //! CNAME from RFC 1035, Domain Implementation and Specification, November 1987: //! //! [RFC 1035, DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987](https://tools.ietf.org/html/rfc1035) //! //! ```text //! 3.3.1. CNAME RDATA format //! //! +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ //! / CNAME / //! / / //! +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ //! //! where: //! //! CNAME A <domain-name> which specifies the canonical or primary //! name for the owner. The owner name is an alias. //! //! CNAME RRs cause no additional section processing, but name servers may //! choose to restart the query at the canonical name in certain cases. See //! the description of name server logic in [RFC-1034] for details. //! ``` use crate::error::*; use crate::rr::domain::Name; use crate::serialize::binary::*; /// Read the RData from the given Decoder pub fn read(decoder: &mut BinDecoder) -> ProtoResult<Name> { Name::read(decoder) } /// [RFC 4034](https://tools.ietf.org/html/rfc4034#section-6), DNSSEC Resource Records, March 2005 /// /// This is accurate for all currently known name records. /// /// ```text /// 6.2. Canonical RR Form /// /// For the purposes of DNS security, the canonical form of an RR is the /// wire format of the RR where: /// /// ... /// /// 3. if the type of the RR is NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR, /// HINFO, MINFO, MX, HINFO, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX, /// SRV, DNAME, A6, RRSIG, or (rfc6840 removes NSEC), all uppercase /// US-ASCII letters in the DNS names contained within the RDATA are replaced /// by the corresponding lowercase US-ASCII letters; /// ``` pub fn emit(encoder: &mut BinEncoder, name_data: &Name) -> ProtoResult<()> { let is_canonical_names = encoder.is_canonical_names(); name_data.emit_with_lowercase(encoder, is_canonical_names)?; Ok(()) } #[test] pub fn
() { #![allow(clippy::dbg_macro, clippy::print_stdout)] let rdata = Name::from_ascii("WWW.example.com.").unwrap(); let mut bytes = Vec::new(); let mut encoder: BinEncoder = BinEncoder::new(&mut bytes); assert!(emit(&mut encoder, &rdata).is_ok()); let bytes = encoder.into_bytes(); println!("bytes: {:?}", bytes); let mut decoder: BinDecoder = BinDecoder::new(bytes); let read_rdata = read(&mut decoder).expect("Decoding error"); assert_eq!(rdata, read_rdata); }
test
identifier_name
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use super::test_common::*; use evm; use ethjson; use rlp::{UntrustedRlp, View}; use transaction::{Action, UnverifiedTransaction}; use ethstore::ethkey::public_to_address; fn
(json_data: &[u8]) -> Vec<String> { let tests = ethjson::transaction::Test::load(json_data).unwrap(); let mut failed = Vec::new(); let old_schedule = evm::Schedule::new_frontier(); let new_schedule = evm::Schedule::new_homestead(); for (name, test) in tests.into_iter() { let mut fail_unless = |cond: bool, title: &str| if!cond { failed.push(name.clone()); println!("Transaction failed: {:?}: {:?}", name, title); }; let number: Option<u64> = test.block_number.map(Into::into); let schedule = match number { None => &old_schedule, Some(x) if x < 1_150_000 => &old_schedule, Some(_) => &new_schedule }; let allow_network_id_of_one = number.map_or(false, |n| n >= 2_675_000); let rlp: Vec<u8> = test.rlp.into(); let res = UntrustedRlp::new(&rlp) .as_val() .map_err(From::from) .and_then(|t: UnverifiedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one)); fail_unless(test.transaction.is_none() == res.is_err(), "Validity different"); if let (Some(tx), Some(sender)) = (test.transaction, test.sender) { let t = res.unwrap(); fail_unless(public_to_address(&t.recover_public().unwrap()) == sender.into(), "sender mismatch"); let is_acceptable_network_id = match t.network_id() { None => true, Some(1) if allow_network_id_of_one => true, _ => false, }; fail_unless(is_acceptable_network_id, "Network ID unacceptable"); let data: Vec<u8> = tx.data.into(); fail_unless(t.data == data, "data mismatch"); fail_unless(t.gas_price == tx.gas_price.into(), "gas_price mismatch"); fail_unless(t.nonce == tx.nonce.into(), "nonce mismatch"); fail_unless(t.value == tx.value.into(), "value mismatch"); let to: Option<ethjson::hash::Address> = tx.to.into(); let to: Option<Address> = to.map(Into::into); match t.action { Action::Call(dest) => fail_unless(Some(dest) == to, "call/destination mismatch"), Action::Create => fail_unless(None == to, "create mismatch"), } } } for f in &failed { println!("FAILED: {:?}", f); } failed } declare_test!{TransactionTests_ttTransactionTest, "TransactionTests/ttTransactionTest"} declare_test!{heavy => TransactionTests_tt10mbDataField, "TransactionTests/tt10mbDataField"} declare_test!{TransactionTests_ttWrongRLPTransaction, "TransactionTests/ttWrongRLPTransaction"} declare_test!{TransactionTests_Homestead_ttTransactionTest, "TransactionTests/Homestead/ttTransactionTest"} declare_test!{heavy => TransactionTests_Homestead_tt10mbDataField, "TransactionTests/Homestead/tt10mbDataField"} declare_test!{TransactionTests_Homestead_ttWrongRLPTransaction, "TransactionTests/Homestead/ttWrongRLPTransaction"} declare_test!{TransactionTests_RandomTests_tr201506052141PYTHON, "TransactionTests/RandomTests/tr201506052141PYTHON"} declare_test!{TransactionTests_Homestead_ttTransactionTestEip155VitaliksTests, "TransactionTests/Homestead/ttTransactionTestEip155VitaliksTests"} declare_test!{TransactionTests_EIP155_ttTransactionTest, "TransactionTests/EIP155/ttTransactionTest"} declare_test!{TransactionTests_EIP155_ttTransactionTestEip155VitaliksTests, "TransactionTests/EIP155/ttTransactionTestEip155VitaliksTests"} declare_test!{TransactionTests_EIP155_ttTransactionTestVRule, "TransactionTests/EIP155/ttTransactionTestVRule"}
do_json_test
identifier_name
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use super::test_common::*; use evm; use ethjson; use rlp::{UntrustedRlp, View}; use transaction::{Action, UnverifiedTransaction}; use ethstore::ethkey::public_to_address; fn do_json_test(json_data: &[u8]) -> Vec<String> { let tests = ethjson::transaction::Test::load(json_data).unwrap(); let mut failed = Vec::new(); let old_schedule = evm::Schedule::new_frontier(); let new_schedule = evm::Schedule::new_homestead(); for (name, test) in tests.into_iter() { let mut fail_unless = |cond: bool, title: &str| if!cond { failed.push(name.clone()); println!("Transaction failed: {:?}: {:?}", name, title); }; let number: Option<u64> = test.block_number.map(Into::into); let schedule = match number { None => &old_schedule, Some(x) if x < 1_150_000 => &old_schedule, Some(_) => &new_schedule }; let allow_network_id_of_one = number.map_or(false, |n| n >= 2_675_000);
let rlp: Vec<u8> = test.rlp.into(); let res = UntrustedRlp::new(&rlp) .as_val() .map_err(From::from) .and_then(|t: UnverifiedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one)); fail_unless(test.transaction.is_none() == res.is_err(), "Validity different"); if let (Some(tx), Some(sender)) = (test.transaction, test.sender) { let t = res.unwrap(); fail_unless(public_to_address(&t.recover_public().unwrap()) == sender.into(), "sender mismatch"); let is_acceptable_network_id = match t.network_id() { None => true, Some(1) if allow_network_id_of_one => true, _ => false, }; fail_unless(is_acceptable_network_id, "Network ID unacceptable"); let data: Vec<u8> = tx.data.into(); fail_unless(t.data == data, "data mismatch"); fail_unless(t.gas_price == tx.gas_price.into(), "gas_price mismatch"); fail_unless(t.nonce == tx.nonce.into(), "nonce mismatch"); fail_unless(t.value == tx.value.into(), "value mismatch"); let to: Option<ethjson::hash::Address> = tx.to.into(); let to: Option<Address> = to.map(Into::into); match t.action { Action::Call(dest) => fail_unless(Some(dest) == to, "call/destination mismatch"), Action::Create => fail_unless(None == to, "create mismatch"), } } } for f in &failed { println!("FAILED: {:?}", f); } failed } declare_test!{TransactionTests_ttTransactionTest, "TransactionTests/ttTransactionTest"} declare_test!{heavy => TransactionTests_tt10mbDataField, "TransactionTests/tt10mbDataField"} declare_test!{TransactionTests_ttWrongRLPTransaction, "TransactionTests/ttWrongRLPTransaction"} declare_test!{TransactionTests_Homestead_ttTransactionTest, "TransactionTests/Homestead/ttTransactionTest"} declare_test!{heavy => TransactionTests_Homestead_tt10mbDataField, "TransactionTests/Homestead/tt10mbDataField"} declare_test!{TransactionTests_Homestead_ttWrongRLPTransaction, "TransactionTests/Homestead/ttWrongRLPTransaction"} declare_test!{TransactionTests_RandomTests_tr201506052141PYTHON, "TransactionTests/RandomTests/tr201506052141PYTHON"} declare_test!{TransactionTests_Homestead_ttTransactionTestEip155VitaliksTests, "TransactionTests/Homestead/ttTransactionTestEip155VitaliksTests"} declare_test!{TransactionTests_EIP155_ttTransactionTest, "TransactionTests/EIP155/ttTransactionTest"} declare_test!{TransactionTests_EIP155_ttTransactionTestEip155VitaliksTests, "TransactionTests/EIP155/ttTransactionTestEip155VitaliksTests"} declare_test!{TransactionTests_EIP155_ttTransactionTestVRule, "TransactionTests/EIP155/ttTransactionTestVRule"}
random_line_split
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use super::test_common::*; use evm; use ethjson; use rlp::{UntrustedRlp, View}; use transaction::{Action, UnverifiedTransaction}; use ethstore::ethkey::public_to_address; fn do_json_test(json_data: &[u8]) -> Vec<String>
.and_then(|t: UnverifiedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one)); fail_unless(test.transaction.is_none() == res.is_err(), "Validity different"); if let (Some(tx), Some(sender)) = (test.transaction, test.sender) { let t = res.unwrap(); fail_unless(public_to_address(&t.recover_public().unwrap()) == sender.into(), "sender mismatch"); let is_acceptable_network_id = match t.network_id() { None => true, Some(1) if allow_network_id_of_one => true, _ => false, }; fail_unless(is_acceptable_network_id, "Network ID unacceptable"); let data: Vec<u8> = tx.data.into(); fail_unless(t.data == data, "data mismatch"); fail_unless(t.gas_price == tx.gas_price.into(), "gas_price mismatch"); fail_unless(t.nonce == tx.nonce.into(), "nonce mismatch"); fail_unless(t.value == tx.value.into(), "value mismatch"); let to: Option<ethjson::hash::Address> = tx.to.into(); let to: Option<Address> = to.map(Into::into); match t.action { Action::Call(dest) => fail_unless(Some(dest) == to, "call/destination mismatch"), Action::Create => fail_unless(None == to, "create mismatch"), } } } for f in &failed { println!("FAILED: {:?}", f); } failed } declare_test!{TransactionTests_ttTransactionTest, "TransactionTests/ttTransactionTest"} declare_test!{heavy => TransactionTests_tt10mbDataField, "TransactionTests/tt10mbDataField"} declare_test!{TransactionTests_ttWrongRLPTransaction, "TransactionTests/ttWrongRLPTransaction"} declare_test!{TransactionTests_Homestead_ttTransactionTest, "TransactionTests/Homestead/ttTransactionTest"} declare_test!{heavy => TransactionTests_Homestead_tt10mbDataField, "TransactionTests/Homestead/tt10mbDataField"} declare_test!{TransactionTests_Homestead_ttWrongRLPTransaction, "TransactionTests/Homestead/ttWrongRLPTransaction"} declare_test!{TransactionTests_RandomTests_tr201506052141PYTHON, "TransactionTests/RandomTests/tr201506052141PYTHON"} declare_test!{TransactionTests_Homestead_ttTransactionTestEip155VitaliksTests, "TransactionTests/Homestead/ttTransactionTestEip155VitaliksTests"} declare_test!{TransactionTests_EIP155_ttTransactionTest, "TransactionTests/EIP155/ttTransactionTest"} declare_test!{TransactionTests_EIP155_ttTransactionTestEip155VitaliksTests, "TransactionTests/EIP155/ttTransactionTestEip155VitaliksTests"} declare_test!{TransactionTests_EIP155_ttTransactionTestVRule, "TransactionTests/EIP155/ttTransactionTestVRule"}
{ let tests = ethjson::transaction::Test::load(json_data).unwrap(); let mut failed = Vec::new(); let old_schedule = evm::Schedule::new_frontier(); let new_schedule = evm::Schedule::new_homestead(); for (name, test) in tests.into_iter() { let mut fail_unless = |cond: bool, title: &str| if !cond { failed.push(name.clone()); println!("Transaction failed: {:?}: {:?}", name, title); }; let number: Option<u64> = test.block_number.map(Into::into); let schedule = match number { None => &old_schedule, Some(x) if x < 1_150_000 => &old_schedule, Some(_) => &new_schedule }; let allow_network_id_of_one = number.map_or(false, |n| n >= 2_675_000); let rlp: Vec<u8> = test.rlp.into(); let res = UntrustedRlp::new(&rlp) .as_val() .map_err(From::from)
identifier_body
lib.rs
//! This crate implements a standard linear Kalman filter and smoothing for //! vectors of arbitrary dimension. Implementation method relies on `rulinalg` //! library for linear algebra computations. Most inputs and outputs rely //! therefore on (derived) constructs from //! [rulinalg](https://athemathmo.github.io/rulinalg/doc/rulinalg/index.html) //! library, in particular //! [`Vector<f64>`](https://athemathmo.github.io/rulinalg/doc/rulinalg/vector/struct.Vector.html) //! and //! [`Matrix<f64>`](https://athemathmo.github.io/rulinalg/doc/rulinalg/matrix/struct.Matrix.html) //! structs. //! //! Currently, implementation method assumes that Kalman filter is time-invariant //! and is based on the equations detailed below. Notations in the below equations //! correspond to annotations in the source code. //! //! Measurement and state equations: //! //! * `z_{t} = H_{t} x_{t} + v_{t}` where `v_{t} ~ N(0, R_{t})` //! * `x_{t} = F_{t} x_{t-1} + B_{t} u_{t} + w_{t}` where `w_{t} ~ N(0, Q_{t})` //! //! Kalman filter equations: //! //! * `P_{t|t-1} = F_{t} P_{t-1|t-1} F'_{t} + Q_{t}` //! * `x_{t|t-1} = F_{t} x_{t-1|t-1} + B_{t} u_{t}` //! * `K_{t} = P_{t|t-1} H'_{t} * (H_{t} P_{t|t-1} H'_{t} + R_{t})^{-1}` //! * `P_{t|t} = (Id - K_{t} H_{t}) * P_{t|t-1}` //! * `x_{t|t} = x_{t|t-1} + K_{t} * (z_{t} - H_{t} x_{t|t-1})` //! //! Kalman smoothing equations: //! //! * `J_{t} = P_{t|t} F'_{t} P_{t+1|t}^{-1}` //! * `x_{t|T} = x_{t|t} + J_{t} * (x_{t+1|T} - x_{t+1|t})` //! * `P_{t|T} = P_{t|t} + J_{t} * (P_{t+1|T} - P_{t+1|t}) * J'_{t}` //! //! Nomenclature: //! //! * `(x_{t+1|t}, P_{t+1|t})` will be referred to as predicted state variables. //! * `(x_{t|t}, P_{t|t})` will be referred to as filtered state variables. //! * `(x_{t|T}, P_{t|T})` will be referred to as smoothed state variables. //! //! For now, it is assumed here that `B_{t}` matrix is null and that `Q_{t}, //! R_{t}, H_{t}` and `F_{t}` matrices are constant over time. //! //! Besides real data, algorithm takes as inputs `H`, `R`, `F` and `Q` matrices //! as well as initial guesses for state mean `x0 = x_{1|0}`and covariance //! matrix `P0 = P_{1|0}`. Covariance matrix `P0` indicates the uncertainty //! related to the guess of `x0`. extern crate rulinalg; use rulinalg::matrix::{BaseMatrix, Matrix}; use rulinalg::vector::Vector; /// Container object with values for matrices used in the Kalman filtering /// procedure as well as initial values for state variables. /// /// # Fields /// * `q`: process noise covariance /// * `r`: measurement noise covariance /// * `h`: observation matrix /// * `f`: state transition matrix /// * `x0`: initial guess for state mean at time 1 /// * `p0`: initial guess for state covariance at time 1 #[derive(Debug)] pub struct KalmanFilter { pub q: Matrix<f64>, // Process noise covariance pub r: Matrix<f64>, // Measurement noise covariance pub h: Matrix<f64>, // Observation matrix pub f: Matrix<f64>, // State transition matrix pub x0: Vector<f64>, // State variable initial value pub p0: Matrix<f64> // State covariance initial value } /// Container with the value of state variable and its covariance. This struct /// is used throughout all parts of Kalman procedure and may refer to predicted, /// filtered and smoothed variables depending on the context. #[derive(Clone, Debug)] pub struct KalmanState { pub x: Vector<f64>, // State vector pub p: Matrix<f64> // State covariance } impl KalmanFilter { /// Takes in measurement data and returns filtered data based on specified /// `KalmanFilter` struct. `filter` actually returns a 2-uple with the first /// coordinate being filtered data whereas the second coordinate is the (a /// priori) prediction data that can be used later in the smoothing /// procedure. /// /// # Examples /// /// ``` /// extern crate rulinalg; /// extern crate linearkalman; /// /// use rulinalg::matrix::Matrix; /// use rulinalg::vector::Vector; /// use linearkalman::KalmanFilter; /// /// fn main() { /// /// let kalman_filter = KalmanFilter { /// // All matrices are identity matrices /// q: Matrix::from_diag(&vec![1.0, 1.0]), /// r: Matrix::from_diag(&vec![1.0, 1.0]), /// h: Matrix::from_diag(&vec![1.0, 1.0]), /// f: Matrix::from_diag(&vec![1.0, 1.0]), /// x0: Vector::new(vec![1.0, 1.0]), /// p0: Matrix::from_diag(&vec![1.0, 1.0]) /// }; /// /// let data: Vec<Vector<f64>> = vec![Vector::new(vec![1.0, 1.0]), /// Vector::new(vec![1.0, 1.0])]; /// /// let run_filter = kalman_filter.filter(&data); /// /// // Due to the setup, filtering is equal to the data /// assert_eq!(data[0], run_filter.0[0].x); /// assert_eq!(data[1], run_filter.0[1].x); /// } /// ``` pub fn filter(&self, data: &Vec<Vector<f64>>) -> (Vec<KalmanState>, Vec<KalmanState>) { let t: usize = data.len(); // Containers for predicted and filtered estimates let mut predicted: Vec<KalmanState> = Vec::with_capacity(t+1); let mut filtered: Vec<KalmanState> = Vec::with_capacity(t); predicted.push(KalmanState { x: (self.x0).clone(), p: (self.p0).clone() }); for k in 0..t { filtered.push(update_step(self, &predicted[k], &data[k])); predicted.push(predict_step(self, &filtered[k])); } (filtered, predicted) } /// Takes in output from `filter` method and returns smoothed data. /// Smoothing procedure uses not only past values as is done by `filter` but /// also future values to better predict value of the underlying state /// variable. Underlying algorithm is known as Rauch-Tung-Striebel smoother /// for a fixed interval. Contrary to the filtering process, incremental /// smoothing would require re-running Kalman filter on the entire dataset. /// /// # Examples /// /// ``` /// extern crate rulinalg; /// extern crate linearkalman; /// /// use rulinalg::matrix::Matrix; /// use rulinalg::vector::Vector; /// use linearkalman::KalmanFilter; /// /// fn main() { /// /// let kalman_filter = KalmanFilter { /// // All matrices are identity matrices /// q: Matrix::from_diag(&vec![1.0, 1.0]), /// r: Matrix::from_diag(&vec![1.0, 1.0]), /// h: Matrix::from_diag(&vec![1.0, 1.0]), /// f: Matrix::from_diag(&vec![1.0, 1.0]), /// x0: Vector::new(vec![1.0, 1.0]), /// p0: Matrix::from_diag(&vec![1.0, 1.0]) /// }; /// /// let data: Vec<Vector<f64>> = vec![Vector::new(vec![1.0, 1.0]), /// Vector::new(vec![1.0, 1.0])]; /// /// let run_filter = kalman_filter.filter(&data); /// let run_smooth = kalman_filter.smooth(&run_filter.0, &run_filter.1); /// /// // Due to the setup, smoothing is equal to the data /// assert_eq!(data[0], run_smooth[0].x); /// assert_eq!(data[1], run_smooth[0].x); /// } /// ``` pub fn smooth(&self, filtered: &Vec<KalmanState>, predicted: &Vec<KalmanState>) -> Vec<KalmanState> { let t: usize = filtered.len(); let mut smoothed: Vec<KalmanState> = Vec::with_capacity(t); // Do Kalman smoothing in reverse order let mut init = (filtered[t - 1]).clone(); smoothed.push((filtered[t - 1]).clone()); for k in 1..t { smoothed.push(smoothing_step(self, &init, &filtered[t-k-1], &predicted[t-k])); init = (&smoothed[k]).clone(); } smoothed.reverse(); smoothed } } /// Returns a predicted state variable mean and covariance. If prediction for /// time `t` is desired, then `KalmanState` object with initial conditions /// contains state mean and covariance at time `t-1` given information up to /// time `t-1`. pub fn predict_step(kalman_filter: &KalmanFilter, init: &KalmanState) -> KalmanState { // Predict state variable and covariance let xp: Vector<f64> = &kalman_filter.f * &init.x; let pp: Matrix<f64> = &kalman_filter.f * &init.p * &kalman_filter.f.transpose() + &kalman_filter.q; KalmanState { x: xp, p: pp} } /// Returns an updated state variable mean and covariance given predicted and /// observed data. Typically, update step will be called after prediction step, /// data of which will be consequently used as input in updating. pub fn update_step(kalman_filter: &KalmanFilter, pred: &KalmanState, measure: &Vector<f64>) -> KalmanState { let identity = Matrix::<f64>::identity(kalman_filter.x0.size()); // Compute Kalman gain let k: Matrix<f64> = &pred.p * &kalman_filter.h.transpose() * (&kalman_filter.h * &pred.p * &kalman_filter.h.transpose() + &kalman_filter.r) .inverse() .expect("Kalman gain computation failed due to failure to invert."); // Update state variable and covariance let x = &pred.x + &k * (measure - &kalman_filter.h * &pred.x); let p = (identity - &k * &kalman_filter.h) * &pred.p; KalmanState { x: x, p: p } } /// Returns a tuple containing updated and predicted estimates (in that order) /// of the state variable and its covariance. This function might be useful for /// cases where data is incoming and being updated in real-time so that Kalman /// filtering is run incrementally. Note that given some initial values for `x` /// and `P`, `filter_step` makes a prediction and then runs the update step to /// correct the prediction based on the observed data. pub fn
(kalman_filter: &KalmanFilter, init: &KalmanState, measure: &Vector<f64>) -> (KalmanState, KalmanState) { let pred = predict_step(kalman_filter, init); let upd = update_step(kalman_filter, &pred, measure); (KalmanState { x: upd.x, p: upd.p }, KalmanState { x: pred.x, p: pred.p }) } fn smoothing_step(kalman_filter: &KalmanFilter, init: &KalmanState, filtered: &KalmanState, predicted: &KalmanState) -> KalmanState { let j: Matrix<f64> = &filtered.p * &kalman_filter.f.transpose() * &predicted.p.clone().inverse() .expect("Predicted state covariance matrix could not be inverted."); let x: Vector<f64> = &filtered.x + &j * (&init.x - &predicted.x); let p: Matrix<f64> = &filtered.p + &j * (&init.p - &predicted.p) * &j.transpose(); KalmanState { x: x, p: p } }
filter_step
identifier_name
lib.rs
//! This crate implements a standard linear Kalman filter and smoothing for //! vectors of arbitrary dimension. Implementation method relies on `rulinalg` //! library for linear algebra computations. Most inputs and outputs rely //! therefore on (derived) constructs from //! [rulinalg](https://athemathmo.github.io/rulinalg/doc/rulinalg/index.html) //! library, in particular //! [`Vector<f64>`](https://athemathmo.github.io/rulinalg/doc/rulinalg/vector/struct.Vector.html) //! and //! [`Matrix<f64>`](https://athemathmo.github.io/rulinalg/doc/rulinalg/matrix/struct.Matrix.html) //! structs. //! //! Currently, implementation method assumes that Kalman filter is time-invariant //! and is based on the equations detailed below. Notations in the below equations //! correspond to annotations in the source code. //! //! Measurement and state equations: //! //! * `z_{t} = H_{t} x_{t} + v_{t}` where `v_{t} ~ N(0, R_{t})` //! * `x_{t} = F_{t} x_{t-1} + B_{t} u_{t} + w_{t}` where `w_{t} ~ N(0, Q_{t})` //! //! Kalman filter equations: //! //! * `P_{t|t-1} = F_{t} P_{t-1|t-1} F'_{t} + Q_{t}` //! * `x_{t|t-1} = F_{t} x_{t-1|t-1} + B_{t} u_{t}` //! * `K_{t} = P_{t|t-1} H'_{t} * (H_{t} P_{t|t-1} H'_{t} + R_{t})^{-1}` //! * `P_{t|t} = (Id - K_{t} H_{t}) * P_{t|t-1}` //! * `x_{t|t} = x_{t|t-1} + K_{t} * (z_{t} - H_{t} x_{t|t-1})` //! //! Kalman smoothing equations: //! //! * `J_{t} = P_{t|t} F'_{t} P_{t+1|t}^{-1}` //! * `x_{t|T} = x_{t|t} + J_{t} * (x_{t+1|T} - x_{t+1|t})` //! * `P_{t|T} = P_{t|t} + J_{t} * (P_{t+1|T} - P_{t+1|t}) * J'_{t}` //! //! Nomenclature: //! //! * `(x_{t+1|t}, P_{t+1|t})` will be referred to as predicted state variables. //! * `(x_{t|t}, P_{t|t})` will be referred to as filtered state variables. //! * `(x_{t|T}, P_{t|T})` will be referred to as smoothed state variables. //! //! For now, it is assumed here that `B_{t}` matrix is null and that `Q_{t}, //! R_{t}, H_{t}` and `F_{t}` matrices are constant over time. //! //! Besides real data, algorithm takes as inputs `H`, `R`, `F` and `Q` matrices //! as well as initial guesses for state mean `x0 = x_{1|0}`and covariance //! matrix `P0 = P_{1|0}`. Covariance matrix `P0` indicates the uncertainty //! related to the guess of `x0`. extern crate rulinalg; use rulinalg::matrix::{BaseMatrix, Matrix}; use rulinalg::vector::Vector; /// Container object with values for matrices used in the Kalman filtering /// procedure as well as initial values for state variables. /// /// # Fields /// * `q`: process noise covariance /// * `r`: measurement noise covariance /// * `h`: observation matrix /// * `f`: state transition matrix /// * `x0`: initial guess for state mean at time 1 /// * `p0`: initial guess for state covariance at time 1 #[derive(Debug)] pub struct KalmanFilter { pub q: Matrix<f64>, // Process noise covariance pub r: Matrix<f64>, // Measurement noise covariance pub h: Matrix<f64>, // Observation matrix pub f: Matrix<f64>, // State transition matrix pub x0: Vector<f64>, // State variable initial value pub p0: Matrix<f64> // State covariance initial value } /// Container with the value of state variable and its covariance. This struct /// is used throughout all parts of Kalman procedure and may refer to predicted, /// filtered and smoothed variables depending on the context. #[derive(Clone, Debug)] pub struct KalmanState { pub x: Vector<f64>, // State vector pub p: Matrix<f64> // State covariance } impl KalmanFilter { /// Takes in measurement data and returns filtered data based on specified /// `KalmanFilter` struct. `filter` actually returns a 2-uple with the first /// coordinate being filtered data whereas the second coordinate is the (a /// priori) prediction data that can be used later in the smoothing /// procedure. /// /// # Examples /// /// ``` /// extern crate rulinalg; /// extern crate linearkalman; /// /// use rulinalg::matrix::Matrix; /// use rulinalg::vector::Vector; /// use linearkalman::KalmanFilter; /// /// fn main() { /// /// let kalman_filter = KalmanFilter { /// // All matrices are identity matrices /// q: Matrix::from_diag(&vec![1.0, 1.0]), /// r: Matrix::from_diag(&vec![1.0, 1.0]), /// h: Matrix::from_diag(&vec![1.0, 1.0]), /// f: Matrix::from_diag(&vec![1.0, 1.0]), /// x0: Vector::new(vec![1.0, 1.0]), /// p0: Matrix::from_diag(&vec![1.0, 1.0]) /// }; /// /// let data: Vec<Vector<f64>> = vec![Vector::new(vec![1.0, 1.0]), /// Vector::new(vec![1.0, 1.0])]; /// /// let run_filter = kalman_filter.filter(&data); /// /// // Due to the setup, filtering is equal to the data /// assert_eq!(data[0], run_filter.0[0].x); /// assert_eq!(data[1], run_filter.0[1].x); /// } /// ``` pub fn filter(&self, data: &Vec<Vector<f64>>) -> (Vec<KalmanState>, Vec<KalmanState>) { let t: usize = data.len(); // Containers for predicted and filtered estimates let mut predicted: Vec<KalmanState> = Vec::with_capacity(t+1); let mut filtered: Vec<KalmanState> = Vec::with_capacity(t); predicted.push(KalmanState { x: (self.x0).clone(), p: (self.p0).clone() }); for k in 0..t { filtered.push(update_step(self, &predicted[k], &data[k])); predicted.push(predict_step(self, &filtered[k])); } (filtered, predicted) } /// Takes in output from `filter` method and returns smoothed data. /// Smoothing procedure uses not only past values as is done by `filter` but /// also future values to better predict value of the underlying state /// variable. Underlying algorithm is known as Rauch-Tung-Striebel smoother /// for a fixed interval. Contrary to the filtering process, incremental /// smoothing would require re-running Kalman filter on the entire dataset. /// /// # Examples /// /// ``` /// extern crate rulinalg; /// extern crate linearkalman; /// /// use rulinalg::matrix::Matrix; /// use rulinalg::vector::Vector; /// use linearkalman::KalmanFilter; /// /// fn main() { /// /// let kalman_filter = KalmanFilter { /// // All matrices are identity matrices /// q: Matrix::from_diag(&vec![1.0, 1.0]), /// r: Matrix::from_diag(&vec![1.0, 1.0]), /// h: Matrix::from_diag(&vec![1.0, 1.0]), /// f: Matrix::from_diag(&vec![1.0, 1.0]), /// x0: Vector::new(vec![1.0, 1.0]), /// p0: Matrix::from_diag(&vec![1.0, 1.0]) /// }; /// /// let data: Vec<Vector<f64>> = vec![Vector::new(vec![1.0, 1.0]), /// Vector::new(vec![1.0, 1.0])]; /// /// let run_filter = kalman_filter.filter(&data); /// let run_smooth = kalman_filter.smooth(&run_filter.0, &run_filter.1); /// /// // Due to the setup, smoothing is equal to the data /// assert_eq!(data[0], run_smooth[0].x); /// assert_eq!(data[1], run_smooth[0].x); /// } /// ``` pub fn smooth(&self, filtered: &Vec<KalmanState>, predicted: &Vec<KalmanState>) -> Vec<KalmanState> { let t: usize = filtered.len(); let mut smoothed: Vec<KalmanState> = Vec::with_capacity(t); // Do Kalman smoothing in reverse order let mut init = (filtered[t - 1]).clone(); smoothed.push((filtered[t - 1]).clone()); for k in 1..t { smoothed.push(smoothing_step(self, &init, &filtered[t-k-1], &predicted[t-k])); init = (&smoothed[k]).clone(); } smoothed.reverse(); smoothed } } /// Returns a predicted state variable mean and covariance. If prediction for /// time `t` is desired, then `KalmanState` object with initial conditions /// contains state mean and covariance at time `t-1` given information up to /// time `t-1`. pub fn predict_step(kalman_filter: &KalmanFilter, init: &KalmanState) -> KalmanState { // Predict state variable and covariance let xp: Vector<f64> = &kalman_filter.f * &init.x; let pp: Matrix<f64> = &kalman_filter.f * &init.p * &kalman_filter.f.transpose() + &kalman_filter.q; KalmanState { x: xp, p: pp} } /// Returns an updated state variable mean and covariance given predicted and /// observed data. Typically, update step will be called after prediction step, /// data of which will be consequently used as input in updating. pub fn update_step(kalman_filter: &KalmanFilter, pred: &KalmanState, measure: &Vector<f64>) -> KalmanState { let identity = Matrix::<f64>::identity(kalman_filter.x0.size()); // Compute Kalman gain let k: Matrix<f64> = &pred.p * &kalman_filter.h.transpose() * (&kalman_filter.h * &pred.p * &kalman_filter.h.transpose() + &kalman_filter.r) .inverse() .expect("Kalman gain computation failed due to failure to invert."); // Update state variable and covariance let x = &pred.x + &k * (measure - &kalman_filter.h * &pred.x); let p = (identity - &k * &kalman_filter.h) * &pred.p; KalmanState { x: x, p: p } } /// Returns a tuple containing updated and predicted estimates (in that order) /// of the state variable and its covariance. This function might be useful for /// cases where data is incoming and being updated in real-time so that Kalman /// filtering is run incrementally. Note that given some initial values for `x` /// and `P`, `filter_step` makes a prediction and then runs the update step to /// correct the prediction based on the observed data. pub fn filter_step(kalman_filter: &KalmanFilter, init: &KalmanState, measure: &Vector<f64>) -> (KalmanState, KalmanState) { let pred = predict_step(kalman_filter, init); let upd = update_step(kalman_filter, &pred, measure); (KalmanState { x: upd.x, p: upd.p }, KalmanState { x: pred.x, p: pred.p }) } fn smoothing_step(kalman_filter: &KalmanFilter, init: &KalmanState, filtered: &KalmanState, predicted: &KalmanState) -> KalmanState
{ let j: Matrix<f64> = &filtered.p * &kalman_filter.f.transpose() * &predicted.p.clone().inverse() .expect("Predicted state covariance matrix could not be inverted."); let x: Vector<f64> = &filtered.x + &j * (&init.x - &predicted.x); let p: Matrix<f64> = &filtered.p + &j * (&init.p - &predicted.p) * &j.transpose(); KalmanState { x: x, p: p } }
identifier_body
lib.rs
//! This crate implements a standard linear Kalman filter and smoothing for //! vectors of arbitrary dimension. Implementation method relies on `rulinalg` //! library for linear algebra computations. Most inputs and outputs rely //! therefore on (derived) constructs from //! [rulinalg](https://athemathmo.github.io/rulinalg/doc/rulinalg/index.html) //! library, in particular //! [`Vector<f64>`](https://athemathmo.github.io/rulinalg/doc/rulinalg/vector/struct.Vector.html) //! and //! [`Matrix<f64>`](https://athemathmo.github.io/rulinalg/doc/rulinalg/matrix/struct.Matrix.html) //! structs. //! //! Currently, implementation method assumes that Kalman filter is time-invariant //! and is based on the equations detailed below. Notations in the below equations //! correspond to annotations in the source code. //! //! Measurement and state equations: //! //! * `z_{t} = H_{t} x_{t} + v_{t}` where `v_{t} ~ N(0, R_{t})` //! * `x_{t} = F_{t} x_{t-1} + B_{t} u_{t} + w_{t}` where `w_{t} ~ N(0, Q_{t})` //! //! Kalman filter equations: //! //! * `P_{t|t-1} = F_{t} P_{t-1|t-1} F'_{t} + Q_{t}` //! * `x_{t|t-1} = F_{t} x_{t-1|t-1} + B_{t} u_{t}` //! * `K_{t} = P_{t|t-1} H'_{t} * (H_{t} P_{t|t-1} H'_{t} + R_{t})^{-1}` //! * `P_{t|t} = (Id - K_{t} H_{t}) * P_{t|t-1}` //! * `x_{t|t} = x_{t|t-1} + K_{t} * (z_{t} - H_{t} x_{t|t-1})` //! //! Kalman smoothing equations: //! //! * `J_{t} = P_{t|t} F'_{t} P_{t+1|t}^{-1}` //! * `x_{t|T} = x_{t|t} + J_{t} * (x_{t+1|T} - x_{t+1|t})` //! * `P_{t|T} = P_{t|t} + J_{t} * (P_{t+1|T} - P_{t+1|t}) * J'_{t}` //! //! Nomenclature: //! //! * `(x_{t+1|t}, P_{t+1|t})` will be referred to as predicted state variables. //! * `(x_{t|t}, P_{t|t})` will be referred to as filtered state variables. //! * `(x_{t|T}, P_{t|T})` will be referred to as smoothed state variables. //! //! For now, it is assumed here that `B_{t}` matrix is null and that `Q_{t}, //! R_{t}, H_{t}` and `F_{t}` matrices are constant over time. //! //! Besides real data, algorithm takes as inputs `H`, `R`, `F` and `Q` matrices //! as well as initial guesses for state mean `x0 = x_{1|0}`and covariance //! matrix `P0 = P_{1|0}`. Covariance matrix `P0` indicates the uncertainty //! related to the guess of `x0`. extern crate rulinalg; use rulinalg::matrix::{BaseMatrix, Matrix}; use rulinalg::vector::Vector; /// Container object with values for matrices used in the Kalman filtering /// procedure as well as initial values for state variables. /// /// # Fields /// * `q`: process noise covariance /// * `r`: measurement noise covariance /// * `h`: observation matrix /// * `f`: state transition matrix /// * `x0`: initial guess for state mean at time 1 /// * `p0`: initial guess for state covariance at time 1 #[derive(Debug)] pub struct KalmanFilter { pub q: Matrix<f64>, // Process noise covariance pub r: Matrix<f64>, // Measurement noise covariance pub h: Matrix<f64>, // Observation matrix pub f: Matrix<f64>, // State transition matrix pub x0: Vector<f64>, // State variable initial value pub p0: Matrix<f64> // State covariance initial value } /// Container with the value of state variable and its covariance. This struct /// is used throughout all parts of Kalman procedure and may refer to predicted, /// filtered and smoothed variables depending on the context. #[derive(Clone, Debug)] pub struct KalmanState { pub x: Vector<f64>, // State vector pub p: Matrix<f64> // State covariance } impl KalmanFilter { /// Takes in measurement data and returns filtered data based on specified /// `KalmanFilter` struct. `filter` actually returns a 2-uple with the first /// coordinate being filtered data whereas the second coordinate is the (a /// priori) prediction data that can be used later in the smoothing /// procedure. /// /// # Examples /// /// ``` /// extern crate rulinalg; /// extern crate linearkalman; /// /// use rulinalg::matrix::Matrix; /// use rulinalg::vector::Vector; /// use linearkalman::KalmanFilter; /// /// fn main() { /// /// let kalman_filter = KalmanFilter { /// // All matrices are identity matrices /// q: Matrix::from_diag(&vec![1.0, 1.0]), /// r: Matrix::from_diag(&vec![1.0, 1.0]), /// h: Matrix::from_diag(&vec![1.0, 1.0]), /// f: Matrix::from_diag(&vec![1.0, 1.0]), /// x0: Vector::new(vec![1.0, 1.0]), /// p0: Matrix::from_diag(&vec![1.0, 1.0]) /// }; /// /// let data: Vec<Vector<f64>> = vec![Vector::new(vec![1.0, 1.0]), /// Vector::new(vec![1.0, 1.0])]; /// /// let run_filter = kalman_filter.filter(&data); /// /// // Due to the setup, filtering is equal to the data /// assert_eq!(data[0], run_filter.0[0].x); /// assert_eq!(data[1], run_filter.0[1].x); /// } /// ``` pub fn filter(&self, data: &Vec<Vector<f64>>) -> (Vec<KalmanState>, Vec<KalmanState>) { let t: usize = data.len(); // Containers for predicted and filtered estimates let mut predicted: Vec<KalmanState> = Vec::with_capacity(t+1); let mut filtered: Vec<KalmanState> = Vec::with_capacity(t); predicted.push(KalmanState { x: (self.x0).clone(), p: (self.p0).clone() }); for k in 0..t { filtered.push(update_step(self, &predicted[k], &data[k])); predicted.push(predict_step(self, &filtered[k])); } (filtered, predicted) } /// Takes in output from `filter` method and returns smoothed data. /// Smoothing procedure uses not only past values as is done by `filter` but /// also future values to better predict value of the underlying state /// variable. Underlying algorithm is known as Rauch-Tung-Striebel smoother /// for a fixed interval. Contrary to the filtering process, incremental /// smoothing would require re-running Kalman filter on the entire dataset. /// /// # Examples /// /// ``` /// extern crate rulinalg; /// extern crate linearkalman; /// /// use rulinalg::matrix::Matrix; /// use rulinalg::vector::Vector;
/// /// fn main() { /// /// let kalman_filter = KalmanFilter { /// // All matrices are identity matrices /// q: Matrix::from_diag(&vec![1.0, 1.0]), /// r: Matrix::from_diag(&vec![1.0, 1.0]), /// h: Matrix::from_diag(&vec![1.0, 1.0]), /// f: Matrix::from_diag(&vec![1.0, 1.0]), /// x0: Vector::new(vec![1.0, 1.0]), /// p0: Matrix::from_diag(&vec![1.0, 1.0]) /// }; /// /// let data: Vec<Vector<f64>> = vec![Vector::new(vec![1.0, 1.0]), /// Vector::new(vec![1.0, 1.0])]; /// /// let run_filter = kalman_filter.filter(&data); /// let run_smooth = kalman_filter.smooth(&run_filter.0, &run_filter.1); /// /// // Due to the setup, smoothing is equal to the data /// assert_eq!(data[0], run_smooth[0].x); /// assert_eq!(data[1], run_smooth[0].x); /// } /// ``` pub fn smooth(&self, filtered: &Vec<KalmanState>, predicted: &Vec<KalmanState>) -> Vec<KalmanState> { let t: usize = filtered.len(); let mut smoothed: Vec<KalmanState> = Vec::with_capacity(t); // Do Kalman smoothing in reverse order let mut init = (filtered[t - 1]).clone(); smoothed.push((filtered[t - 1]).clone()); for k in 1..t { smoothed.push(smoothing_step(self, &init, &filtered[t-k-1], &predicted[t-k])); init = (&smoothed[k]).clone(); } smoothed.reverse(); smoothed } } /// Returns a predicted state variable mean and covariance. If prediction for /// time `t` is desired, then `KalmanState` object with initial conditions /// contains state mean and covariance at time `t-1` given information up to /// time `t-1`. pub fn predict_step(kalman_filter: &KalmanFilter, init: &KalmanState) -> KalmanState { // Predict state variable and covariance let xp: Vector<f64> = &kalman_filter.f * &init.x; let pp: Matrix<f64> = &kalman_filter.f * &init.p * &kalman_filter.f.transpose() + &kalman_filter.q; KalmanState { x: xp, p: pp} } /// Returns an updated state variable mean and covariance given predicted and /// observed data. Typically, update step will be called after prediction step, /// data of which will be consequently used as input in updating. pub fn update_step(kalman_filter: &KalmanFilter, pred: &KalmanState, measure: &Vector<f64>) -> KalmanState { let identity = Matrix::<f64>::identity(kalman_filter.x0.size()); // Compute Kalman gain let k: Matrix<f64> = &pred.p * &kalman_filter.h.transpose() * (&kalman_filter.h * &pred.p * &kalman_filter.h.transpose() + &kalman_filter.r) .inverse() .expect("Kalman gain computation failed due to failure to invert."); // Update state variable and covariance let x = &pred.x + &k * (measure - &kalman_filter.h * &pred.x); let p = (identity - &k * &kalman_filter.h) * &pred.p; KalmanState { x: x, p: p } } /// Returns a tuple containing updated and predicted estimates (in that order) /// of the state variable and its covariance. This function might be useful for /// cases where data is incoming and being updated in real-time so that Kalman /// filtering is run incrementally. Note that given some initial values for `x` /// and `P`, `filter_step` makes a prediction and then runs the update step to /// correct the prediction based on the observed data. pub fn filter_step(kalman_filter: &KalmanFilter, init: &KalmanState, measure: &Vector<f64>) -> (KalmanState, KalmanState) { let pred = predict_step(kalman_filter, init); let upd = update_step(kalman_filter, &pred, measure); (KalmanState { x: upd.x, p: upd.p }, KalmanState { x: pred.x, p: pred.p }) } fn smoothing_step(kalman_filter: &KalmanFilter, init: &KalmanState, filtered: &KalmanState, predicted: &KalmanState) -> KalmanState { let j: Matrix<f64> = &filtered.p * &kalman_filter.f.transpose() * &predicted.p.clone().inverse() .expect("Predicted state covariance matrix could not be inverted."); let x: Vector<f64> = &filtered.x + &j * (&init.x - &predicted.x); let p: Matrix<f64> = &filtered.p + &j * (&init.p - &predicted.p) * &j.transpose(); KalmanState { x: x, p: p } }
/// use linearkalman::KalmanFilter;
random_line_split
explicit_null.rs
use juniper::{ graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription, GraphQLInputObject, Nullable, Variables, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[derive(GraphQLInputObject)] struct ObjectInput { field: Nullable<i32>, } #[graphql_object(context = Context)] impl Query { fn is_explicit_null(arg: Nullable<i32>) -> bool { arg.is_explicit_null() } fn object_field_is_explicit_null(obj: ObjectInput) -> bool { obj.field.is_explicit_null() } } type Schema = juniper::RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; #[tokio::test] async fn explicit_null() { let query = r#" query Foo($emptyObj: ObjectInput!, $literalNullObj: ObjectInput!) { literalOneIsExplicitNull: isExplicitNull(arg: 1) literalNullIsExplicitNull: isExplicitNull(arg: null) noArgIsExplicitNull: isExplicitNull literalOneFieldIsExplicitNull: objectFieldIsExplicitNull(obj: {field: 1}) literalNullFieldIsExplicitNull: objectFieldIsExplicitNull(obj: {field: null}) noFieldIsExplicitNull: objectFieldIsExplicitNull(obj: {}) emptyVariableObjectFieldIsExplicitNull: objectFieldIsExplicitNull(obj: $emptyObj) literalNullVariableObjectFieldIsExplicitNull: objectFieldIsExplicitNull(obj: $literalNullObj) } "#; let schema = &Schema::new( Query, EmptyMutation::<Context>::new(), EmptySubscription::<Context>::new(), ); let vars: Variables = graphql_vars! { "emptyObj": {}, "literalNullObj": {"field": null}, }; assert_eq!( juniper::execute(query, None, &schema, &vars, &Context).await, Ok(( graphql_value!({
"noArgIsExplicitNull": false, "literalOneFieldIsExplicitNull": false, "literalNullFieldIsExplicitNull": true, "noFieldIsExplicitNull": false, "emptyVariableObjectFieldIsExplicitNull": false, "literalNullVariableObjectFieldIsExplicitNull": true, }), vec![], )), ); }
"literalOneIsExplicitNull": false, "literalNullIsExplicitNull": true,
random_line_split
explicit_null.rs
use juniper::{ graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription, GraphQLInputObject, Nullable, Variables, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[derive(GraphQLInputObject)] struct ObjectInput { field: Nullable<i32>, } #[graphql_object(context = Context)] impl Query { fn is_explicit_null(arg: Nullable<i32>) -> bool { arg.is_explicit_null() } fn object_field_is_explicit_null(obj: ObjectInput) -> bool { obj.field.is_explicit_null() } } type Schema = juniper::RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; #[tokio::test] async fn
() { let query = r#" query Foo($emptyObj: ObjectInput!, $literalNullObj: ObjectInput!) { literalOneIsExplicitNull: isExplicitNull(arg: 1) literalNullIsExplicitNull: isExplicitNull(arg: null) noArgIsExplicitNull: isExplicitNull literalOneFieldIsExplicitNull: objectFieldIsExplicitNull(obj: {field: 1}) literalNullFieldIsExplicitNull: objectFieldIsExplicitNull(obj: {field: null}) noFieldIsExplicitNull: objectFieldIsExplicitNull(obj: {}) emptyVariableObjectFieldIsExplicitNull: objectFieldIsExplicitNull(obj: $emptyObj) literalNullVariableObjectFieldIsExplicitNull: objectFieldIsExplicitNull(obj: $literalNullObj) } "#; let schema = &Schema::new( Query, EmptyMutation::<Context>::new(), EmptySubscription::<Context>::new(), ); let vars: Variables = graphql_vars! { "emptyObj": {}, "literalNullObj": {"field": null}, }; assert_eq!( juniper::execute(query, None, &schema, &vars, &Context).await, Ok(( graphql_value!({ "literalOneIsExplicitNull": false, "literalNullIsExplicitNull": true, "noArgIsExplicitNull": false, "literalOneFieldIsExplicitNull": false, "literalNullFieldIsExplicitNull": true, "noFieldIsExplicitNull": false, "emptyVariableObjectFieldIsExplicitNull": false, "literalNullVariableObjectFieldIsExplicitNull": true, }), vec![], )), ); }
explicit_null
identifier_name
resource-destruct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; struct shrinky_pointer<'a> { i: &'a Cell<isize>, } impl<'a> Drop for shrinky_pointer<'a> { fn drop(&mut self) { println!("Hello!"); self.i.set(self.i.get() - 1); } } impl<'a> shrinky_pointer<'a> { pub fn look_at(&self) -> isize { return self.i.get(); } } fn shrinky_pointer(i: &Cell<isize>) -> shrinky_pointer { shrinky_pointer { i: i } } pub fn
() { let my_total = &Cell::new(10); { let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); } println!("my_total = {}", my_total.get()); assert_eq!(my_total.get(), 9); }
main
identifier_name
resource-destruct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; struct shrinky_pointer<'a> { i: &'a Cell<isize>, } impl<'a> Drop for shrinky_pointer<'a> { fn drop(&mut self) { println!("Hello!"); self.i.set(self.i.get() - 1); } } impl<'a> shrinky_pointer<'a> { pub fn look_at(&self) -> isize
} fn shrinky_pointer(i: &Cell<isize>) -> shrinky_pointer { shrinky_pointer { i: i } } pub fn main() { let my_total = &Cell::new(10); { let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); } println!("my_total = {}", my_total.get()); assert_eq!(my_total.get(), 9); }
{ return self.i.get(); }
identifier_body
resource-destruct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; struct shrinky_pointer<'a> { i: &'a Cell<isize>, } impl<'a> Drop for shrinky_pointer<'a> { fn drop(&mut self) { println!("Hello!"); self.i.set(self.i.get() - 1); } } impl<'a> shrinky_pointer<'a> { pub fn look_at(&self) -> isize { return self.i.get(); } } fn shrinky_pointer(i: &Cell<isize>) -> shrinky_pointer { shrinky_pointer { i: i } } pub fn main() { let my_total = &Cell::new(10); { let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); } println!("my_total = {}", my_total.get()); assert_eq!(my_total.get(), 9); }
random_line_split
main.rs
extern crate graphics; extern crate freetype as ft; extern crate sdl2_window; extern crate opengl_graphics; extern crate piston; extern crate find_folder; use sdl2_window::Sdl2Window; use opengl_graphics::{ GlGraphics, Texture, OpenGL }; use graphics::math::Matrix2d; use piston::window::WindowSettings; use piston::event::*; fn render_text(face: &mut ft::Face, gl: &mut GlGraphics, t: Matrix2d, text: &str) { use graphics::*; let mut x = 10; let mut y = 0; for ch in text.chars() { face.load_char(ch as usize, ft::face::RENDER).unwrap(); let g = face.glyph(); let bitmap = g.bitmap(); let texture = Texture::from_memory_alpha(bitmap.buffer(), bitmap.width() as u32, bitmap.rows() as u32).unwrap(); Image::new_colored(color::BLACK).draw( &texture, default_draw_state(), t.trans((x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64), gl ); x += (g.advance().x >> 6) as i32; y += (g.advance().y >> 6) as i32; } } fn main() { let opengl = OpenGL::V3_2; let window: Sdl2Window = WindowSettings::new("piston-example-freetype", [300, 300]) .exit_on_esc(true) .opengl(opengl) .into(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let freetype = ft::Library::init().unwrap(); let font = assets.join("FiraSans-Regular.ttf"); let mut face = freetype.new_face(&font, 0).unwrap(); face.set_pixel_sizes(0, 48).unwrap(); let ref mut gl = GlGraphics::new(opengl); for e in window.events() { if let Some(args) = e.render_args()
} }
{ use graphics::*; gl.draw(args.viewport(), |c, gl| { let transform = c.transform.trans(0.0, 100.0); clear(color::WHITE, gl); render_text(&mut face, gl, transform, "Hello Piston!"); }); }
conditional_block
main.rs
extern crate graphics; extern crate freetype as ft; extern crate sdl2_window; extern crate opengl_graphics; extern crate piston; extern crate find_folder; use sdl2_window::Sdl2Window; use opengl_graphics::{ GlGraphics, Texture, OpenGL }; use graphics::math::Matrix2d; use piston::window::WindowSettings; use piston::event::*; fn render_text(face: &mut ft::Face, gl: &mut GlGraphics, t: Matrix2d, text: &str) { use graphics::*; let mut x = 10; let mut y = 0; for ch in text.chars() { face.load_char(ch as usize, ft::face::RENDER).unwrap(); let g = face.glyph(); let bitmap = g.bitmap(); let texture = Texture::from_memory_alpha(bitmap.buffer(), bitmap.width() as u32, bitmap.rows() as u32).unwrap(); Image::new_colored(color::BLACK).draw( &texture, default_draw_state(), t.trans((x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64), gl ); x += (g.advance().x >> 6) as i32; y += (g.advance().y >> 6) as i32; } } fn main()
gl.draw(args.viewport(), |c, gl| { let transform = c.transform.trans(0.0, 100.0); clear(color::WHITE, gl); render_text(&mut face, gl, transform, "Hello Piston!"); }); } } }
{ let opengl = OpenGL::V3_2; let window: Sdl2Window = WindowSettings::new("piston-example-freetype", [300, 300]) .exit_on_esc(true) .opengl(opengl) .into(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let freetype = ft::Library::init().unwrap(); let font = assets.join("FiraSans-Regular.ttf"); let mut face = freetype.new_face(&font, 0).unwrap(); face.set_pixel_sizes(0, 48).unwrap(); let ref mut gl = GlGraphics::new(opengl); for e in window.events() { if let Some(args) = e.render_args() { use graphics::*;
identifier_body
main.rs
extern crate graphics; extern crate freetype as ft; extern crate sdl2_window; extern crate opengl_graphics; extern crate piston; extern crate find_folder; use sdl2_window::Sdl2Window; use opengl_graphics::{ GlGraphics, Texture, OpenGL }; use graphics::math::Matrix2d; use piston::window::WindowSettings; use piston::event::*; fn
(face: &mut ft::Face, gl: &mut GlGraphics, t: Matrix2d, text: &str) { use graphics::*; let mut x = 10; let mut y = 0; for ch in text.chars() { face.load_char(ch as usize, ft::face::RENDER).unwrap(); let g = face.glyph(); let bitmap = g.bitmap(); let texture = Texture::from_memory_alpha(bitmap.buffer(), bitmap.width() as u32, bitmap.rows() as u32).unwrap(); Image::new_colored(color::BLACK).draw( &texture, default_draw_state(), t.trans((x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64), gl ); x += (g.advance().x >> 6) as i32; y += (g.advance().y >> 6) as i32; } } fn main() { let opengl = OpenGL::V3_2; let window: Sdl2Window = WindowSettings::new("piston-example-freetype", [300, 300]) .exit_on_esc(true) .opengl(opengl) .into(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let freetype = ft::Library::init().unwrap(); let font = assets.join("FiraSans-Regular.ttf"); let mut face = freetype.new_face(&font, 0).unwrap(); face.set_pixel_sizes(0, 48).unwrap(); let ref mut gl = GlGraphics::new(opengl); for e in window.events() { if let Some(args) = e.render_args() { use graphics::*; gl.draw(args.viewport(), |c, gl| { let transform = c.transform.trans(0.0, 100.0); clear(color::WHITE, gl); render_text(&mut face, gl, transform, "Hello Piston!"); }); } } }
render_text
identifier_name
main.rs
extern crate graphics; extern crate freetype as ft; extern crate sdl2_window; extern crate opengl_graphics; extern crate piston; extern crate find_folder; use sdl2_window::Sdl2Window; use opengl_graphics::{ GlGraphics, Texture, OpenGL }; use graphics::math::Matrix2d; use piston::window::WindowSettings; use piston::event::*; fn render_text(face: &mut ft::Face, gl: &mut GlGraphics, t: Matrix2d, text: &str) { use graphics::*; let mut x = 10; let mut y = 0; for ch in text.chars() { face.load_char(ch as usize, ft::face::RENDER).unwrap(); let g = face.glyph(); let bitmap = g.bitmap(); let texture = Texture::from_memory_alpha(bitmap.buffer(), bitmap.width() as u32, bitmap.rows() as u32).unwrap(); Image::new_colored(color::BLACK).draw( &texture, default_draw_state(), t.trans((x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64), gl ); x += (g.advance().x >> 6) as i32; y += (g.advance().y >> 6) as i32; } } fn main() { let opengl = OpenGL::V3_2; let window: Sdl2Window = WindowSettings::new("piston-example-freetype", [300, 300]) .exit_on_esc(true) .opengl(opengl) .into(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let freetype = ft::Library::init().unwrap(); let font = assets.join("FiraSans-Regular.ttf"); let mut face = freetype.new_face(&font, 0).unwrap(); face.set_pixel_sizes(0, 48).unwrap(); let ref mut gl = GlGraphics::new(opengl); for e in window.events() { if let Some(args) = e.render_args() { use graphics::*; gl.draw(args.viewport(), |c, gl| { let transform = c.transform.trans(0.0, 100.0); clear(color::WHITE, gl); render_text(&mut face, gl, transform, "Hello Piston!"); });
} } }
random_line_split
navigatorinfo.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::str::DOMString; use util::opts; pub fn Product() -> DOMString { DOMString::from("Gecko") } pub fn
() -> bool { false } pub fn AppName() -> DOMString { DOMString::from("Netscape") // Like Gecko/Webkit } pub fn AppCodeName() -> DOMString { DOMString::from("Mozilla") } #[cfg(target_os = "windows")] pub fn Platform() -> DOMString { DOMString::from("Win32") } #[cfg(any(target_os = "android", target_os = "linux"))] pub fn Platform() -> DOMString { DOMString::from("Linux") } #[cfg(target_os = "macos")] pub fn Platform() -> DOMString { DOMString::from("Mac") } pub fn UserAgent() -> DOMString { DOMString::from(&*opts::get().user_agent) } pub fn AppVersion() -> DOMString { DOMString::from("4.0") } pub fn Language() -> DOMString { DOMString::from("en-US") }
TaintEnabled
identifier_name
navigatorinfo.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::str::DOMString; use util::opts; pub fn Product() -> DOMString { DOMString::from("Gecko") } pub fn TaintEnabled() -> bool { false } pub fn AppName() -> DOMString { DOMString::from("Netscape") // Like Gecko/Webkit } pub fn AppCodeName() -> DOMString { DOMString::from("Mozilla") } #[cfg(target_os = "windows")] pub fn Platform() -> DOMString { DOMString::from("Win32") } #[cfg(any(target_os = "android", target_os = "linux"))] pub fn Platform() -> DOMString { DOMString::from("Linux") } #[cfg(target_os = "macos")] pub fn Platform() -> DOMString
pub fn UserAgent() -> DOMString { DOMString::from(&*opts::get().user_agent) } pub fn AppVersion() -> DOMString { DOMString::from("4.0") } pub fn Language() -> DOMString { DOMString::from("en-US") }
{ DOMString::from("Mac") }
identifier_body
navigatorinfo.rs
use util::opts; pub fn Product() -> DOMString { DOMString::from("Gecko") } pub fn TaintEnabled() -> bool { false } pub fn AppName() -> DOMString { DOMString::from("Netscape") // Like Gecko/Webkit } pub fn AppCodeName() -> DOMString { DOMString::from("Mozilla") } #[cfg(target_os = "windows")] pub fn Platform() -> DOMString { DOMString::from("Win32") } #[cfg(any(target_os = "android", target_os = "linux"))] pub fn Platform() -> DOMString { DOMString::from("Linux") } #[cfg(target_os = "macos")] pub fn Platform() -> DOMString { DOMString::from("Mac") } pub fn UserAgent() -> DOMString { DOMString::from(&*opts::get().user_agent) } pub fn AppVersion() -> DOMString { DOMString::from("4.0") } pub fn Language() -> DOMString { DOMString::from("en-US") }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::str::DOMString;
random_line_split
format.rs
use super::{ Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10, EventFormatSerializerV03, EventFormatSerializerV10, }; use crate::event::{AttributesReader, ExtensionValue}; use serde::de::{Error, IntoDeserializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{Map, Value}; use std::collections::HashMap; macro_rules! parse_field { ($value:expr, $target_type:ty, $error:ty) => { <$target_type>::deserialize($value.into_deserializer()).map_err(<$error>::custom) }; ($value:expr, $target_type:ty, $error:ty, $mapper:expr) => { <$target_type>::deserialize($value.into_deserializer()) .map_err(<$error>::custom) .and_then(|v| $mapper(v).map_err(<$error>::custom)) }; } macro_rules! extract_optional_field { ($map:ident, $name:literal, $target_type:ty, $error:ty) => { $map.remove($name) .filter(|v|!v.is_null()) .map(|v| parse_field!(v, $target_type, $error)) .transpose() }; ($map:ident, $name:literal, $target_type:ty, $error:ty, $mapper:expr) => { $map.remove($name) .filter(|v|!v.is_null()) .map(|v| parse_field!(v, $target_type, $error, $mapper)) .transpose() }; } macro_rules! extract_field { ($map:ident, $name:literal, $target_type:ty, $error:ty) => { extract_optional_field!($map, $name, $target_type, $error)? .ok_or_else(|| <$error>::missing_field($name)) }; ($map:ident, $name:literal, $target_type:ty, $error:ty, $mapper:expr) => { extract_optional_field!($map, $name, $target_type, $error, $mapper)? .ok_or_else(|| <$error>::missing_field($name)) }; } pub fn parse_data_json<E: serde::de::Error>(v: Value) -> Result<Value, E>
pub fn parse_data_string<E: serde::de::Error>(v: Value) -> Result<String, E> { parse_field!(v, String, E) } pub fn parse_data_base64<E: serde::de::Error>(v: Value) -> Result<Vec<u8>, E> { parse_field!(v, String, E).and_then(|s| { base64::decode(&s).map_err(|e| E::custom(format_args!("decode error `{}`", e))) }) } pub fn parse_data_base64_json<E: serde::de::Error>(v: Value) -> Result<Value, E> { let data = parse_data_base64(v)?; serde_json::from_slice(&data).map_err(E::custom) } pub(crate) trait EventFormatDeserializer { fn deserialize_attributes<E: serde::de::Error>( map: &mut Map<String, Value>, ) -> Result<Attributes, E>; fn deserialize_data<E: serde::de::Error>( content_type: &str, map: &mut Map<String, Value>, ) -> Result<Option<Data>, E>; fn deserialize_event<E: serde::de::Error>(mut map: Map<String, Value>) -> Result<Event, E> { let attributes = Self::deserialize_attributes(&mut map)?; let data = Self::deserialize_data( attributes.datacontenttype().unwrap_or("application/json"), &mut map, )?; let extensions = map .into_iter() .filter(|v|!v.1.is_null()) .map(|(k, v)| { Ok(( k, ExtensionValue::deserialize(v.into_deserializer()).map_err(E::custom)?, )) }) .collect::<Result<HashMap<String, ExtensionValue>, E>>()?; Ok(Event { attributes, data, extensions, }) } } pub(crate) trait EventFormatSerializer<S: Serializer, A: Sized> { fn serialize( attributes: &A, data: &Option<Data>, extensions: &HashMap<String, ExtensionValue>, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>; } impl<'de> Deserialize<'de> for Event { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de>, { let root_value = Value::deserialize(deserializer)?; let mut map: Map<String, Value> = Map::deserialize(root_value.into_deserializer()).map_err(D::Error::custom)?; match extract_field!(map, "specversion", String, <D as Deserializer<'de>>::Error)?.as_str() { "0.3" => EventFormatDeserializerV03::deserialize_event(map), "1.0" => EventFormatDeserializerV10::deserialize_event(map), s => Err(D::Error::unknown_variant( s, &super::spec_version::SPEC_VERSIONS, )), } } } impl Serialize for Event { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { match &self.attributes { Attributes::V03(a) => { EventFormatSerializerV03::serialize(a, &self.data, &self.extensions, serializer) } Attributes::V10(a) => { EventFormatSerializerV10::serialize(a, &self.data, &self.extensions, serializer) } } } }
{ Value::deserialize(v.into_deserializer()).map_err(E::custom) }
identifier_body
format.rs
use super::{ Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10, EventFormatSerializerV03, EventFormatSerializerV10, }; use crate::event::{AttributesReader, ExtensionValue}; use serde::de::{Error, IntoDeserializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{Map, Value}; use std::collections::HashMap; macro_rules! parse_field { ($value:expr, $target_type:ty, $error:ty) => { <$target_type>::deserialize($value.into_deserializer()).map_err(<$error>::custom) }; ($value:expr, $target_type:ty, $error:ty, $mapper:expr) => { <$target_type>::deserialize($value.into_deserializer()) .map_err(<$error>::custom) .and_then(|v| $mapper(v).map_err(<$error>::custom)) }; } macro_rules! extract_optional_field { ($map:ident, $name:literal, $target_type:ty, $error:ty) => { $map.remove($name) .filter(|v|!v.is_null()) .map(|v| parse_field!(v, $target_type, $error)) .transpose() }; ($map:ident, $name:literal, $target_type:ty, $error:ty, $mapper:expr) => { $map.remove($name) .filter(|v|!v.is_null()) .map(|v| parse_field!(v, $target_type, $error, $mapper)) .transpose() }; } macro_rules! extract_field { ($map:ident, $name:literal, $target_type:ty, $error:ty) => { extract_optional_field!($map, $name, $target_type, $error)? .ok_or_else(|| <$error>::missing_field($name)) }; ($map:ident, $name:literal, $target_type:ty, $error:ty, $mapper:expr) => { extract_optional_field!($map, $name, $target_type, $error, $mapper)? .ok_or_else(|| <$error>::missing_field($name)) }; } pub fn parse_data_json<E: serde::de::Error>(v: Value) -> Result<Value, E> { Value::deserialize(v.into_deserializer()).map_err(E::custom) } pub fn parse_data_string<E: serde::de::Error>(v: Value) -> Result<String, E> { parse_field!(v, String, E) } pub fn parse_data_base64<E: serde::de::Error>(v: Value) -> Result<Vec<u8>, E> { parse_field!(v, String, E).and_then(|s| { base64::decode(&s).map_err(|e| E::custom(format_args!("decode error `{}`", e))) }) } pub fn
<E: serde::de::Error>(v: Value) -> Result<Value, E> { let data = parse_data_base64(v)?; serde_json::from_slice(&data).map_err(E::custom) } pub(crate) trait EventFormatDeserializer { fn deserialize_attributes<E: serde::de::Error>( map: &mut Map<String, Value>, ) -> Result<Attributes, E>; fn deserialize_data<E: serde::de::Error>( content_type: &str, map: &mut Map<String, Value>, ) -> Result<Option<Data>, E>; fn deserialize_event<E: serde::de::Error>(mut map: Map<String, Value>) -> Result<Event, E> { let attributes = Self::deserialize_attributes(&mut map)?; let data = Self::deserialize_data( attributes.datacontenttype().unwrap_or("application/json"), &mut map, )?; let extensions = map .into_iter() .filter(|v|!v.1.is_null()) .map(|(k, v)| { Ok(( k, ExtensionValue::deserialize(v.into_deserializer()).map_err(E::custom)?, )) }) .collect::<Result<HashMap<String, ExtensionValue>, E>>()?; Ok(Event { attributes, data, extensions, }) } } pub(crate) trait EventFormatSerializer<S: Serializer, A: Sized> { fn serialize( attributes: &A, data: &Option<Data>, extensions: &HashMap<String, ExtensionValue>, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>; } impl<'de> Deserialize<'de> for Event { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de>, { let root_value = Value::deserialize(deserializer)?; let mut map: Map<String, Value> = Map::deserialize(root_value.into_deserializer()).map_err(D::Error::custom)?; match extract_field!(map, "specversion", String, <D as Deserializer<'de>>::Error)?.as_str() { "0.3" => EventFormatDeserializerV03::deserialize_event(map), "1.0" => EventFormatDeserializerV10::deserialize_event(map), s => Err(D::Error::unknown_variant( s, &super::spec_version::SPEC_VERSIONS, )), } } } impl Serialize for Event { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { match &self.attributes { Attributes::V03(a) => { EventFormatSerializerV03::serialize(a, &self.data, &self.extensions, serializer) } Attributes::V10(a) => { EventFormatSerializerV10::serialize(a, &self.data, &self.extensions, serializer) } } } }
parse_data_base64_json
identifier_name