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
point_alga.rs
use alga::general::{Field, JoinSemilattice, Lattice, MeetSemilattice, RealField}; use alga::linear::{AffineSpace, EuclideanSpace}; use crate::base::allocator::Allocator; use crate::base::dimension::DimName; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Point; impl<N: Scalar + Field, D: DimName> AffineSpace for Point<N, D> where N: Scalar + Field, DefaultAllocator: Allocator<N, D>, { type Translation = VectorN<N, D>; } impl<N: RealField + simba::scalar::RealField, D: DimName> EuclideanSpace for Point<N, D> where DefaultAllocator: Allocator<N, D>, { type Coordinates = VectorN<N, D>; type RealField = N; #[inline] fn origin() -> Self { Self::origin() } #[inline] fn coordinates(&self) -> Self::Coordinates { self.coords.clone() } #[inline] fn from_coordinates(coords: Self::Coordinates) -> Self { Self::from(coords) } #[inline] fn scale_by(&self, n: N) -> Self { self * n } } /* * * Ordering * */ impl<N, D: DimName> MeetSemilattice for Point<N, D> where N: Scalar + MeetSemilattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn
(&self, other: &Self) -> Self { Self::from(self.coords.meet(&other.coords)) } } impl<N, D: DimName> JoinSemilattice for Point<N, D> where N: Scalar + JoinSemilattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn join(&self, other: &Self) -> Self { Self::from(self.coords.join(&other.coords)) } } impl<N, D: DimName> Lattice for Point<N, D> where N: Scalar + Lattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn meet_join(&self, other: &Self) -> (Self, Self) { let (meet, join) = self.coords.meet_join(&other.coords); (Self::from(meet), Self::from(join)) } }
meet
identifier_name
point_alga.rs
use alga::general::{Field, JoinSemilattice, Lattice, MeetSemilattice, RealField}; use alga::linear::{AffineSpace, EuclideanSpace}; use crate::base::allocator::Allocator; use crate::base::dimension::DimName; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Point; impl<N: Scalar + Field, D: DimName> AffineSpace for Point<N, D> where N: Scalar + Field, DefaultAllocator: Allocator<N, D>, { type Translation = VectorN<N, D>; } impl<N: RealField + simba::scalar::RealField, D: DimName> EuclideanSpace for Point<N, D> where DefaultAllocator: Allocator<N, D>, { type Coordinates = VectorN<N, D>; type RealField = N; #[inline] fn origin() -> Self { Self::origin()
} #[inline] fn coordinates(&self) -> Self::Coordinates { self.coords.clone() } #[inline] fn from_coordinates(coords: Self::Coordinates) -> Self { Self::from(coords) } #[inline] fn scale_by(&self, n: N) -> Self { self * n } } /* * * Ordering * */ impl<N, D: DimName> MeetSemilattice for Point<N, D> where N: Scalar + MeetSemilattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn meet(&self, other: &Self) -> Self { Self::from(self.coords.meet(&other.coords)) } } impl<N, D: DimName> JoinSemilattice for Point<N, D> where N: Scalar + JoinSemilattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn join(&self, other: &Self) -> Self { Self::from(self.coords.join(&other.coords)) } } impl<N, D: DimName> Lattice for Point<N, D> where N: Scalar + Lattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn meet_join(&self, other: &Self) -> (Self, Self) { let (meet, join) = self.coords.meet_join(&other.coords); (Self::from(meet), Self::from(join)) } }
random_line_split
point_alga.rs
use alga::general::{Field, JoinSemilattice, Lattice, MeetSemilattice, RealField}; use alga::linear::{AffineSpace, EuclideanSpace}; use crate::base::allocator::Allocator; use crate::base::dimension::DimName; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Point; impl<N: Scalar + Field, D: DimName> AffineSpace for Point<N, D> where N: Scalar + Field, DefaultAllocator: Allocator<N, D>, { type Translation = VectorN<N, D>; } impl<N: RealField + simba::scalar::RealField, D: DimName> EuclideanSpace for Point<N, D> where DefaultAllocator: Allocator<N, D>, { type Coordinates = VectorN<N, D>; type RealField = N; #[inline] fn origin() -> Self { Self::origin() } #[inline] fn coordinates(&self) -> Self::Coordinates { self.coords.clone() } #[inline] fn from_coordinates(coords: Self::Coordinates) -> Self { Self::from(coords) } #[inline] fn scale_by(&self, n: N) -> Self { self * n } } /* * * Ordering * */ impl<N, D: DimName> MeetSemilattice for Point<N, D> where N: Scalar + MeetSemilattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn meet(&self, other: &Self) -> Self { Self::from(self.coords.meet(&other.coords)) } } impl<N, D: DimName> JoinSemilattice for Point<N, D> where N: Scalar + JoinSemilattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn join(&self, other: &Self) -> Self
} impl<N, D: DimName> Lattice for Point<N, D> where N: Scalar + Lattice, DefaultAllocator: Allocator<N, D>, { #[inline] fn meet_join(&self, other: &Self) -> (Self, Self) { let (meet, join) = self.coords.meet_join(&other.coords); (Self::from(meet), Self::from(join)) } }
{ Self::from(self.coords.join(&other.coords)) }
identifier_body
get_id_issue.rs
extern crate gitlab_api as gitlab; use std::env; #[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate clap; use gitlab::GitLab; use gitlab::errors::*; fn
() { if let Err(ref e) = run() { println!("error: {}", e); for e in e.iter().skip(1) { println!("caused by: {}", e); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { println!("backtrace: {:?}", backtrace); } ::std::process::exit(1); } } fn run() -> Result<()> { env_logger::init().unwrap(); info!("starting up"); let hostname = match env::var("GITLAB_HOSTNAME") { Ok(val) => val, Err(_) => { let default = String::from("gitlab.com"); println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.", default); default } }; let token = match env::var("GITLAB_TOKEN") { Ok(val) => val, Err(_) => { panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \ http://{}/profile/account", hostname); } }; let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?; // let gl = GitLab::new(&hostname, &token) // .chain_err(|| "failure to create GitLab instance")? // .scheme("http").port(80); // let gl = gl.scheme("http").port(80); let matches = clap::App::new("get_id_issue") .version("1.0") .author("Nicolas Bigaouette <[email protected]>") .about("Get the id of a GitLab issue from namespace/project#iid.") .arg(clap::Arg::with_name("namespace") .help("The project's namespace (or group)") .long("namespace") .short("n") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("project") .help("The project's name") .long("project") .short("p") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("id") .help("The issue's id") .long("id") .short("i") .takes_value(true) .required(true)) .get_matches(); let project_namespace = matches.value_of("namespace").unwrap(); let project_name = matches.value_of("project").unwrap(); let issue_iid = value_t!(matches, "id", i64).unwrap_or_else(|e| e.exit()); let issue = gl.get_issue(project_namespace, project_name, issue_iid) .chain_err(|| "cannot get issue")?; // println!("issue: {:?}", issue); println!("Id for {}/{}#{}: {}", project_namespace, project_name, issue_iid, issue.id); Ok(()) }
main
identifier_name
get_id_issue.rs
extern crate gitlab_api as gitlab; use std::env; #[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate clap; use gitlab::GitLab; use gitlab::errors::*; fn main() { if let Err(ref e) = run() {
println!("caused by: {}", e); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { println!("backtrace: {:?}", backtrace); } ::std::process::exit(1); } } fn run() -> Result<()> { env_logger::init().unwrap(); info!("starting up"); let hostname = match env::var("GITLAB_HOSTNAME") { Ok(val) => val, Err(_) => { let default = String::from("gitlab.com"); println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.", default); default } }; let token = match env::var("GITLAB_TOKEN") { Ok(val) => val, Err(_) => { panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \ http://{}/profile/account", hostname); } }; let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?; // let gl = GitLab::new(&hostname, &token) // .chain_err(|| "failure to create GitLab instance")? // .scheme("http").port(80); // let gl = gl.scheme("http").port(80); let matches = clap::App::new("get_id_issue") .version("1.0") .author("Nicolas Bigaouette <[email protected]>") .about("Get the id of a GitLab issue from namespace/project#iid.") .arg(clap::Arg::with_name("namespace") .help("The project's namespace (or group)") .long("namespace") .short("n") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("project") .help("The project's name") .long("project") .short("p") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("id") .help("The issue's id") .long("id") .short("i") .takes_value(true) .required(true)) .get_matches(); let project_namespace = matches.value_of("namespace").unwrap(); let project_name = matches.value_of("project").unwrap(); let issue_iid = value_t!(matches, "id", i64).unwrap_or_else(|e| e.exit()); let issue = gl.get_issue(project_namespace, project_name, issue_iid) .chain_err(|| "cannot get issue")?; // println!("issue: {:?}", issue); println!("Id for {}/{}#{}: {}", project_namespace, project_name, issue_iid, issue.id); Ok(()) }
println!("error: {}", e); for e in e.iter().skip(1) {
random_line_split
get_id_issue.rs
extern crate gitlab_api as gitlab; use std::env; #[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate clap; use gitlab::GitLab; use gitlab::errors::*; fn main() { if let Err(ref e) = run() { println!("error: {}", e); for e in e.iter().skip(1) { println!("caused by: {}", e); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { println!("backtrace: {:?}", backtrace); } ::std::process::exit(1); } } fn run() -> Result<()> { env_logger::init().unwrap(); info!("starting up"); let hostname = match env::var("GITLAB_HOSTNAME") { Ok(val) => val, Err(_) =>
}; let token = match env::var("GITLAB_TOKEN") { Ok(val) => val, Err(_) => { panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \ http://{}/profile/account", hostname); } }; let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?; // let gl = GitLab::new(&hostname, &token) // .chain_err(|| "failure to create GitLab instance")? // .scheme("http").port(80); // let gl = gl.scheme("http").port(80); let matches = clap::App::new("get_id_issue") .version("1.0") .author("Nicolas Bigaouette <[email protected]>") .about("Get the id of a GitLab issue from namespace/project#iid.") .arg(clap::Arg::with_name("namespace") .help("The project's namespace (or group)") .long("namespace") .short("n") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("project") .help("The project's name") .long("project") .short("p") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("id") .help("The issue's id") .long("id") .short("i") .takes_value(true) .required(true)) .get_matches(); let project_namespace = matches.value_of("namespace").unwrap(); let project_name = matches.value_of("project").unwrap(); let issue_iid = value_t!(matches, "id", i64).unwrap_or_else(|e| e.exit()); let issue = gl.get_issue(project_namespace, project_name, issue_iid) .chain_err(|| "cannot get issue")?; // println!("issue: {:?}", issue); println!("Id for {}/{}#{}: {}", project_namespace, project_name, issue_iid, issue.id); Ok(()) }
{ let default = String::from("gitlab.com"); println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.", default); default }
conditional_block
get_id_issue.rs
extern crate gitlab_api as gitlab; use std::env; #[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate clap; use gitlab::GitLab; use gitlab::errors::*; fn main()
fn run() -> Result<()> { env_logger::init().unwrap(); info!("starting up"); let hostname = match env::var("GITLAB_HOSTNAME") { Ok(val) => val, Err(_) => { let default = String::from("gitlab.com"); println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.", default); default } }; let token = match env::var("GITLAB_TOKEN") { Ok(val) => val, Err(_) => { panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \ http://{}/profile/account", hostname); } }; let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?; // let gl = GitLab::new(&hostname, &token) // .chain_err(|| "failure to create GitLab instance")? // .scheme("http").port(80); // let gl = gl.scheme("http").port(80); let matches = clap::App::new("get_id_issue") .version("1.0") .author("Nicolas Bigaouette <[email protected]>") .about("Get the id of a GitLab issue from namespace/project#iid.") .arg(clap::Arg::with_name("namespace") .help("The project's namespace (or group)") .long("namespace") .short("n") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("project") .help("The project's name") .long("project") .short("p") .takes_value(true) .required(true)) .arg(clap::Arg::with_name("id") .help("The issue's id") .long("id") .short("i") .takes_value(true) .required(true)) .get_matches(); let project_namespace = matches.value_of("namespace").unwrap(); let project_name = matches.value_of("project").unwrap(); let issue_iid = value_t!(matches, "id", i64).unwrap_or_else(|e| e.exit()); let issue = gl.get_issue(project_namespace, project_name, issue_iid) .chain_err(|| "cannot get issue")?; // println!("issue: {:?}", issue); println!("Id for {}/{}#{}: {}", project_namespace, project_name, issue_iid, issue.id); Ok(()) }
{ if let Err(ref e) = run() { println!("error: {}", e); for e in e.iter().skip(1) { println!("caused by: {}", e); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { println!("backtrace: {:?}", backtrace); } ::std::process::exit(1); } }
identifier_body
htmlheadingelement.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::codegen::Bindings::HTMLHeadingElementBinding; use dom::bindings::codegen::InheritTypes::HTMLHeadingElementDerived; use dom::bindings::js::Root; use dom::document::Document; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[derive(JSTraceable, HeapSizeOf)] pub enum HeadingLevel { Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, } #[dom_struct] pub struct HTMLHeadingElement { htmlelement: HTMLElement, level: HeadingLevel, } impl HTMLHeadingElementDerived for EventTarget { fn is_htmlheadingelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadingElement))) } } impl HTMLHeadingElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document, level: HeadingLevel) -> HTMLHeadingElement { HTMLHeadingElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLHeadingElement, localName, prefix, document), level: level, } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document, level: HeadingLevel) -> Root<HTMLHeadingElement>
}
{ let element = HTMLHeadingElement::new_inherited(localName, prefix, document, level); Node::reflect_node(box element, document, HTMLHeadingElementBinding::Wrap) }
identifier_body
htmlheadingelement.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::codegen::Bindings::HTMLHeadingElementBinding; use dom::bindings::codegen::InheritTypes::HTMLHeadingElementDerived; use dom::bindings::js::Root; use dom::document::Document; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[derive(JSTraceable, HeapSizeOf)] pub enum HeadingLevel { Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, } #[dom_struct] pub struct HTMLHeadingElement { htmlelement: HTMLElement, level: HeadingLevel, } impl HTMLHeadingElementDerived for EventTarget { fn
(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadingElement))) } } impl HTMLHeadingElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document, level: HeadingLevel) -> HTMLHeadingElement { HTMLHeadingElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLHeadingElement, localName, prefix, document), level: level, } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document, level: HeadingLevel) -> Root<HTMLHeadingElement> { let element = HTMLHeadingElement::new_inherited(localName, prefix, document, level); Node::reflect_node(box element, document, HTMLHeadingElementBinding::Wrap) } }
is_htmlheadingelement
identifier_name
htmlheadingelement.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::codegen::Bindings::HTMLHeadingElementBinding; use dom::bindings::codegen::InheritTypes::HTMLHeadingElementDerived; use dom::bindings::js::Root; use dom::document::Document; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[derive(JSTraceable, HeapSizeOf)] pub enum HeadingLevel { Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, } #[dom_struct]
level: HeadingLevel, } impl HTMLHeadingElementDerived for EventTarget { fn is_htmlheadingelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadingElement))) } } impl HTMLHeadingElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document, level: HeadingLevel) -> HTMLHeadingElement { HTMLHeadingElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLHeadingElement, localName, prefix, document), level: level, } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document, level: HeadingLevel) -> Root<HTMLHeadingElement> { let element = HTMLHeadingElement::new_inherited(localName, prefix, document, level); Node::reflect_node(box element, document, HTMLHeadingElementBinding::Wrap) } }
pub struct HTMLHeadingElement { htmlelement: HTMLElement,
random_line_split
bitmap_font.rs
use std::collections::HashMap; use std::old_io::{File}; use xml::Element; /// /// Representation of a bitmap font, generated with a tool like /// [BMFont](http://www.angelcode.com/products/bmfont/) /// /// A BitmapFont describes a bitmap font texture, providing a mapping from character /// codes to a rectangular area within a corresponding font texture that contains a /// bitmap representation for that character code. /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// pub struct
{ pub scale_w: u8, pub scale_h: u8, pub characters: HashMap<char, BitmapCharacter> } #[derive(Debug)] #[derive(Default)] pub struct BitmapCharacter { pub x: u8, pub y: u8, pub width: u8, pub height: u8, pub xoffset: u8, pub yoffset: u8, pub xadvance: u8, } impl BitmapFont { /// /// Constructs a BitmapFont for the xml configuration file at the given path /// /// Expects file format like: /// /// ```xml /// <font> /// <common scaleW="128" scaleH="128"... /> /// <chars count="95"> /// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16"... /> /// ... /// </chars> /// ``` /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// pub fn from_path(path: &Path) -> Result<BitmapFont, &'static str> { let mut file = match File::open(path) { Ok(file) => file, Err(_) => return Err("Failed to open font file at path.") }; let xml_string = match file.read_to_string() { Ok(file_string) => file_string, Err(_) => return Err("Failed to read font file.") }; BitmapFont::from_string(&xml_string[..]) } /// /// Constructs a BitmapFont from the given string /// /// Expects string format like: /// /// ```xml /// <font> /// <common scaleW="128" scaleH="128"... /> /// <chars count="95"> /// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16"... /> /// ... /// </chars> /// ``` /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// /// pub fn from_string(xml_string: &str) -> Result<BitmapFont, &'static str> { match xml_string.parse() { Ok(xml_root) => { BitmapFont::from_xml_document(&xml_root) }, Err(_) => Err("Error while parsing font document."), } } /// /// Constructs a BitmapFont for the given root xml element /// fn from_xml_document(xml_root: &Element) -> Result<BitmapFont, &'static str> { let chars_element = match xml_root.get_child("chars", None) { Some(chars_element) => chars_element, None => return Err("Missing <chars> element"), }; let common_element = match xml_root.get_child("common", None) { Some(e) => e, None => return Err("Missing <common> element"), }; let mut bitmap_font = BitmapFont{ characters: HashMap::new(), scale_w: get_attribute(&common_element, "scaleW"), scale_h: get_attribute(&common_element, "scaleH"), }; for char_elem in chars_element.get_children("char", None).iter() { let character = BitmapCharacter { x: get_attribute(char_elem, "x"), y: get_attribute(char_elem, "y"), width: get_attribute(char_elem, "width"), height: get_attribute(char_elem, "height"), xoffset: get_attribute(char_elem, "xoffset"), yoffset: get_attribute(char_elem, "yoffset"), xadvance: get_attribute(char_elem, "xadvance"), }; let id = get_attribute(char_elem, "id"); bitmap_font.characters.insert(id as char, character); } Ok(bitmap_font) } } /// /// Get a u8 value for for the attribute name on the given element, /// defaulting to 0 if attribute unavaiable or failing to parse /// fn get_attribute(element: &Element, name: &str) -> u8 { match element.get_attribute(name, None) { Some(value_string) => match value_string.parse() { Ok(value) => value, Err(_) => 0, }, None => 0 } }
BitmapFont
identifier_name
bitmap_font.rs
use std::collections::HashMap; use std::old_io::{File}; use xml::Element; /// /// Representation of a bitmap font, generated with a tool like /// [BMFont](http://www.angelcode.com/products/bmfont/) /// /// A BitmapFont describes a bitmap font texture, providing a mapping from character /// codes to a rectangular area within a corresponding font texture that contains a /// bitmap representation for that character code. /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// pub struct BitmapFont { pub scale_w: u8, pub scale_h: u8, pub characters: HashMap<char, BitmapCharacter> } #[derive(Debug)] #[derive(Default)] pub struct BitmapCharacter { pub x: u8, pub y: u8, pub width: u8, pub height: u8, pub xoffset: u8, pub yoffset: u8, pub xadvance: u8, } impl BitmapFont { /// /// Constructs a BitmapFont for the xml configuration file at the given path /// /// Expects file format like: /// /// ```xml /// <font> /// <common scaleW="128" scaleH="128"... /> /// <chars count="95"> /// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16"... /> /// ... /// </chars> /// ``` /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// pub fn from_path(path: &Path) -> Result<BitmapFont, &'static str> { let mut file = match File::open(path) { Ok(file) => file, Err(_) => return Err("Failed to open font file at path.") }; let xml_string = match file.read_to_string() { Ok(file_string) => file_string, Err(_) => return Err("Failed to read font file.") }; BitmapFont::from_string(&xml_string[..]) } /// /// Constructs a BitmapFont from the given string /// /// Expects string format like: /// /// ```xml /// <font> /// <common scaleW="128" scaleH="128"... /> /// <chars count="95"> /// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16"... /> /// ... /// </chars> /// ``` /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// /// pub fn from_string(xml_string: &str) -> Result<BitmapFont, &'static str> { match xml_string.parse() { Ok(xml_root) =>
, Err(_) => Err("Error while parsing font document."), } } /// /// Constructs a BitmapFont for the given root xml element /// fn from_xml_document(xml_root: &Element) -> Result<BitmapFont, &'static str> { let chars_element = match xml_root.get_child("chars", None) { Some(chars_element) => chars_element, None => return Err("Missing <chars> element"), }; let common_element = match xml_root.get_child("common", None) { Some(e) => e, None => return Err("Missing <common> element"), }; let mut bitmap_font = BitmapFont{ characters: HashMap::new(), scale_w: get_attribute(&common_element, "scaleW"), scale_h: get_attribute(&common_element, "scaleH"), }; for char_elem in chars_element.get_children("char", None).iter() { let character = BitmapCharacter { x: get_attribute(char_elem, "x"), y: get_attribute(char_elem, "y"), width: get_attribute(char_elem, "width"), height: get_attribute(char_elem, "height"), xoffset: get_attribute(char_elem, "xoffset"), yoffset: get_attribute(char_elem, "yoffset"), xadvance: get_attribute(char_elem, "xadvance"), }; let id = get_attribute(char_elem, "id"); bitmap_font.characters.insert(id as char, character); } Ok(bitmap_font) } } /// /// Get a u8 value for for the attribute name on the given element, /// defaulting to 0 if attribute unavaiable or failing to parse /// fn get_attribute(element: &Element, name: &str) -> u8 { match element.get_attribute(name, None) { Some(value_string) => match value_string.parse() { Ok(value) => value, Err(_) => 0, }, None => 0 } }
{ BitmapFont::from_xml_document(&xml_root) }
conditional_block
bitmap_font.rs
use std::collections::HashMap; use std::old_io::{File}; use xml::Element; /// /// Representation of a bitmap font, generated with a tool like /// [BMFont](http://www.angelcode.com/products/bmfont/) /// /// A BitmapFont describes a bitmap font texture, providing a mapping from character /// codes to a rectangular area within a corresponding font texture that contains a /// bitmap representation for that character code. /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// pub struct BitmapFont { pub scale_w: u8, pub scale_h: u8, pub characters: HashMap<char, BitmapCharacter> } #[derive(Debug)] #[derive(Default)] pub struct BitmapCharacter { pub x: u8, pub y: u8, pub width: u8, pub height: u8, pub xoffset: u8, pub yoffset: u8, pub xadvance: u8, } impl BitmapFont { /// /// Constructs a BitmapFont for the xml configuration file at the given path /// /// Expects file format like: /// /// ```xml /// <font> /// <common scaleW="128" scaleH="128"... /> /// <chars count="95"> /// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16"... /> /// ... /// </chars> /// ``` /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// pub fn from_path(path: &Path) -> Result<BitmapFont, &'static str> { let mut file = match File::open(path) { Ok(file) => file, Err(_) => return Err("Failed to open font file at path.") }; let xml_string = match file.read_to_string() { Ok(file_string) => file_string, Err(_) => return Err("Failed to read font file.") }; BitmapFont::from_string(&xml_string[..]) } /// /// Constructs a BitmapFont from the given string /// /// Expects string format like: /// /// ```xml /// <font> /// <common scaleW="128" scaleH="128"... /> /// <chars count="95"> /// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16"... /> /// ... /// </chars> /// ``` /// /// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information. /// /// pub fn from_string(xml_string: &str) -> Result<BitmapFont, &'static str> { match xml_string.parse() { Ok(xml_root) => { BitmapFont::from_xml_document(&xml_root) }, Err(_) => Err("Error while parsing font document."), } } /// /// Constructs a BitmapFont for the given root xml element /// fn from_xml_document(xml_root: &Element) -> Result<BitmapFont, &'static str> { let chars_element = match xml_root.get_child("chars", None) { Some(chars_element) => chars_element, None => return Err("Missing <chars> element"), };
let mut bitmap_font = BitmapFont{ characters: HashMap::new(), scale_w: get_attribute(&common_element, "scaleW"), scale_h: get_attribute(&common_element, "scaleH"), }; for char_elem in chars_element.get_children("char", None).iter() { let character = BitmapCharacter { x: get_attribute(char_elem, "x"), y: get_attribute(char_elem, "y"), width: get_attribute(char_elem, "width"), height: get_attribute(char_elem, "height"), xoffset: get_attribute(char_elem, "xoffset"), yoffset: get_attribute(char_elem, "yoffset"), xadvance: get_attribute(char_elem, "xadvance"), }; let id = get_attribute(char_elem, "id"); bitmap_font.characters.insert(id as char, character); } Ok(bitmap_font) } } /// /// Get a u8 value for for the attribute name on the given element, /// defaulting to 0 if attribute unavaiable or failing to parse /// fn get_attribute(element: &Element, name: &str) -> u8 { match element.get_attribute(name, None) { Some(value_string) => match value_string.parse() { Ok(value) => value, Err(_) => 0, }, None => 0 } }
let common_element = match xml_root.get_child("common", None) { Some(e) => e, None => return Err("Missing <common> element"), };
random_line_split
test.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![cfg(test)] use graph::test::TestGraph; use super::*; #[test] fn diamond() { let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 3)]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 4); assert_eq!(sccs.num_sccs(), 4); } #[test] fn test_big_scc() { // The order in which things will be visited is important to this // test. // // We will visit: // // 0 -> 1 -> 2 -> 0 // // and at this point detect a cycle. 2 will return back to 1 which // will visit 3. 3 will visit 2 before the cycle is complete, and // hence it too will return a cycle. /* +-> 0 | | | v | 1 -> 3 | | | | v | +-- 2 <--+ */ let graph = TestGraph::new(0, &[ (0, 1), (1, 2), (1, 3), (2, 0), (3, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 1); } #[test] fn test_three_sccs() { /* 0 | v +-> 1 3 | | | | v | +-- 2 <--+ */ let graph = TestGraph::new(0, &[ (0, 1), (1, 2), (2, 1), (3, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 3); assert_eq!(sccs.scc(0), 1); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 2); assert_eq!(sccs.successors(0), &[]); assert_eq!(sccs.successors(1), &[0]); assert_eq!(sccs.successors(2), &[0]); } #[test] fn test_find_state_2() { // The order in which things will be visited is important to this // test. It tests part of the `find_state` behavior. Here is the // graph: // // // /----+ // 0 <--+ | // | | | // v | | // +-> 1 -> 3 4 // | | | // | v | // +-- 2 <----+ let graph = TestGraph::new(0, &[ (0, 1), (0, 4), (1, 2), (1, 3), (2, 1), (3, 0), (4, 2), ]); // For this graph, we will start in our DFS by visiting: // // 0 -> 1 -> 2 -> 1 // // and at this point detect a cycle. The state of 2 will thus be // `InCycleWith { 1 }`. We will then visit the 1 -> 3 edge, which // will attempt to visit 0 as well, thus going to the state // `InCycleWith { 0 }`. Finally, node 1 will complete; the lowest // depth of any successor was 3 which had depth 0, and thus it // will be in the state `InCycleWith { 3 }`. // // When we finally traverse the `0 -> 4` edge and then visit node 2, // the states of the nodes are: // // 0 BeingVisited { 0 } // 1 InCycleWith { 3 } // 2 InCycleWith { 1 } // 3 InCycleWith { 0 } // // and hence 4 will traverse the links, finding an ultimate depth of 0. // If will also collapse the states to the following: // // 0 BeingVisited { 0 } // 1 InCycleWith { 3 } // 2 InCycleWith { 1 } // 3 InCycleWith { 0 } let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 1); assert_eq!(sccs.scc(0), 0); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 0); assert_eq!(sccs.scc(4), 0); assert_eq!(sccs.successors(0), &[]); } #[test] fn test_find_state_3()
]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 2); assert_eq!(sccs.scc(0), 0); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 0); assert_eq!(sccs.scc(4), 0); assert_eq!(sccs.scc(5), 1); assert_eq!(sccs.successors(0), &[]); assert_eq!(sccs.successors(1), &[0]); }
{ /* /----+ 0 <--+ | | | | v | | +-> 1 -> 3 4 5 | | | | | v | | +-- 2 <----+-+ */ let graph = TestGraph::new(0, &[ (0, 1), (0, 4), (1, 2), (1, 3), (2, 1), (3, 0), (4, 2), (5, 2),
identifier_body
test.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![cfg(test)] use graph::test::TestGraph; use super::*; #[test] fn diamond() { let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 3)]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 4); assert_eq!(sccs.num_sccs(), 4); } #[test] fn test_big_scc() { // The order in which things will be visited is important to this // test. // // We will visit: // // 0 -> 1 -> 2 -> 0 // // and at this point detect a cycle. 2 will return back to 1 which // will visit 3. 3 will visit 2 before the cycle is complete, and // hence it too will return a cycle. /* +-> 0 | | | v | 1 -> 3 | | | | v | +-- 2 <--+ */ let graph = TestGraph::new(0, &[ (0, 1), (1, 2), (1, 3), (2, 0), (3, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 1); } #[test] fn test_three_sccs() { /* 0 | v +-> 1 3 | | | | v | +-- 2 <--+ */ let graph = TestGraph::new(0, &[ (0, 1), (1, 2), (2, 1), (3, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 3); assert_eq!(sccs.scc(0), 1); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 2); assert_eq!(sccs.successors(0), &[]); assert_eq!(sccs.successors(1), &[0]); assert_eq!(sccs.successors(2), &[0]); } #[test] fn
() { // The order in which things will be visited is important to this // test. It tests part of the `find_state` behavior. Here is the // graph: // // // /----+ // 0 <--+ | // | | | // v | | // +-> 1 -> 3 4 // | | | // | v | // +-- 2 <----+ let graph = TestGraph::new(0, &[ (0, 1), (0, 4), (1, 2), (1, 3), (2, 1), (3, 0), (4, 2), ]); // For this graph, we will start in our DFS by visiting: // // 0 -> 1 -> 2 -> 1 // // and at this point detect a cycle. The state of 2 will thus be // `InCycleWith { 1 }`. We will then visit the 1 -> 3 edge, which // will attempt to visit 0 as well, thus going to the state // `InCycleWith { 0 }`. Finally, node 1 will complete; the lowest // depth of any successor was 3 which had depth 0, and thus it // will be in the state `InCycleWith { 3 }`. // // When we finally traverse the `0 -> 4` edge and then visit node 2, // the states of the nodes are: // // 0 BeingVisited { 0 } // 1 InCycleWith { 3 } // 2 InCycleWith { 1 } // 3 InCycleWith { 0 } // // and hence 4 will traverse the links, finding an ultimate depth of 0. // If will also collapse the states to the following: // // 0 BeingVisited { 0 } // 1 InCycleWith { 3 } // 2 InCycleWith { 1 } // 3 InCycleWith { 0 } let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 1); assert_eq!(sccs.scc(0), 0); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 0); assert_eq!(sccs.scc(4), 0); assert_eq!(sccs.successors(0), &[]); } #[test] fn test_find_state_3() { /* /----+ 0 <--+ | | | | v | | +-> 1 -> 3 4 5 | | | | | v | | +-- 2 <----+-+ */ let graph = TestGraph::new(0, &[ (0, 1), (0, 4), (1, 2), (1, 3), (2, 1), (3, 0), (4, 2), (5, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 2); assert_eq!(sccs.scc(0), 0); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 0); assert_eq!(sccs.scc(4), 0); assert_eq!(sccs.scc(5), 1); assert_eq!(sccs.successors(0), &[]); assert_eq!(sccs.successors(1), &[0]); }
test_find_state_2
identifier_name
test.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![cfg(test)] use graph::test::TestGraph; use super::*; #[test] fn diamond() { let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 3)]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 4); assert_eq!(sccs.num_sccs(), 4); } #[test] fn test_big_scc() { // The order in which things will be visited is important to this // test. // // We will visit: // // 0 -> 1 -> 2 -> 0 // // and at this point detect a cycle. 2 will return back to 1 which // will visit 3. 3 will visit 2 before the cycle is complete, and // hence it too will return a cycle. /* +-> 0 | | | v | 1 -> 3 | | | | v | +-- 2 <--+ */ let graph = TestGraph::new(0, &[ (0, 1), (1, 2), (1, 3), (2, 0), (3, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 1); } #[test] fn test_three_sccs() { /* 0 | v +-> 1 3 | | | | v | +-- 2 <--+ */ let graph = TestGraph::new(0, &[ (0, 1), (1, 2), (2, 1), (3, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 3); assert_eq!(sccs.scc(0), 1); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 2); assert_eq!(sccs.successors(0), &[]); assert_eq!(sccs.successors(1), &[0]); assert_eq!(sccs.successors(2), &[0]); } #[test] fn test_find_state_2() { // The order in which things will be visited is important to this // test. It tests part of the `find_state` behavior. Here is the // graph: // // // /----+ // 0 <--+ | // | | | // v | | // +-> 1 -> 3 4 // | | | // | v | // +-- 2 <----+ let graph = TestGraph::new(0, &[ (0, 1), (0, 4), (1, 2), (1, 3), (2, 1), (3, 0), (4, 2), ]); // For this graph, we will start in our DFS by visiting: // // 0 -> 1 -> 2 -> 1 // // and at this point detect a cycle. The state of 2 will thus be // `InCycleWith { 1 }`. We will then visit the 1 -> 3 edge, which // will attempt to visit 0 as well, thus going to the state // `InCycleWith { 0 }`. Finally, node 1 will complete; the lowest // depth of any successor was 3 which had depth 0, and thus it // will be in the state `InCycleWith { 3 }`. // // When we finally traverse the `0 -> 4` edge and then visit node 2, // the states of the nodes are: // // 0 BeingVisited { 0 } // 1 InCycleWith { 3 } // 2 InCycleWith { 1 } // 3 InCycleWith { 0 } // // and hence 4 will traverse the links, finding an ultimate depth of 0. // If will also collapse the states to the following: // // 0 BeingVisited { 0 } // 1 InCycleWith { 3 } // 2 InCycleWith { 1 } // 3 InCycleWith { 0 } let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 1); assert_eq!(sccs.scc(0), 0); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 0); assert_eq!(sccs.scc(4), 0); assert_eq!(sccs.successors(0), &[]); } #[test] fn test_find_state_3() { /* /----+ 0 <--+ | | | | v | | +-> 1 -> 3 4 5 | | | | | v | | +-- 2 <----+-+ */ let graph = TestGraph::new(0, &[
(0, 4), (1, 2), (1, 3), (2, 1), (3, 0), (4, 2), (5, 2), ]); let sccs: Sccs<_, usize> = Sccs::new(&graph); assert_eq!(sccs.num_sccs(), 2); assert_eq!(sccs.scc(0), 0); assert_eq!(sccs.scc(1), 0); assert_eq!(sccs.scc(2), 0); assert_eq!(sccs.scc(3), 0); assert_eq!(sccs.scc(4), 0); assert_eq!(sccs.scc(5), 1); assert_eq!(sccs.successors(0), &[]); assert_eq!(sccs.successors(1), &[0]); }
(0, 1),
random_line_split
ui.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version
// 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use clap::App; pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> { app }
random_line_split
ui.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use clap::App; pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a>
{ app }
identifier_body
ui.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use clap::App; pub fn
<'a>(app: App<'a, 'a>) -> App<'a, 'a> { app }
build_ui
identifier_name
auto-ref-bounded-ty-param.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::io; trait Foo { fn f(&self); } struct Bar { x: int }
fn g(&self); } impl<T:Baz> Foo for T { fn f(&self) { self.g(); } } impl Baz for Bar { fn g(&self) { io::println(self.x.to_str()); } } pub fn main() { let y = Bar { x: 42 }; y.f(); }
trait Baz {
random_line_split
auto-ref-bounded-ty-param.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::io; trait Foo { fn f(&self); } struct
{ x: int } trait Baz { fn g(&self); } impl<T:Baz> Foo for T { fn f(&self) { self.g(); } } impl Baz for Bar { fn g(&self) { io::println(self.x.to_str()); } } pub fn main() { let y = Bar { x: 42 }; y.f(); }
Bar
identifier_name
raft_server.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of 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 this program. If not, see <http://www.gnu.org/licenses/>. // Raft's major components. See comments in code on usage and things. use libraft::{Server, ServerId}; use log_store::*; // A payload datatype. We're just using a simple enum. You can use whatever. use machine::*; use mio::EventLoop; use std::collections::HashMap; use std::net::{SocketAddr, ToSocketAddrs}; #[derive(Debug, RustcDecodable)] pub struct Args { cmd_server: bool, // When creating a server you will necessarily need some sort of unique ID for it as well // as a list of peers. In this example we just accept them straight from args. You might // find it best to use a `toml` or `yaml` or `json` file. arg_id: Option<u64>, arg_node_address: Vec<String>, } /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr
/// Creates a Raft server using the specified ID from the list of nodes. pub fn server(args: &Args) -> (Server<Store, HashmapStateMachine>, EventLoop<Server<Store, HashmapStateMachine>>) { // Creating a raft server requires several things: // A persistent log implementation, which manages the persistent, replicated log... let persistent_log = Store::new(); // A state machine which replicates state. This state should be the same on all nodes. let state_machine = HashmapStateMachine::new(); // As well as a unique server id. let id = ServerId::from(args.arg_id.unwrap() + 1); println!("id:{:?}", id); let mut node_id: Vec<u64> = vec![]; for i in 0..args.arg_node_address.len() { node_id.push(i as u64 + 1); } //... And a list of peers. let mut peers = node_id.iter() .zip(args.arg_node_address.iter()) .map(|(&id, addr)| (ServerId::from(id), parse_addr(&addr))) .collect::<HashMap<_, _>>(); println!("peers:{:?}", peers); // The Raft Server will return an error if its ID is inside of its peer set. Don't do that. // Instead, take it out and use it! let addr = peers.remove(&id).unwrap(); println!("addr:{:?}", addr); // Using all of the above components. // You probably shouldn't `.unwrap()` in production code unless you're totally sure it works // 100% of the time, all the time. //Server::spawn(id, addr, peers, persistent_log, state_machine).unwrap(); Server::new(id, addr, peers, persistent_log, state_machine).unwrap() }
{ addr.to_socket_addrs() .ok() .expect(&format!("unable to parse socket address: {}", addr)) .next() .unwrap() }
identifier_body
raft_server.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of 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 this program. If not, see <http://www.gnu.org/licenses/>. // Raft's major components. See comments in code on usage and things. use libraft::{Server, ServerId}; use log_store::*; // A payload datatype. We're just using a simple enum. You can use whatever. use machine::*; use mio::EventLoop; use std::collections::HashMap; use std::net::{SocketAddr, ToSocketAddrs}; #[derive(Debug, RustcDecodable)] pub struct
{ cmd_server: bool, // When creating a server you will necessarily need some sort of unique ID for it as well // as a list of peers. In this example we just accept them straight from args. You might // find it best to use a `toml` or `yaml` or `json` file. arg_id: Option<u64>, arg_node_address: Vec<String>, } /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr { addr.to_socket_addrs() .ok() .expect(&format!("unable to parse socket address: {}", addr)) .next() .unwrap() } /// Creates a Raft server using the specified ID from the list of nodes. pub fn server(args: &Args) -> (Server<Store, HashmapStateMachine>, EventLoop<Server<Store, HashmapStateMachine>>) { // Creating a raft server requires several things: // A persistent log implementation, which manages the persistent, replicated log... let persistent_log = Store::new(); // A state machine which replicates state. This state should be the same on all nodes. let state_machine = HashmapStateMachine::new(); // As well as a unique server id. let id = ServerId::from(args.arg_id.unwrap() + 1); println!("id:{:?}", id); let mut node_id: Vec<u64> = vec![]; for i in 0..args.arg_node_address.len() { node_id.push(i as u64 + 1); } //... And a list of peers. let mut peers = node_id.iter() .zip(args.arg_node_address.iter()) .map(|(&id, addr)| (ServerId::from(id), parse_addr(&addr))) .collect::<HashMap<_, _>>(); println!("peers:{:?}", peers); // The Raft Server will return an error if its ID is inside of its peer set. Don't do that. // Instead, take it out and use it! let addr = peers.remove(&id).unwrap(); println!("addr:{:?}", addr); // Using all of the above components. // You probably shouldn't `.unwrap()` in production code unless you're totally sure it works // 100% of the time, all the time. //Server::spawn(id, addr, peers, persistent_log, state_machine).unwrap(); Server::new(id, addr, peers, persistent_log, state_machine).unwrap() }
Args
identifier_name
raft_server.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of 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 this program. If not, see <http://www.gnu.org/licenses/>. // Raft's major components. See comments in code on usage and things. use libraft::{Server, ServerId}; use log_store::*; // A payload datatype. We're just using a simple enum. You can use whatever. use machine::*; use mio::EventLoop; use std::collections::HashMap; use std::net::{SocketAddr, ToSocketAddrs}; #[derive(Debug, RustcDecodable)] pub struct Args { cmd_server: bool, // When creating a server you will necessarily need some sort of unique ID for it as well // as a list of peers. In this example we just accept them straight from args. You might // find it best to use a `toml` or `yaml` or `json` file. arg_id: Option<u64>, arg_node_address: Vec<String>, } /// A simple convenience method since this is an example and it should exit if given invalid params. fn parse_addr(addr: &str) -> SocketAddr { addr.to_socket_addrs() .ok()
/// Creates a Raft server using the specified ID from the list of nodes. pub fn server(args: &Args) -> (Server<Store, HashmapStateMachine>, EventLoop<Server<Store, HashmapStateMachine>>) { // Creating a raft server requires several things: // A persistent log implementation, which manages the persistent, replicated log... let persistent_log = Store::new(); // A state machine which replicates state. This state should be the same on all nodes. let state_machine = HashmapStateMachine::new(); // As well as a unique server id. let id = ServerId::from(args.arg_id.unwrap() + 1); println!("id:{:?}", id); let mut node_id: Vec<u64> = vec![]; for i in 0..args.arg_node_address.len() { node_id.push(i as u64 + 1); } //... And a list of peers. let mut peers = node_id.iter() .zip(args.arg_node_address.iter()) .map(|(&id, addr)| (ServerId::from(id), parse_addr(&addr))) .collect::<HashMap<_, _>>(); println!("peers:{:?}", peers); // The Raft Server will return an error if its ID is inside of its peer set. Don't do that. // Instead, take it out and use it! let addr = peers.remove(&id).unwrap(); println!("addr:{:?}", addr); // Using all of the above components. // You probably shouldn't `.unwrap()` in production code unless you're totally sure it works // 100% of the time, all the time. //Server::spawn(id, addr, peers, persistent_log, state_machine).unwrap(); Server::new(id, addr, peers, persistent_log, state_machine).unwrap() }
.expect(&format!("unable to parse socket address: {}", addr)) .next() .unwrap() }
random_line_split
unix.rs
// // Copyright:: Copyright (c) 2015 Chef Software, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use errors::{DeliveryError, Kind}; use libc; use std::convert::AsRef; use std::env; use std::error; use std::path::{Path, PathBuf}; use std::process::Command; use utils::path_to_string; pub fn copy_recursive<A, B>(f: &A, t: &B) -> Result<(), DeliveryError> where A: AsRef<Path> +?Sized, B: AsRef<Path> +?Sized,
pub fn remove_recursive<P:?Sized>(path: &P) -> Result<(), DeliveryError> where P: AsRef<Path>, { try!( Command::new("rm") .arg("-rf") .arg(path.as_ref().to_str().unwrap()) .output() ); Ok(()) } pub fn chmod<P:?Sized>(path: &P, setting: &str) -> Result<(), DeliveryError> where P: AsRef<Path>, { let result = try!( Command::new("chmod") .arg(setting) .arg(path.as_ref().to_str().unwrap()) .output() ); super::cmd_success_or_err(&result, Kind::ChmodFailed) } pub fn chown_all<P: AsRef<Path>>(who: &str, paths: &[P]) -> Result<(), DeliveryError> { let mut command = Command::new("chown"); command.arg("-R").arg(who); for p in paths { command.arg(&path_to_string(p)); } let output = match command.output() { Ok(o) => o, Err(e) => { return Err(DeliveryError { kind: Kind::FailedToExecute, detail: Some(format!( "failed to execute chown: {}", error::Error::description(&e) )), }) } }; super::cmd_success_or_err(&output, Kind::ChmodFailed) } pub fn privileged_process() -> bool { match unsafe { libc::getuid() } { 0 => true, _ => false, } } // Abstraction for command creation. Needed because of how we're // wrapping commands in Windows. See this function in the // corresponding windows module. pub fn make_command(cmd: &str) -> Command { Command::new(cmd) } /// Returns the absolute path for a given command, if it exists, by searching the `PATH` /// environment variable. /// /// If the command represents an absolute path, then the `PATH` searching will not be performed. /// If no absolute path can be found for the command, then `None` is returned. pub fn find_command(command: &str) -> Option<PathBuf> { // If the command path is absolute and a file exists, then use that. let candidate = PathBuf::from(command); if candidate.is_absolute() && candidate.is_file() { return Some(candidate); } // Find the command by checking each entry in `PATH`. If we still can't find it, // give up and return `None`. if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { let candidate = PathBuf::from(&path).join(command); if candidate.is_file() { return Some(candidate); } } } None } pub fn ca_path() -> String { String::from("/opt/chefdk/embedded/ssl/certs/cacert.pem") }
{ let from = f.as_ref(); let to = t.as_ref(); let result = try!( Command::new("cp") .arg("-R") .arg("-a") .arg(from.to_str().unwrap()) .arg(to.to_str().unwrap()) .output() ); super::cmd_success_or_err(&result, Kind::CopyFailed) }
identifier_body
unix.rs
// // Copyright:: Copyright (c) 2015 Chef Software, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use errors::{DeliveryError, Kind}; use libc; use std::convert::AsRef; use std::env; use std::error; use std::path::{Path, PathBuf}; use std::process::Command; use utils::path_to_string; pub fn
<A, B>(f: &A, t: &B) -> Result<(), DeliveryError> where A: AsRef<Path> +?Sized, B: AsRef<Path> +?Sized, { let from = f.as_ref(); let to = t.as_ref(); let result = try!( Command::new("cp") .arg("-R") .arg("-a") .arg(from.to_str().unwrap()) .arg(to.to_str().unwrap()) .output() ); super::cmd_success_or_err(&result, Kind::CopyFailed) } pub fn remove_recursive<P:?Sized>(path: &P) -> Result<(), DeliveryError> where P: AsRef<Path>, { try!( Command::new("rm") .arg("-rf") .arg(path.as_ref().to_str().unwrap()) .output() ); Ok(()) } pub fn chmod<P:?Sized>(path: &P, setting: &str) -> Result<(), DeliveryError> where P: AsRef<Path>, { let result = try!( Command::new("chmod") .arg(setting) .arg(path.as_ref().to_str().unwrap()) .output() ); super::cmd_success_or_err(&result, Kind::ChmodFailed) } pub fn chown_all<P: AsRef<Path>>(who: &str, paths: &[P]) -> Result<(), DeliveryError> { let mut command = Command::new("chown"); command.arg("-R").arg(who); for p in paths { command.arg(&path_to_string(p)); } let output = match command.output() { Ok(o) => o, Err(e) => { return Err(DeliveryError { kind: Kind::FailedToExecute, detail: Some(format!( "failed to execute chown: {}", error::Error::description(&e) )), }) } }; super::cmd_success_or_err(&output, Kind::ChmodFailed) } pub fn privileged_process() -> bool { match unsafe { libc::getuid() } { 0 => true, _ => false, } } // Abstraction for command creation. Needed because of how we're // wrapping commands in Windows. See this function in the // corresponding windows module. pub fn make_command(cmd: &str) -> Command { Command::new(cmd) } /// Returns the absolute path for a given command, if it exists, by searching the `PATH` /// environment variable. /// /// If the command represents an absolute path, then the `PATH` searching will not be performed. /// If no absolute path can be found for the command, then `None` is returned. pub fn find_command(command: &str) -> Option<PathBuf> { // If the command path is absolute and a file exists, then use that. let candidate = PathBuf::from(command); if candidate.is_absolute() && candidate.is_file() { return Some(candidate); } // Find the command by checking each entry in `PATH`. If we still can't find it, // give up and return `None`. if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { let candidate = PathBuf::from(&path).join(command); if candidate.is_file() { return Some(candidate); } } } None } pub fn ca_path() -> String { String::from("/opt/chefdk/embedded/ssl/certs/cacert.pem") }
copy_recursive
identifier_name
unix.rs
// // Copyright:: Copyright (c) 2015 Chef Software, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use errors::{DeliveryError, Kind}; use libc; use std::convert::AsRef; use std::env; use std::error; use std::path::{Path, PathBuf}; use std::process::Command; use utils::path_to_string; pub fn copy_recursive<A, B>(f: &A, t: &B) -> Result<(), DeliveryError> where A: AsRef<Path> +?Sized, B: AsRef<Path> +?Sized, { let from = f.as_ref(); let to = t.as_ref(); let result = try!( Command::new("cp") .arg("-R") .arg("-a") .arg(from.to_str().unwrap()) .arg(to.to_str().unwrap()) .output() ); super::cmd_success_or_err(&result, Kind::CopyFailed) } pub fn remove_recursive<P:?Sized>(path: &P) -> Result<(), DeliveryError> where P: AsRef<Path>, { try!( Command::new("rm") .arg("-rf") .arg(path.as_ref().to_str().unwrap()) .output() ); Ok(()) } pub fn chmod<P:?Sized>(path: &P, setting: &str) -> Result<(), DeliveryError> where P: AsRef<Path>, { let result = try!( Command::new("chmod") .arg(setting) .arg(path.as_ref().to_str().unwrap()) .output() ); super::cmd_success_or_err(&result, Kind::ChmodFailed) } pub fn chown_all<P: AsRef<Path>>(who: &str, paths: &[P]) -> Result<(), DeliveryError> { let mut command = Command::new("chown"); command.arg("-R").arg(who); for p in paths { command.arg(&path_to_string(p)); } let output = match command.output() { Ok(o) => o, Err(e) => { return Err(DeliveryError { kind: Kind::FailedToExecute, detail: Some(format!( "failed to execute chown: {}", error::Error::description(&e) )), }) } }; super::cmd_success_or_err(&output, Kind::ChmodFailed) } pub fn privileged_process() -> bool { match unsafe { libc::getuid() } { 0 => true, _ => false, } } // Abstraction for command creation. Needed because of how we're // wrapping commands in Windows. See this function in the // corresponding windows module. pub fn make_command(cmd: &str) -> Command { Command::new(cmd) } /// Returns the absolute path for a given command, if it exists, by searching the `PATH` /// environment variable. /// /// If the command represents an absolute path, then the `PATH` searching will not be performed. /// If no absolute path can be found for the command, then `None` is returned. pub fn find_command(command: &str) -> Option<PathBuf> { // If the command path is absolute and a file exists, then use that. let candidate = PathBuf::from(command); if candidate.is_absolute() && candidate.is_file() { return Some(candidate); } // Find the command by checking each entry in `PATH`. If we still can't find it, // give up and return `None`. if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { let candidate = PathBuf::from(&path).join(command); if candidate.is_file() { return Some(candidate); }
} } None } pub fn ca_path() -> String { String::from("/opt/chefdk/embedded/ssl/certs/cacert.pem") }
random_line_split
trailing_zeros.rs
use integer::Integer; impl Integer { /// Returns the number of trailing zeros in the binary expansion of an `Integer` (equivalently, /// the multiplicity of 2 in its prime factorization) or `None` is the `Integer` is 0. /// /// Time: worst case O(n) /// /// Additional memory: worst case O(1) /// /// where n = `self.significant_bits()` /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// /// assert_eq!(Integer::ZERO.trailing_zeros(), None); /// assert_eq!(Integer::from(3).trailing_zeros(), Some(0)); /// assert_eq!(Integer::from(-72).trailing_zeros(), Some(3)); /// assert_eq!(Integer::from(100).trailing_zeros(), Some(2)); /// assert_eq!((-Integer::trillion()).trailing_zeros(), Some(12)); /// ``` pub fn trailing_zeros(&self) -> Option<u64>
}
{ self.abs.trailing_zeros() }
identifier_body
trailing_zeros.rs
use integer::Integer; impl Integer { /// Returns the number of trailing zeros in the binary expansion of an `Integer` (equivalently, /// the multiplicity of 2 in its prime factorization) or `None` is the `Integer` is 0. /// /// Time: worst case O(n) /// /// Additional memory: worst case O(1) /// /// where n = `self.significant_bits()` /// /// # Examples /// ``` /// extern crate malachite_base;
/// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// /// assert_eq!(Integer::ZERO.trailing_zeros(), None); /// assert_eq!(Integer::from(3).trailing_zeros(), Some(0)); /// assert_eq!(Integer::from(-72).trailing_zeros(), Some(3)); /// assert_eq!(Integer::from(100).trailing_zeros(), Some(2)); /// assert_eq!((-Integer::trillion()).trailing_zeros(), Some(12)); /// ``` pub fn trailing_zeros(&self) -> Option<u64> { self.abs.trailing_zeros() } }
/// extern crate malachite_nz; ///
random_line_split
trailing_zeros.rs
use integer::Integer; impl Integer { /// Returns the number of trailing zeros in the binary expansion of an `Integer` (equivalently, /// the multiplicity of 2 in its prime factorization) or `None` is the `Integer` is 0. /// /// Time: worst case O(n) /// /// Additional memory: worst case O(1) /// /// where n = `self.significant_bits()` /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// /// assert_eq!(Integer::ZERO.trailing_zeros(), None); /// assert_eq!(Integer::from(3).trailing_zeros(), Some(0)); /// assert_eq!(Integer::from(-72).trailing_zeros(), Some(3)); /// assert_eq!(Integer::from(100).trailing_zeros(), Some(2)); /// assert_eq!((-Integer::trillion()).trailing_zeros(), Some(12)); /// ``` pub fn
(&self) -> Option<u64> { self.abs.trailing_zeros() } }
trailing_zeros
identifier_name
data_loader.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/. */ extern crate hyper; extern crate hyper_serde; use hyper_serde::Serde; use ipc_channel::ipc; use msg::constellation_msg::{PipelineId, ReferrerPolicy}; use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, LoadContext, NetworkError, LoadOrigin}; use self::hyper::header::ContentType; use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use url::Url; struct DataLoadTest; impl LoadOrigin for DataLoadTest { fn referrer_url(&self) -> Option<Url> { None } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn pipeline_id(&self) -> Option<PipelineId> { None } } #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use net::data_loader::load; use net::mime_classifier::MimeClassifier; use net::resource_thread::CancellationListener; use std::sync::Arc; let (start_chan, start_port) = ipc::channel().unwrap(); let classifier = Arc::new(MimeClassifier::new()); load(LoadData::new(LoadContext::Browsing, Url::parse(url).unwrap(), &DataLoadTest), Channel(start_chan), classifier, CancellationListener::new(None)); let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type.map(Serde::into_inner), &content_type); assert_eq!(&response.metadata.charset, &charset); let progress = response.progress_port.recv().unwrap(); match data { None => { assert_eq!(progress, Done(Err(NetworkError::Internal("invalid data uri".to_owned())))); } Some(dat) => { assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); } } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse(
vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(b"hello world".iter().map(|&x| x).collect())); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_charset() { assert_parse("data:text/plain;charset=latin1,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("latin1".to_owned())))))), Some("latin1".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Utf8))))), Some("utf-8".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_ct() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset() { assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))), Some("koi8-r".to_owned()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); }
"data:,hello%20world", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain,
random_line_split
data_loader.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/. */ extern crate hyper; extern crate hyper_serde; use hyper_serde::Serde; use ipc_channel::ipc; use msg::constellation_msg::{PipelineId, ReferrerPolicy}; use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, LoadContext, NetworkError, LoadOrigin}; use self::hyper::header::ContentType; use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use url::Url; struct DataLoadTest; impl LoadOrigin for DataLoadTest { fn referrer_url(&self) -> Option<Url> { None } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn pipeline_id(&self) -> Option<PipelineId> { None } } #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use net::data_loader::load; use net::mime_classifier::MimeClassifier; use net::resource_thread::CancellationListener; use std::sync::Arc; let (start_chan, start_port) = ipc::channel().unwrap(); let classifier = Arc::new(MimeClassifier::new()); load(LoadData::new(LoadContext::Browsing, Url::parse(url).unwrap(), &DataLoadTest), Channel(start_chan), classifier, CancellationListener::new(None)); let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type.map(Serde::into_inner), &content_type); assert_eq!(&response.metadata.charset, &charset); let progress = response.progress_port.recv().unwrap(); match data { None => { assert_eq!(progress, Done(Err(NetworkError::Internal("invalid data uri".to_owned())))); } Some(dat) =>
} } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(b"hello world".iter().map(|&x| x).collect())); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_charset() { assert_parse("data:text/plain;charset=latin1,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("latin1".to_owned())))))), Some("latin1".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Utf8))))), Some("utf-8".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_ct() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset() { assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))), Some("koi8-r".to_owned()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); }
{ assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); }
conditional_block
data_loader.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/. */ extern crate hyper; extern crate hyper_serde; use hyper_serde::Serde; use ipc_channel::ipc; use msg::constellation_msg::{PipelineId, ReferrerPolicy}; use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, LoadContext, NetworkError, LoadOrigin}; use self::hyper::header::ContentType; use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use url::Url; struct DataLoadTest; impl LoadOrigin for DataLoadTest { fn referrer_url(&self) -> Option<Url>
fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn pipeline_id(&self) -> Option<PipelineId> { None } } #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use net::data_loader::load; use net::mime_classifier::MimeClassifier; use net::resource_thread::CancellationListener; use std::sync::Arc; let (start_chan, start_port) = ipc::channel().unwrap(); let classifier = Arc::new(MimeClassifier::new()); load(LoadData::new(LoadContext::Browsing, Url::parse(url).unwrap(), &DataLoadTest), Channel(start_chan), classifier, CancellationListener::new(None)); let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type.map(Serde::into_inner), &content_type); assert_eq!(&response.metadata.charset, &charset); let progress = response.progress_port.recv().unwrap(); match data { None => { assert_eq!(progress, Done(Err(NetworkError::Internal("invalid data uri".to_owned())))); } Some(dat) => { assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); } } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(b"hello world".iter().map(|&x| x).collect())); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_charset() { assert_parse("data:text/plain;charset=latin1,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("latin1".to_owned())))))), Some("latin1".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Utf8))))), Some("utf-8".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_ct() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset() { assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))), Some("koi8-r".to_owned()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); }
{ None }
identifier_body
data_loader.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/. */ extern crate hyper; extern crate hyper_serde; use hyper_serde::Serde; use ipc_channel::ipc; use msg::constellation_msg::{PipelineId, ReferrerPolicy}; use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, LoadContext, NetworkError, LoadOrigin}; use self::hyper::header::ContentType; use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use url::Url; struct DataLoadTest; impl LoadOrigin for DataLoadTest { fn referrer_url(&self) -> Option<Url> { None } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn pipeline_id(&self) -> Option<PipelineId> { None } } #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use net::data_loader::load; use net::mime_classifier::MimeClassifier; use net::resource_thread::CancellationListener; use std::sync::Arc; let (start_chan, start_port) = ipc::channel().unwrap(); let classifier = Arc::new(MimeClassifier::new()); load(LoadData::new(LoadContext::Browsing, Url::parse(url).unwrap(), &DataLoadTest), Channel(start_chan), classifier, CancellationListener::new(None)); let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type.map(Serde::into_inner), &content_type); assert_eq!(&response.metadata.charset, &charset); let progress = response.progress_port.recv().unwrap(); match data { None => { assert_eq!(progress, Done(Err(NetworkError::Internal("invalid data uri".to_owned())))); } Some(dat) => { assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); } } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(b"hello world".iter().map(|&x| x).collect())); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_charset() { assert_parse("data:text/plain;charset=latin1,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("latin1".to_owned())))))), Some("latin1".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Utf8))))), Some("utf-8".to_owned()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), Some("US-ASCII".to_owned()), Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn
() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset() { assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))), Some("koi8-r".to_owned()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); }
base64_ct
identifier_name
custom_errors.rs
#![allow(dead_code)] use nom::bytes::streaming::tag; use nom::character::streaming::digit1 as digit; use nom::combinator::verify; use nom::error::{ErrorKind, ParseError}; #[cfg(feature = "alloc")] use nom::multi::count; use nom::sequence::terminated; use nom::IResult; #[derive(Debug)] pub struct CustomError(String); impl<'a> From<(&'a str, ErrorKind)> for CustomError { fn from(error: (&'a str, ErrorKind)) -> Self { CustomError(format!("error code was: {:?}", error)) } } impl<'a> ParseError<&'a str> for CustomError { fn from_error_kind(_: &'a str, kind: ErrorKind) -> Self { CustomError(format!("error code was: {:?}", kind)) } fn append(_: &'a str, kind: ErrorKind, other: CustomError) -> Self { CustomError(format!("{:?}\nerror code was: {:?}", other, kind)) } } fn
(input: &str) -> IResult<&str, &str, CustomError> { //fix_error!(input, CustomError, tag!("abcd")) tag("abcd")(input) } fn test2(input: &str) -> IResult<&str, &str, CustomError> { //terminated!(input, test1, fix_error!(CustomError, digit)) terminated(test1, digit)(input) } fn test3(input: &str) -> IResult<&str, &str, CustomError> { verify(test1, |s: &str| s.starts_with("abcd"))(input) } #[cfg(feature = "alloc")] fn test4(input: &str) -> IResult<&str, Vec<&str>, CustomError> { count(test1, 4)(input) }
test1
identifier_name
custom_errors.rs
#![allow(dead_code)] use nom::bytes::streaming::tag; use nom::character::streaming::digit1 as digit; use nom::combinator::verify; use nom::error::{ErrorKind, ParseError}; #[cfg(feature = "alloc")] use nom::multi::count; use nom::sequence::terminated; use nom::IResult; #[derive(Debug)] pub struct CustomError(String); impl<'a> From<(&'a str, ErrorKind)> for CustomError { fn from(error: (&'a str, ErrorKind)) -> Self { CustomError(format!("error code was: {:?}", error)) } } impl<'a> ParseError<&'a str> for CustomError { fn from_error_kind(_: &'a str, kind: ErrorKind) -> Self { CustomError(format!("error code was: {:?}", kind)) } fn append(_: &'a str, kind: ErrorKind, other: CustomError) -> Self { CustomError(format!("{:?}\nerror code was: {:?}", other, kind)) } } fn test1(input: &str) -> IResult<&str, &str, CustomError> { //fix_error!(input, CustomError, tag!("abcd")) tag("abcd")(input) } fn test2(input: &str) -> IResult<&str, &str, CustomError> { //terminated!(input, test1, fix_error!(CustomError, digit)) terminated(test1, digit)(input) } fn test3(input: &str) -> IResult<&str, &str, CustomError> { verify(test1, |s: &str| s.starts_with("abcd"))(input) } #[cfg(feature = "alloc")]
count(test1, 4)(input) }
fn test4(input: &str) -> IResult<&str, Vec<&str>, CustomError> {
random_line_split
custom_errors.rs
#![allow(dead_code)] use nom::bytes::streaming::tag; use nom::character::streaming::digit1 as digit; use nom::combinator::verify; use nom::error::{ErrorKind, ParseError}; #[cfg(feature = "alloc")] use nom::multi::count; use nom::sequence::terminated; use nom::IResult; #[derive(Debug)] pub struct CustomError(String); impl<'a> From<(&'a str, ErrorKind)> for CustomError { fn from(error: (&'a str, ErrorKind)) -> Self
} impl<'a> ParseError<&'a str> for CustomError { fn from_error_kind(_: &'a str, kind: ErrorKind) -> Self { CustomError(format!("error code was: {:?}", kind)) } fn append(_: &'a str, kind: ErrorKind, other: CustomError) -> Self { CustomError(format!("{:?}\nerror code was: {:?}", other, kind)) } } fn test1(input: &str) -> IResult<&str, &str, CustomError> { //fix_error!(input, CustomError, tag!("abcd")) tag("abcd")(input) } fn test2(input: &str) -> IResult<&str, &str, CustomError> { //terminated!(input, test1, fix_error!(CustomError, digit)) terminated(test1, digit)(input) } fn test3(input: &str) -> IResult<&str, &str, CustomError> { verify(test1, |s: &str| s.starts_with("abcd"))(input) } #[cfg(feature = "alloc")] fn test4(input: &str) -> IResult<&str, Vec<&str>, CustomError> { count(test1, 4)(input) }
{ CustomError(format!("error code was: {:?}", error)) }
identifier_body
blobstore.rs
// Copyright 2018 Benjamin Bader // Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::azure::credentials::*; use hmac::{Hmac, Mac, NewMac}; use hyperx::header; use md5::{Digest, Md5}; use reqwest::Url; use reqwest::{header::HeaderValue, Client, Method, Request}; use sha2::Sha256; use std::fmt; use std::str::FromStr; use crate::errors::*; use crate::util::HeadersExt; const BLOB_API_VERSION: &str = "2017-04-17"; fn hmac(data: &[u8], secret: &[u8]) -> Vec<u8> { let mut hmac = Hmac::<Sha256>::new_varkey(secret).expect("HMAC can take key of any size"); hmac.update(data); hmac.finalize().into_bytes().as_slice().to_vec() } fn signature(to_sign: &str, secret: &str) -> String { let decoded_secret = base64::decode_config(secret.as_bytes(), base64::STANDARD).unwrap(); let sig = hmac(to_sign.as_bytes(), &decoded_secret); base64::encode_config(&sig, base64::STANDARD) } fn md5(data: &[u8]) -> String { let mut digest = Md5::new(); digest.update(data); base64::encode_config(&digest.finalize(), base64::STANDARD) } pub struct BlobContainer { url: String, client: Client, } impl fmt::Display for BlobContainer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "BlobContainer(url={})", self.url) } } impl BlobContainer { pub fn new(base_url: &str, container_name: &str) -> Result<BlobContainer> { assert!( base_url.ends_with('/'), "base_url is assumed to end in a trailing slash" ); Ok(BlobContainer { url: format!("{}{}/", base_url, container_name), client: Client::new(), }) } pub async fn get(&self, key: &str, creds: &AzureCredentials) -> Result<Vec<u8>> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let canonical_headers = format!("x-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION); let auth = compute_auth_header( "GET", "", // content_length "", // content_md5 "", // content_type &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::GET, uri.clone()); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Date is an invalid header value"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth
let res = self .client .execute(request) .await .with_context(|| format!("failed GET: {}", &uri))?; let (bytes, content_length) = if res.status().is_success() { let content_length = res.content_length(); (res.bytes().await?, content_length) } else { return Err(BadHttpStatusError(res.status()).into()); }; if let Some(len) = content_length { if len!= bytes.len() as u64 { bail!(format!( "Bad HTTP body size read: {}, expected {}", bytes.len(), len )); } else { info!("Read {} bytes from {}", bytes.len(), &uri); } } Ok(bytes.into_iter().collect()) } pub async fn put(&self, key: &str, content: Vec<u8>, creds: &AzureCredentials) -> Result<()> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let content_type = "application/octet-stream"; let content_md5 = md5(&content); let content_length = if content.is_empty() { "".to_owned() } else { format!("{}", content.len()) }; let canonical_headers = format!( "x-ms-blob-type:BlockBlob\nx-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION ); let auth = compute_auth_header( "PUT", &content_length, &content_md5, content_type, &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::PUT, uri); request .headers_mut() .set(header::ContentType(content_type.parse().unwrap())); request .headers_mut() .set(header::ContentLength(content.len() as u64)); request .headers_mut() .insert("x-ms-blob-type", HeaderValue::from_static("BlockBlob")); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Invalid x-ms-date header"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth { request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid Authorization header"), ); } request.headers_mut().insert( "Content-MD5", HeaderValue::from_str(&content_md5).expect("Invalid Content-MD5 header"), ); *request.body_mut() = Some(content.into()); match self.client.execute(request).await { Ok(res) => { if res.status().is_success() { trace!("PUT succeeded"); Ok(()) } else { trace!("PUT failed with HTTP status: {}", res.status()); Err(BadHttpStatusError(res.status()).into()) } } Err(e) => { trace!("PUT failed with error: {:?}", e); Err(e.into()) } } } } fn compute_auth_header( verb: &str, content_length: &str, md5: &str, content_type: &str, canonical_headers: &str, uri: &Url, creds: &AzureCredentials, ) -> Option<String> { /* Signature format taken from MSDN docs: https://docs.microsoft.com/en-us/azure/storage/common/storage-rest-api-auth Authorization: SharedKey [AccountName]:[Base64(HMAC(SHA-256, StringToSign))] StringToSign = VERB + "\n" + Content-Encoding + "\n" + Content-Language + "\n" + Content-Length + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + If-Modified-Since + "\n" + If-Match + "\n" + If-None-Match + "\n" + If-Unmodified-Since + "\n" + Range + "\n" + CanonicalizedHeaders + // CanonicalizedHeaders is defined to end with "\n" CanonicalizedResource; */ creds.azure_account_key().as_ref().map(|account_key| { let canonical_resource = canonicalize_resource(uri, creds.azure_account_name()); let string_to_sign = format!("{verb}\n\n\n{length}\n{md5}\n{type}\n\n\n\n\n\n\n{headers}{resource}", verb = verb, length = content_length, md5 = md5, type = content_type, headers = canonical_headers, resource = canonical_resource); format!( "SharedKey {}:{}", creds.azure_account_name(), signature(&string_to_sign, account_key) ) }) } fn canonicalize_resource(uri: &Url, account_name: &str) -> String { let mut canonical_resource = String::new(); canonical_resource.push('/'); canonical_resource.push_str(account_name); canonical_resource.push_str(uri.path()); // Deliberately ignoring query params, because we aren't using them. canonical_resource } #[cfg(test)] mod test { use super::*; use tokio::runtime::Runtime; #[test] fn test_signing() { // Test values copied from https://github.com/MindFlavor/AzureSDKForRust, // which we are treating as an oracle in this test. let string_to_sign = "53d7e14aee681a00340300032015-01-01T10:00:00.0000000".to_owned(); let hmac_key = "pXeTVaaaaU9XxH6fPcPlq8Y9D9G3Cdo5Eh2nMSgKj/DWqeSFFXDdmpz5Trv+L2hQNM+nGa704Rf8Z22W9O1jdQ==" .to_owned(); assert_eq!( signature(&string_to_sign, &hmac_key), "gZzaRaIkvC9jYRY123tq3xXZdsMAcgAbjKQo8y0p0Fs=".to_owned() ); } #[test] fn test_canonicalize_resource() { let url = Url::from_str("https://testaccount.blob.core.windows.net/container/key").unwrap(); let canon = canonicalize_resource(&url, "testaccount"); assert_eq!("/testaccount/container/key", &canon); } #[test] #[ignore] fn test_put_blob() { /* NOTE: This test assumes that you are running a local storage emulator, such as azurite. It will fail, perhaps hanging indefinitely, if you aren't! You may also replace the hardcoded constants with your own Azure credentials, if you wish to run the test against an actual blob store. If you do this, **don't check your credentials in**! Run this test with `cargo test --features azure -- --ignored`. */ let blob_endpoint = "http://localhost:10000/devstoreaccount1/"; let client_name = "devstoreaccount1"; let client_key = Some("Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==".to_string()); let container_name = "sccache"; let creds = AzureCredentials::new( blob_endpoint, client_name, client_key, container_name.to_string(), ); let runtime = Runtime::new().unwrap(); let container = BlobContainer::new(creds.azure_blob_endpoint(), container_name).unwrap(); let put_future = container.put("foo", b"barbell".to_vec(), &creds); runtime.block_on(put_future).unwrap(); let get_future = container.get("foo", &creds); let result = runtime.block_on(get_future).unwrap(); assert_eq!(b"barbell".to_vec(), result); } }
{ request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Authorization is an invalid header value"), ); }
conditional_block
blobstore.rs
// Copyright 2018 Benjamin Bader // Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::azure::credentials::*; use hmac::{Hmac, Mac, NewMac}; use hyperx::header; use md5::{Digest, Md5}; use reqwest::Url; use reqwest::{header::HeaderValue, Client, Method, Request}; use sha2::Sha256; use std::fmt; use std::str::FromStr; use crate::errors::*; use crate::util::HeadersExt; const BLOB_API_VERSION: &str = "2017-04-17"; fn hmac(data: &[u8], secret: &[u8]) -> Vec<u8> { let mut hmac = Hmac::<Sha256>::new_varkey(secret).expect("HMAC can take key of any size"); hmac.update(data); hmac.finalize().into_bytes().as_slice().to_vec() } fn signature(to_sign: &str, secret: &str) -> String { let decoded_secret = base64::decode_config(secret.as_bytes(), base64::STANDARD).unwrap(); let sig = hmac(to_sign.as_bytes(), &decoded_secret); base64::encode_config(&sig, base64::STANDARD) } fn md5(data: &[u8]) -> String { let mut digest = Md5::new(); digest.update(data); base64::encode_config(&digest.finalize(), base64::STANDARD) } pub struct BlobContainer { url: String, client: Client, } impl fmt::Display for BlobContainer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "BlobContainer(url={})", self.url) } } impl BlobContainer { pub fn new(base_url: &str, container_name: &str) -> Result<BlobContainer> { assert!( base_url.ends_with('/'), "base_url is assumed to end in a trailing slash" ); Ok(BlobContainer { url: format!("{}{}/", base_url, container_name), client: Client::new(), }) } pub async fn get(&self, key: &str, creds: &AzureCredentials) -> Result<Vec<u8>> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let canonical_headers = format!("x-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION); let auth = compute_auth_header( "GET", "", // content_length "", // content_md5 "", // content_type &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::GET, uri.clone()); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Date is an invalid header value"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth { request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Authorization is an invalid header value"), );
let res = self .client .execute(request) .await .with_context(|| format!("failed GET: {}", &uri))?; let (bytes, content_length) = if res.status().is_success() { let content_length = res.content_length(); (res.bytes().await?, content_length) } else { return Err(BadHttpStatusError(res.status()).into()); }; if let Some(len) = content_length { if len!= bytes.len() as u64 { bail!(format!( "Bad HTTP body size read: {}, expected {}", bytes.len(), len )); } else { info!("Read {} bytes from {}", bytes.len(), &uri); } } Ok(bytes.into_iter().collect()) } pub async fn put(&self, key: &str, content: Vec<u8>, creds: &AzureCredentials) -> Result<()> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let content_type = "application/octet-stream"; let content_md5 = md5(&content); let content_length = if content.is_empty() { "".to_owned() } else { format!("{}", content.len()) }; let canonical_headers = format!( "x-ms-blob-type:BlockBlob\nx-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION ); let auth = compute_auth_header( "PUT", &content_length, &content_md5, content_type, &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::PUT, uri); request .headers_mut() .set(header::ContentType(content_type.parse().unwrap())); request .headers_mut() .set(header::ContentLength(content.len() as u64)); request .headers_mut() .insert("x-ms-blob-type", HeaderValue::from_static("BlockBlob")); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Invalid x-ms-date header"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth { request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid Authorization header"), ); } request.headers_mut().insert( "Content-MD5", HeaderValue::from_str(&content_md5).expect("Invalid Content-MD5 header"), ); *request.body_mut() = Some(content.into()); match self.client.execute(request).await { Ok(res) => { if res.status().is_success() { trace!("PUT succeeded"); Ok(()) } else { trace!("PUT failed with HTTP status: {}", res.status()); Err(BadHttpStatusError(res.status()).into()) } } Err(e) => { trace!("PUT failed with error: {:?}", e); Err(e.into()) } } } } fn compute_auth_header( verb: &str, content_length: &str, md5: &str, content_type: &str, canonical_headers: &str, uri: &Url, creds: &AzureCredentials, ) -> Option<String> { /* Signature format taken from MSDN docs: https://docs.microsoft.com/en-us/azure/storage/common/storage-rest-api-auth Authorization: SharedKey [AccountName]:[Base64(HMAC(SHA-256, StringToSign))] StringToSign = VERB + "\n" + Content-Encoding + "\n" + Content-Language + "\n" + Content-Length + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + If-Modified-Since + "\n" + If-Match + "\n" + If-None-Match + "\n" + If-Unmodified-Since + "\n" + Range + "\n" + CanonicalizedHeaders + // CanonicalizedHeaders is defined to end with "\n" CanonicalizedResource; */ creds.azure_account_key().as_ref().map(|account_key| { let canonical_resource = canonicalize_resource(uri, creds.azure_account_name()); let string_to_sign = format!("{verb}\n\n\n{length}\n{md5}\n{type}\n\n\n\n\n\n\n{headers}{resource}", verb = verb, length = content_length, md5 = md5, type = content_type, headers = canonical_headers, resource = canonical_resource); format!( "SharedKey {}:{}", creds.azure_account_name(), signature(&string_to_sign, account_key) ) }) } fn canonicalize_resource(uri: &Url, account_name: &str) -> String { let mut canonical_resource = String::new(); canonical_resource.push('/'); canonical_resource.push_str(account_name); canonical_resource.push_str(uri.path()); // Deliberately ignoring query params, because we aren't using them. canonical_resource } #[cfg(test)] mod test { use super::*; use tokio::runtime::Runtime; #[test] fn test_signing() { // Test values copied from https://github.com/MindFlavor/AzureSDKForRust, // which we are treating as an oracle in this test. let string_to_sign = "53d7e14aee681a00340300032015-01-01T10:00:00.0000000".to_owned(); let hmac_key = "pXeTVaaaaU9XxH6fPcPlq8Y9D9G3Cdo5Eh2nMSgKj/DWqeSFFXDdmpz5Trv+L2hQNM+nGa704Rf8Z22W9O1jdQ==" .to_owned(); assert_eq!( signature(&string_to_sign, &hmac_key), "gZzaRaIkvC9jYRY123tq3xXZdsMAcgAbjKQo8y0p0Fs=".to_owned() ); } #[test] fn test_canonicalize_resource() { let url = Url::from_str("https://testaccount.blob.core.windows.net/container/key").unwrap(); let canon = canonicalize_resource(&url, "testaccount"); assert_eq!("/testaccount/container/key", &canon); } #[test] #[ignore] fn test_put_blob() { /* NOTE: This test assumes that you are running a local storage emulator, such as azurite. It will fail, perhaps hanging indefinitely, if you aren't! You may also replace the hardcoded constants with your own Azure credentials, if you wish to run the test against an actual blob store. If you do this, **don't check your credentials in**! Run this test with `cargo test --features azure -- --ignored`. */ let blob_endpoint = "http://localhost:10000/devstoreaccount1/"; let client_name = "devstoreaccount1"; let client_key = Some("Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==".to_string()); let container_name = "sccache"; let creds = AzureCredentials::new( blob_endpoint, client_name, client_key, container_name.to_string(), ); let runtime = Runtime::new().unwrap(); let container = BlobContainer::new(creds.azure_blob_endpoint(), container_name).unwrap(); let put_future = container.put("foo", b"barbell".to_vec(), &creds); runtime.block_on(put_future).unwrap(); let get_future = container.get("foo", &creds); let result = runtime.block_on(get_future).unwrap(); assert_eq!(b"barbell".to_vec(), result); } }
}
random_line_split
blobstore.rs
// Copyright 2018 Benjamin Bader // Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::azure::credentials::*; use hmac::{Hmac, Mac, NewMac}; use hyperx::header; use md5::{Digest, Md5}; use reqwest::Url; use reqwest::{header::HeaderValue, Client, Method, Request}; use sha2::Sha256; use std::fmt; use std::str::FromStr; use crate::errors::*; use crate::util::HeadersExt; const BLOB_API_VERSION: &str = "2017-04-17"; fn hmac(data: &[u8], secret: &[u8]) -> Vec<u8> { let mut hmac = Hmac::<Sha256>::new_varkey(secret).expect("HMAC can take key of any size"); hmac.update(data); hmac.finalize().into_bytes().as_slice().to_vec() } fn signature(to_sign: &str, secret: &str) -> String { let decoded_secret = base64::decode_config(secret.as_bytes(), base64::STANDARD).unwrap(); let sig = hmac(to_sign.as_bytes(), &decoded_secret); base64::encode_config(&sig, base64::STANDARD) } fn md5(data: &[u8]) -> String { let mut digest = Md5::new(); digest.update(data); base64::encode_config(&digest.finalize(), base64::STANDARD) } pub struct BlobContainer { url: String, client: Client, } impl fmt::Display for BlobContainer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "BlobContainer(url={})", self.url) } } impl BlobContainer { pub fn new(base_url: &str, container_name: &str) -> Result<BlobContainer> { assert!( base_url.ends_with('/'), "base_url is assumed to end in a trailing slash" ); Ok(BlobContainer { url: format!("{}{}/", base_url, container_name), client: Client::new(), }) } pub async fn get(&self, key: &str, creds: &AzureCredentials) -> Result<Vec<u8>> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let canonical_headers = format!("x-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION); let auth = compute_auth_header( "GET", "", // content_length "", // content_md5 "", // content_type &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::GET, uri.clone()); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Date is an invalid header value"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth { request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Authorization is an invalid header value"), ); } let res = self .client .execute(request) .await .with_context(|| format!("failed GET: {}", &uri))?; let (bytes, content_length) = if res.status().is_success() { let content_length = res.content_length(); (res.bytes().await?, content_length) } else { return Err(BadHttpStatusError(res.status()).into()); }; if let Some(len) = content_length { if len!= bytes.len() as u64 { bail!(format!( "Bad HTTP body size read: {}, expected {}", bytes.len(), len )); } else { info!("Read {} bytes from {}", bytes.len(), &uri); } } Ok(bytes.into_iter().collect()) } pub async fn put(&self, key: &str, content: Vec<u8>, creds: &AzureCredentials) -> Result<()> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let content_type = "application/octet-stream"; let content_md5 = md5(&content); let content_length = if content.is_empty() { "".to_owned() } else { format!("{}", content.len()) }; let canonical_headers = format!( "x-ms-blob-type:BlockBlob\nx-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION ); let auth = compute_auth_header( "PUT", &content_length, &content_md5, content_type, &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::PUT, uri); request .headers_mut() .set(header::ContentType(content_type.parse().unwrap())); request .headers_mut() .set(header::ContentLength(content.len() as u64)); request .headers_mut() .insert("x-ms-blob-type", HeaderValue::from_static("BlockBlob")); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Invalid x-ms-date header"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth { request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid Authorization header"), ); } request.headers_mut().insert( "Content-MD5", HeaderValue::from_str(&content_md5).expect("Invalid Content-MD5 header"), ); *request.body_mut() = Some(content.into()); match self.client.execute(request).await { Ok(res) => { if res.status().is_success() { trace!("PUT succeeded"); Ok(()) } else { trace!("PUT failed with HTTP status: {}", res.status()); Err(BadHttpStatusError(res.status()).into()) } } Err(e) => { trace!("PUT failed with error: {:?}", e); Err(e.into()) } } } } fn compute_auth_header( verb: &str, content_length: &str, md5: &str, content_type: &str, canonical_headers: &str, uri: &Url, creds: &AzureCredentials, ) -> Option<String> { /* Signature format taken from MSDN docs: https://docs.microsoft.com/en-us/azure/storage/common/storage-rest-api-auth Authorization: SharedKey [AccountName]:[Base64(HMAC(SHA-256, StringToSign))] StringToSign = VERB + "\n" + Content-Encoding + "\n" + Content-Language + "\n" + Content-Length + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + If-Modified-Since + "\n" + If-Match + "\n" + If-None-Match + "\n" + If-Unmodified-Since + "\n" + Range + "\n" + CanonicalizedHeaders + // CanonicalizedHeaders is defined to end with "\n" CanonicalizedResource; */ creds.azure_account_key().as_ref().map(|account_key| { let canonical_resource = canonicalize_resource(uri, creds.azure_account_name()); let string_to_sign = format!("{verb}\n\n\n{length}\n{md5}\n{type}\n\n\n\n\n\n\n{headers}{resource}", verb = verb, length = content_length, md5 = md5, type = content_type, headers = canonical_headers, resource = canonical_resource); format!( "SharedKey {}:{}", creds.azure_account_name(), signature(&string_to_sign, account_key) ) }) } fn canonicalize_resource(uri: &Url, account_name: &str) -> String { let mut canonical_resource = String::new(); canonical_resource.push('/'); canonical_resource.push_str(account_name); canonical_resource.push_str(uri.path()); // Deliberately ignoring query params, because we aren't using them. canonical_resource } #[cfg(test)] mod test { use super::*; use tokio::runtime::Runtime; #[test] fn test_signing() { // Test values copied from https://github.com/MindFlavor/AzureSDKForRust, // which we are treating as an oracle in this test. let string_to_sign = "53d7e14aee681a00340300032015-01-01T10:00:00.0000000".to_owned(); let hmac_key = "pXeTVaaaaU9XxH6fPcPlq8Y9D9G3Cdo5Eh2nMSgKj/DWqeSFFXDdmpz5Trv+L2hQNM+nGa704Rf8Z22W9O1jdQ==" .to_owned(); assert_eq!( signature(&string_to_sign, &hmac_key), "gZzaRaIkvC9jYRY123tq3xXZdsMAcgAbjKQo8y0p0Fs=".to_owned() ); } #[test] fn test_canonicalize_resource()
#[test] #[ignore] fn test_put_blob() { /* NOTE: This test assumes that you are running a local storage emulator, such as azurite. It will fail, perhaps hanging indefinitely, if you aren't! You may also replace the hardcoded constants with your own Azure credentials, if you wish to run the test against an actual blob store. If you do this, **don't check your credentials in**! Run this test with `cargo test --features azure -- --ignored`. */ let blob_endpoint = "http://localhost:10000/devstoreaccount1/"; let client_name = "devstoreaccount1"; let client_key = Some("Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==".to_string()); let container_name = "sccache"; let creds = AzureCredentials::new( blob_endpoint, client_name, client_key, container_name.to_string(), ); let runtime = Runtime::new().unwrap(); let container = BlobContainer::new(creds.azure_blob_endpoint(), container_name).unwrap(); let put_future = container.put("foo", b"barbell".to_vec(), &creds); runtime.block_on(put_future).unwrap(); let get_future = container.get("foo", &creds); let result = runtime.block_on(get_future).unwrap(); assert_eq!(b"barbell".to_vec(), result); } }
{ let url = Url::from_str("https://testaccount.blob.core.windows.net/container/key").unwrap(); let canon = canonicalize_resource(&url, "testaccount"); assert_eq!("/testaccount/container/key", &canon); }
identifier_body
blobstore.rs
// Copyright 2018 Benjamin Bader // Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::azure::credentials::*; use hmac::{Hmac, Mac, NewMac}; use hyperx::header; use md5::{Digest, Md5}; use reqwest::Url; use reqwest::{header::HeaderValue, Client, Method, Request}; use sha2::Sha256; use std::fmt; use std::str::FromStr; use crate::errors::*; use crate::util::HeadersExt; const BLOB_API_VERSION: &str = "2017-04-17"; fn hmac(data: &[u8], secret: &[u8]) -> Vec<u8> { let mut hmac = Hmac::<Sha256>::new_varkey(secret).expect("HMAC can take key of any size"); hmac.update(data); hmac.finalize().into_bytes().as_slice().to_vec() } fn signature(to_sign: &str, secret: &str) -> String { let decoded_secret = base64::decode_config(secret.as_bytes(), base64::STANDARD).unwrap(); let sig = hmac(to_sign.as_bytes(), &decoded_secret); base64::encode_config(&sig, base64::STANDARD) } fn md5(data: &[u8]) -> String { let mut digest = Md5::new(); digest.update(data); base64::encode_config(&digest.finalize(), base64::STANDARD) } pub struct BlobContainer { url: String, client: Client, } impl fmt::Display for BlobContainer { fn
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "BlobContainer(url={})", self.url) } } impl BlobContainer { pub fn new(base_url: &str, container_name: &str) -> Result<BlobContainer> { assert!( base_url.ends_with('/'), "base_url is assumed to end in a trailing slash" ); Ok(BlobContainer { url: format!("{}{}/", base_url, container_name), client: Client::new(), }) } pub async fn get(&self, key: &str, creds: &AzureCredentials) -> Result<Vec<u8>> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let canonical_headers = format!("x-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION); let auth = compute_auth_header( "GET", "", // content_length "", // content_md5 "", // content_type &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::GET, uri.clone()); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Date is an invalid header value"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth { request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Authorization is an invalid header value"), ); } let res = self .client .execute(request) .await .with_context(|| format!("failed GET: {}", &uri))?; let (bytes, content_length) = if res.status().is_success() { let content_length = res.content_length(); (res.bytes().await?, content_length) } else { return Err(BadHttpStatusError(res.status()).into()); }; if let Some(len) = content_length { if len!= bytes.len() as u64 { bail!(format!( "Bad HTTP body size read: {}, expected {}", bytes.len(), len )); } else { info!("Read {} bytes from {}", bytes.len(), &uri); } } Ok(bytes.into_iter().collect()) } pub async fn put(&self, key: &str, content: Vec<u8>, creds: &AzureCredentials) -> Result<()> { let url_string = format!("{}{}", self.url, key); let uri = Url::from_str(&url_string).unwrap(); let dt = chrono::Utc::now(); let date = format!("{}", dt.format("%a, %d %b %Y %T GMT")); let content_type = "application/octet-stream"; let content_md5 = md5(&content); let content_length = if content.is_empty() { "".to_owned() } else { format!("{}", content.len()) }; let canonical_headers = format!( "x-ms-blob-type:BlockBlob\nx-ms-date:{}\nx-ms-version:{}\n", date, BLOB_API_VERSION ); let auth = compute_auth_header( "PUT", &content_length, &content_md5, content_type, &canonical_headers, &uri, creds, ); let mut request = Request::new(Method::PUT, uri); request .headers_mut() .set(header::ContentType(content_type.parse().unwrap())); request .headers_mut() .set(header::ContentLength(content.len() as u64)); request .headers_mut() .insert("x-ms-blob-type", HeaderValue::from_static("BlockBlob")); request.headers_mut().insert( "x-ms-date", HeaderValue::from_str(&date).expect("Invalid x-ms-date header"), ); request .headers_mut() .insert("x-ms-version", HeaderValue::from_static(BLOB_API_VERSION)); if let Some(auth) = auth { request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid Authorization header"), ); } request.headers_mut().insert( "Content-MD5", HeaderValue::from_str(&content_md5).expect("Invalid Content-MD5 header"), ); *request.body_mut() = Some(content.into()); match self.client.execute(request).await { Ok(res) => { if res.status().is_success() { trace!("PUT succeeded"); Ok(()) } else { trace!("PUT failed with HTTP status: {}", res.status()); Err(BadHttpStatusError(res.status()).into()) } } Err(e) => { trace!("PUT failed with error: {:?}", e); Err(e.into()) } } } } fn compute_auth_header( verb: &str, content_length: &str, md5: &str, content_type: &str, canonical_headers: &str, uri: &Url, creds: &AzureCredentials, ) -> Option<String> { /* Signature format taken from MSDN docs: https://docs.microsoft.com/en-us/azure/storage/common/storage-rest-api-auth Authorization: SharedKey [AccountName]:[Base64(HMAC(SHA-256, StringToSign))] StringToSign = VERB + "\n" + Content-Encoding + "\n" + Content-Language + "\n" + Content-Length + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + If-Modified-Since + "\n" + If-Match + "\n" + If-None-Match + "\n" + If-Unmodified-Since + "\n" + Range + "\n" + CanonicalizedHeaders + // CanonicalizedHeaders is defined to end with "\n" CanonicalizedResource; */ creds.azure_account_key().as_ref().map(|account_key| { let canonical_resource = canonicalize_resource(uri, creds.azure_account_name()); let string_to_sign = format!("{verb}\n\n\n{length}\n{md5}\n{type}\n\n\n\n\n\n\n{headers}{resource}", verb = verb, length = content_length, md5 = md5, type = content_type, headers = canonical_headers, resource = canonical_resource); format!( "SharedKey {}:{}", creds.azure_account_name(), signature(&string_to_sign, account_key) ) }) } fn canonicalize_resource(uri: &Url, account_name: &str) -> String { let mut canonical_resource = String::new(); canonical_resource.push('/'); canonical_resource.push_str(account_name); canonical_resource.push_str(uri.path()); // Deliberately ignoring query params, because we aren't using them. canonical_resource } #[cfg(test)] mod test { use super::*; use tokio::runtime::Runtime; #[test] fn test_signing() { // Test values copied from https://github.com/MindFlavor/AzureSDKForRust, // which we are treating as an oracle in this test. let string_to_sign = "53d7e14aee681a00340300032015-01-01T10:00:00.0000000".to_owned(); let hmac_key = "pXeTVaaaaU9XxH6fPcPlq8Y9D9G3Cdo5Eh2nMSgKj/DWqeSFFXDdmpz5Trv+L2hQNM+nGa704Rf8Z22W9O1jdQ==" .to_owned(); assert_eq!( signature(&string_to_sign, &hmac_key), "gZzaRaIkvC9jYRY123tq3xXZdsMAcgAbjKQo8y0p0Fs=".to_owned() ); } #[test] fn test_canonicalize_resource() { let url = Url::from_str("https://testaccount.blob.core.windows.net/container/key").unwrap(); let canon = canonicalize_resource(&url, "testaccount"); assert_eq!("/testaccount/container/key", &canon); } #[test] #[ignore] fn test_put_blob() { /* NOTE: This test assumes that you are running a local storage emulator, such as azurite. It will fail, perhaps hanging indefinitely, if you aren't! You may also replace the hardcoded constants with your own Azure credentials, if you wish to run the test against an actual blob store. If you do this, **don't check your credentials in**! Run this test with `cargo test --features azure -- --ignored`. */ let blob_endpoint = "http://localhost:10000/devstoreaccount1/"; let client_name = "devstoreaccount1"; let client_key = Some("Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==".to_string()); let container_name = "sccache"; let creds = AzureCredentials::new( blob_endpoint, client_name, client_key, container_name.to_string(), ); let runtime = Runtime::new().unwrap(); let container = BlobContainer::new(creds.azure_blob_endpoint(), container_name).unwrap(); let put_future = container.put("foo", b"barbell".to_vec(), &creds); runtime.block_on(put_future).unwrap(); let get_future = container.get("foo", &creds); let result = runtime.block_on(get_future).unwrap(); assert_eq!(b"barbell".to_vec(), result); } }
fmt
identifier_name
iri.rs
//! CSS funciri values. use cssparser::Parser; use crate::document::NodeId; use crate::error::*; use crate::parsers::Parse; /// Used where style properties take a funciri or "none" /// /// This is not to be used for values which don't come from properties. /// For example, the `xlink:href` attribute in the `<image>` element /// does not take a funciri value (which looks like `url(...)`), but rather /// it takes a plain URL. #[derive(Debug, Clone, PartialEq)] pub enum Iri { None, Resource(Box<NodeId>), } impl Iri { /// Returns the contents of an `IRI::Resource`, or `None` pub fn get(&self) -> Option<&NodeId> { match *self { Iri::None => None, Iri::Resource(ref f) => Some(&*f), } } } impl Parse for Iri { fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Iri, ParseError<'i>> { if parser .try_parse(|i| i.expect_ident_matching("none")) .is_ok() { Ok(Iri::None) } else { let loc = parser.current_source_location(); let url = parser.expect_url()?; let node_id = NodeId::parse(&url).map_err(|e| loc.new_custom_error(ValueErrorKind::from(e)))?;
} #[cfg(test)] mod tests { use super::*; #[test] fn parses_none() { assert_eq!(Iri::parse_str("none").unwrap(), Iri::None); } #[test] fn parses_url() { assert_eq!( Iri::parse_str("url(#bar)").unwrap(), Iri::Resource(Box::new(NodeId::Internal("bar".to_string()))) ); assert_eq!( Iri::parse_str("url(foo#bar)").unwrap(), Iri::Resource(Box::new(NodeId::External( "foo".to_string(), "bar".to_string() ))) ); // be permissive if the closing ) is missing assert_eq!( Iri::parse_str("url(#bar").unwrap(), Iri::Resource(Box::new(NodeId::Internal("bar".to_string()))) ); assert_eq!( Iri::parse_str("url(foo#bar").unwrap(), Iri::Resource(Box::new(NodeId::External( "foo".to_string(), "bar".to_string() ))) ); assert!(Iri::parse_str("").is_err()); assert!(Iri::parse_str("foo").is_err()); assert!(Iri::parse_str("url(foo)bar").is_err()); } }
Ok(Iri::Resource(Box::new(node_id))) } }
random_line_split
iri.rs
//! CSS funciri values. use cssparser::Parser; use crate::document::NodeId; use crate::error::*; use crate::parsers::Parse; /// Used where style properties take a funciri or "none" /// /// This is not to be used for values which don't come from properties. /// For example, the `xlink:href` attribute in the `<image>` element /// does not take a funciri value (which looks like `url(...)`), but rather /// it takes a plain URL. #[derive(Debug, Clone, PartialEq)] pub enum Iri { None, Resource(Box<NodeId>), } impl Iri { /// Returns the contents of an `IRI::Resource`, or `None` pub fn get(&self) -> Option<&NodeId> { match *self { Iri::None => None, Iri::Resource(ref f) => Some(&*f), } } } impl Parse for Iri { fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Iri, ParseError<'i>> { if parser .try_parse(|i| i.expect_ident_matching("none")) .is_ok() { Ok(Iri::None) } else { let loc = parser.current_source_location(); let url = parser.expect_url()?; let node_id = NodeId::parse(&url).map_err(|e| loc.new_custom_error(ValueErrorKind::from(e)))?; Ok(Iri::Resource(Box::new(node_id))) } } } #[cfg(test)] mod tests { use super::*; #[test] fn parses_none() { assert_eq!(Iri::parse_str("none").unwrap(), Iri::None); } #[test] fn
() { assert_eq!( Iri::parse_str("url(#bar)").unwrap(), Iri::Resource(Box::new(NodeId::Internal("bar".to_string()))) ); assert_eq!( Iri::parse_str("url(foo#bar)").unwrap(), Iri::Resource(Box::new(NodeId::External( "foo".to_string(), "bar".to_string() ))) ); // be permissive if the closing ) is missing assert_eq!( Iri::parse_str("url(#bar").unwrap(), Iri::Resource(Box::new(NodeId::Internal("bar".to_string()))) ); assert_eq!( Iri::parse_str("url(foo#bar").unwrap(), Iri::Resource(Box::new(NodeId::External( "foo".to_string(), "bar".to_string() ))) ); assert!(Iri::parse_str("").is_err()); assert!(Iri::parse_str("foo").is_err()); assert!(Iri::parse_str("url(foo)bar").is_err()); } }
parses_url
identifier_name
iri.rs
//! CSS funciri values. use cssparser::Parser; use crate::document::NodeId; use crate::error::*; use crate::parsers::Parse; /// Used where style properties take a funciri or "none" /// /// This is not to be used for values which don't come from properties. /// For example, the `xlink:href` attribute in the `<image>` element /// does not take a funciri value (which looks like `url(...)`), but rather /// it takes a plain URL. #[derive(Debug, Clone, PartialEq)] pub enum Iri { None, Resource(Box<NodeId>), } impl Iri { /// Returns the contents of an `IRI::Resource`, or `None` pub fn get(&self) -> Option<&NodeId> { match *self { Iri::None => None, Iri::Resource(ref f) => Some(&*f), } } } impl Parse for Iri { fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Iri, ParseError<'i>> { if parser .try_parse(|i| i.expect_ident_matching("none")) .is_ok() { Ok(Iri::None) } else { let loc = parser.current_source_location(); let url = parser.expect_url()?; let node_id = NodeId::parse(&url).map_err(|e| loc.new_custom_error(ValueErrorKind::from(e)))?; Ok(Iri::Resource(Box::new(node_id))) } } } #[cfg(test)] mod tests { use super::*; #[test] fn parses_none()
#[test] fn parses_url() { assert_eq!( Iri::parse_str("url(#bar)").unwrap(), Iri::Resource(Box::new(NodeId::Internal("bar".to_string()))) ); assert_eq!( Iri::parse_str("url(foo#bar)").unwrap(), Iri::Resource(Box::new(NodeId::External( "foo".to_string(), "bar".to_string() ))) ); // be permissive if the closing ) is missing assert_eq!( Iri::parse_str("url(#bar").unwrap(), Iri::Resource(Box::new(NodeId::Internal("bar".to_string()))) ); assert_eq!( Iri::parse_str("url(foo#bar").unwrap(), Iri::Resource(Box::new(NodeId::External( "foo".to_string(), "bar".to_string() ))) ); assert!(Iri::parse_str("").is_err()); assert!(Iri::parse_str("foo").is_err()); assert!(Iri::parse_str("url(foo)bar").is_err()); } }
{ assert_eq!(Iri::parse_str("none").unwrap(), Iri::None); }
identifier_body
htmldetailselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::root::DomRoot;
use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::cell::Cell; use task_source::TaskSource; #[dom_struct] pub struct HTMLDetailsElement { htmlelement: HTMLElement, toggle_counter: Cell<u32>, } impl HTMLDetailsElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLDetailsElement { HTMLDetailsElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), toggle_counter: Cell::new(0), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDetailsElement> { Node::reflect_node( Box::new(HTMLDetailsElement::new_inherited( local_name, prefix, document, )), document, HTMLDetailsElementBinding::Wrap, ) } } impl HTMLDetailsElementMethods for HTMLDetailsElement { // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_setter!(SetOpen, "open"); } impl VirtualMethods for HTMLDetailsElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &local_name!("open") { let counter = self.toggle_counter.get() + 1; self.toggle_counter.set(counter); let window = window_from_node(self); let this = Trusted::new(self); // FIXME(nox): Why are errors silenced here? let _ = window.dom_manipulation_task_source().queue( task!(details_notification_task_steps: move || { let this = this.root(); if counter == this.toggle_counter.get() { this.upcast::<EventTarget>().fire_event(atom!("toggle")); } }), window.upcast(), ); } } }
use dom::document::Document; use dom::element::AttributeMutation; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node};
random_line_split
htmldetailselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::element::AttributeMutation; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::cell::Cell; use task_source::TaskSource; #[dom_struct] pub struct HTMLDetailsElement { htmlelement: HTMLElement, toggle_counter: Cell<u32>, } impl HTMLDetailsElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLDetailsElement { HTMLDetailsElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), toggle_counter: Cell::new(0), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDetailsElement> { Node::reflect_node( Box::new(HTMLDetailsElement::new_inherited( local_name, prefix, document, )), document, HTMLDetailsElementBinding::Wrap, ) } } impl HTMLDetailsElementMethods for HTMLDetailsElement { // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_setter!(SetOpen, "open"); } impl VirtualMethods for HTMLDetailsElement { fn
(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &local_name!("open") { let counter = self.toggle_counter.get() + 1; self.toggle_counter.set(counter); let window = window_from_node(self); let this = Trusted::new(self); // FIXME(nox): Why are errors silenced here? let _ = window.dom_manipulation_task_source().queue( task!(details_notification_task_steps: move || { let this = this.root(); if counter == this.toggle_counter.get() { this.upcast::<EventTarget>().fire_event(atom!("toggle")); } }), window.upcast(), ); } } }
super_type
identifier_name
htmldetailselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::element::AttributeMutation; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::cell::Cell; use task_source::TaskSource; #[dom_struct] pub struct HTMLDetailsElement { htmlelement: HTMLElement, toggle_counter: Cell<u32>, } impl HTMLDetailsElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLDetailsElement { HTMLDetailsElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), toggle_counter: Cell::new(0), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDetailsElement> { Node::reflect_node( Box::new(HTMLDetailsElement::new_inherited( local_name, prefix, document, )), document, HTMLDetailsElementBinding::Wrap, ) } } impl HTMLDetailsElementMethods for HTMLDetailsElement { // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_setter!(SetOpen, "open"); } impl VirtualMethods for HTMLDetailsElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &local_name!("open")
} }
{ let counter = self.toggle_counter.get() + 1; self.toggle_counter.set(counter); let window = window_from_node(self); let this = Trusted::new(self); // FIXME(nox): Why are errors silenced here? let _ = window.dom_manipulation_task_source().queue( task!(details_notification_task_steps: move || { let this = this.root(); if counter == this.toggle_counter.get() { this.upcast::<EventTarget>().fire_event(atom!("toggle")); } }), window.upcast(), ); }
conditional_block
htmldetailselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::element::AttributeMutation; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::cell::Cell; use task_source::TaskSource; #[dom_struct] pub struct HTMLDetailsElement { htmlelement: HTMLElement, toggle_counter: Cell<u32>, } impl HTMLDetailsElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLDetailsElement { HTMLDetailsElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), toggle_counter: Cell::new(0), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDetailsElement>
} impl HTMLDetailsElementMethods for HTMLDetailsElement { // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-details-open make_bool_setter!(SetOpen, "open"); } impl VirtualMethods for HTMLDetailsElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &local_name!("open") { let counter = self.toggle_counter.get() + 1; self.toggle_counter.set(counter); let window = window_from_node(self); let this = Trusted::new(self); // FIXME(nox): Why are errors silenced here? let _ = window.dom_manipulation_task_source().queue( task!(details_notification_task_steps: move || { let this = this.root(); if counter == this.toggle_counter.get() { this.upcast::<EventTarget>().fire_event(atom!("toggle")); } }), window.upcast(), ); } } }
{ Node::reflect_node( Box::new(HTMLDetailsElement::new_inherited( local_name, prefix, document, )), document, HTMLDetailsElementBinding::Wrap, ) }
identifier_body
test_butterfly.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Encapsulate a butterfly client and expose its functionality via a //! test-focused API. Clients are configured for a specific service //! group (namely, the one of the test package we are running). //! //! No ring key or encryption abilities are currently supported. extern crate habitat_butterfly; use self::habitat_butterfly::client::Client as ButterflyClient; extern crate habitat_core; use self::habitat_core::service::ServiceGroup; extern crate toml; use std::net::SocketAddr; use std::time::{SystemTime, UNIX_EPOCH}; pub struct Client { butterfly_client: ButterflyClient, pub package_name: String, pub service_group: String, } impl Client { pub fn new<T, U>(package_name: T, service_group: U, port: u16) -> Client where T: ToString, U: ToString, { let gossip_addr = format!("127.0.0.1:{}", port) .parse::<SocketAddr>() .expect("Could not parse Butterfly gossip address!"); let c = ButterflyClient::new(&gossip_addr, None) .expect("Could not create Butterfly Client for test!"); Client { butterfly_client: c, package_name: package_name.to_string(), service_group: service_group.to_string(), } } /// Apply the given configuration to the Supervisor. It will /// always be applied to the service group for which the client was /// initially configured. /// /// A time-based incarnation value is automatically used, /// resulting in less clutter in your tests. pub fn apply<T>(&mut self, config: T) where T: ToString, { let config = config.to_string(); // Validate the TOML, to save you from typos in your tests if let Err(err) = self::toml::de::from_slice::<self::toml::value::Value>(&config.as_bytes())
let payload = Vec::from(config.as_bytes()); let incarnation = Self::new_incarnation(); self.butterfly_client .send_service_config( ServiceGroup::new(None, &self.package_name, &self.service_group, None).unwrap(), incarnation, payload, false, ) .expect("Cannot send the service configuration"); } /// Generate a new incarnation number using the number of seconds /// since the Unix Epoch. As a result, this is unique to within a /// second, so beware! Might need to incorporate nanoseconds as well. fn new_incarnation() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } }
{ panic!("Invalid TOML! {:?} ==> {:?}", config, err); }
conditional_block
test_butterfly.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Encapsulate a butterfly client and expose its functionality via a //! test-focused API. Clients are configured for a specific service //! group (namely, the one of the test package we are running). //! //! No ring key or encryption abilities are currently supported. extern crate habitat_butterfly; use self::habitat_butterfly::client::Client as ButterflyClient; extern crate habitat_core; use self::habitat_core::service::ServiceGroup; extern crate toml; use std::net::SocketAddr; use std::time::{SystemTime, UNIX_EPOCH}; pub struct Client { butterfly_client: ButterflyClient, pub package_name: String, pub service_group: String, } impl Client { pub fn new<T, U>(package_name: T, service_group: U, port: u16) -> Client where T: ToString, U: ToString,
/// Apply the given configuration to the Supervisor. It will /// always be applied to the service group for which the client was /// initially configured. /// /// A time-based incarnation value is automatically used, /// resulting in less clutter in your tests. pub fn apply<T>(&mut self, config: T) where T: ToString, { let config = config.to_string(); // Validate the TOML, to save you from typos in your tests if let Err(err) = self::toml::de::from_slice::<self::toml::value::Value>(&config.as_bytes()) { panic!("Invalid TOML! {:?} ==> {:?}", config, err); } let payload = Vec::from(config.as_bytes()); let incarnation = Self::new_incarnation(); self.butterfly_client .send_service_config( ServiceGroup::new(None, &self.package_name, &self.service_group, None).unwrap(), incarnation, payload, false, ) .expect("Cannot send the service configuration"); } /// Generate a new incarnation number using the number of seconds /// since the Unix Epoch. As a result, this is unique to within a /// second, so beware! Might need to incorporate nanoseconds as well. fn new_incarnation() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } }
{ let gossip_addr = format!("127.0.0.1:{}", port) .parse::<SocketAddr>() .expect("Could not parse Butterfly gossip address!"); let c = ButterflyClient::new(&gossip_addr, None) .expect("Could not create Butterfly Client for test!"); Client { butterfly_client: c, package_name: package_name.to_string(), service_group: service_group.to_string(), } }
identifier_body
test_butterfly.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Encapsulate a butterfly client and expose its functionality via a //! test-focused API. Clients are configured for a specific service //! group (namely, the one of the test package we are running). //!
extern crate habitat_butterfly; use self::habitat_butterfly::client::Client as ButterflyClient; extern crate habitat_core; use self::habitat_core::service::ServiceGroup; extern crate toml; use std::net::SocketAddr; use std::time::{SystemTime, UNIX_EPOCH}; pub struct Client { butterfly_client: ButterflyClient, pub package_name: String, pub service_group: String, } impl Client { pub fn new<T, U>(package_name: T, service_group: U, port: u16) -> Client where T: ToString, U: ToString, { let gossip_addr = format!("127.0.0.1:{}", port) .parse::<SocketAddr>() .expect("Could not parse Butterfly gossip address!"); let c = ButterflyClient::new(&gossip_addr, None) .expect("Could not create Butterfly Client for test!"); Client { butterfly_client: c, package_name: package_name.to_string(), service_group: service_group.to_string(), } } /// Apply the given configuration to the Supervisor. It will /// always be applied to the service group for which the client was /// initially configured. /// /// A time-based incarnation value is automatically used, /// resulting in less clutter in your tests. pub fn apply<T>(&mut self, config: T) where T: ToString, { let config = config.to_string(); // Validate the TOML, to save you from typos in your tests if let Err(err) = self::toml::de::from_slice::<self::toml::value::Value>(&config.as_bytes()) { panic!("Invalid TOML! {:?} ==> {:?}", config, err); } let payload = Vec::from(config.as_bytes()); let incarnation = Self::new_incarnation(); self.butterfly_client .send_service_config( ServiceGroup::new(None, &self.package_name, &self.service_group, None).unwrap(), incarnation, payload, false, ) .expect("Cannot send the service configuration"); } /// Generate a new incarnation number using the number of seconds /// since the Unix Epoch. As a result, this is unique to within a /// second, so beware! Might need to incorporate nanoseconds as well. fn new_incarnation() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } }
//! No ring key or encryption abilities are currently supported.
random_line_split
test_butterfly.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Encapsulate a butterfly client and expose its functionality via a //! test-focused API. Clients are configured for a specific service //! group (namely, the one of the test package we are running). //! //! No ring key or encryption abilities are currently supported. extern crate habitat_butterfly; use self::habitat_butterfly::client::Client as ButterflyClient; extern crate habitat_core; use self::habitat_core::service::ServiceGroup; extern crate toml; use std::net::SocketAddr; use std::time::{SystemTime, UNIX_EPOCH}; pub struct Client { butterfly_client: ButterflyClient, pub package_name: String, pub service_group: String, } impl Client { pub fn
<T, U>(package_name: T, service_group: U, port: u16) -> Client where T: ToString, U: ToString, { let gossip_addr = format!("127.0.0.1:{}", port) .parse::<SocketAddr>() .expect("Could not parse Butterfly gossip address!"); let c = ButterflyClient::new(&gossip_addr, None) .expect("Could not create Butterfly Client for test!"); Client { butterfly_client: c, package_name: package_name.to_string(), service_group: service_group.to_string(), } } /// Apply the given configuration to the Supervisor. It will /// always be applied to the service group for which the client was /// initially configured. /// /// A time-based incarnation value is automatically used, /// resulting in less clutter in your tests. pub fn apply<T>(&mut self, config: T) where T: ToString, { let config = config.to_string(); // Validate the TOML, to save you from typos in your tests if let Err(err) = self::toml::de::from_slice::<self::toml::value::Value>(&config.as_bytes()) { panic!("Invalid TOML! {:?} ==> {:?}", config, err); } let payload = Vec::from(config.as_bytes()); let incarnation = Self::new_incarnation(); self.butterfly_client .send_service_config( ServiceGroup::new(None, &self.package_name, &self.service_group, None).unwrap(), incarnation, payload, false, ) .expect("Cannot send the service configuration"); } /// Generate a new incarnation number using the number of seconds /// since the Unix Epoch. As a result, this is unique to within a /// second, so beware! Might need to incorporate nanoseconds as well. fn new_incarnation() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } }
new
identifier_name
test_sync.rs
use std::sync::Arc; use std::thread; use protobuf::CodedInputStream; use protobuf::Message; use super::test_sync_pb::*; // test messages are sync #[test] fn test_sync() { let m = Arc::new({ let mut r = TestSync::new(); r.set_int32_field(23); r }); let threads: Vec<_> = (0..4) .map(|_| { let m_copy = m.clone(); thread::spawn(move || { let bytes = m_copy.write_to_bytes().unwrap(); let mut is = CodedInputStream::from_bytes(&bytes); let mut read = TestSync::new(); // API is not very convenient here read.merge_from(&mut is).unwrap(); read.check_initialized().unwrap(); read.int32_field() }) }) .collect(); let results = threads .into_iter()
.collect::<Vec<_>>(); assert_eq!(&[23, 23, 23, 23], &results[..]); }
.map(|t| t.join().unwrap())
random_line_split
test_sync.rs
use std::sync::Arc; use std::thread; use protobuf::CodedInputStream; use protobuf::Message; use super::test_sync_pb::*; // test messages are sync #[test] fn test_sync()
.collect(); let results = threads .into_iter() .map(|t| t.join().unwrap()) .collect::<Vec<_>>(); assert_eq!(&[23, 23, 23, 23], &results[..]); }
{ let m = Arc::new({ let mut r = TestSync::new(); r.set_int32_field(23); r }); let threads: Vec<_> = (0..4) .map(|_| { let m_copy = m.clone(); thread::spawn(move || { let bytes = m_copy.write_to_bytes().unwrap(); let mut is = CodedInputStream::from_bytes(&bytes); let mut read = TestSync::new(); // API is not very convenient here read.merge_from(&mut is).unwrap(); read.check_initialized().unwrap(); read.int32_field() }) })
identifier_body
test_sync.rs
use std::sync::Arc; use std::thread; use protobuf::CodedInputStream; use protobuf::Message; use super::test_sync_pb::*; // test messages are sync #[test] fn
() { let m = Arc::new({ let mut r = TestSync::new(); r.set_int32_field(23); r }); let threads: Vec<_> = (0..4) .map(|_| { let m_copy = m.clone(); thread::spawn(move || { let bytes = m_copy.write_to_bytes().unwrap(); let mut is = CodedInputStream::from_bytes(&bytes); let mut read = TestSync::new(); // API is not very convenient here read.merge_from(&mut is).unwrap(); read.check_initialized().unwrap(); read.int32_field() }) }) .collect(); let results = threads .into_iter() .map(|t| t.join().unwrap()) .collect::<Vec<_>>(); assert_eq!(&[23, 23, 23, 23], &results[..]); }
test_sync
identifier_name
method-call-err-msg.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that parameter cardinality or missing method error gets span exactly. pub struct Foo; impl Foo { fn zero(self) -> Foo { self } fn one(self, _: int) -> Foo { self } fn two(self, _: int, _: int) -> Foo { self } } fn
() { let x = Foo; x.zero(0) //~ ERROR this function takes 0 parameters but 1 parameter was supplied .one() //~ ERROR this function takes 1 parameter but 0 parameters were supplied .two(0); //~ ERROR this function takes 2 parameters but 1 parameter was supplied let y = Foo; y.zero() .take() //~ ERROR type `Foo` does not implement any method in scope named `take` .one(0); }
main
identifier_name
method-call-err-msg.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that parameter cardinality or missing method error gets span exactly. pub struct Foo; impl Foo { fn zero(self) -> Foo { self } fn one(self, _: int) -> Foo { self } fn two(self, _: int, _: int) -> Foo { self } } fn main() { let x = Foo; x.zero(0) //~ ERROR this function takes 0 parameters but 1 parameter was supplied .one() //~ ERROR this function takes 1 parameter but 0 parameters were supplied .two(0); //~ ERROR this function takes 2 parameters but 1 parameter was supplied let y = Foo; y.zero() .take() //~ ERROR type `Foo` does not implement any method in scope named `take`
}
.one(0);
random_line_split
method-call-err-msg.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that parameter cardinality or missing method error gets span exactly. pub struct Foo; impl Foo { fn zero(self) -> Foo { self } fn one(self, _: int) -> Foo { self } fn two(self, _: int, _: int) -> Foo
} fn main() { let x = Foo; x.zero(0) //~ ERROR this function takes 0 parameters but 1 parameter was supplied .one() //~ ERROR this function takes 1 parameter but 0 parameters were supplied .two(0); //~ ERROR this function takes 2 parameters but 1 parameter was supplied let y = Foo; y.zero() .take() //~ ERROR type `Foo` does not implement any method in scope named `take` .one(0); }
{ self }
identifier_body
day4.rs
use std::collections::HashMap; use get_input::get_input; const IS_PART1: bool = false; fn sector_id(room_name: &str) -> Option<(&str, u32)>
ch1.cmp(&ch2) } }); let actual_checksum: String = v.iter().take(checksum.len()).map(|&(c,_)| c).collect(); if actual_checksum == checksum { Some((&room_name[..room_name.rfind('-').unwrap()], sector_id)) } else { None } } fn decode(s: &str, id: u32) -> String { let a = 'a' as u8; let rot = (id % 26) as u8; // get rid of full rotations let mut decoded = String::with_capacity(s.len()); for c in s.bytes() { if c == '-' as u8 { decoded.push(' '); } else { decoded.push(((c - a + rot) % 26 + a) as char); } } decoded } pub fn solve() { let input = get_input("assets/day/4/input"); let real_rooms = input.lines().filter_map(sector_id); if IS_PART1 { let solution: u32 = real_rooms.map(|(_,c)| c).sum(); println!("Sector IDs sum is {}", solution); } else { for (encoded_name, id) in real_rooms { let decoded_name = decode(encoded_name, id); println!("{}: {}", id, decoded_name); } } }
{ let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' }); let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at end of input let checksum = name_parts.next_back().unwrap(); let sector_id = name_parts.next_back().unwrap().parse::<u32>().unwrap(); let mut histogram = HashMap::new(); for part in name_parts { for c in part.chars() { let entry = histogram.entry(c).or_insert(0u32); *entry += 1u32; } } let mut v: Vec<(char, u32)> = histogram.iter().map(|(k,v)| (*k, *v)).collect(); v.sort_by(|&(ch1, count1), &(ch2, count2)| { if count1 != count2 { count1.cmp(&count2).reverse() } else {
identifier_body
day4.rs
use std::collections::HashMap; use get_input::get_input; const IS_PART1: bool = false; fn
(room_name: &str) -> Option<(&str, u32)> { let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' }); let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at end of input let checksum = name_parts.next_back().unwrap(); let sector_id = name_parts.next_back().unwrap().parse::<u32>().unwrap(); let mut histogram = HashMap::new(); for part in name_parts { for c in part.chars() { let entry = histogram.entry(c).or_insert(0u32); *entry += 1u32; } } let mut v: Vec<(char, u32)> = histogram.iter().map(|(k,v)| (*k, *v)).collect(); v.sort_by(|&(ch1, count1), &(ch2, count2)| { if count1!= count2 { count1.cmp(&count2).reverse() } else { ch1.cmp(&ch2) } }); let actual_checksum: String = v.iter().take(checksum.len()).map(|&(c,_)| c).collect(); if actual_checksum == checksum { Some((&room_name[..room_name.rfind('-').unwrap()], sector_id)) } else { None } } fn decode(s: &str, id: u32) -> String { let a = 'a' as u8; let rot = (id % 26) as u8; // get rid of full rotations let mut decoded = String::with_capacity(s.len()); for c in s.bytes() { if c == '-' as u8 { decoded.push(' '); } else { decoded.push(((c - a + rot) % 26 + a) as char); } } decoded } pub fn solve() { let input = get_input("assets/day/4/input"); let real_rooms = input.lines().filter_map(sector_id); if IS_PART1 { let solution: u32 = real_rooms.map(|(_,c)| c).sum(); println!("Sector IDs sum is {}", solution); } else { for (encoded_name, id) in real_rooms { let decoded_name = decode(encoded_name, id); println!("{}: {}", id, decoded_name); } } }
sector_id
identifier_name
day4.rs
use std::collections::HashMap; use get_input::get_input; const IS_PART1: bool = false; fn sector_id(room_name: &str) -> Option<(&str, u32)> { let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' }); let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at end of input let checksum = name_parts.next_back().unwrap(); let sector_id = name_parts.next_back().unwrap().parse::<u32>().unwrap(); let mut histogram = HashMap::new(); for part in name_parts { for c in part.chars() { let entry = histogram.entry(c).or_insert(0u32); *entry += 1u32; } } let mut v: Vec<(char, u32)> = histogram.iter().map(|(k,v)| (*k, *v)).collect(); v.sort_by(|&(ch1, count1), &(ch2, count2)| { if count1!= count2 { count1.cmp(&count2).reverse() } else
}); let actual_checksum: String = v.iter().take(checksum.len()).map(|&(c,_)| c).collect(); if actual_checksum == checksum { Some((&room_name[..room_name.rfind('-').unwrap()], sector_id)) } else { None } } fn decode(s: &str, id: u32) -> String { let a = 'a' as u8; let rot = (id % 26) as u8; // get rid of full rotations let mut decoded = String::with_capacity(s.len()); for c in s.bytes() { if c == '-' as u8 { decoded.push(' '); } else { decoded.push(((c - a + rot) % 26 + a) as char); } } decoded } pub fn solve() { let input = get_input("assets/day/4/input"); let real_rooms = input.lines().filter_map(sector_id); if IS_PART1 { let solution: u32 = real_rooms.map(|(_,c)| c).sum(); println!("Sector IDs sum is {}", solution); } else { for (encoded_name, id) in real_rooms { let decoded_name = decode(encoded_name, id); println!("{}: {}", id, decoded_name); } } }
{ ch1.cmp(&ch2) }
conditional_block
day4.rs
use std::collections::HashMap; use get_input::get_input; const IS_PART1: bool = false; fn sector_id(room_name: &str) -> Option<(&str, u32)> { let mut name_parts = room_name.split(|c| { c == '-' || c == '[' || c == ']' }); let _ = name_parts.next_back(); // skip empty string due to delimiter ']' at end of input let checksum = name_parts.next_back().unwrap(); let sector_id = name_parts.next_back().unwrap().parse::<u32>().unwrap(); let mut histogram = HashMap::new(); for part in name_parts { for c in part.chars() { let entry = histogram.entry(c).or_insert(0u32); *entry += 1u32; } } let mut v: Vec<(char, u32)> = histogram.iter().map(|(k,v)| (*k, *v)).collect(); v.sort_by(|&(ch1, count1), &(ch2, count2)| { if count1!= count2 { count1.cmp(&count2).reverse() } else { ch1.cmp(&ch2) } }); let actual_checksum: String = v.iter().take(checksum.len()).map(|&(c,_)| c).collect(); if actual_checksum == checksum { Some((&room_name[..room_name.rfind('-').unwrap()], sector_id)) } else { None } }
fn decode(s: &str, id: u32) -> String { let a = 'a' as u8; let rot = (id % 26) as u8; // get rid of full rotations let mut decoded = String::with_capacity(s.len()); for c in s.bytes() { if c == '-' as u8 { decoded.push(' '); } else { decoded.push(((c - a + rot) % 26 + a) as char); } } decoded } pub fn solve() { let input = get_input("assets/day/4/input"); let real_rooms = input.lines().filter_map(sector_id); if IS_PART1 { let solution: u32 = real_rooms.map(|(_,c)| c).sum(); println!("Sector IDs sum is {}", solution); } else { for (encoded_name, id) in real_rooms { let decoded_name = decode(encoded_name, id); println!("{}: {}", id, decoded_name); } } }
random_line_split
issue-5688.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 /* # Corrupted initialization in the static struct ...should print &[1, 2, 3] but instead prints something like &[4492532864, 24]. It is pretty evident that the compiler messed up with the representation of [isize; n] and [isize] somehow, or at least failed to typecheck correctly. */ #[derive(Copy, Clone)] struct
{ vec: &'static [isize] } static V: &'static [X] = &[X { vec: &[1, 2, 3] }]; pub fn main() { for &v in V { println!("{:?}", v.vec); } }
X
identifier_name
issue-5688.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 /* # Corrupted initialization in the static struct ...should print &[1, 2, 3] but instead prints something like &[4492532864, 24]. It is pretty evident that the compiler messed up with the representation of [isize; n] and [isize] somehow, or at least failed to typecheck correctly. */ #[derive(Copy, Clone)] struct X { vec: &'static [isize] } static V: &'static [X] = &[X { vec: &[1, 2, 3] }]; pub fn main() { for &v in V { println!("{:?}", v.vec);
}
}
random_line_split
issue-5688.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 /* # Corrupted initialization in the static struct ...should print &[1, 2, 3] but instead prints something like &[4492532864, 24]. It is pretty evident that the compiler messed up with the representation of [isize; n] and [isize] somehow, or at least failed to typecheck correctly. */ #[derive(Copy, Clone)] struct X { vec: &'static [isize] } static V: &'static [X] = &[X { vec: &[1, 2, 3] }]; pub fn main()
{ for &v in V { println!("{:?}", v.vec); } }
identifier_body
main.rs
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; extern crate serde_json; #[macro_use] extern crate serde_derive; #[cfg(test)] mod tests; use rocket::Request; use rocket::response::content; #[derive(Debug, Serialize, Deserialize)] struct Person { name: String, age: u8, } // In a `GET` request and all other non-payload supporting request types, the // preferred media type in the Accept header is matched against the `format` in // the route attribute. #[get("/<name>/<age>", format = "application/json")] fn get_hello(name: String, age: u8) -> content::JSON<String> { // In a real application, we'd use the JSON contrib type. let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) } // In a `POST` request and all other payload supporting request types, the // content type is matched against the `format` in the route attribute. #[post("/<age>", format = "text/plain", data = "<name>")] fn post_hello(age: u8, name: String) -> content::JSON<String> { let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) } #[error(404)] fn not_found(request: &Request) -> content::HTML<String> { let html = match request.format() { Some(ref mt) if!mt.is_json() &&!mt.is_plain() =>
_ => format!("<p>Sorry, '{}' is an invalid path! Try \ /hello/&lt;name&gt;/&lt;age&gt; instead.</p>", request.uri()) }; content::HTML(html) } fn main() { rocket::ignite() .mount("/hello", routes![get_hello, post_hello]) .catch(errors![not_found]) .launch(); }
{ format!("<p>'{}' requests are not supported.</p>", mt) }
conditional_block
main.rs
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; extern crate serde_json; #[macro_use] extern crate serde_derive; #[cfg(test)] mod tests; use rocket::Request; use rocket::response::content; #[derive(Debug, Serialize, Deserialize)] struct Person { name: String, age: u8, } // In a `GET` request and all other non-payload supporting request types, the // preferred media type in the Accept header is matched against the `format` in // the route attribute. #[get("/<name>/<age>", format = "application/json")] fn get_hello(name: String, age: u8) -> content::JSON<String>
// In a `POST` request and all other payload supporting request types, the // content type is matched against the `format` in the route attribute. #[post("/<age>", format = "text/plain", data = "<name>")] fn post_hello(age: u8, name: String) -> content::JSON<String> { let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) } #[error(404)] fn not_found(request: &Request) -> content::HTML<String> { let html = match request.format() { Some(ref mt) if!mt.is_json() &&!mt.is_plain() => { format!("<p>'{}' requests are not supported.</p>", mt) } _ => format!("<p>Sorry, '{}' is an invalid path! Try \ /hello/&lt;name&gt;/&lt;age&gt; instead.</p>", request.uri()) }; content::HTML(html) } fn main() { rocket::ignite() .mount("/hello", routes![get_hello, post_hello]) .catch(errors![not_found]) .launch(); }
{ // In a real application, we'd use the JSON contrib type. let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) }
identifier_body
main.rs
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; extern crate serde_json; #[macro_use] extern crate serde_derive; #[cfg(test)] mod tests; use rocket::Request; use rocket::response::content; #[derive(Debug, Serialize, Deserialize)] struct Person { name: String, age: u8, } // In a `GET` request and all other non-payload supporting request types, the // preferred media type in the Accept header is matched against the `format` in // the route attribute. #[get("/<name>/<age>", format = "application/json")] fn get_hello(name: String, age: u8) -> content::JSON<String> { // In a real application, we'd use the JSON contrib type. let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) } // In a `POST` request and all other payload supporting request types, the // content type is matched against the `format` in the route attribute.
fn post_hello(age: u8, name: String) -> content::JSON<String> { let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) } #[error(404)] fn not_found(request: &Request) -> content::HTML<String> { let html = match request.format() { Some(ref mt) if!mt.is_json() &&!mt.is_plain() => { format!("<p>'{}' requests are not supported.</p>", mt) } _ => format!("<p>Sorry, '{}' is an invalid path! Try \ /hello/&lt;name&gt;/&lt;age&gt; instead.</p>", request.uri()) }; content::HTML(html) } fn main() { rocket::ignite() .mount("/hello", routes![get_hello, post_hello]) .catch(errors![not_found]) .launch(); }
#[post("/<age>", format = "text/plain", data = "<name>")]
random_line_split
main.rs
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; extern crate serde_json; #[macro_use] extern crate serde_derive; #[cfg(test)] mod tests; use rocket::Request; use rocket::response::content; #[derive(Debug, Serialize, Deserialize)] struct Person { name: String, age: u8, } // In a `GET` request and all other non-payload supporting request types, the // preferred media type in the Accept header is matched against the `format` in // the route attribute. #[get("/<name>/<age>", format = "application/json")] fn get_hello(name: String, age: u8) -> content::JSON<String> { // In a real application, we'd use the JSON contrib type. let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) } // In a `POST` request and all other payload supporting request types, the // content type is matched against the `format` in the route attribute. #[post("/<age>", format = "text/plain", data = "<name>")] fn post_hello(age: u8, name: String) -> content::JSON<String> { let person = Person { name: name, age: age, }; content::JSON(serde_json::to_string(&person).unwrap()) } #[error(404)] fn not_found(request: &Request) -> content::HTML<String> { let html = match request.format() { Some(ref mt) if!mt.is_json() &&!mt.is_plain() => { format!("<p>'{}' requests are not supported.</p>", mt) } _ => format!("<p>Sorry, '{}' is an invalid path! Try \ /hello/&lt;name&gt;/&lt;age&gt; instead.</p>", request.uri()) }; content::HTML(html) } fn
() { rocket::ignite() .mount("/hello", routes![get_hello, post_hello]) .catch(errors![not_found]) .launch(); }
main
identifier_name
machine_config.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use serde::{de, Deserialize, Serialize}; use std::fmt; /// The default memory size of the VM, in MiB. pub const DEFAULT_MEM_SIZE_MIB: usize = 128; /// Firecracker aims to support small scale workloads only, so limit the maximum /// vCPUs supported. pub const MAX_SUPPORTED_VCPUS: u8 = 32; /// Errors associated with configuring the microVM. #[derive(Debug, PartialEq)] pub enum VmConfigError { /// The memory size is smaller than the target size set in the balloon device configuration. IncompatibleBalloonSize, /// The memory size is invalid. The memory can only be an unsigned integer. InvalidMemorySize, /// The vcpu count is invalid. When SMT is enabled, the `cpu_count` must be either /// 1 or an even number. InvalidVcpuCount, /// Could not get the config of the balloon device from the VM resources, even though a /// balloon device was previously installed. InvalidVmState, } impl fmt::Display for VmConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::VmConfigError::*; match *self { IncompatibleBalloonSize => write!( f, "The memory size (MiB) is smaller than the previously \ set balloon device target size.", ), InvalidMemorySize => write!(f, "The memory size (MiB) is invalid.",), InvalidVcpuCount => write!( f, "The vCPU number is invalid! The vCPU number can only \ be 1 or an even number when SMT is enabled.", ), InvalidVmState => write!( f, "Could not get the configuration of the previously \ installed balloon device to validate the memory size.", ), } } } /// Strongly typed structure that represents the configuration of the /// microvm. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct VmConfig { /// Number of vcpu to start. #[serde(deserialize_with = "deserialize_vcpu_num")] pub vcpu_count: u8, /// The memory size in MiB. pub mem_size_mib: usize, /// Enables or disabled SMT. #[serde(default, deserialize_with = "deserialize_smt")] pub smt: bool, /// A CPU template that it is used to filter the CPU features exposed to the guest. #[serde( default, deserialize_with = "deserialize_cpu_template", skip_serializing_if = "CpuFeaturesTemplate::is_none" )] pub cpu_template: CpuFeaturesTemplate, /// Enables or disables dirty page tracking. Enabling allows incremental snapshots. #[serde(default)] pub track_dirty_pages: bool, } impl Default for VmConfig { fn default() -> Self { VmConfig { vcpu_count: 1, mem_size_mib: DEFAULT_MEM_SIZE_MIB, smt: false, cpu_template: CpuFeaturesTemplate::None, track_dirty_pages: false, } } } impl fmt::Display for VmConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{{ \"vcpu_count\": {:?}, \"mem_size_mib\": {:?}, \"smt\": {:?}, \ \"cpu_template\": {:?}, \"track_dirty_pages\": {:?} }}", self.vcpu_count, self.mem_size_mib, self.smt, self.cpu_template, self.track_dirty_pages ) } } /// Spec for partial configuration of the machine. /// This struct mirrors all the fields in `VmConfig`. /// All fields are optional, but at least one needs to be specified. /// If a field is `Some(value)` then we assume an update is requested /// for that field. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct VmUpdateConfig { /// Number of vcpu to start. #[serde( default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_vcpu_num" )] pub vcpu_count: Option<u8>, /// The memory size in MiB. #[serde(skip_serializing_if = "Option::is_none")] pub mem_size_mib: Option<usize>, /// Enables or disabled SMT. #[serde( default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_smt" )] pub smt: Option<bool>, /// A CPU template that it is used to filter the CPU features exposed to the guest. #[serde( default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_cpu_template" )] pub cpu_template: Option<CpuFeaturesTemplate>, /// Enables or disables dirty page tracking. Enabling allows incremental snapshots. #[serde(skip_serializing_if = "Option::is_none")] pub track_dirty_pages: Option<bool>, } impl VmUpdateConfig { /// Checks if the update request contains any data. /// Returns `true` if all fields are set to `None` which means that there is nothing /// to be updated. pub fn is_empty(&self) -> bool { if self.vcpu_count.is_none() && self.mem_size_mib.is_none() && self.cpu_template.is_none() && self.smt.is_none() && self.track_dirty_pages.is_none() { return true; } false } } impl From<VmConfig> for VmUpdateConfig { fn from(cfg: VmConfig) -> Self { VmUpdateConfig { vcpu_count: Some(cfg.vcpu_count), mem_size_mib: Some(cfg.mem_size_mib), smt: Some(cfg.smt), cpu_template: Some(cfg.cpu_template), track_dirty_pages: Some(cfg.track_dirty_pages), } } } /// Deserialization function for the `vcpu_num` field in `VmConfig` and `VmUpdateConfig`. /// This is called only when `vcpu_num` is present in the JSON configuration. /// `T` can be either `u8` or `Option<u8>` which both support ordering if `vcpu_num` is /// present in the JSON. fn deserialize_vcpu_num<'de, D, T>(d: D) -> std::result::Result<T, D::Error> where D: de::Deserializer<'de>, T: Deserialize<'de> + PartialOrd + From<u8>, { let val = T::deserialize(d)?; if val > T::from(MAX_SUPPORTED_VCPUS) { return Err(de::Error::invalid_value( de::Unexpected::Other(&"vcpu_num"), &"number of vCPUs exceeds the maximum limitation", )); } if val < T::from(1) { return Err(de::Error::invalid_value( de::Unexpected::Other(&"vcpu_num"), &"number of vCPUs should be larger than 0", )); } Ok(val) } /// Deserialization function for the `smt` field in `VmConfig` and `VmUpdateConfig`. /// This is called only when `smt` is present in the JSON configuration. fn deserialize_smt<'de, D, T>(d: D) -> std::result::Result<T, D::Error> where D: de::Deserializer<'de>, T: Deserialize<'de> + PartialEq + From<bool>, { let val = T::deserialize(d)?; // If this function was called it means that `smt` was specified in // the JSON. On aarch64 the only accepted value is `false` so throw an // error if `true` was specified. #[cfg(target_arch = "aarch64")] if val == T::from(true) { return Err(de::Error::invalid_value( de::Unexpected::Other(&"smt"), &"Enabling simultaneous multithreading is not supported on aarch64", )); } Ok(val) } /// Deserialization function for the `cpu_template` field in `VmConfig` and `VmUpdateConfig`. /// This is called only when `cpu_template` is present in the JSON configuration. fn deserialize_cpu_template<'de, D, T>(_d: D) -> std::result::Result<T, D::Error> where D: de::Deserializer<'de>, T: Deserialize<'de>, { // If this function was called it means that `cpu_template` was specified in // the JSON. Return an error since `cpu_template` is not supported on aarch64. #[cfg(target_arch = "aarch64")]
&"CPU templates are not supported on aarch64", )); #[cfg(target_arch = "x86_64")] T::deserialize(_d) } /// Template types available for configuring the CPU features that map /// to EC2 instances. #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] pub enum CpuFeaturesTemplate { /// C3 Template. C3, /// T2 Template. T2, /// No CPU template is used. None, } /// Utility methods for handling CPU template types impl CpuFeaturesTemplate { fn is_none(&self) -> bool { *self == CpuFeaturesTemplate::None } } impl fmt::Display for CpuFeaturesTemplate { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CpuFeaturesTemplate::C3 => write!(f, "C3"), CpuFeaturesTemplate::T2 => write!(f, "T2"), CpuFeaturesTemplate::None => write!(f, "None"), } } } impl Default for CpuFeaturesTemplate { fn default() -> Self { CpuFeaturesTemplate::None } } #[cfg(test)] mod tests { use super::*; #[test] fn test_display_cpu_features_template() { assert_eq!(CpuFeaturesTemplate::C3.to_string(), "C3".to_string()); assert_eq!(CpuFeaturesTemplate::T2.to_string(), "T2".to_string()); } #[test] fn test_display_vm_config_error() { let expected_str = "The vCPU number is invalid! The vCPU number can only \ be 1 or an even number when SMT is enabled."; assert_eq!(VmConfigError::InvalidVcpuCount.to_string(), expected_str); let expected_str = "The memory size (MiB) is invalid."; assert_eq!(VmConfigError::InvalidMemorySize.to_string(), expected_str); } }
return Err(de::Error::invalid_value( de::Unexpected::Enum,
random_line_split
machine_config.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use serde::{de, Deserialize, Serialize}; use std::fmt; /// The default memory size of the VM, in MiB. pub const DEFAULT_MEM_SIZE_MIB: usize = 128; /// Firecracker aims to support small scale workloads only, so limit the maximum /// vCPUs supported. pub const MAX_SUPPORTED_VCPUS: u8 = 32; /// Errors associated with configuring the microVM. #[derive(Debug, PartialEq)] pub enum VmConfigError { /// The memory size is smaller than the target size set in the balloon device configuration. IncompatibleBalloonSize, /// The memory size is invalid. The memory can only be an unsigned integer. InvalidMemorySize, /// The vcpu count is invalid. When SMT is enabled, the `cpu_count` must be either /// 1 or an even number. InvalidVcpuCount, /// Could not get the config of the balloon device from the VM resources, even though a /// balloon device was previously installed. InvalidVmState, } impl fmt::Display for VmConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::VmConfigError::*; match *self { IncompatibleBalloonSize => write!( f, "The memory size (MiB) is smaller than the previously \ set balloon device target size.", ), InvalidMemorySize => write!(f, "The memory size (MiB) is invalid.",), InvalidVcpuCount => write!( f, "The vCPU number is invalid! The vCPU number can only \ be 1 or an even number when SMT is enabled.", ), InvalidVmState => write!( f, "Could not get the configuration of the previously \ installed balloon device to validate the memory size.", ), } } } /// Strongly typed structure that represents the configuration of the /// microvm. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct VmConfig { /// Number of vcpu to start. #[serde(deserialize_with = "deserialize_vcpu_num")] pub vcpu_count: u8, /// The memory size in MiB. pub mem_size_mib: usize, /// Enables or disabled SMT. #[serde(default, deserialize_with = "deserialize_smt")] pub smt: bool, /// A CPU template that it is used to filter the CPU features exposed to the guest. #[serde( default, deserialize_with = "deserialize_cpu_template", skip_serializing_if = "CpuFeaturesTemplate::is_none" )] pub cpu_template: CpuFeaturesTemplate, /// Enables or disables dirty page tracking. Enabling allows incremental snapshots. #[serde(default)] pub track_dirty_pages: bool, } impl Default for VmConfig { fn default() -> Self { VmConfig { vcpu_count: 1, mem_size_mib: DEFAULT_MEM_SIZE_MIB, smt: false, cpu_template: CpuFeaturesTemplate::None, track_dirty_pages: false, } } } impl fmt::Display for VmConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{{ \"vcpu_count\": {:?}, \"mem_size_mib\": {:?}, \"smt\": {:?}, \ \"cpu_template\": {:?}, \"track_dirty_pages\": {:?} }}", self.vcpu_count, self.mem_size_mib, self.smt, self.cpu_template, self.track_dirty_pages ) } } /// Spec for partial configuration of the machine. /// This struct mirrors all the fields in `VmConfig`. /// All fields are optional, but at least one needs to be specified. /// If a field is `Some(value)` then we assume an update is requested /// for that field. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct VmUpdateConfig { /// Number of vcpu to start. #[serde( default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_vcpu_num" )] pub vcpu_count: Option<u8>, /// The memory size in MiB. #[serde(skip_serializing_if = "Option::is_none")] pub mem_size_mib: Option<usize>, /// Enables or disabled SMT. #[serde( default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_smt" )] pub smt: Option<bool>, /// A CPU template that it is used to filter the CPU features exposed to the guest. #[serde( default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_cpu_template" )] pub cpu_template: Option<CpuFeaturesTemplate>, /// Enables or disables dirty page tracking. Enabling allows incremental snapshots. #[serde(skip_serializing_if = "Option::is_none")] pub track_dirty_pages: Option<bool>, } impl VmUpdateConfig { /// Checks if the update request contains any data. /// Returns `true` if all fields are set to `None` which means that there is nothing /// to be updated. pub fn is_empty(&self) -> bool { if self.vcpu_count.is_none() && self.mem_size_mib.is_none() && self.cpu_template.is_none() && self.smt.is_none() && self.track_dirty_pages.is_none() { return true; } false } } impl From<VmConfig> for VmUpdateConfig { fn from(cfg: VmConfig) -> Self { VmUpdateConfig { vcpu_count: Some(cfg.vcpu_count), mem_size_mib: Some(cfg.mem_size_mib), smt: Some(cfg.smt), cpu_template: Some(cfg.cpu_template), track_dirty_pages: Some(cfg.track_dirty_pages), } } } /// Deserialization function for the `vcpu_num` field in `VmConfig` and `VmUpdateConfig`. /// This is called only when `vcpu_num` is present in the JSON configuration. /// `T` can be either `u8` or `Option<u8>` which both support ordering if `vcpu_num` is /// present in the JSON. fn deserialize_vcpu_num<'de, D, T>(d: D) -> std::result::Result<T, D::Error> where D: de::Deserializer<'de>, T: Deserialize<'de> + PartialOrd + From<u8>, { let val = T::deserialize(d)?; if val > T::from(MAX_SUPPORTED_VCPUS) { return Err(de::Error::invalid_value( de::Unexpected::Other(&"vcpu_num"), &"number of vCPUs exceeds the maximum limitation", )); } if val < T::from(1) { return Err(de::Error::invalid_value( de::Unexpected::Other(&"vcpu_num"), &"number of vCPUs should be larger than 0", )); } Ok(val) } /// Deserialization function for the `smt` field in `VmConfig` and `VmUpdateConfig`. /// This is called only when `smt` is present in the JSON configuration. fn deserialize_smt<'de, D, T>(d: D) -> std::result::Result<T, D::Error> where D: de::Deserializer<'de>, T: Deserialize<'de> + PartialEq + From<bool>, { let val = T::deserialize(d)?; // If this function was called it means that `smt` was specified in // the JSON. On aarch64 the only accepted value is `false` so throw an // error if `true` was specified. #[cfg(target_arch = "aarch64")] if val == T::from(true) { return Err(de::Error::invalid_value( de::Unexpected::Other(&"smt"), &"Enabling simultaneous multithreading is not supported on aarch64", )); } Ok(val) } /// Deserialization function for the `cpu_template` field in `VmConfig` and `VmUpdateConfig`. /// This is called only when `cpu_template` is present in the JSON configuration. fn deserialize_cpu_template<'de, D, T>(_d: D) -> std::result::Result<T, D::Error> where D: de::Deserializer<'de>, T: Deserialize<'de>, { // If this function was called it means that `cpu_template` was specified in // the JSON. Return an error since `cpu_template` is not supported on aarch64. #[cfg(target_arch = "aarch64")] return Err(de::Error::invalid_value( de::Unexpected::Enum, &"CPU templates are not supported on aarch64", )); #[cfg(target_arch = "x86_64")] T::deserialize(_d) } /// Template types available for configuring the CPU features that map /// to EC2 instances. #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] pub enum CpuFeaturesTemplate { /// C3 Template. C3, /// T2 Template. T2, /// No CPU template is used. None, } /// Utility methods for handling CPU template types impl CpuFeaturesTemplate { fn is_none(&self) -> bool { *self == CpuFeaturesTemplate::None } } impl fmt::Display for CpuFeaturesTemplate { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CpuFeaturesTemplate::C3 => write!(f, "C3"), CpuFeaturesTemplate::T2 => write!(f, "T2"), CpuFeaturesTemplate::None => write!(f, "None"), } } } impl Default for CpuFeaturesTemplate { fn default() -> Self { CpuFeaturesTemplate::None } } #[cfg(test)] mod tests { use super::*; #[test] fn test_display_cpu_features_template() { assert_eq!(CpuFeaturesTemplate::C3.to_string(), "C3".to_string()); assert_eq!(CpuFeaturesTemplate::T2.to_string(), "T2".to_string()); } #[test] fn test_display_vm_config_error() { let expected_str = "The vCPU number is invalid! The vCPU number can only \ be 1 or an even number when SMT is enabled."; assert_eq!(VmConfigError::InvalidVcpuCount.to_string(), expected_str); let expected_str = "The memory size (MiB) is invalid."; assert_eq!(VmConfigError::InvalidMemorySize.to_string(), expected_str); } }
fmt
identifier_name
allocator.rs
use rustc_span::symbol::{sym, Symbol}; #[derive(Clone, Debug, Copy, HashStable_Generic)] pub enum AllocatorKind { Global, Default, } impl AllocatorKind {
} } } pub enum AllocatorTy { Layout, Ptr, ResultPtr, Unit, Usize, } pub struct AllocatorMethod { pub name: Symbol, pub inputs: &'static [AllocatorTy], pub output: AllocatorTy, } pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[ AllocatorMethod { name: sym::alloc, inputs: &[AllocatorTy::Layout], output: AllocatorTy::ResultPtr, }, AllocatorMethod { name: sym::dealloc, inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout], output: AllocatorTy::Unit, }, AllocatorMethod { name: sym::realloc, inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Usize], output: AllocatorTy::ResultPtr, }, AllocatorMethod { name: sym::alloc_zeroed, inputs: &[AllocatorTy::Layout], output: AllocatorTy::ResultPtr, }, ];
pub fn fn_name(&self, base: Symbol) -> String { match *self { AllocatorKind::Global => format!("__rg_{}", base), AllocatorKind::Default => format!("__rdl_{}", base),
random_line_split
allocator.rs
use rustc_span::symbol::{sym, Symbol}; #[derive(Clone, Debug, Copy, HashStable_Generic)] pub enum AllocatorKind { Global, Default, } impl AllocatorKind { pub fn fn_name(&self, base: Symbol) -> String { match *self { AllocatorKind::Global => format!("__rg_{}", base), AllocatorKind::Default => format!("__rdl_{}", base), } } } pub enum AllocatorTy { Layout, Ptr, ResultPtr, Unit, Usize, } pub struct
{ pub name: Symbol, pub inputs: &'static [AllocatorTy], pub output: AllocatorTy, } pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[ AllocatorMethod { name: sym::alloc, inputs: &[AllocatorTy::Layout], output: AllocatorTy::ResultPtr, }, AllocatorMethod { name: sym::dealloc, inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout], output: AllocatorTy::Unit, }, AllocatorMethod { name: sym::realloc, inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Usize], output: AllocatorTy::ResultPtr, }, AllocatorMethod { name: sym::alloc_zeroed, inputs: &[AllocatorTy::Layout], output: AllocatorTy::ResultPtr, }, ];
AllocatorMethod
identifier_name
testbindingiterable.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ // check-tidy: no specs after this line use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TestBindingIterableBinding::{ self, TestBindingIterableMethods, }; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; #[dom_struct] pub struct TestBindingIterable { reflector: Reflector, vals: DomRefCell<Vec<DOMString>>, } impl TestBindingIterable { fn new(global: &GlobalScope) -> DomRoot<TestBindingIterable> { reflect_dom_object( Box::new(TestBindingIterable { reflector: Reflector::new(), vals: DomRefCell::new(vec![]), }), global, TestBindingIterableBinding::Wrap, ) } pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<TestBindingIterable>> { Ok(TestBindingIterable::new(global)) } } impl TestBindingIterableMethods for TestBindingIterable { fn Add(&self, v: DOMString) { self.vals.borrow_mut().push(v); } fn Length(&self) -> u32 { self.vals.borrow().len() as u32 } fn GetItem(&self, n: u32) -> DOMString { self.IndexedGetter(n).unwrap_or_default() } fn IndexedGetter(&self, n: u32) -> Option<DOMString> { self.vals.borrow().get(n as usize).cloned() }
}
random_line_split
testbindingiterable.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ // check-tidy: no specs after this line use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TestBindingIterableBinding::{ self, TestBindingIterableMethods, }; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; #[dom_struct] pub struct TestBindingIterable { reflector: Reflector, vals: DomRefCell<Vec<DOMString>>, } impl TestBindingIterable { fn new(global: &GlobalScope) -> DomRoot<TestBindingIterable> { reflect_dom_object( Box::new(TestBindingIterable { reflector: Reflector::new(), vals: DomRefCell::new(vec![]), }), global, TestBindingIterableBinding::Wrap, ) } pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<TestBindingIterable>> { Ok(TestBindingIterable::new(global)) } } impl TestBindingIterableMethods for TestBindingIterable { fn Add(&self, v: DOMString) { self.vals.borrow_mut().push(v); } fn Length(&self) -> u32
fn GetItem(&self, n: u32) -> DOMString { self.IndexedGetter(n).unwrap_or_default() } fn IndexedGetter(&self, n: u32) -> Option<DOMString> { self.vals.borrow().get(n as usize).cloned() } }
{ self.vals.borrow().len() as u32 }
identifier_body
testbindingiterable.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ // check-tidy: no specs after this line use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TestBindingIterableBinding::{ self, TestBindingIterableMethods, }; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; #[dom_struct] pub struct TestBindingIterable { reflector: Reflector, vals: DomRefCell<Vec<DOMString>>, } impl TestBindingIterable { fn new(global: &GlobalScope) -> DomRoot<TestBindingIterable> { reflect_dom_object( Box::new(TestBindingIterable { reflector: Reflector::new(), vals: DomRefCell::new(vec![]), }), global, TestBindingIterableBinding::Wrap, ) } pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<TestBindingIterable>> { Ok(TestBindingIterable::new(global)) } } impl TestBindingIterableMethods for TestBindingIterable { fn Add(&self, v: DOMString) { self.vals.borrow_mut().push(v); } fn Length(&self) -> u32 { self.vals.borrow().len() as u32 } fn
(&self, n: u32) -> DOMString { self.IndexedGetter(n).unwrap_or_default() } fn IndexedGetter(&self, n: u32) -> Option<DOMString> { self.vals.borrow().get(n as usize).cloned() } }
GetItem
identifier_name
caps.rs
// Copyright (c) 2017-2019 Linaro LTD // Copyright (c) 2019 JUUL Labs // Copyright (c) 2019 Arm Limited // // SPDX-License-Identifier: Apache-2.0 // Query the bootloader's capabilities. #[repr(u32)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(unused)] pub enum Caps { RSA2048 = (1 << 0), EcdsaP224 = (1 << 1), EcdsaP256 = (1 << 2), SwapUsingScratch = (1 << 3), OverwriteUpgrade = (1 << 4), EncRsa = (1 << 5), EncKw = (1 << 6), ValidatePrimarySlot = (1 << 7), RSA3072 = (1 << 8), Ed25519 = (1 << 9), EncEc256 = (1 << 10), SwapUsingMove = (1 << 11), DowngradePrevention = (1 << 12), EncX25519 = (1 << 13), } impl Caps { pub fn present(self) -> bool
/// Query for the number of images that have been configured into this /// MCUboot build. pub fn get_num_images() -> usize { (unsafe { bootutil_get_num_images() }) as usize } } extern "C" { fn bootutil_get_caps() -> Caps; fn bootutil_get_num_images() -> u32; }
{ let caps = unsafe { bootutil_get_caps() }; (caps as u32) & (self as u32) != 0 }
identifier_body
caps.rs
// Copyright (c) 2017-2019 Linaro LTD // Copyright (c) 2019 JUUL Labs // Copyright (c) 2019 Arm Limited // // SPDX-License-Identifier: Apache-2.0 // Query the bootloader's capabilities. #[repr(u32)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(unused)] pub enum
{ RSA2048 = (1 << 0), EcdsaP224 = (1 << 1), EcdsaP256 = (1 << 2), SwapUsingScratch = (1 << 3), OverwriteUpgrade = (1 << 4), EncRsa = (1 << 5), EncKw = (1 << 6), ValidatePrimarySlot = (1 << 7), RSA3072 = (1 << 8), Ed25519 = (1 << 9), EncEc256 = (1 << 10), SwapUsingMove = (1 << 11), DowngradePrevention = (1 << 12), EncX25519 = (1 << 13), } impl Caps { pub fn present(self) -> bool { let caps = unsafe { bootutil_get_caps() }; (caps as u32) & (self as u32)!= 0 } /// Query for the number of images that have been configured into this /// MCUboot build. pub fn get_num_images() -> usize { (unsafe { bootutil_get_num_images() }) as usize } } extern "C" { fn bootutil_get_caps() -> Caps; fn bootutil_get_num_images() -> u32; }
Caps
identifier_name
caps.rs
// Copyright (c) 2017-2019 Linaro LTD // Copyright (c) 2019 JUUL Labs // Copyright (c) 2019 Arm Limited // // SPDX-License-Identifier: Apache-2.0 // Query the bootloader's capabilities. #[repr(u32)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(unused)] pub enum Caps { RSA2048 = (1 << 0), EcdsaP224 = (1 << 1), EcdsaP256 = (1 << 2), SwapUsingScratch = (1 << 3), OverwriteUpgrade = (1 << 4), EncRsa = (1 << 5), EncKw = (1 << 6), ValidatePrimarySlot = (1 << 7), RSA3072 = (1 << 8), Ed25519 = (1 << 9), EncEc256 = (1 << 10), SwapUsingMove = (1 << 11), DowngradePrevention = (1 << 12), EncX25519 = (1 << 13), }
pub fn present(self) -> bool { let caps = unsafe { bootutil_get_caps() }; (caps as u32) & (self as u32)!= 0 } /// Query for the number of images that have been configured into this /// MCUboot build. pub fn get_num_images() -> usize { (unsafe { bootutil_get_num_images() }) as usize } } extern "C" { fn bootutil_get_caps() -> Caps; fn bootutil_get_num_images() -> u32; }
impl Caps {
random_line_split
task_queue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue). use crate::dom::bindings::cell::DomRefCell; use crate::dom::worker::TrustedWorkerAddress; use crate::script_runtime::ScriptThreadEventCategory; use crate::script_thread::ScriptThread; use crate::task::TaskBox; use crate::task_source::TaskSourceName; use crossbeam_channel::{self, Receiver, Sender}; use msg::constellation_msg::PipelineId; use std::cell::Cell; use std::collections::{HashMap, HashSet, VecDeque}; use std::default::Default; pub type QueuedTask = ( Option<TrustedWorkerAddress>, ScriptThreadEventCategory, Box<dyn TaskBox>, Option<PipelineId>, TaskSourceName, ); /// Defining the operations used to convert from a msg T to a QueuedTask. pub trait QueuedTaskConversion { fn task_source_name(&self) -> Option<&TaskSourceName>; fn pipeline_id(&self) -> Option<PipelineId>; fn into_queued_task(self) -> Option<QueuedTask>; fn from_queued_task(queued_task: QueuedTask) -> Self; fn inactive_msg() -> Self; fn wake_up_msg() -> Self; fn is_wake_up(&self) -> bool; } pub struct TaskQueue<T> { /// The original port on which the task-sources send tasks as messages. port: Receiver<T>, /// A sender to ensure the port doesn't block on select while there are throttled tasks. wake_up_sender: Sender<T>, /// A queue from which the event-loop can drain tasks. msg_queue: DomRefCell<VecDeque<T>>, /// A "business" counter, reset for each iteration of the event-loop taken_task_counter: Cell<u64>, /// Tasks that will be throttled for as long as we are "busy". throttled: DomRefCell<HashMap<TaskSourceName, VecDeque<QueuedTask>>>, /// Tasks for not fully-active documents. inactive: DomRefCell<HashMap<PipelineId, VecDeque<QueuedTask>>>, } impl<T: QueuedTaskConversion> TaskQueue<T> { pub fn new(port: Receiver<T>, wake_up_sender: Sender<T>) -> TaskQueue<T> { TaskQueue { port, wake_up_sender, msg_queue: DomRefCell::new(VecDeque::new()), taken_task_counter: Default::default(), throttled: Default::default(), inactive: Default::default(), } } /// Release previously held-back tasks for documents that are now fully-active. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn release_tasks_for_fully_active_documents( &self, fully_active: &HashSet<PipelineId>, ) -> Vec<T>
/// Hold back tasks for currently not fully-active documents. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn store_task_for_inactive_pipeline(&self, msg: T, pipeline_id: &PipelineId) { let mut inactive = self.inactive.borrow_mut(); let inactive_queue = inactive.entry(pipeline_id.clone()).or_default(); inactive_queue.push_back( msg.into_queued_task() .expect("Incoming messages should always be convertible into queued tasks"), ); let mut msg_queue = self.msg_queue.borrow_mut(); if msg_queue.is_empty() { // Ensure there is at least one message. // Otherwise if the just stored inactive message // was the first and last of this iteration, // it will result in a spurious wake-up of the event-loop. msg_queue.push_back(T::inactive_msg()); } } /// Process incoming tasks, immediately sending priority ones downstream, /// and categorizing potential throttles. fn process_incoming_tasks(&self, first_msg: T, fully_active: &HashSet<PipelineId>) { // 1. Make any previously stored task from now fully-active document available. let mut incoming = self.release_tasks_for_fully_active_documents(fully_active); // 2. Process the first message(artifact of the fact that select always returns a message). if!first_msg.is_wake_up() { incoming.push(first_msg); } // 3. Process any other incoming message. while let Ok(msg) = self.port.try_recv() { if!msg.is_wake_up() { incoming.push(msg); } } // 4. Filter tasks from non-priority task-sources. let to_be_throttled: Vec<T> = incoming .drain_filter(|msg| { let task_source = match msg.task_source_name() { Some(task_source) => task_source, None => return false, }; match task_source { TaskSourceName::PerformanceTimeline => return true, _ => { // A task that will not be throttled, start counting "business" self.taken_task_counter .set(self.taken_task_counter.get() + 1); return false; }, } }) .collect(); for msg in incoming { if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id) { self.store_task_for_inactive_pipeline(msg, &pipeline_id); continue; } } // Immediately send non-throttled tasks for processing. let _ = self.msg_queue.borrow_mut().push_back(msg); } for msg in to_be_throttled { // Categorize tasks per task queue. let (worker, category, boxed, pipeline_id, task_source) = match msg.into_queued_task() { Some(queued_task) => queued_task, None => unreachable!( "A message to be throttled should always be convertible into a queued task" ), }; let mut throttled_tasks = self.throttled.borrow_mut(); throttled_tasks .entry(task_source.clone()) .or_default() .push_back((worker, category, boxed, pipeline_id, task_source)); } } /// Reset the queue for a new iteration of the event-loop, /// returning the port about whose readiness we want to be notified. pub fn select(&self) -> &crossbeam_channel::Receiver<T> { // This is a new iteration of the event-loop, so we reset the "business" counter. self.taken_task_counter.set(0); // We want to be notified when the script-port is ready to receive. // Hence that's the one we need to include in the select. &self.port } /// Take a message from the front of the queue, without waiting if empty. pub fn recv(&self) -> Result<T, ()> { self.msg_queue.borrow_mut().pop_front().ok_or(()) } /// Same as recv. pub fn try_recv(&self) -> Result<T, ()> { self.recv() } /// Drain the queue for the current iteration of the event-loop. /// Holding-back throttles above a given high-water mark. pub fn take_tasks(&self, first_msg: T) { // High-watermark: once reached, throttled tasks will be held-back. const PER_ITERATION_MAX: u64 = 5; let fully_active = ScriptThread::get_fully_active_document_ids(); // Always first check for new tasks, but don't reset 'taken_task_counter'. self.process_incoming_tasks(first_msg, &fully_active); let mut throttled = self.throttled.borrow_mut(); let mut throttled_length: usize = throttled.values().map(|queue| queue.len()).sum(); let task_source_names = TaskSourceName::all(); let mut task_source_cycler = task_source_names.iter().cycle(); // "being busy", is defined as having more than x tasks for this loop's iteration. // As long as we're not busy, and there are throttled tasks left: loop { let max_reached = self.taken_task_counter.get() > PER_ITERATION_MAX; let none_left = throttled_length == 0; match (max_reached, none_left) { (_, true) => break, (true, false) => { // We have reached the high-watermark for this iteration of the event-loop, // yet also have throttled messages left in the queue. // Ensure the select wakes up in the next iteration of the event-loop let _ = self.wake_up_sender.send(T::wake_up_msg()); break; }, (false, false) => { // Cycle through non-priority task sources, taking one throttled task from each. let task_source = task_source_cycler.next().unwrap(); let throttled_queue = match throttled.get_mut(&task_source) { Some(queue) => queue, None => continue, }; let queued_task = match throttled_queue.pop_front() { Some(queued_task) => queued_task, None => continue, }; let msg = T::from_queued_task(queued_task); // Hold back tasks for currently inactive documents. if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id) { self.store_task_for_inactive_pipeline(msg, &pipeline_id); // Reduce the length of throttles, // but don't add the task to "msg_queue", // and neither increment "taken_task_counter". throttled_length = throttled_length - 1; continue; } } // Make the task available for the event-loop to handle as a message. let _ = self.msg_queue.borrow_mut().push_back(msg); self.taken_task_counter .set(self.taken_task_counter.get() + 1); throttled_length = throttled_length - 1; }, } } } }
{ self.inactive .borrow_mut() .iter_mut() .filter(|(pipeline_id, _)| fully_active.contains(pipeline_id)) .flat_map(|(_, inactive_queue)| { inactive_queue .drain(0..) .map(|queued_task| T::from_queued_task(queued_task)) }) .collect() }
identifier_body
task_queue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue). use crate::dom::bindings::cell::DomRefCell; use crate::dom::worker::TrustedWorkerAddress; use crate::script_runtime::ScriptThreadEventCategory;
use crate::script_thread::ScriptThread; use crate::task::TaskBox; use crate::task_source::TaskSourceName; use crossbeam_channel::{self, Receiver, Sender}; use msg::constellation_msg::PipelineId; use std::cell::Cell; use std::collections::{HashMap, HashSet, VecDeque}; use std::default::Default; pub type QueuedTask = ( Option<TrustedWorkerAddress>, ScriptThreadEventCategory, Box<dyn TaskBox>, Option<PipelineId>, TaskSourceName, ); /// Defining the operations used to convert from a msg T to a QueuedTask. pub trait QueuedTaskConversion { fn task_source_name(&self) -> Option<&TaskSourceName>; fn pipeline_id(&self) -> Option<PipelineId>; fn into_queued_task(self) -> Option<QueuedTask>; fn from_queued_task(queued_task: QueuedTask) -> Self; fn inactive_msg() -> Self; fn wake_up_msg() -> Self; fn is_wake_up(&self) -> bool; } pub struct TaskQueue<T> { /// The original port on which the task-sources send tasks as messages. port: Receiver<T>, /// A sender to ensure the port doesn't block on select while there are throttled tasks. wake_up_sender: Sender<T>, /// A queue from which the event-loop can drain tasks. msg_queue: DomRefCell<VecDeque<T>>, /// A "business" counter, reset for each iteration of the event-loop taken_task_counter: Cell<u64>, /// Tasks that will be throttled for as long as we are "busy". throttled: DomRefCell<HashMap<TaskSourceName, VecDeque<QueuedTask>>>, /// Tasks for not fully-active documents. inactive: DomRefCell<HashMap<PipelineId, VecDeque<QueuedTask>>>, } impl<T: QueuedTaskConversion> TaskQueue<T> { pub fn new(port: Receiver<T>, wake_up_sender: Sender<T>) -> TaskQueue<T> { TaskQueue { port, wake_up_sender, msg_queue: DomRefCell::new(VecDeque::new()), taken_task_counter: Default::default(), throttled: Default::default(), inactive: Default::default(), } } /// Release previously held-back tasks for documents that are now fully-active. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn release_tasks_for_fully_active_documents( &self, fully_active: &HashSet<PipelineId>, ) -> Vec<T> { self.inactive .borrow_mut() .iter_mut() .filter(|(pipeline_id, _)| fully_active.contains(pipeline_id)) .flat_map(|(_, inactive_queue)| { inactive_queue .drain(0..) .map(|queued_task| T::from_queued_task(queued_task)) }) .collect() } /// Hold back tasks for currently not fully-active documents. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn store_task_for_inactive_pipeline(&self, msg: T, pipeline_id: &PipelineId) { let mut inactive = self.inactive.borrow_mut(); let inactive_queue = inactive.entry(pipeline_id.clone()).or_default(); inactive_queue.push_back( msg.into_queued_task() .expect("Incoming messages should always be convertible into queued tasks"), ); let mut msg_queue = self.msg_queue.borrow_mut(); if msg_queue.is_empty() { // Ensure there is at least one message. // Otherwise if the just stored inactive message // was the first and last of this iteration, // it will result in a spurious wake-up of the event-loop. msg_queue.push_back(T::inactive_msg()); } } /// Process incoming tasks, immediately sending priority ones downstream, /// and categorizing potential throttles. fn process_incoming_tasks(&self, first_msg: T, fully_active: &HashSet<PipelineId>) { // 1. Make any previously stored task from now fully-active document available. let mut incoming = self.release_tasks_for_fully_active_documents(fully_active); // 2. Process the first message(artifact of the fact that select always returns a message). if!first_msg.is_wake_up() { incoming.push(first_msg); } // 3. Process any other incoming message. while let Ok(msg) = self.port.try_recv() { if!msg.is_wake_up() { incoming.push(msg); } } // 4. Filter tasks from non-priority task-sources. let to_be_throttled: Vec<T> = incoming .drain_filter(|msg| { let task_source = match msg.task_source_name() { Some(task_source) => task_source, None => return false, }; match task_source { TaskSourceName::PerformanceTimeline => return true, _ => { // A task that will not be throttled, start counting "business" self.taken_task_counter .set(self.taken_task_counter.get() + 1); return false; }, } }) .collect(); for msg in incoming { if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id) { self.store_task_for_inactive_pipeline(msg, &pipeline_id); continue; } } // Immediately send non-throttled tasks for processing. let _ = self.msg_queue.borrow_mut().push_back(msg); } for msg in to_be_throttled { // Categorize tasks per task queue. let (worker, category, boxed, pipeline_id, task_source) = match msg.into_queued_task() { Some(queued_task) => queued_task, None => unreachable!( "A message to be throttled should always be convertible into a queued task" ), }; let mut throttled_tasks = self.throttled.borrow_mut(); throttled_tasks .entry(task_source.clone()) .or_default() .push_back((worker, category, boxed, pipeline_id, task_source)); } } /// Reset the queue for a new iteration of the event-loop, /// returning the port about whose readiness we want to be notified. pub fn select(&self) -> &crossbeam_channel::Receiver<T> { // This is a new iteration of the event-loop, so we reset the "business" counter. self.taken_task_counter.set(0); // We want to be notified when the script-port is ready to receive. // Hence that's the one we need to include in the select. &self.port } /// Take a message from the front of the queue, without waiting if empty. pub fn recv(&self) -> Result<T, ()> { self.msg_queue.borrow_mut().pop_front().ok_or(()) } /// Same as recv. pub fn try_recv(&self) -> Result<T, ()> { self.recv() } /// Drain the queue for the current iteration of the event-loop. /// Holding-back throttles above a given high-water mark. pub fn take_tasks(&self, first_msg: T) { // High-watermark: once reached, throttled tasks will be held-back. const PER_ITERATION_MAX: u64 = 5; let fully_active = ScriptThread::get_fully_active_document_ids(); // Always first check for new tasks, but don't reset 'taken_task_counter'. self.process_incoming_tasks(first_msg, &fully_active); let mut throttled = self.throttled.borrow_mut(); let mut throttled_length: usize = throttled.values().map(|queue| queue.len()).sum(); let task_source_names = TaskSourceName::all(); let mut task_source_cycler = task_source_names.iter().cycle(); // "being busy", is defined as having more than x tasks for this loop's iteration. // As long as we're not busy, and there are throttled tasks left: loop { let max_reached = self.taken_task_counter.get() > PER_ITERATION_MAX; let none_left = throttled_length == 0; match (max_reached, none_left) { (_, true) => break, (true, false) => { // We have reached the high-watermark for this iteration of the event-loop, // yet also have throttled messages left in the queue. // Ensure the select wakes up in the next iteration of the event-loop let _ = self.wake_up_sender.send(T::wake_up_msg()); break; }, (false, false) => { // Cycle through non-priority task sources, taking one throttled task from each. let task_source = task_source_cycler.next().unwrap(); let throttled_queue = match throttled.get_mut(&task_source) { Some(queue) => queue, None => continue, }; let queued_task = match throttled_queue.pop_front() { Some(queued_task) => queued_task, None => continue, }; let msg = T::from_queued_task(queued_task); // Hold back tasks for currently inactive documents. if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id) { self.store_task_for_inactive_pipeline(msg, &pipeline_id); // Reduce the length of throttles, // but don't add the task to "msg_queue", // and neither increment "taken_task_counter". throttled_length = throttled_length - 1; continue; } } // Make the task available for the event-loop to handle as a message. let _ = self.msg_queue.borrow_mut().push_back(msg); self.taken_task_counter .set(self.taken_task_counter.get() + 1); throttled_length = throttled_length - 1; }, } } } }
random_line_split
task_queue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue). use crate::dom::bindings::cell::DomRefCell; use crate::dom::worker::TrustedWorkerAddress; use crate::script_runtime::ScriptThreadEventCategory; use crate::script_thread::ScriptThread; use crate::task::TaskBox; use crate::task_source::TaskSourceName; use crossbeam_channel::{self, Receiver, Sender}; use msg::constellation_msg::PipelineId; use std::cell::Cell; use std::collections::{HashMap, HashSet, VecDeque}; use std::default::Default; pub type QueuedTask = ( Option<TrustedWorkerAddress>, ScriptThreadEventCategory, Box<dyn TaskBox>, Option<PipelineId>, TaskSourceName, ); /// Defining the operations used to convert from a msg T to a QueuedTask. pub trait QueuedTaskConversion { fn task_source_name(&self) -> Option<&TaskSourceName>; fn pipeline_id(&self) -> Option<PipelineId>; fn into_queued_task(self) -> Option<QueuedTask>; fn from_queued_task(queued_task: QueuedTask) -> Self; fn inactive_msg() -> Self; fn wake_up_msg() -> Self; fn is_wake_up(&self) -> bool; } pub struct TaskQueue<T> { /// The original port on which the task-sources send tasks as messages. port: Receiver<T>, /// A sender to ensure the port doesn't block on select while there are throttled tasks. wake_up_sender: Sender<T>, /// A queue from which the event-loop can drain tasks. msg_queue: DomRefCell<VecDeque<T>>, /// A "business" counter, reset for each iteration of the event-loop taken_task_counter: Cell<u64>, /// Tasks that will be throttled for as long as we are "busy". throttled: DomRefCell<HashMap<TaskSourceName, VecDeque<QueuedTask>>>, /// Tasks for not fully-active documents. inactive: DomRefCell<HashMap<PipelineId, VecDeque<QueuedTask>>>, } impl<T: QueuedTaskConversion> TaskQueue<T> { pub fn new(port: Receiver<T>, wake_up_sender: Sender<T>) -> TaskQueue<T> { TaskQueue { port, wake_up_sender, msg_queue: DomRefCell::new(VecDeque::new()), taken_task_counter: Default::default(), throttled: Default::default(), inactive: Default::default(), } } /// Release previously held-back tasks for documents that are now fully-active. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn
( &self, fully_active: &HashSet<PipelineId>, ) -> Vec<T> { self.inactive .borrow_mut() .iter_mut() .filter(|(pipeline_id, _)| fully_active.contains(pipeline_id)) .flat_map(|(_, inactive_queue)| { inactive_queue .drain(0..) .map(|queued_task| T::from_queued_task(queued_task)) }) .collect() } /// Hold back tasks for currently not fully-active documents. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn store_task_for_inactive_pipeline(&self, msg: T, pipeline_id: &PipelineId) { let mut inactive = self.inactive.borrow_mut(); let inactive_queue = inactive.entry(pipeline_id.clone()).or_default(); inactive_queue.push_back( msg.into_queued_task() .expect("Incoming messages should always be convertible into queued tasks"), ); let mut msg_queue = self.msg_queue.borrow_mut(); if msg_queue.is_empty() { // Ensure there is at least one message. // Otherwise if the just stored inactive message // was the first and last of this iteration, // it will result in a spurious wake-up of the event-loop. msg_queue.push_back(T::inactive_msg()); } } /// Process incoming tasks, immediately sending priority ones downstream, /// and categorizing potential throttles. fn process_incoming_tasks(&self, first_msg: T, fully_active: &HashSet<PipelineId>) { // 1. Make any previously stored task from now fully-active document available. let mut incoming = self.release_tasks_for_fully_active_documents(fully_active); // 2. Process the first message(artifact of the fact that select always returns a message). if!first_msg.is_wake_up() { incoming.push(first_msg); } // 3. Process any other incoming message. while let Ok(msg) = self.port.try_recv() { if!msg.is_wake_up() { incoming.push(msg); } } // 4. Filter tasks from non-priority task-sources. let to_be_throttled: Vec<T> = incoming .drain_filter(|msg| { let task_source = match msg.task_source_name() { Some(task_source) => task_source, None => return false, }; match task_source { TaskSourceName::PerformanceTimeline => return true, _ => { // A task that will not be throttled, start counting "business" self.taken_task_counter .set(self.taken_task_counter.get() + 1); return false; }, } }) .collect(); for msg in incoming { if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id) { self.store_task_for_inactive_pipeline(msg, &pipeline_id); continue; } } // Immediately send non-throttled tasks for processing. let _ = self.msg_queue.borrow_mut().push_back(msg); } for msg in to_be_throttled { // Categorize tasks per task queue. let (worker, category, boxed, pipeline_id, task_source) = match msg.into_queued_task() { Some(queued_task) => queued_task, None => unreachable!( "A message to be throttled should always be convertible into a queued task" ), }; let mut throttled_tasks = self.throttled.borrow_mut(); throttled_tasks .entry(task_source.clone()) .or_default() .push_back((worker, category, boxed, pipeline_id, task_source)); } } /// Reset the queue for a new iteration of the event-loop, /// returning the port about whose readiness we want to be notified. pub fn select(&self) -> &crossbeam_channel::Receiver<T> { // This is a new iteration of the event-loop, so we reset the "business" counter. self.taken_task_counter.set(0); // We want to be notified when the script-port is ready to receive. // Hence that's the one we need to include in the select. &self.port } /// Take a message from the front of the queue, without waiting if empty. pub fn recv(&self) -> Result<T, ()> { self.msg_queue.borrow_mut().pop_front().ok_or(()) } /// Same as recv. pub fn try_recv(&self) -> Result<T, ()> { self.recv() } /// Drain the queue for the current iteration of the event-loop. /// Holding-back throttles above a given high-water mark. pub fn take_tasks(&self, first_msg: T) { // High-watermark: once reached, throttled tasks will be held-back. const PER_ITERATION_MAX: u64 = 5; let fully_active = ScriptThread::get_fully_active_document_ids(); // Always first check for new tasks, but don't reset 'taken_task_counter'. self.process_incoming_tasks(first_msg, &fully_active); let mut throttled = self.throttled.borrow_mut(); let mut throttled_length: usize = throttled.values().map(|queue| queue.len()).sum(); let task_source_names = TaskSourceName::all(); let mut task_source_cycler = task_source_names.iter().cycle(); // "being busy", is defined as having more than x tasks for this loop's iteration. // As long as we're not busy, and there are throttled tasks left: loop { let max_reached = self.taken_task_counter.get() > PER_ITERATION_MAX; let none_left = throttled_length == 0; match (max_reached, none_left) { (_, true) => break, (true, false) => { // We have reached the high-watermark for this iteration of the event-loop, // yet also have throttled messages left in the queue. // Ensure the select wakes up in the next iteration of the event-loop let _ = self.wake_up_sender.send(T::wake_up_msg()); break; }, (false, false) => { // Cycle through non-priority task sources, taking one throttled task from each. let task_source = task_source_cycler.next().unwrap(); let throttled_queue = match throttled.get_mut(&task_source) { Some(queue) => queue, None => continue, }; let queued_task = match throttled_queue.pop_front() { Some(queued_task) => queued_task, None => continue, }; let msg = T::from_queued_task(queued_task); // Hold back tasks for currently inactive documents. if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id) { self.store_task_for_inactive_pipeline(msg, &pipeline_id); // Reduce the length of throttles, // but don't add the task to "msg_queue", // and neither increment "taken_task_counter". throttled_length = throttled_length - 1; continue; } } // Make the task available for the event-loop to handle as a message. let _ = self.msg_queue.borrow_mut().push_back(msg); self.taken_task_counter .set(self.taken_task_counter.get() + 1); throttled_length = throttled_length - 1; }, } } } }
release_tasks_for_fully_active_documents
identifier_name
task_queue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue). use crate::dom::bindings::cell::DomRefCell; use crate::dom::worker::TrustedWorkerAddress; use crate::script_runtime::ScriptThreadEventCategory; use crate::script_thread::ScriptThread; use crate::task::TaskBox; use crate::task_source::TaskSourceName; use crossbeam_channel::{self, Receiver, Sender}; use msg::constellation_msg::PipelineId; use std::cell::Cell; use std::collections::{HashMap, HashSet, VecDeque}; use std::default::Default; pub type QueuedTask = ( Option<TrustedWorkerAddress>, ScriptThreadEventCategory, Box<dyn TaskBox>, Option<PipelineId>, TaskSourceName, ); /// Defining the operations used to convert from a msg T to a QueuedTask. pub trait QueuedTaskConversion { fn task_source_name(&self) -> Option<&TaskSourceName>; fn pipeline_id(&self) -> Option<PipelineId>; fn into_queued_task(self) -> Option<QueuedTask>; fn from_queued_task(queued_task: QueuedTask) -> Self; fn inactive_msg() -> Self; fn wake_up_msg() -> Self; fn is_wake_up(&self) -> bool; } pub struct TaskQueue<T> { /// The original port on which the task-sources send tasks as messages. port: Receiver<T>, /// A sender to ensure the port doesn't block on select while there are throttled tasks. wake_up_sender: Sender<T>, /// A queue from which the event-loop can drain tasks. msg_queue: DomRefCell<VecDeque<T>>, /// A "business" counter, reset for each iteration of the event-loop taken_task_counter: Cell<u64>, /// Tasks that will be throttled for as long as we are "busy". throttled: DomRefCell<HashMap<TaskSourceName, VecDeque<QueuedTask>>>, /// Tasks for not fully-active documents. inactive: DomRefCell<HashMap<PipelineId, VecDeque<QueuedTask>>>, } impl<T: QueuedTaskConversion> TaskQueue<T> { pub fn new(port: Receiver<T>, wake_up_sender: Sender<T>) -> TaskQueue<T> { TaskQueue { port, wake_up_sender, msg_queue: DomRefCell::new(VecDeque::new()), taken_task_counter: Default::default(), throttled: Default::default(), inactive: Default::default(), } } /// Release previously held-back tasks for documents that are now fully-active. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn release_tasks_for_fully_active_documents( &self, fully_active: &HashSet<PipelineId>, ) -> Vec<T> { self.inactive .borrow_mut() .iter_mut() .filter(|(pipeline_id, _)| fully_active.contains(pipeline_id)) .flat_map(|(_, inactive_queue)| { inactive_queue .drain(0..) .map(|queued_task| T::from_queued_task(queued_task)) }) .collect() } /// Hold back tasks for currently not fully-active documents. /// https://html.spec.whatwg.org/multipage/#event-loop-processing-model:fully-active fn store_task_for_inactive_pipeline(&self, msg: T, pipeline_id: &PipelineId) { let mut inactive = self.inactive.borrow_mut(); let inactive_queue = inactive.entry(pipeline_id.clone()).or_default(); inactive_queue.push_back( msg.into_queued_task() .expect("Incoming messages should always be convertible into queued tasks"), ); let mut msg_queue = self.msg_queue.borrow_mut(); if msg_queue.is_empty() { // Ensure there is at least one message. // Otherwise if the just stored inactive message // was the first and last of this iteration, // it will result in a spurious wake-up of the event-loop. msg_queue.push_back(T::inactive_msg()); } } /// Process incoming tasks, immediately sending priority ones downstream, /// and categorizing potential throttles. fn process_incoming_tasks(&self, first_msg: T, fully_active: &HashSet<PipelineId>) { // 1. Make any previously stored task from now fully-active document available. let mut incoming = self.release_tasks_for_fully_active_documents(fully_active); // 2. Process the first message(artifact of the fact that select always returns a message). if!first_msg.is_wake_up() { incoming.push(first_msg); } // 3. Process any other incoming message. while let Ok(msg) = self.port.try_recv() { if!msg.is_wake_up() { incoming.push(msg); } } // 4. Filter tasks from non-priority task-sources. let to_be_throttled: Vec<T> = incoming .drain_filter(|msg| { let task_source = match msg.task_source_name() { Some(task_source) => task_source, None => return false, }; match task_source { TaskSourceName::PerformanceTimeline => return true, _ => { // A task that will not be throttled, start counting "business" self.taken_task_counter .set(self.taken_task_counter.get() + 1); return false; }, } }) .collect(); for msg in incoming { if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id)
} // Immediately send non-throttled tasks for processing. let _ = self.msg_queue.borrow_mut().push_back(msg); } for msg in to_be_throttled { // Categorize tasks per task queue. let (worker, category, boxed, pipeline_id, task_source) = match msg.into_queued_task() { Some(queued_task) => queued_task, None => unreachable!( "A message to be throttled should always be convertible into a queued task" ), }; let mut throttled_tasks = self.throttled.borrow_mut(); throttled_tasks .entry(task_source.clone()) .or_default() .push_back((worker, category, boxed, pipeline_id, task_source)); } } /// Reset the queue for a new iteration of the event-loop, /// returning the port about whose readiness we want to be notified. pub fn select(&self) -> &crossbeam_channel::Receiver<T> { // This is a new iteration of the event-loop, so we reset the "business" counter. self.taken_task_counter.set(0); // We want to be notified when the script-port is ready to receive. // Hence that's the one we need to include in the select. &self.port } /// Take a message from the front of the queue, without waiting if empty. pub fn recv(&self) -> Result<T, ()> { self.msg_queue.borrow_mut().pop_front().ok_or(()) } /// Same as recv. pub fn try_recv(&self) -> Result<T, ()> { self.recv() } /// Drain the queue for the current iteration of the event-loop. /// Holding-back throttles above a given high-water mark. pub fn take_tasks(&self, first_msg: T) { // High-watermark: once reached, throttled tasks will be held-back. const PER_ITERATION_MAX: u64 = 5; let fully_active = ScriptThread::get_fully_active_document_ids(); // Always first check for new tasks, but don't reset 'taken_task_counter'. self.process_incoming_tasks(first_msg, &fully_active); let mut throttled = self.throttled.borrow_mut(); let mut throttled_length: usize = throttled.values().map(|queue| queue.len()).sum(); let task_source_names = TaskSourceName::all(); let mut task_source_cycler = task_source_names.iter().cycle(); // "being busy", is defined as having more than x tasks for this loop's iteration. // As long as we're not busy, and there are throttled tasks left: loop { let max_reached = self.taken_task_counter.get() > PER_ITERATION_MAX; let none_left = throttled_length == 0; match (max_reached, none_left) { (_, true) => break, (true, false) => { // We have reached the high-watermark for this iteration of the event-loop, // yet also have throttled messages left in the queue. // Ensure the select wakes up in the next iteration of the event-loop let _ = self.wake_up_sender.send(T::wake_up_msg()); break; }, (false, false) => { // Cycle through non-priority task sources, taking one throttled task from each. let task_source = task_source_cycler.next().unwrap(); let throttled_queue = match throttled.get_mut(&task_source) { Some(queue) => queue, None => continue, }; let queued_task = match throttled_queue.pop_front() { Some(queued_task) => queued_task, None => continue, }; let msg = T::from_queued_task(queued_task); // Hold back tasks for currently inactive documents. if let Some(pipeline_id) = msg.pipeline_id() { if!fully_active.contains(&pipeline_id) { self.store_task_for_inactive_pipeline(msg, &pipeline_id); // Reduce the length of throttles, // but don't add the task to "msg_queue", // and neither increment "taken_task_counter". throttled_length = throttled_length - 1; continue; } } // Make the task available for the event-loop to handle as a message. let _ = self.msg_queue.borrow_mut().push_back(msg); self.taken_task_counter .set(self.taken_task_counter.get() + 1); throttled_length = throttled_length - 1; }, } } } }
{ self.store_task_for_inactive_pipeline(msg, &pipeline_id); continue; }
conditional_block
callback.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/. */ //! Base classes to work with IDL callbacks. use dom::bindings::error::{Fallible, Error}; use dom::bindings::global::global_object_for_js_object; use dom::bindings::utils::Reflectable; use js::jsapi::GetGlobalForObjectCrossCompartment; use js::jsapi::{JSAutoCompartment}; use js::jsapi::{JSContext, JSObject, JS_WrapObject, IsCallable}; use js::jsapi::{JS_BeginRequest, JS_EndRequest}; use js::jsapi::{JS_EnterCompartment, JS_LeaveCompartment, JSCompartment}; use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException}; use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain}; use js::jsapi::{RootedObject, RootedValue, MutableHandleObject, Heap}; use js::jsval::{JSVal, UndefinedValue}; use std::default::Default; use std::ffi::CString; use std::intrinsics::return_address; use std::ptr; use std::rc::Rc; /// The exception handling used for a call. #[derive(Copy, Clone, PartialEq)] pub enum ExceptionHandling { /// Report any exception and don't throw it to the caller code. Report, /// Throw any exception to the caller code. Rethrow } /// A common base class for representing IDL callback function types. #[derive(JSTraceable, PartialEq)] pub struct CallbackFunction { object: CallbackObject } impl CallbackFunction { /// Create a new `CallbackFunction` for this object. pub fn new() -> CallbackFunction { CallbackFunction { object: CallbackObject { callback: Heap::default() } } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } } /// A common base class for representing IDL callback interface types. #[derive(JSTraceable, PartialEq)] pub struct CallbackInterface { object: CallbackObject } /// A common base class for representing IDL callback function and /// callback interface types. #[allow(raw_pointer_derive)] #[derive(JSTraceable)] struct CallbackObject { /// The underlying `JSObject`. callback: Heap<*mut JSObject>, } impl PartialEq for CallbackObject { fn eq(&self, other: &CallbackObject) -> bool { self.callback.get() == other.callback.get() } } /// A trait to be implemented by concrete IDL callback function and /// callback interface types. pub trait CallbackContainer { /// Create a new CallbackContainer object for the given `JSObject`. fn new(callback: *mut JSObject) -> Rc<Self>; /// Returns the underlying `JSObject`. fn callback(&self) -> *mut JSObject; } impl CallbackInterface { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackFunction { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackInterface { /// Create a new CallbackInterface object for the given `JSObject`. pub fn new() -> CallbackInterface { CallbackInterface { object: CallbackObject { callback: Heap::default() } } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } /// Returns the property with the given `name`, if it is a callable object,
let obj = RootedObject::new(cx, self.callback()); unsafe { let c_name = CString::new(name).unwrap(); if JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) == 0 { return Err(Error::JSFailed); } if!callable.ptr.is_object() || IsCallable(callable.ptr.to_object()) == 0 { return Err(Error::Type( format!("The value of the {} property is not callable", name))); } } Ok(callable.ptr) } } /// Wraps the reflector for `p` into the compartment of `cx`. pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext, p: &T, rval: MutableHandleObject) { rval.set(p.reflector().get_jsobject().get()); assert!(!rval.get().is_null()); unsafe { if JS_WrapObject(cx, rval) == 0 { rval.set(ptr::null_mut()); } } } /// A class that performs whatever setup we need to safely make a call while /// this class is on the stack. After `new` returns, the call is safe to make. pub struct CallSetup { /// The compartment for reporting exceptions. /// As a RootedObject, this must be the first field in order to /// determine the final address on the stack correctly. exception_compartment: RootedObject, /// The `JSContext` used for the call. cx: *mut JSContext, /// The compartment we were in before the call. old_compartment: *mut JSCompartment, /// The exception handling used for the call. handling: ExceptionHandling, } impl CallSetup { /// Performs the setup needed to make a call. #[allow(unrooted_must_root)] pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup { let global = global_object_for_js_object(callback.callback()); let cx = global.r().get_cx(); unsafe { JS_BeginRequest(cx); } let exception_compartment = unsafe { GetGlobalForObjectCrossCompartment(callback.callback()) }; CallSetup { exception_compartment: RootedObject::new_with_addr(cx, exception_compartment, unsafe { return_address() }), cx: cx, old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) }, handling: handling, } } /// Returns the `JSContext` used for the call. pub fn get_context(&self) -> *mut JSContext { self.cx } } impl Drop for CallSetup { fn drop(&mut self) { unsafe { JS_LeaveCompartment(self.cx, self.old_compartment); } let need_to_deal_with_exception = self.handling == ExceptionHandling::Report && unsafe { JS_IsExceptionPending(self.cx) }!= 0; if need_to_deal_with_exception { unsafe { let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr); let saved = JS_SaveFrameChain(self.cx)!= 0; { let _ac = JSAutoCompartment::new(self.cx, old_global.ptr); JS_ReportPendingException(self.cx); } if saved { JS_RestoreFrameChain(self.cx); } } } unsafe { JS_EndRequest(self.cx); } } }
/// or an error otherwise. pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> { let mut callable = RootedValue::new(cx, UndefinedValue());
random_line_split
callback.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/. */ //! Base classes to work with IDL callbacks. use dom::bindings::error::{Fallible, Error}; use dom::bindings::global::global_object_for_js_object; use dom::bindings::utils::Reflectable; use js::jsapi::GetGlobalForObjectCrossCompartment; use js::jsapi::{JSAutoCompartment}; use js::jsapi::{JSContext, JSObject, JS_WrapObject, IsCallable}; use js::jsapi::{JS_BeginRequest, JS_EndRequest}; use js::jsapi::{JS_EnterCompartment, JS_LeaveCompartment, JSCompartment}; use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException}; use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain}; use js::jsapi::{RootedObject, RootedValue, MutableHandleObject, Heap}; use js::jsval::{JSVal, UndefinedValue}; use std::default::Default; use std::ffi::CString; use std::intrinsics::return_address; use std::ptr; use std::rc::Rc; /// The exception handling used for a call. #[derive(Copy, Clone, PartialEq)] pub enum ExceptionHandling { /// Report any exception and don't throw it to the caller code. Report, /// Throw any exception to the caller code. Rethrow } /// A common base class for representing IDL callback function types. #[derive(JSTraceable, PartialEq)] pub struct CallbackFunction { object: CallbackObject } impl CallbackFunction { /// Create a new `CallbackFunction` for this object. pub fn new() -> CallbackFunction { CallbackFunction { object: CallbackObject { callback: Heap::default() } } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } } /// A common base class for representing IDL callback interface types. #[derive(JSTraceable, PartialEq)] pub struct CallbackInterface { object: CallbackObject } /// A common base class for representing IDL callback function and /// callback interface types. #[allow(raw_pointer_derive)] #[derive(JSTraceable)] struct CallbackObject { /// The underlying `JSObject`. callback: Heap<*mut JSObject>, } impl PartialEq for CallbackObject { fn eq(&self, other: &CallbackObject) -> bool { self.callback.get() == other.callback.get() } } /// A trait to be implemented by concrete IDL callback function and /// callback interface types. pub trait CallbackContainer { /// Create a new CallbackContainer object for the given `JSObject`. fn new(callback: *mut JSObject) -> Rc<Self>; /// Returns the underlying `JSObject`. fn callback(&self) -> *mut JSObject; } impl CallbackInterface { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackFunction { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackInterface { /// Create a new CallbackInterface object for the given `JSObject`. pub fn new() -> CallbackInterface { CallbackInterface { object: CallbackObject { callback: Heap::default() } } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } /// Returns the property with the given `name`, if it is a callable object, /// or an error otherwise. pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> { let mut callable = RootedValue::new(cx, UndefinedValue()); let obj = RootedObject::new(cx, self.callback()); unsafe { let c_name = CString::new(name).unwrap(); if JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) == 0
if!callable.ptr.is_object() || IsCallable(callable.ptr.to_object()) == 0 { return Err(Error::Type( format!("The value of the {} property is not callable", name))); } } Ok(callable.ptr) } } /// Wraps the reflector for `p` into the compartment of `cx`. pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext, p: &T, rval: MutableHandleObject) { rval.set(p.reflector().get_jsobject().get()); assert!(!rval.get().is_null()); unsafe { if JS_WrapObject(cx, rval) == 0 { rval.set(ptr::null_mut()); } } } /// A class that performs whatever setup we need to safely make a call while /// this class is on the stack. After `new` returns, the call is safe to make. pub struct CallSetup { /// The compartment for reporting exceptions. /// As a RootedObject, this must be the first field in order to /// determine the final address on the stack correctly. exception_compartment: RootedObject, /// The `JSContext` used for the call. cx: *mut JSContext, /// The compartment we were in before the call. old_compartment: *mut JSCompartment, /// The exception handling used for the call. handling: ExceptionHandling, } impl CallSetup { /// Performs the setup needed to make a call. #[allow(unrooted_must_root)] pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup { let global = global_object_for_js_object(callback.callback()); let cx = global.r().get_cx(); unsafe { JS_BeginRequest(cx); } let exception_compartment = unsafe { GetGlobalForObjectCrossCompartment(callback.callback()) }; CallSetup { exception_compartment: RootedObject::new_with_addr(cx, exception_compartment, unsafe { return_address() }), cx: cx, old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) }, handling: handling, } } /// Returns the `JSContext` used for the call. pub fn get_context(&self) -> *mut JSContext { self.cx } } impl Drop for CallSetup { fn drop(&mut self) { unsafe { JS_LeaveCompartment(self.cx, self.old_compartment); } let need_to_deal_with_exception = self.handling == ExceptionHandling::Report && unsafe { JS_IsExceptionPending(self.cx) }!= 0; if need_to_deal_with_exception { unsafe { let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr); let saved = JS_SaveFrameChain(self.cx)!= 0; { let _ac = JSAutoCompartment::new(self.cx, old_global.ptr); JS_ReportPendingException(self.cx); } if saved { JS_RestoreFrameChain(self.cx); } } } unsafe { JS_EndRequest(self.cx); } } }
{ return Err(Error::JSFailed); }
conditional_block
callback.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/. */ //! Base classes to work with IDL callbacks. use dom::bindings::error::{Fallible, Error}; use dom::bindings::global::global_object_for_js_object; use dom::bindings::utils::Reflectable; use js::jsapi::GetGlobalForObjectCrossCompartment; use js::jsapi::{JSAutoCompartment}; use js::jsapi::{JSContext, JSObject, JS_WrapObject, IsCallable}; use js::jsapi::{JS_BeginRequest, JS_EndRequest}; use js::jsapi::{JS_EnterCompartment, JS_LeaveCompartment, JSCompartment}; use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException}; use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain}; use js::jsapi::{RootedObject, RootedValue, MutableHandleObject, Heap}; use js::jsval::{JSVal, UndefinedValue}; use std::default::Default; use std::ffi::CString; use std::intrinsics::return_address; use std::ptr; use std::rc::Rc; /// The exception handling used for a call. #[derive(Copy, Clone, PartialEq)] pub enum ExceptionHandling { /// Report any exception and don't throw it to the caller code. Report, /// Throw any exception to the caller code. Rethrow } /// A common base class for representing IDL callback function types. #[derive(JSTraceable, PartialEq)] pub struct
{ object: CallbackObject } impl CallbackFunction { /// Create a new `CallbackFunction` for this object. pub fn new() -> CallbackFunction { CallbackFunction { object: CallbackObject { callback: Heap::default() } } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } } /// A common base class for representing IDL callback interface types. #[derive(JSTraceable, PartialEq)] pub struct CallbackInterface { object: CallbackObject } /// A common base class for representing IDL callback function and /// callback interface types. #[allow(raw_pointer_derive)] #[derive(JSTraceable)] struct CallbackObject { /// The underlying `JSObject`. callback: Heap<*mut JSObject>, } impl PartialEq for CallbackObject { fn eq(&self, other: &CallbackObject) -> bool { self.callback.get() == other.callback.get() } } /// A trait to be implemented by concrete IDL callback function and /// callback interface types. pub trait CallbackContainer { /// Create a new CallbackContainer object for the given `JSObject`. fn new(callback: *mut JSObject) -> Rc<Self>; /// Returns the underlying `JSObject`. fn callback(&self) -> *mut JSObject; } impl CallbackInterface { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackFunction { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackInterface { /// Create a new CallbackInterface object for the given `JSObject`. pub fn new() -> CallbackInterface { CallbackInterface { object: CallbackObject { callback: Heap::default() } } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } /// Returns the property with the given `name`, if it is a callable object, /// or an error otherwise. pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> { let mut callable = RootedValue::new(cx, UndefinedValue()); let obj = RootedObject::new(cx, self.callback()); unsafe { let c_name = CString::new(name).unwrap(); if JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) == 0 { return Err(Error::JSFailed); } if!callable.ptr.is_object() || IsCallable(callable.ptr.to_object()) == 0 { return Err(Error::Type( format!("The value of the {} property is not callable", name))); } } Ok(callable.ptr) } } /// Wraps the reflector for `p` into the compartment of `cx`. pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext, p: &T, rval: MutableHandleObject) { rval.set(p.reflector().get_jsobject().get()); assert!(!rval.get().is_null()); unsafe { if JS_WrapObject(cx, rval) == 0 { rval.set(ptr::null_mut()); } } } /// A class that performs whatever setup we need to safely make a call while /// this class is on the stack. After `new` returns, the call is safe to make. pub struct CallSetup { /// The compartment for reporting exceptions. /// As a RootedObject, this must be the first field in order to /// determine the final address on the stack correctly. exception_compartment: RootedObject, /// The `JSContext` used for the call. cx: *mut JSContext, /// The compartment we were in before the call. old_compartment: *mut JSCompartment, /// The exception handling used for the call. handling: ExceptionHandling, } impl CallSetup { /// Performs the setup needed to make a call. #[allow(unrooted_must_root)] pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup { let global = global_object_for_js_object(callback.callback()); let cx = global.r().get_cx(); unsafe { JS_BeginRequest(cx); } let exception_compartment = unsafe { GetGlobalForObjectCrossCompartment(callback.callback()) }; CallSetup { exception_compartment: RootedObject::new_with_addr(cx, exception_compartment, unsafe { return_address() }), cx: cx, old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) }, handling: handling, } } /// Returns the `JSContext` used for the call. pub fn get_context(&self) -> *mut JSContext { self.cx } } impl Drop for CallSetup { fn drop(&mut self) { unsafe { JS_LeaveCompartment(self.cx, self.old_compartment); } let need_to_deal_with_exception = self.handling == ExceptionHandling::Report && unsafe { JS_IsExceptionPending(self.cx) }!= 0; if need_to_deal_with_exception { unsafe { let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr); let saved = JS_SaveFrameChain(self.cx)!= 0; { let _ac = JSAutoCompartment::new(self.cx, old_global.ptr); JS_ReportPendingException(self.cx); } if saved { JS_RestoreFrameChain(self.cx); } } } unsafe { JS_EndRequest(self.cx); } } }
CallbackFunction
identifier_name
sleep.rs
#![crate_name = "uu_sleep"] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use std::io::Write; use std::thread::{self}; use std::time::Duration; static NAME: &'static str = "sleep"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); return 1; } }; if matches.opt_present("help") { let msg = format!("{0} {1} Usage: {0} NUMBER[SUFFIX] or {0} OPTION Pause for NUMBER seconds. SUFFIX may be's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.", NAME, VERSION); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else if matches.free.is_empty() { show_error!("missing an argument"); show_error!("for help, try '{0} --help'", NAME); return 1; } else { sleep(matches.free); } 0 } fn
(args: Vec<String>) { let sleep_dur = args.iter().fold(Duration::new(0, 0), |result, arg| match uucore::parse_time::from_str(&arg[..]) { Ok(m) => m + result, Err(f) => crash!(1, "{}", f), }); thread::sleep(sleep_dur); }
sleep
identifier_name
sleep.rs
#![crate_name = "uu_sleep"] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use std::io::Write; use std::thread::{self}; use std::time::Duration; static NAME: &'static str = "sleep"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32
Pause for NUMBER seconds. SUFFIX may be's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.", NAME, VERSION); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else if matches.free.is_empty() { show_error!("missing an argument"); show_error!("for help, try '{0} --help'", NAME); return 1; } else { sleep(matches.free); } 0 } fn sleep(args: Vec<String>) { let sleep_dur = args.iter().fold(Duration::new(0, 0), |result, arg| match uucore::parse_time::from_str(&arg[..]) { Ok(m) => m + result, Err(f) => crash!(1, "{}", f), }); thread::sleep(sleep_dur); }
{ let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); return 1; } }; if matches.opt_present("help") { let msg = format!("{0} {1} Usage: {0} NUMBER[SUFFIX] or {0} OPTION
identifier_body
sleep.rs
#![crate_name = "uu_sleep"] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use std::io::Write; use std::thread::{self}; use std::time::Duration; static NAME: &'static str = "sleep"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); return 1; } }; if matches.opt_present("help") { let msg = format!("{0} {1} Usage:
'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.", NAME, VERSION); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else if matches.free.is_empty() { show_error!("missing an argument"); show_error!("for help, try '{0} --help'", NAME); return 1; } else { sleep(matches.free); } 0 } fn sleep(args: Vec<String>) { let sleep_dur = args.iter().fold(Duration::new(0, 0), |result, arg| match uucore::parse_time::from_str(&arg[..]) { Ok(m) => m + result, Err(f) => crash!(1, "{}", f), }); thread::sleep(sleep_dur); }
{0} NUMBER[SUFFIX] or {0} OPTION Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default),
random_line_split
flatten.rs
use {Future, IntoFuture, Task, Poll}; use chain::Chain; /// Future for the `flatten` combinator, flattening a future-of-a-future to get just /// the result of the final future. /// /// This is created by this `Future::flatten` method. pub struct Flatten<A> where A: Future, A::Item: IntoFuture { state: Chain<A, <A::Item as IntoFuture>::Future, ()>, } pub fn new<A>(future: A) -> Flatten<A> where A: Future, A::Item: IntoFuture, { Flatten { state: Chain::new(future, ()), } } impl<A> Future for Flatten<A> where A: Future, A::Item: IntoFuture, <<A as Future>::Item as IntoFuture>::Error: From<<A as Future>::Error> { type Item = <<A as Future>::Item as IntoFuture>::Item; type Error = <<A as Future>::Item as IntoFuture>::Error; fn poll(&mut self, task: &mut Task) -> Poll<Self::Item, Self::Error> { self.state.poll(task, |a, ()| { let future = try!(a).into_future(); Ok(Err(future)) }) } fn schedule(&mut self, task: &mut Task) { self.state.schedule(task) } fn
(&mut self) -> Option<Box<Future<Item=Self::Item, Error=Self::Error>>> { self.state.tailcall() } }
tailcall
identifier_name
flatten.rs
use {Future, IntoFuture, Task, Poll}; use chain::Chain; /// Future for the `flatten` combinator, flattening a future-of-a-future to get just /// the result of the final future. /// /// This is created by this `Future::flatten` method. pub struct Flatten<A> where A: Future, A::Item: IntoFuture { state: Chain<A, <A::Item as IntoFuture>::Future, ()>, } pub fn new<A>(future: A) -> Flatten<A> where A: Future, A::Item: IntoFuture, { Flatten { state: Chain::new(future, ()), } } impl<A> Future for Flatten<A> where A: Future, A::Item: IntoFuture, <<A as Future>::Item as IntoFuture>::Error: From<<A as Future>::Error> { type Item = <<A as Future>::Item as IntoFuture>::Item; type Error = <<A as Future>::Item as IntoFuture>::Error;
}) } fn schedule(&mut self, task: &mut Task) { self.state.schedule(task) } fn tailcall(&mut self) -> Option<Box<Future<Item=Self::Item, Error=Self::Error>>> { self.state.tailcall() } }
fn poll(&mut self, task: &mut Task) -> Poll<Self::Item, Self::Error> { self.state.poll(task, |a, ()| { let future = try!(a).into_future(); Ok(Err(future))
random_line_split
flatten.rs
use {Future, IntoFuture, Task, Poll}; use chain::Chain; /// Future for the `flatten` combinator, flattening a future-of-a-future to get just /// the result of the final future. /// /// This is created by this `Future::flatten` method. pub struct Flatten<A> where A: Future, A::Item: IntoFuture { state: Chain<A, <A::Item as IntoFuture>::Future, ()>, } pub fn new<A>(future: A) -> Flatten<A> where A: Future, A::Item: IntoFuture,
impl<A> Future for Flatten<A> where A: Future, A::Item: IntoFuture, <<A as Future>::Item as IntoFuture>::Error: From<<A as Future>::Error> { type Item = <<A as Future>::Item as IntoFuture>::Item; type Error = <<A as Future>::Item as IntoFuture>::Error; fn poll(&mut self, task: &mut Task) -> Poll<Self::Item, Self::Error> { self.state.poll(task, |a, ()| { let future = try!(a).into_future(); Ok(Err(future)) }) } fn schedule(&mut self, task: &mut Task) { self.state.schedule(task) } fn tailcall(&mut self) -> Option<Box<Future<Item=Self::Item, Error=Self::Error>>> { self.state.tailcall() } }
{ Flatten { state: Chain::new(future, ()), } }
identifier_body
coherence-orphan.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. // aux-build:coherence_orphan_lib.rs #![feature(optin_builtin_traits)] extern crate coherence_orphan_lib as lib; use lib::TheTrait; struct TheType; impl TheTrait<usize> for isize { } //~^ ERROR E0117 impl TheTrait<TheType> for isize { } impl TheTrait<isize> for TheType { } impl!Send for Vec<isize> { } //~^ ERROR E0117 //~| ERROR E0119 fn
() { }
main
identifier_name
coherence-orphan.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. // aux-build:coherence_orphan_lib.rs #![feature(optin_builtin_traits)] extern crate coherence_orphan_lib as lib; use lib::TheTrait; struct TheType; impl TheTrait<usize> for isize { } //~^ ERROR E0117 impl TheTrait<TheType> for isize { } impl TheTrait<isize> for TheType { } impl!Send for Vec<isize> { } //~^ ERROR E0117 //~| ERROR E0119 fn main()
{ }
identifier_body
coherence-orphan.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. // aux-build:coherence_orphan_lib.rs #![feature(optin_builtin_traits)] extern crate coherence_orphan_lib as lib; use lib::TheTrait; struct TheType; impl TheTrait<usize> for isize { } //~^ ERROR E0117 impl TheTrait<TheType> for isize { } impl TheTrait<isize> for TheType { }
impl!Send for Vec<isize> { } //~^ ERROR E0117 //~| ERROR E0119 fn main() { }
random_line_split
lib.rs
running Workunit as being in a blocked state. /// /// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any /// local mutated values as the final value of the Workunit. /// #[derive(Clone, Debug)] pub struct Workunit { pub name: String, pub span_id: SpanId, pub parent_id: Option<SpanId>, pub state: WorkunitState, pub metadata: WorkunitMetadata, } impl Workunit { fn log_workunit_state(&self, canceled: bool) { if!log::log_enabled!(self.metadata.level) { return; } let state = match (&self.state, canceled) { (_, true) => "Canceled:", (WorkunitState::Started {.. }, _) => "Starting:", (WorkunitState::Completed {.. }, _) => "Completed:", }; let level = self.metadata.level; let identifier = if let Some(ref s) = self.metadata.desc { s.as_str() } else { self.name.as_str() }; /* This length calculation doesn't treat multi-byte unicode charcters identically * to single-byte ones for the purpose of figuring out where to truncate the string. But that's * ok, since we just want to truncate the log string if it's roughly "too long", we don't care * exactly what the max_len is or whether it effectively changes slightly if there are * multibyte unicode characters in the string */ let max_len = 200; let effective_identifier = if identifier.len() > max_len { let truncated_identifier: String = identifier.chars().take(max_len).collect(); let trunc = identifier.len() - max_len; format!( "{}... ({} characters truncated)", truncated_identifier, trunc ) } else { identifier.to_string() }; let message = if let Some(ref s) = self.metadata.message { format!(" - {}", s) } else { "".to_string() }; log!(level, "{} {}{}", state, effective_identifier, message); } } #[derive(Clone, Debug)] pub enum WorkunitState { Started { start_time: SystemTime, blocked: Arc<AtomicBool>, }, Completed { time_span: TimeSpan, }, } impl WorkunitState { fn
(&self) -> bool { match self { WorkunitState::Completed {.. } => true, WorkunitState::Started {.. } => false, } } fn blocked(&self) -> bool { match self { WorkunitState::Started { blocked,.. } => blocked.load(atomic::Ordering::Relaxed), WorkunitState::Completed {.. } => false, } } } // NB: Only implemented for `fs::DirectoryDigest`, but is boxed to avoid a cycle between this crate // and the `fs` crate. pub trait DirectoryDigest: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } // NB: Only implemented for `Value`, but is boxed to avoid a cycle between this crate and the // `engine` crate. pub trait Value: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } #[derive(Clone, Debug)] pub enum ArtifactOutput { FileDigest(hashing::Digest), Snapshot(Arc<dyn DirectoryDigest>), } #[derive(Clone, Debug)] pub struct WorkunitMetadata { pub desc: Option<String>, pub message: Option<String>, pub level: Level, pub stdout: Option<hashing::Digest>, pub stderr: Option<hashing::Digest>, pub artifacts: Vec<(String, ArtifactOutput)>, pub user_metadata: Vec<(String, UserMetadataItem)>, } impl Default for WorkunitMetadata { fn default() -> WorkunitMetadata { WorkunitMetadata { level: Level::Info, desc: None, message: None, stdout: None, stderr: None, artifacts: Vec::new(), user_metadata: Vec::new(), } } } /// Abstract id for passing user metadata items around #[derive(Clone, Debug)] pub enum UserMetadataItem { PyValue(Arc<dyn Value>), ImmediateInt(i64), ImmediateString(String), } enum StoreMsg { Started(Workunit), Completed(SpanId, Option<WorkunitMetadata>, SystemTime), Canceled(SpanId), } #[derive(Clone)] pub struct WorkunitStore { log_starting_workunits: bool, max_level: Level, streaming_workunit_data: StreamingWorkunitData, heavy_hitters_data: HeavyHittersData, metrics_data: Arc<MetricsData>, } #[derive(Clone)] struct StreamingWorkunitData { msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, workunit_records: Arc<Mutex<HashMap<SpanId, Workunit>>>, } impl StreamingWorkunitData { fn new() -> StreamingWorkunitData { let (msg_tx, msg_rx) = channel(); StreamingWorkunitData { msg_tx: Arc::new(Mutex::new(msg_tx)), msg_rx: Arc::new(Mutex::new(msg_rx)), workunit_records: Arc::new(Mutex::new(HashMap::new())), } } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { let should_emit = |workunit: &Workunit| -> bool { workunit.metadata.level <= max_verbosity }; let mut started_messages = vec![]; let mut completed_messages = vec![]; { let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() { match msg { StoreMsg::Started(started) => started_messages.push(started), StoreMsg::Completed(span, metadata, time) => { completed_messages.push((span, metadata, time)) } StoreMsg::Canceled(..) => (), } } } let mut workunit_records = self.workunit_records.lock(); let mut started_workunits: Vec<Workunit> = vec![]; for mut started in started_messages.into_iter() { let span_id = started.span_id; workunit_records.insert(span_id, started.clone()); if should_emit(&started) { started.parent_id = first_matched_parent(&workunit_records, started.parent_id, |_| false, should_emit); started_workunits.push(started); } } let mut completed_workunits: Vec<Workunit> = vec![]; for (span_id, new_metadata, end_time) in completed_messages.into_iter() { match workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); continue; } Entry::Occupied(o) => { let (span_id, mut workunit) = o.remove_entry(); let time_span = match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); continue; } WorkunitState::Started { start_time,.. } => { TimeSpan::from_start_and_end_systemtime(&start_time, &end_time) } }; let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } workunit_records.insert(span_id, workunit.clone()); if should_emit(&workunit) { workunit.parent_id = first_matched_parent( &workunit_records, workunit.parent_id, |_| false, should_emit, ); completed_workunits.push(workunit); } } } } (started_workunits, completed_workunits) } } #[derive(Clone)] struct HeavyHittersData { inner: Arc<Mutex<HeavyHittersInnerStore>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, } impl HeavyHittersData { fn new() -> HeavyHittersData { let (msg_tx, msg_rx) = channel(); HeavyHittersData { inner: Arc::new(Mutex::new(HeavyHittersInnerStore { running_graph: RunningWorkunitGraph::new(), span_id_to_graph: HashMap::new(), workunit_records: HashMap::new(), })), msg_rx: Arc::new(Mutex::new(msg_rx)), msg_tx: Arc::new(Mutex::new(msg_tx)), } } fn add_started_workunit_to_store(started: Workunit, inner_store: &mut HeavyHittersInnerStore) { let span_id = started.span_id; let parent_id = started.parent_id; inner_store.workunit_records.insert(span_id, started); let child = inner_store.running_graph.add_node(span_id); inner_store.span_id_to_graph.insert(span_id, child); if let Some(parent_id) = parent_id { if let Some(parent) = inner_store.span_id_to_graph.get(&parent_id) { inner_store.running_graph.add_edge(*parent, child, ()); } } } fn add_completed_workunit_to_store( span_id: SpanId, new_metadata: Option<WorkunitMetadata>, end_time: SystemTime, inner_store: &mut HeavyHittersInnerStore, ) { if let Some(node) = inner_store.span_id_to_graph.remove(&span_id) { inner_store.running_graph.remove_node(node); } match inner_store.workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); } Entry::Occupied(mut o) => { let workunit = o.get_mut(); match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); } WorkunitState::Started { start_time,.. } => { let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); workunit.state = WorkunitState::Completed { time_span }; } }; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } } } } fn refresh_store(&self) { let mut inner = self.inner.lock(); let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() { match msg { StoreMsg::Started(started) => Self::add_started_workunit_to_store(started, &mut inner), StoreMsg::Completed(span_id, new_metadata, time) => { Self::add_completed_workunit_to_store(span_id, new_metadata, time, &mut inner) } StoreMsg::Canceled(span_id) => { inner.workunit_records.remove(&span_id); if let Some(node) = inner.span_id_to_graph.remove(&span_id) { inner.running_graph.remove_node(node); } } } } } fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.refresh_store(); let inner = self.inner.lock(); // Initialize the heap with the leaves of the running workunit graph, sorted oldest first. let mut queue: BinaryHeap<(Reverse<SystemTime>, SpanId)> = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| { let workunit: &Workunit = inner.workunit_records.get(&span_id)?; match workunit.state { WorkunitState::Started { ref blocked, start_time, .. } if!blocked.load(atomic::Ordering::Relaxed) => Some((Reverse(start_time), span_id)), _ => None, } }) .collect(); // Output the visible parents of the longest running leaves. let mut res = HashMap::new(); while let Some((_dur, span_id)) = queue.pop() { // If the leaf is visible or has a visible parent, emit it. let parent_span_id = if let Some(span_id) = first_matched_parent( &inner.workunit_records, Some(span_id), |wu| wu.state.completed(), Self::is_visible, ) { span_id } else { continue; }; let workunit = inner.workunit_records.get(&parent_span_id).unwrap(); if let Some(effective_name) = workunit.metadata.desc.as_ref() { if let Some(start_time) = Self::start_time_for(workunit) { res.insert(parent_span_id, (effective_name.to_string(), start_time)); if res.len() >= k { break; } } } } res } fn straggling_workunits(&self, duration_threshold: Duration) -> Vec<(Duration, String)> { self.refresh_store(); let now = SystemTime::now(); let inner = self.inner.lock(); let matching_visible_parents = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| inner.workunit_records.get(&span_id)) .filter_map(|workunit| match Self::duration_for(now, workunit) { Some(duration) if!workunit.state.blocked() && duration >= duration_threshold => { first_matched_parent( &inner.workunit_records, Some(workunit.span_id), |wu| wu.state.completed(), Self::is_visible, ) .and_then(|span_id| inner.workunit_records.get(&span_id)) .and_then(|wu| wu.metadata.desc.as_ref()) .map(|desc| (desc.clone(), duration)) } _ => None, }) .collect::<HashMap<_, _>>(); if matching_visible_parents.is_empty() { return vec![]; } let mut stragglers = matching_visible_parents .into_iter() .map(|(k, v)| (v, k)) .collect::<Vec<_>>(); // NB: Because the Duration is first in the tuple, we get ascending Duration order. stragglers.sort(); stragglers } fn is_visible(workunit: &Workunit) -> bool { workunit.metadata.level <= Level::Debug && workunit.metadata.desc.is_some() && matches!(workunit.state, WorkunitState::Started {.. }) } fn start_time_for(workunit: &Workunit) -> Option<SystemTime> { match workunit.state { WorkunitState::Started { start_time,.. } => Some(start_time), _ => None, } } fn duration_for(now: SystemTime, workunit: &Workunit) -> Option<Duration> { now.duration_since(Self::start_time_for(workunit)?).ok() } } #[derive(Default)] pub struct HeavyHittersInnerStore { running_graph: RunningWorkunitGraph, span_id_to_graph: HashMap<SpanId, NodeIndex<u32>>, workunit_records: HashMap<SpanId, Workunit>, } fn first_matched_parent( workunit_records: &HashMap<SpanId, Workunit>, mut span_id: Option<SpanId>, is_terminal: impl Fn(&Workunit) -> bool, is_visible: impl Fn(&Workunit) -> bool, ) -> Option<SpanId> { while let Some(current_span_id) = span_id { let workunit = workunit_records.get(&current_span_id); if let Some(workunit) = workunit { // Should we continue visiting parents? if is_terminal(workunit) { break; } // Is the current workunit visible? if is_visible(workunit) { return Some(current_span_id); } } // If not, try its parent. span_id = workunit.and_then(|workunit| workunit.parent_id); } None } impl WorkunitStore { pub fn new(log_starting_workunits: bool, max_level: Level) -> WorkunitStore { WorkunitStore { log_starting_workunits, max_level, // TODO: Create one `StreamingWorkunitData` per subscriber, and zero if no subscribers are // installed. streaming_workunit_data: StreamingWorkunitData::new(), heavy_hitters_data: HeavyHittersData::new(), metrics_data: Arc::default(), } } pub fn init_thread_state(&self, parent_id: Option<SpanId>) { set_thread_workunit_store_handle(Some(WorkunitStoreHandle { store: self.clone(), parent_id, })) } pub fn max_level(&self) -> Level { self.max_level } /// /// Return visible workunits which have been running longer than the duration_threshold, sorted /// in ascending order by their duration. /// pub fn straggling_workunits(&self, threshold: Duration) -> Vec<(Duration, String)> { self.heavy_hitters_data.straggling_workunits(threshold) } /// /// Find the longest running leaf workunits, and return the description and start time of their /// first visible parents. /// pub fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.heavy_hitters_data.heavy_hitters(k) } fn start_workunit( &self, span_id: SpanId, name: String, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) -> Workunit { let started = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time: std::time::SystemTime::now(), blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); if self.log_starting_workunits { started.log_workunit_state(false) } started } fn complete_workunit(&self, workunit: Workunit) { let time = std::time::SystemTime::now(); self.complete_workunit_impl(workunit, time) } fn cancel_workunit(&self, workunit: Workunit) { workunit.log_workunit_state(true); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Canceled(workunit.span_id)) .unwrap(); } fn complete_workunit_impl(&self, mut workunit: Workunit, end_time: SystemTime) { let span_id = workunit.span_id; let new_metadata = Some(workunit.metadata.clone()); let tx = self.streaming_workunit_data.msg_tx.lock(); tx.send(StoreMsg::Completed(span_id, new_metadata.clone(), end_time)) .unwrap(); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Completed(span_id, new_metadata, end_time)) .unwrap(); let start_time = match workunit.state { WorkunitState::Started { start_time,.. } => start_time, _ => { log::warn!("Workunit {} was already completed", span_id); return; } }; let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; workunit.log_workunit_state(false); } pub fn add_completed_workunit( &self, name: String, start_time: SystemTime, end_time: SystemTime, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) { let span_id = SpanId::new(); let workunit = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time, blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self.complete_workunit_impl(workunit, end_time); } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { self.streaming_workunit_data.latest_workunits(max_verbosity) } pub fn increment_counter(&mut self, counter_name: Metric, change: u64) { self .metrics_data .counters .lock() .entry(counter_name) .and_modify(|e| *e += change) .or_insert(change); } pub fn get_metrics(&self) -> HashMap<&'static str, u64> { let counters = self.metrics_data.counters.lock(); counters .iter() .map(|(metric, value)| (metric.into(), *value)) .collect() } /// /// Records an observation of a time-like metric into a histogram. /// pub fn record_observation(&self, metric: ObservationMetric, value: u64) { let mut histograms_by_metric = self.metrics_data.observations.lock(); histograms_by_metric .entry(metric) .and_modify(|h| { let _ = h.record(value); }) .or_insert_with(|| { let mut h = hdrhistogram::Histogram::<u64>::new(3).expect("Failed to allocate histogram"); let _ = h.record(value); h }); } /// /// Return all observations in binary encoded format. /// pub fn encode_observations(&self) -> Result<HashMap<&'static str, Bytes>, String> { use hdrhistogram::serialization::V2DeflateSerializer; let mut serializer = V2DeflateSerializer::new(); let mut result = HashMap::new(); let histograms_by_metric = self.metrics_data.observations.lock(); for (metric, histogram) in histograms_by_metric.iter() { let mut writer = BytesMut::new().writer(); serializer
completed
identifier_name
lib.rs
running Workunit as being in a blocked state. /// /// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any /// local mutated values as the final value of the Workunit. /// #[derive(Clone, Debug)] pub struct Workunit { pub name: String, pub span_id: SpanId, pub parent_id: Option<SpanId>, pub state: WorkunitState, pub metadata: WorkunitMetadata, } impl Workunit { fn log_workunit_state(&self, canceled: bool) { if!log::log_enabled!(self.metadata.level) { return; } let state = match (&self.state, canceled) { (_, true) => "Canceled:", (WorkunitState::Started {.. }, _) => "Starting:", (WorkunitState::Completed {.. }, _) => "Completed:", }; let level = self.metadata.level; let identifier = if let Some(ref s) = self.metadata.desc { s.as_str() } else { self.name.as_str() }; /* This length calculation doesn't treat multi-byte unicode charcters identically * to single-byte ones for the purpose of figuring out where to truncate the string. But that's * ok, since we just want to truncate the log string if it's roughly "too long", we don't care * exactly what the max_len is or whether it effectively changes slightly if there are * multibyte unicode characters in the string */ let max_len = 200; let effective_identifier = if identifier.len() > max_len { let truncated_identifier: String = identifier.chars().take(max_len).collect(); let trunc = identifier.len() - max_len; format!( "{}... ({} characters truncated)", truncated_identifier, trunc ) } else { identifier.to_string() }; let message = if let Some(ref s) = self.metadata.message { format!(" - {}", s) } else { "".to_string() }; log!(level, "{} {}{}", state, effective_identifier, message); } } #[derive(Clone, Debug)] pub enum WorkunitState { Started { start_time: SystemTime, blocked: Arc<AtomicBool>, }, Completed { time_span: TimeSpan, }, } impl WorkunitState { fn completed(&self) -> bool { match self { WorkunitState::Completed {.. } => true, WorkunitState::Started {.. } => false, } } fn blocked(&self) -> bool { match self { WorkunitState::Started { blocked,.. } => blocked.load(atomic::Ordering::Relaxed), WorkunitState::Completed {.. } => false, } } } // NB: Only implemented for `fs::DirectoryDigest`, but is boxed to avoid a cycle between this crate // and the `fs` crate. pub trait DirectoryDigest: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } // NB: Only implemented for `Value`, but is boxed to avoid a cycle between this crate and the // `engine` crate. pub trait Value: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } #[derive(Clone, Debug)] pub enum ArtifactOutput { FileDigest(hashing::Digest), Snapshot(Arc<dyn DirectoryDigest>), } #[derive(Clone, Debug)] pub struct WorkunitMetadata { pub desc: Option<String>, pub message: Option<String>, pub level: Level, pub stdout: Option<hashing::Digest>, pub stderr: Option<hashing::Digest>, pub artifacts: Vec<(String, ArtifactOutput)>, pub user_metadata: Vec<(String, UserMetadataItem)>, } impl Default for WorkunitMetadata { fn default() -> WorkunitMetadata { WorkunitMetadata { level: Level::Info, desc: None, message: None, stdout: None, stderr: None, artifacts: Vec::new(), user_metadata: Vec::new(), } } } /// Abstract id for passing user metadata items around #[derive(Clone, Debug)] pub enum UserMetadataItem { PyValue(Arc<dyn Value>), ImmediateInt(i64), ImmediateString(String), } enum StoreMsg { Started(Workunit), Completed(SpanId, Option<WorkunitMetadata>, SystemTime), Canceled(SpanId), } #[derive(Clone)] pub struct WorkunitStore { log_starting_workunits: bool, max_level: Level, streaming_workunit_data: StreamingWorkunitData, heavy_hitters_data: HeavyHittersData, metrics_data: Arc<MetricsData>, } #[derive(Clone)] struct StreamingWorkunitData { msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, workunit_records: Arc<Mutex<HashMap<SpanId, Workunit>>>, } impl StreamingWorkunitData { fn new() -> StreamingWorkunitData { let (msg_tx, msg_rx) = channel(); StreamingWorkunitData { msg_tx: Arc::new(Mutex::new(msg_tx)), msg_rx: Arc::new(Mutex::new(msg_rx)), workunit_records: Arc::new(Mutex::new(HashMap::new())), } } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { let should_emit = |workunit: &Workunit| -> bool { workunit.metadata.level <= max_verbosity }; let mut started_messages = vec![]; let mut completed_messages = vec![]; { let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() { match msg { StoreMsg::Started(started) => started_messages.push(started), StoreMsg::Completed(span, metadata, time) => { completed_messages.push((span, metadata, time)) } StoreMsg::Canceled(..) => (), } } } let mut workunit_records = self.workunit_records.lock(); let mut started_workunits: Vec<Workunit> = vec![]; for mut started in started_messages.into_iter() { let span_id = started.span_id; workunit_records.insert(span_id, started.clone()); if should_emit(&started) { started.parent_id = first_matched_parent(&workunit_records, started.parent_id, |_| false, should_emit); started_workunits.push(started); } } let mut completed_workunits: Vec<Workunit> = vec![]; for (span_id, new_metadata, end_time) in completed_messages.into_iter() { match workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); continue; } Entry::Occupied(o) => { let (span_id, mut workunit) = o.remove_entry(); let time_span = match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); continue; } WorkunitState::Started { start_time,.. } => { TimeSpan::from_start_and_end_systemtime(&start_time, &end_time) } }; let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } workunit_records.insert(span_id, workunit.clone()); if should_emit(&workunit) { workunit.parent_id = first_matched_parent( &workunit_records, workunit.parent_id, |_| false, should_emit, ); completed_workunits.push(workunit); } } } } (started_workunits, completed_workunits) } } #[derive(Clone)] struct HeavyHittersData { inner: Arc<Mutex<HeavyHittersInnerStore>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, } impl HeavyHittersData { fn new() -> HeavyHittersData { let (msg_tx, msg_rx) = channel(); HeavyHittersData { inner: Arc::new(Mutex::new(HeavyHittersInnerStore { running_graph: RunningWorkunitGraph::new(), span_id_to_graph: HashMap::new(), workunit_records: HashMap::new(), })), msg_rx: Arc::new(Mutex::new(msg_rx)), msg_tx: Arc::new(Mutex::new(msg_tx)), } } fn add_started_workunit_to_store(started: Workunit, inner_store: &mut HeavyHittersInnerStore) { let span_id = started.span_id; let parent_id = started.parent_id; inner_store.workunit_records.insert(span_id, started); let child = inner_store.running_graph.add_node(span_id); inner_store.span_id_to_graph.insert(span_id, child); if let Some(parent_id) = parent_id { if let Some(parent) = inner_store.span_id_to_graph.get(&parent_id) { inner_store.running_graph.add_edge(*parent, child, ()); } } } fn add_completed_workunit_to_store( span_id: SpanId, new_metadata: Option<WorkunitMetadata>, end_time: SystemTime, inner_store: &mut HeavyHittersInnerStore, ) { if let Some(node) = inner_store.span_id_to_graph.remove(&span_id) { inner_store.running_graph.remove_node(node); } match inner_store.workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); } Entry::Occupied(mut o) => { let workunit = o.get_mut(); match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); } WorkunitState::Started { start_time,.. } =>
}; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } } } } fn refresh_store(&self) { let mut inner = self.inner.lock(); let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() { match msg { StoreMsg::Started(started) => Self::add_started_workunit_to_store(started, &mut inner), StoreMsg::Completed(span_id, new_metadata, time) => { Self::add_completed_workunit_to_store(span_id, new_metadata, time, &mut inner) } StoreMsg::Canceled(span_id) => { inner.workunit_records.remove(&span_id); if let Some(node) = inner.span_id_to_graph.remove(&span_id) { inner.running_graph.remove_node(node); } } } } } fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.refresh_store(); let inner = self.inner.lock(); // Initialize the heap with the leaves of the running workunit graph, sorted oldest first. let mut queue: BinaryHeap<(Reverse<SystemTime>, SpanId)> = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| { let workunit: &Workunit = inner.workunit_records.get(&span_id)?; match workunit.state { WorkunitState::Started { ref blocked, start_time, .. } if!blocked.load(atomic::Ordering::Relaxed) => Some((Reverse(start_time), span_id)), _ => None, } }) .collect(); // Output the visible parents of the longest running leaves. let mut res = HashMap::new(); while let Some((_dur, span_id)) = queue.pop() { // If the leaf is visible or has a visible parent, emit it. let parent_span_id = if let Some(span_id) = first_matched_parent( &inner.workunit_records, Some(span_id), |wu| wu.state.completed(), Self::is_visible, ) { span_id } else { continue; }; let workunit = inner.workunit_records.get(&parent_span_id).unwrap(); if let Some(effective_name) = workunit.metadata.desc.as_ref() { if let Some(start_time) = Self::start_time_for(workunit) { res.insert(parent_span_id, (effective_name.to_string(), start_time)); if res.len() >= k { break; } } } } res } fn straggling_workunits(&self, duration_threshold: Duration) -> Vec<(Duration, String)> { self.refresh_store(); let now = SystemTime::now(); let inner = self.inner.lock(); let matching_visible_parents = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| inner.workunit_records.get(&span_id)) .filter_map(|workunit| match Self::duration_for(now, workunit) { Some(duration) if!workunit.state.blocked() && duration >= duration_threshold => { first_matched_parent( &inner.workunit_records, Some(workunit.span_id), |wu| wu.state.completed(), Self::is_visible, ) .and_then(|span_id| inner.workunit_records.get(&span_id)) .and_then(|wu| wu.metadata.desc.as_ref()) .map(|desc| (desc.clone(), duration)) } _ => None, }) .collect::<HashMap<_, _>>(); if matching_visible_parents.is_empty() { return vec![]; } let mut stragglers = matching_visible_parents .into_iter() .map(|(k, v)| (v, k)) .collect::<Vec<_>>(); // NB: Because the Duration is first in the tuple, we get ascending Duration order. stragglers.sort(); stragglers } fn is_visible(workunit: &Workunit) -> bool { workunit.metadata.level <= Level::Debug && workunit.metadata.desc.is_some() && matches!(workunit.state, WorkunitState::Started {.. }) } fn start_time_for(workunit: &Workunit) -> Option<SystemTime> { match workunit.state { WorkunitState::Started { start_time,.. } => Some(start_time), _ => None, } } fn duration_for(now: SystemTime, workunit: &Workunit) -> Option<Duration> { now.duration_since(Self::start_time_for(workunit)?).ok() } } #[derive(Default)] pub struct HeavyHittersInnerStore { running_graph: RunningWorkunitGraph, span_id_to_graph: HashMap<SpanId, NodeIndex<u32>>, workunit_records: HashMap<SpanId, Workunit>, } fn first_matched_parent( workunit_records: &HashMap<SpanId, Workunit>, mut span_id: Option<SpanId>, is_terminal: impl Fn(&Workunit) -> bool, is_visible: impl Fn(&Workunit) -> bool, ) -> Option<SpanId> { while let Some(current_span_id) = span_id { let workunit = workunit_records.get(&current_span_id); if let Some(workunit) = workunit { // Should we continue visiting parents? if is_terminal(workunit) { break; } // Is the current workunit visible? if is_visible(workunit) { return Some(current_span_id); } } // If not, try its parent. span_id = workunit.and_then(|workunit| workunit.parent_id); } None } impl WorkunitStore { pub fn new(log_starting_workunits: bool, max_level: Level) -> WorkunitStore { WorkunitStore { log_starting_workunits, max_level, // TODO: Create one `StreamingWorkunitData` per subscriber, and zero if no subscribers are // installed. streaming_workunit_data: StreamingWorkunitData::new(), heavy_hitters_data: HeavyHittersData::new(), metrics_data: Arc::default(), } } pub fn init_thread_state(&self, parent_id: Option<SpanId>) { set_thread_workunit_store_handle(Some(WorkunitStoreHandle { store: self.clone(), parent_id, })) } pub fn max_level(&self) -> Level { self.max_level } /// /// Return visible workunits which have been running longer than the duration_threshold, sorted /// in ascending order by their duration. /// pub fn straggling_workunits(&self, threshold: Duration) -> Vec<(Duration, String)> { self.heavy_hitters_data.straggling_workunits(threshold) } /// /// Find the longest running leaf workunits, and return the description and start time of their /// first visible parents. /// pub fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.heavy_hitters_data.heavy_hitters(k) } fn start_workunit( &self, span_id: SpanId, name: String, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) -> Workunit { let started = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time: std::time::SystemTime::now(), blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); if self.log_starting_workunits { started.log_workunit_state(false) } started } fn complete_workunit(&self, workunit: Workunit) { let time = std::time::SystemTime::now(); self.complete_workunit_impl(workunit, time) } fn cancel_workunit(&self, workunit: Workunit) { workunit.log_workunit_state(true); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Canceled(workunit.span_id)) .unwrap(); } fn complete_workunit_impl(&self, mut workunit: Workunit, end_time: SystemTime) { let span_id = workunit.span_id; let new_metadata = Some(workunit.metadata.clone()); let tx = self.streaming_workunit_data.msg_tx.lock(); tx.send(StoreMsg::Completed(span_id, new_metadata.clone(), end_time)) .unwrap(); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Completed(span_id, new_metadata, end_time)) .unwrap(); let start_time = match workunit.state { WorkunitState::Started { start_time,.. } => start_time, _ => { log::warn!("Workunit {} was already completed", span_id); return; } }; let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; workunit.log_workunit_state(false); } pub fn add_completed_workunit( &self, name: String, start_time: SystemTime, end_time: SystemTime, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) { let span_id = SpanId::new(); let workunit = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time, blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self.complete_workunit_impl(workunit, end_time); } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { self.streaming_workunit_data.latest_workunits(max_verbosity) } pub fn increment_counter(&mut self, counter_name: Metric, change: u64) { self .metrics_data .counters .lock() .entry(counter_name) .and_modify(|e| *e += change) .or_insert(change); } pub fn get_metrics(&self) -> HashMap<&'static str, u64> { let counters = self.metrics_data.counters.lock(); counters .iter() .map(|(metric, value)| (metric.into(), *value)) .collect() } /// /// Records an observation of a time-like metric into a histogram. /// pub fn record_observation(&self, metric: ObservationMetric, value: u64) { let mut histograms_by_metric = self.metrics_data.observations.lock(); histograms_by_metric .entry(metric) .and_modify(|h| { let _ = h.record(value); }) .or_insert_with(|| { let mut h = hdrhistogram::Histogram::<u64>::new(3).expect("Failed to allocate histogram"); let _ = h.record(value); h }); } /// /// Return all observations in binary encoded format. /// pub fn encode_observations(&self) -> Result<HashMap<&'static str, Bytes>, String> { use hdrhistogram::serialization::V2DeflateSerializer; let mut serializer = V2DeflateSerializer::new(); let mut result = HashMap::new(); let histograms_by_metric = self.metrics_data.observations.lock(); for (metric, histogram) in histograms_by_metric.iter() { let mut writer = BytesMut::new().writer(); serializer
{ let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); workunit.state = WorkunitState::Completed { time_span }; }
conditional_block
lib.rs
running Workunit as being in a blocked state. /// /// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any /// local mutated values as the final value of the Workunit. /// #[derive(Clone, Debug)] pub struct Workunit { pub name: String, pub span_id: SpanId, pub parent_id: Option<SpanId>, pub state: WorkunitState, pub metadata: WorkunitMetadata, } impl Workunit { fn log_workunit_state(&self, canceled: bool) { if!log::log_enabled!(self.metadata.level) { return; } let state = match (&self.state, canceled) { (_, true) => "Canceled:", (WorkunitState::Started {.. }, _) => "Starting:", (WorkunitState::Completed {.. }, _) => "Completed:", }; let level = self.metadata.level; let identifier = if let Some(ref s) = self.metadata.desc { s.as_str() } else { self.name.as_str() }; /* This length calculation doesn't treat multi-byte unicode charcters identically * to single-byte ones for the purpose of figuring out where to truncate the string. But that's * ok, since we just want to truncate the log string if it's roughly "too long", we don't care * exactly what the max_len is or whether it effectively changes slightly if there are * multibyte unicode characters in the string */ let max_len = 200; let effective_identifier = if identifier.len() > max_len { let truncated_identifier: String = identifier.chars().take(max_len).collect(); let trunc = identifier.len() - max_len; format!( "{}... ({} characters truncated)", truncated_identifier, trunc ) } else { identifier.to_string() }; let message = if let Some(ref s) = self.metadata.message { format!(" - {}", s) } else { "".to_string() }; log!(level, "{} {}{}", state, effective_identifier, message); } } #[derive(Clone, Debug)] pub enum WorkunitState { Started { start_time: SystemTime, blocked: Arc<AtomicBool>, }, Completed { time_span: TimeSpan, }, } impl WorkunitState { fn completed(&self) -> bool
fn blocked(&self) -> bool { match self { WorkunitState::Started { blocked,.. } => blocked.load(atomic::Ordering::Relaxed), WorkunitState::Completed {.. } => false, } } } // NB: Only implemented for `fs::DirectoryDigest`, but is boxed to avoid a cycle between this crate // and the `fs` crate. pub trait DirectoryDigest: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } // NB: Only implemented for `Value`, but is boxed to avoid a cycle between this crate and the // `engine` crate. pub trait Value: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } #[derive(Clone, Debug)] pub enum ArtifactOutput { FileDigest(hashing::Digest), Snapshot(Arc<dyn DirectoryDigest>), } #[derive(Clone, Debug)] pub struct WorkunitMetadata { pub desc: Option<String>, pub message: Option<String>, pub level: Level, pub stdout: Option<hashing::Digest>, pub stderr: Option<hashing::Digest>, pub artifacts: Vec<(String, ArtifactOutput)>, pub user_metadata: Vec<(String, UserMetadataItem)>, } impl Default for WorkunitMetadata { fn default() -> WorkunitMetadata { WorkunitMetadata { level: Level::Info, desc: None, message: None, stdout: None, stderr: None, artifacts: Vec::new(), user_metadata: Vec::new(), } } } /// Abstract id for passing user metadata items around #[derive(Clone, Debug)] pub enum UserMetadataItem { PyValue(Arc<dyn Value>), ImmediateInt(i64), ImmediateString(String), } enum StoreMsg { Started(Workunit), Completed(SpanId, Option<WorkunitMetadata>, SystemTime), Canceled(SpanId), } #[derive(Clone)] pub struct WorkunitStore { log_starting_workunits: bool, max_level: Level, streaming_workunit_data: StreamingWorkunitData, heavy_hitters_data: HeavyHittersData, metrics_data: Arc<MetricsData>, } #[derive(Clone)] struct StreamingWorkunitData { msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, workunit_records: Arc<Mutex<HashMap<SpanId, Workunit>>>, } impl StreamingWorkunitData { fn new() -> StreamingWorkunitData { let (msg_tx, msg_rx) = channel(); StreamingWorkunitData { msg_tx: Arc::new(Mutex::new(msg_tx)), msg_rx: Arc::new(Mutex::new(msg_rx)), workunit_records: Arc::new(Mutex::new(HashMap::new())), } } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { let should_emit = |workunit: &Workunit| -> bool { workunit.metadata.level <= max_verbosity }; let mut started_messages = vec![]; let mut completed_messages = vec![]; { let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() { match msg { StoreMsg::Started(started) => started_messages.push(started), StoreMsg::Completed(span, metadata, time) => { completed_messages.push((span, metadata, time)) } StoreMsg::Canceled(..) => (), } } } let mut workunit_records = self.workunit_records.lock(); let mut started_workunits: Vec<Workunit> = vec![]; for mut started in started_messages.into_iter() { let span_id = started.span_id; workunit_records.insert(span_id, started.clone()); if should_emit(&started) { started.parent_id = first_matched_parent(&workunit_records, started.parent_id, |_| false, should_emit); started_workunits.push(started); } } let mut completed_workunits: Vec<Workunit> = vec![]; for (span_id, new_metadata, end_time) in completed_messages.into_iter() { match workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); continue; } Entry::Occupied(o) => { let (span_id, mut workunit) = o.remove_entry(); let time_span = match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); continue; } WorkunitState::Started { start_time,.. } => { TimeSpan::from_start_and_end_systemtime(&start_time, &end_time) } }; let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } workunit_records.insert(span_id, workunit.clone()); if should_emit(&workunit) { workunit.parent_id = first_matched_parent( &workunit_records, workunit.parent_id, |_| false, should_emit, ); completed_workunits.push(workunit); } } } } (started_workunits, completed_workunits) } } #[derive(Clone)] struct HeavyHittersData { inner: Arc<Mutex<HeavyHittersInnerStore>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, } impl HeavyHittersData { fn new() -> HeavyHittersData { let (msg_tx, msg_rx) = channel(); HeavyHittersData { inner: Arc::new(Mutex::new(HeavyHittersInnerStore { running_graph: RunningWorkunitGraph::new(), span_id_to_graph: HashMap::new(), workunit_records: HashMap::new(), })), msg_rx: Arc::new(Mutex::new(msg_rx)), msg_tx: Arc::new(Mutex::new(msg_tx)), } } fn add_started_workunit_to_store(started: Workunit, inner_store: &mut HeavyHittersInnerStore) { let span_id = started.span_id; let parent_id = started.parent_id; inner_store.workunit_records.insert(span_id, started); let child = inner_store.running_graph.add_node(span_id); inner_store.span_id_to_graph.insert(span_id, child); if let Some(parent_id) = parent_id { if let Some(parent) = inner_store.span_id_to_graph.get(&parent_id) { inner_store.running_graph.add_edge(*parent, child, ()); } } } fn add_completed_workunit_to_store( span_id: SpanId, new_metadata: Option<WorkunitMetadata>, end_time: SystemTime, inner_store: &mut HeavyHittersInnerStore, ) { if let Some(node) = inner_store.span_id_to_graph.remove(&span_id) { inner_store.running_graph.remove_node(node); } match inner_store.workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); } Entry::Occupied(mut o) => { let workunit = o.get_mut(); match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); } WorkunitState::Started { start_time,.. } => { let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); workunit.state = WorkunitState::Completed { time_span }; } }; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } } } } fn refresh_store(&self) { let mut inner = self.inner.lock(); let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() { match msg { StoreMsg::Started(started) => Self::add_started_workunit_to_store(started, &mut inner), StoreMsg::Completed(span_id, new_metadata, time) => { Self::add_completed_workunit_to_store(span_id, new_metadata, time, &mut inner) } StoreMsg::Canceled(span_id) => { inner.workunit_records.remove(&span_id); if let Some(node) = inner.span_id_to_graph.remove(&span_id) { inner.running_graph.remove_node(node); } } } } } fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.refresh_store(); let inner = self.inner.lock(); // Initialize the heap with the leaves of the running workunit graph, sorted oldest first. let mut queue: BinaryHeap<(Reverse<SystemTime>, SpanId)> = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| { let workunit: &Workunit = inner.workunit_records.get(&span_id)?; match workunit.state { WorkunitState::Started { ref blocked, start_time, .. } if!blocked.load(atomic::Ordering::Relaxed) => Some((Reverse(start_time), span_id)), _ => None, } }) .collect(); // Output the visible parents of the longest running leaves. let mut res = HashMap::new(); while let Some((_dur, span_id)) = queue.pop() { // If the leaf is visible or has a visible parent, emit it. let parent_span_id = if let Some(span_id) = first_matched_parent( &inner.workunit_records, Some(span_id), |wu| wu.state.completed(), Self::is_visible, ) { span_id } else { continue; }; let workunit = inner.workunit_records.get(&parent_span_id).unwrap(); if let Some(effective_name) = workunit.metadata.desc.as_ref() { if let Some(start_time) = Self::start_time_for(workunit) { res.insert(parent_span_id, (effective_name.to_string(), start_time)); if res.len() >= k { break; } } } } res } fn straggling_workunits(&self, duration_threshold: Duration) -> Vec<(Duration, String)> { self.refresh_store(); let now = SystemTime::now(); let inner = self.inner.lock(); let matching_visible_parents = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| inner.workunit_records.get(&span_id)) .filter_map(|workunit| match Self::duration_for(now, workunit) { Some(duration) if!workunit.state.blocked() && duration >= duration_threshold => { first_matched_parent( &inner.workunit_records, Some(workunit.span_id), |wu| wu.state.completed(), Self::is_visible, ) .and_then(|span_id| inner.workunit_records.get(&span_id)) .and_then(|wu| wu.metadata.desc.as_ref()) .map(|desc| (desc.clone(), duration)) } _ => None, }) .collect::<HashMap<_, _>>(); if matching_visible_parents.is_empty() { return vec![]; } let mut stragglers = matching_visible_parents .into_iter() .map(|(k, v)| (v, k)) .collect::<Vec<_>>(); // NB: Because the Duration is first in the tuple, we get ascending Duration order. stragglers.sort(); stragglers } fn is_visible(workunit: &Workunit) -> bool { workunit.metadata.level <= Level::Debug && workunit.metadata.desc.is_some() && matches!(workunit.state, WorkunitState::Started {.. }) } fn start_time_for(workunit: &Workunit) -> Option<SystemTime> { match workunit.state { WorkunitState::Started { start_time,.. } => Some(start_time), _ => None, } } fn duration_for(now: SystemTime, workunit: &Workunit) -> Option<Duration> { now.duration_since(Self::start_time_for(workunit)?).ok() } } #[derive(Default)] pub struct HeavyHittersInnerStore { running_graph: RunningWorkunitGraph, span_id_to_graph: HashMap<SpanId, NodeIndex<u32>>, workunit_records: HashMap<SpanId, Workunit>, } fn first_matched_parent( workunit_records: &HashMap<SpanId, Workunit>, mut span_id: Option<SpanId>, is_terminal: impl Fn(&Workunit) -> bool, is_visible: impl Fn(&Workunit) -> bool, ) -> Option<SpanId> { while let Some(current_span_id) = span_id { let workunit = workunit_records.get(&current_span_id); if let Some(workunit) = workunit { // Should we continue visiting parents? if is_terminal(workunit) { break; } // Is the current workunit visible? if is_visible(workunit) { return Some(current_span_id); } } // If not, try its parent. span_id = workunit.and_then(|workunit| workunit.parent_id); } None } impl WorkunitStore { pub fn new(log_starting_workunits: bool, max_level: Level) -> WorkunitStore { WorkunitStore { log_starting_workunits, max_level, // TODO: Create one `StreamingWorkunitData` per subscriber, and zero if no subscribers are // installed. streaming_workunit_data: StreamingWorkunitData::new(), heavy_hitters_data: HeavyHittersData::new(), metrics_data: Arc::default(), } } pub fn init_thread_state(&self, parent_id: Option<SpanId>) { set_thread_workunit_store_handle(Some(WorkunitStoreHandle { store: self.clone(), parent_id, })) } pub fn max_level(&self) -> Level { self.max_level } /// /// Return visible workunits which have been running longer than the duration_threshold, sorted /// in ascending order by their duration. /// pub fn straggling_workunits(&self, threshold: Duration) -> Vec<(Duration, String)> { self.heavy_hitters_data.straggling_workunits(threshold) } /// /// Find the longest running leaf workunits, and return the description and start time of their /// first visible parents. /// pub fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.heavy_hitters_data.heavy_hitters(k) } fn start_workunit( &self, span_id: SpanId, name: String, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) -> Workunit { let started = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time: std::time::SystemTime::now(), blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); if self.log_starting_workunits { started.log_workunit_state(false) } started } fn complete_workunit(&self, workunit: Workunit) { let time = std::time::SystemTime::now(); self.complete_workunit_impl(workunit, time) } fn cancel_workunit(&self, workunit: Workunit) { workunit.log_workunit_state(true); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Canceled(workunit.span_id)) .unwrap(); } fn complete_workunit_impl(&self, mut workunit: Workunit, end_time: SystemTime) { let span_id = workunit.span_id; let new_metadata = Some(workunit.metadata.clone()); let tx = self.streaming_workunit_data.msg_tx.lock(); tx.send(StoreMsg::Completed(span_id, new_metadata.clone(), end_time)) .unwrap(); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Completed(span_id, new_metadata, end_time)) .unwrap(); let start_time = match workunit.state { WorkunitState::Started { start_time,.. } => start_time, _ => { log::warn!("Workunit {} was already completed", span_id); return; } }; let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; workunit.log_workunit_state(false); } pub fn add_completed_workunit( &self, name: String, start_time: SystemTime, end_time: SystemTime, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) { let span_id = SpanId::new(); let workunit = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time, blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self.complete_workunit_impl(workunit, end_time); } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { self.streaming_workunit_data.latest_workunits(max_verbosity) } pub fn increment_counter(&mut self, counter_name: Metric, change: u64) { self .metrics_data .counters .lock() .entry(counter_name) .and_modify(|e| *e += change) .or_insert(change); } pub fn get_metrics(&self) -> HashMap<&'static str, u64> { let counters = self.metrics_data.counters.lock(); counters .iter() .map(|(metric, value)| (metric.into(), *value)) .collect() } /// /// Records an observation of a time-like metric into a histogram. /// pub fn record_observation(&self, metric: ObservationMetric, value: u64) { let mut histograms_by_metric = self.metrics_data.observations.lock(); histograms_by_metric .entry(metric) .and_modify(|h| { let _ = h.record(value); }) .or_insert_with(|| { let mut h = hdrhistogram::Histogram::<u64>::new(3).expect("Failed to allocate histogram"); let _ = h.record(value); h }); } /// /// Return all observations in binary encoded format. /// pub fn encode_observations(&self) -> Result<HashMap<&'static str, Bytes>, String> { use hdrhistogram::serialization::V2DeflateSerializer; let mut serializer = V2DeflateSerializer::new(); let mut result = HashMap::new(); let histograms_by_metric = self.metrics_data.observations.lock(); for (metric, histogram) in histograms_by_metric.iter() { let mut writer = BytesMut::new().writer(); serializer
{ match self { WorkunitState::Completed { .. } => true, WorkunitState::Started { .. } => false, } }
identifier_body
lib.rs
the running Workunit as being in a blocked state. /// /// When the `in_workunit!` macro exits, the Workunit on the stack is completed by storing any /// local mutated values as the final value of the Workunit. /// #[derive(Clone, Debug)] pub struct Workunit { pub name: String, pub span_id: SpanId, pub parent_id: Option<SpanId>, pub state: WorkunitState, pub metadata: WorkunitMetadata, } impl Workunit { fn log_workunit_state(&self, canceled: bool) { if!log::log_enabled!(self.metadata.level) { return; } let state = match (&self.state, canceled) { (_, true) => "Canceled:", (WorkunitState::Started {.. }, _) => "Starting:", (WorkunitState::Completed {.. }, _) => "Completed:", }; let level = self.metadata.level; let identifier = if let Some(ref s) = self.metadata.desc { s.as_str() } else { self.name.as_str() }; /* This length calculation doesn't treat multi-byte unicode charcters identically * to single-byte ones for the purpose of figuring out where to truncate the string. But that's * ok, since we just want to truncate the log string if it's roughly "too long", we don't care * exactly what the max_len is or whether it effectively changes slightly if there are * multibyte unicode characters in the string */ let max_len = 200; let effective_identifier = if identifier.len() > max_len { let truncated_identifier: String = identifier.chars().take(max_len).collect(); let trunc = identifier.len() - max_len; format!( "{}... ({} characters truncated)", truncated_identifier, trunc ) } else { identifier.to_string() }; let message = if let Some(ref s) = self.metadata.message { format!(" - {}", s) } else { "".to_string() }; log!(level, "{} {}{}", state, effective_identifier, message); } } #[derive(Clone, Debug)] pub enum WorkunitState { Started { start_time: SystemTime, blocked: Arc<AtomicBool>, }, Completed { time_span: TimeSpan, }, } impl WorkunitState { fn completed(&self) -> bool { match self { WorkunitState::Completed {.. } => true, WorkunitState::Started {.. } => false, } } fn blocked(&self) -> bool { match self { WorkunitState::Started { blocked,.. } => blocked.load(atomic::Ordering::Relaxed), WorkunitState::Completed {.. } => false, } } } // NB: Only implemented for `fs::DirectoryDigest`, but is boxed to avoid a cycle between this crate // and the `fs` crate. pub trait DirectoryDigest: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } // NB: Only implemented for `Value`, but is boxed to avoid a cycle between this crate and the // `engine` crate. pub trait Value: Any + Debug + Send + Sync +'static { // See https://vorner.github.io/2020/08/02/fights-with-downcasting.html. fn as_any(&self) -> &dyn Any; } #[derive(Clone, Debug)] pub enum ArtifactOutput { FileDigest(hashing::Digest), Snapshot(Arc<dyn DirectoryDigest>), } #[derive(Clone, Debug)] pub struct WorkunitMetadata { pub desc: Option<String>, pub message: Option<String>, pub level: Level, pub stdout: Option<hashing::Digest>, pub stderr: Option<hashing::Digest>, pub artifacts: Vec<(String, ArtifactOutput)>, pub user_metadata: Vec<(String, UserMetadataItem)>, } impl Default for WorkunitMetadata { fn default() -> WorkunitMetadata { WorkunitMetadata { level: Level::Info, desc: None, message: None, stdout: None, stderr: None, artifacts: Vec::new(), user_metadata: Vec::new(), } } } /// Abstract id for passing user metadata items around #[derive(Clone, Debug)] pub enum UserMetadataItem { PyValue(Arc<dyn Value>), ImmediateInt(i64), ImmediateString(String), } enum StoreMsg { Started(Workunit), Completed(SpanId, Option<WorkunitMetadata>, SystemTime), Canceled(SpanId), } #[derive(Clone)] pub struct WorkunitStore { log_starting_workunits: bool, max_level: Level, streaming_workunit_data: StreamingWorkunitData, heavy_hitters_data: HeavyHittersData, metrics_data: Arc<MetricsData>, } #[derive(Clone)] struct StreamingWorkunitData { msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, workunit_records: Arc<Mutex<HashMap<SpanId, Workunit>>>, } impl StreamingWorkunitData { fn new() -> StreamingWorkunitData { let (msg_tx, msg_rx) = channel(); StreamingWorkunitData { msg_tx: Arc::new(Mutex::new(msg_tx)), msg_rx: Arc::new(Mutex::new(msg_rx)), workunit_records: Arc::new(Mutex::new(HashMap::new())), } } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { let should_emit = |workunit: &Workunit| -> bool { workunit.metadata.level <= max_verbosity }; let mut started_messages = vec![]; let mut completed_messages = vec![]; { let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() {
completed_messages.push((span, metadata, time)) } StoreMsg::Canceled(..) => (), } } } let mut workunit_records = self.workunit_records.lock(); let mut started_workunits: Vec<Workunit> = vec![]; for mut started in started_messages.into_iter() { let span_id = started.span_id; workunit_records.insert(span_id, started.clone()); if should_emit(&started) { started.parent_id = first_matched_parent(&workunit_records, started.parent_id, |_| false, should_emit); started_workunits.push(started); } } let mut completed_workunits: Vec<Workunit> = vec![]; for (span_id, new_metadata, end_time) in completed_messages.into_iter() { match workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); continue; } Entry::Occupied(o) => { let (span_id, mut workunit) = o.remove_entry(); let time_span = match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); continue; } WorkunitState::Started { start_time,.. } => { TimeSpan::from_start_and_end_systemtime(&start_time, &end_time) } }; let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } workunit_records.insert(span_id, workunit.clone()); if should_emit(&workunit) { workunit.parent_id = first_matched_parent( &workunit_records, workunit.parent_id, |_| false, should_emit, ); completed_workunits.push(workunit); } } } } (started_workunits, completed_workunits) } } #[derive(Clone)] struct HeavyHittersData { inner: Arc<Mutex<HeavyHittersInnerStore>>, msg_tx: Arc<Mutex<Sender<StoreMsg>>>, msg_rx: Arc<Mutex<Receiver<StoreMsg>>>, } impl HeavyHittersData { fn new() -> HeavyHittersData { let (msg_tx, msg_rx) = channel(); HeavyHittersData { inner: Arc::new(Mutex::new(HeavyHittersInnerStore { running_graph: RunningWorkunitGraph::new(), span_id_to_graph: HashMap::new(), workunit_records: HashMap::new(), })), msg_rx: Arc::new(Mutex::new(msg_rx)), msg_tx: Arc::new(Mutex::new(msg_tx)), } } fn add_started_workunit_to_store(started: Workunit, inner_store: &mut HeavyHittersInnerStore) { let span_id = started.span_id; let parent_id = started.parent_id; inner_store.workunit_records.insert(span_id, started); let child = inner_store.running_graph.add_node(span_id); inner_store.span_id_to_graph.insert(span_id, child); if let Some(parent_id) = parent_id { if let Some(parent) = inner_store.span_id_to_graph.get(&parent_id) { inner_store.running_graph.add_edge(*parent, child, ()); } } } fn add_completed_workunit_to_store( span_id: SpanId, new_metadata: Option<WorkunitMetadata>, end_time: SystemTime, inner_store: &mut HeavyHittersInnerStore, ) { if let Some(node) = inner_store.span_id_to_graph.remove(&span_id) { inner_store.running_graph.remove_node(node); } match inner_store.workunit_records.entry(span_id) { Entry::Vacant(_) => { log::warn!("No previously-started workunit found for id: {}", span_id); } Entry::Occupied(mut o) => { let workunit = o.get_mut(); match workunit.state { WorkunitState::Completed {.. } => { log::warn!("Workunit {} was already completed", span_id); } WorkunitState::Started { start_time,.. } => { let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); workunit.state = WorkunitState::Completed { time_span }; } }; if let Some(metadata) = new_metadata { workunit.metadata = metadata; } } } } fn refresh_store(&self) { let mut inner = self.inner.lock(); let receiver = self.msg_rx.lock(); while let Ok(msg) = receiver.try_recv() { match msg { StoreMsg::Started(started) => Self::add_started_workunit_to_store(started, &mut inner), StoreMsg::Completed(span_id, new_metadata, time) => { Self::add_completed_workunit_to_store(span_id, new_metadata, time, &mut inner) } StoreMsg::Canceled(span_id) => { inner.workunit_records.remove(&span_id); if let Some(node) = inner.span_id_to_graph.remove(&span_id) { inner.running_graph.remove_node(node); } } } } } fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.refresh_store(); let inner = self.inner.lock(); // Initialize the heap with the leaves of the running workunit graph, sorted oldest first. let mut queue: BinaryHeap<(Reverse<SystemTime>, SpanId)> = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| { let workunit: &Workunit = inner.workunit_records.get(&span_id)?; match workunit.state { WorkunitState::Started { ref blocked, start_time, .. } if!blocked.load(atomic::Ordering::Relaxed) => Some((Reverse(start_time), span_id)), _ => None, } }) .collect(); // Output the visible parents of the longest running leaves. let mut res = HashMap::new(); while let Some((_dur, span_id)) = queue.pop() { // If the leaf is visible or has a visible parent, emit it. let parent_span_id = if let Some(span_id) = first_matched_parent( &inner.workunit_records, Some(span_id), |wu| wu.state.completed(), Self::is_visible, ) { span_id } else { continue; }; let workunit = inner.workunit_records.get(&parent_span_id).unwrap(); if let Some(effective_name) = workunit.metadata.desc.as_ref() { if let Some(start_time) = Self::start_time_for(workunit) { res.insert(parent_span_id, (effective_name.to_string(), start_time)); if res.len() >= k { break; } } } } res } fn straggling_workunits(&self, duration_threshold: Duration) -> Vec<(Duration, String)> { self.refresh_store(); let now = SystemTime::now(); let inner = self.inner.lock(); let matching_visible_parents = inner .running_graph .externals(petgraph::Direction::Outgoing) .map(|entry| inner.running_graph[entry]) .flat_map(|span_id: SpanId| inner.workunit_records.get(&span_id)) .filter_map(|workunit| match Self::duration_for(now, workunit) { Some(duration) if!workunit.state.blocked() && duration >= duration_threshold => { first_matched_parent( &inner.workunit_records, Some(workunit.span_id), |wu| wu.state.completed(), Self::is_visible, ) .and_then(|span_id| inner.workunit_records.get(&span_id)) .and_then(|wu| wu.metadata.desc.as_ref()) .map(|desc| (desc.clone(), duration)) } _ => None, }) .collect::<HashMap<_, _>>(); if matching_visible_parents.is_empty() { return vec![]; } let mut stragglers = matching_visible_parents .into_iter() .map(|(k, v)| (v, k)) .collect::<Vec<_>>(); // NB: Because the Duration is first in the tuple, we get ascending Duration order. stragglers.sort(); stragglers } fn is_visible(workunit: &Workunit) -> bool { workunit.metadata.level <= Level::Debug && workunit.metadata.desc.is_some() && matches!(workunit.state, WorkunitState::Started {.. }) } fn start_time_for(workunit: &Workunit) -> Option<SystemTime> { match workunit.state { WorkunitState::Started { start_time,.. } => Some(start_time), _ => None, } } fn duration_for(now: SystemTime, workunit: &Workunit) -> Option<Duration> { now.duration_since(Self::start_time_for(workunit)?).ok() } } #[derive(Default)] pub struct HeavyHittersInnerStore { running_graph: RunningWorkunitGraph, span_id_to_graph: HashMap<SpanId, NodeIndex<u32>>, workunit_records: HashMap<SpanId, Workunit>, } fn first_matched_parent( workunit_records: &HashMap<SpanId, Workunit>, mut span_id: Option<SpanId>, is_terminal: impl Fn(&Workunit) -> bool, is_visible: impl Fn(&Workunit) -> bool, ) -> Option<SpanId> { while let Some(current_span_id) = span_id { let workunit = workunit_records.get(&current_span_id); if let Some(workunit) = workunit { // Should we continue visiting parents? if is_terminal(workunit) { break; } // Is the current workunit visible? if is_visible(workunit) { return Some(current_span_id); } } // If not, try its parent. span_id = workunit.and_then(|workunit| workunit.parent_id); } None } impl WorkunitStore { pub fn new(log_starting_workunits: bool, max_level: Level) -> WorkunitStore { WorkunitStore { log_starting_workunits, max_level, // TODO: Create one `StreamingWorkunitData` per subscriber, and zero if no subscribers are // installed. streaming_workunit_data: StreamingWorkunitData::new(), heavy_hitters_data: HeavyHittersData::new(), metrics_data: Arc::default(), } } pub fn init_thread_state(&self, parent_id: Option<SpanId>) { set_thread_workunit_store_handle(Some(WorkunitStoreHandle { store: self.clone(), parent_id, })) } pub fn max_level(&self) -> Level { self.max_level } /// /// Return visible workunits which have been running longer than the duration_threshold, sorted /// in ascending order by their duration. /// pub fn straggling_workunits(&self, threshold: Duration) -> Vec<(Duration, String)> { self.heavy_hitters_data.straggling_workunits(threshold) } /// /// Find the longest running leaf workunits, and return the description and start time of their /// first visible parents. /// pub fn heavy_hitters(&self, k: usize) -> HashMap<SpanId, (String, SystemTime)> { self.heavy_hitters_data.heavy_hitters(k) } fn start_workunit( &self, span_id: SpanId, name: String, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) -> Workunit { let started = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time: std::time::SystemTime::now(), blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(started.clone())) .unwrap(); if self.log_starting_workunits { started.log_workunit_state(false) } started } fn complete_workunit(&self, workunit: Workunit) { let time = std::time::SystemTime::now(); self.complete_workunit_impl(workunit, time) } fn cancel_workunit(&self, workunit: Workunit) { workunit.log_workunit_state(true); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Canceled(workunit.span_id)) .unwrap(); } fn complete_workunit_impl(&self, mut workunit: Workunit, end_time: SystemTime) { let span_id = workunit.span_id; let new_metadata = Some(workunit.metadata.clone()); let tx = self.streaming_workunit_data.msg_tx.lock(); tx.send(StoreMsg::Completed(span_id, new_metadata.clone(), end_time)) .unwrap(); self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Completed(span_id, new_metadata, end_time)) .unwrap(); let start_time = match workunit.state { WorkunitState::Started { start_time,.. } => start_time, _ => { log::warn!("Workunit {} was already completed", span_id); return; } }; let time_span = TimeSpan::from_start_and_end_systemtime(&start_time, &end_time); let new_state = WorkunitState::Completed { time_span }; workunit.state = new_state; workunit.log_workunit_state(false); } pub fn add_completed_workunit( &self, name: String, start_time: SystemTime, end_time: SystemTime, parent_id: Option<SpanId>, metadata: WorkunitMetadata, ) { let span_id = SpanId::new(); let workunit = Workunit { name, span_id, parent_id, state: WorkunitState::Started { start_time, blocked: Arc::new(AtomicBool::new(false)), }, metadata, }; self .heavy_hitters_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self .streaming_workunit_data .msg_tx .lock() .send(StoreMsg::Started(workunit.clone())) .unwrap(); self.complete_workunit_impl(workunit, end_time); } pub fn latest_workunits(&mut self, max_verbosity: log::Level) -> (Vec<Workunit>, Vec<Workunit>) { self.streaming_workunit_data.latest_workunits(max_verbosity) } pub fn increment_counter(&mut self, counter_name: Metric, change: u64) { self .metrics_data .counters .lock() .entry(counter_name) .and_modify(|e| *e += change) .or_insert(change); } pub fn get_metrics(&self) -> HashMap<&'static str, u64> { let counters = self.metrics_data.counters.lock(); counters .iter() .map(|(metric, value)| (metric.into(), *value)) .collect() } /// /// Records an observation of a time-like metric into a histogram. /// pub fn record_observation(&self, metric: ObservationMetric, value: u64) { let mut histograms_by_metric = self.metrics_data.observations.lock(); histograms_by_metric .entry(metric) .and_modify(|h| { let _ = h.record(value); }) .or_insert_with(|| { let mut h = hdrhistogram::Histogram::<u64>::new(3).expect("Failed to allocate histogram"); let _ = h.record(value); h }); } /// /// Return all observations in binary encoded format. /// pub fn encode_observations(&self) -> Result<HashMap<&'static str, Bytes>, String> { use hdrhistogram::serialization::V2DeflateSerializer; let mut serializer = V2DeflateSerializer::new(); let mut result = HashMap::new(); let histograms_by_metric = self.metrics_data.observations.lock(); for (metric, histogram) in histograms_by_metric.iter() { let mut writer = BytesMut::new().writer(); serializer .
match msg { StoreMsg::Started(started) => started_messages.push(started), StoreMsg::Completed(span, metadata, time) => {
random_line_split
builder.rs
use super::{op::*, Script}; use crate::{constants::MAX_SCRIPT_BYTE_SIZE, serializer::*}; type FnRef = (u8, u32); // ID, pointer #[derive(Clone, Debug, Default)] pub struct Builder { lookup_table: Vec<FnRef>, body: Vec<u8>, } impl Builder { pub fn new() -> Self { Self { lookup_table: Vec::new(), body: Vec::new(), } } /// Returns the script on success, otherwise an error with the total script size that has exceeded the max script /// byte size. pub fn build(self) -> Result<Script, usize>
); debug_assert_eq!( script.capacity(), total_len, "additional allocation was performed, total length is incorrect" ); Ok(Script::new(script)) } pub fn push(mut self, function: FnBuilder) -> Self { if self.lookup_table.len() + 1 > usize::from(u8::max_value()) { panic!("cannot push more than {} functions", u8::max_value()); } let byte_pos = self.body.len() as u32; self.lookup_table.push((function.id, byte_pos)); self.body.extend(&function.byte_code); self } } #[derive(Clone, Debug)] pub struct FnBuilder { id: u8, byte_code: Vec<u8>, } impl FnBuilder { /// Creates a function builder with the specified `id` and function definition `fn_def`. The function definition /// frame must represent an OpDefine operation. pub fn new(id: u8, fn_def: OpFrame) -> Self { let mut byte_code = vec![]; match fn_def { OpFrame::OpDefine(args) => { assert!( args.len() <= usize::from(u8::max_value()), "too many arguments provided" ); byte_code.push(Operand::OpDefine.into()); byte_code.push(args.len() as u8); for arg in args { byte_code.push(arg.into()); } } _ => panic!("expected a function definition"), } Self { id, byte_code } } pub fn push(mut self, frame: OpFrame) -> Self { match frame { // Function definition OpFrame::OpDefine(_) => panic!("OpDefine cannot be pushed in a function"), // Events OpFrame::OpTransfer => self.byte_code.push(Operand::OpTransfer.into()), // Push value OpFrame::False => self.byte_code.push(Operand::PushFalse.into()), OpFrame::True => self.byte_code.push(Operand::PushTrue.into()), OpFrame::PubKey(key) => { self.byte_code.push(Operand::PushPubKey.into()); self.byte_code.extend(key.as_ref()); } OpFrame::ScriptHash(hash) => { self.byte_code.push(Operand::PushScriptHash.into()); self.byte_code.extend(hash.as_ref()); } OpFrame::Asset(asset) => { self.byte_code.push(Operand::PushAsset.into()); self.byte_code.extend(&asset.amount.to_be_bytes()); } // Arithmetic OpFrame::OpLoadAmt => self.byte_code.push(Operand::OpLoadAmt.into()), OpFrame::OpLoadRemAmt => self.byte_code.push(Operand::OpLoadRemAmt.into()), OpFrame::OpAdd => self.byte_code.push(Operand::OpAdd.into()), OpFrame::OpSub => self.byte_code.push(Operand::OpSub.into()), OpFrame::OpMul => self.byte_code.push(Operand::OpMul.into()), OpFrame::OpDiv => self.byte_code.push(Operand::OpDiv.into()), // Logic OpFrame::OpNot => self.byte_code.push(Operand::OpNot.into()), OpFrame::OpIf => self.byte_code.push(Operand::OpIf.into()), OpFrame::OpElse => self.byte_code.push(Operand::OpElse.into()), OpFrame::OpEndIf => self.byte_code.push(Operand::OpEndIf.into()), OpFrame::OpReturn => self.byte_code.push(Operand::OpReturn.into()), // Crypto OpFrame::OpCheckSig => self.byte_code.push(Operand::OpCheckSig.into()), OpFrame::OpCheckSigFastFail => { self.byte_code.push(Operand::OpCheckSigFastFail.into()); } OpFrame::OpCheckMultiSig(threshold, key_count) => { self.byte_code .extend(&[Operand::OpCheckMultiSig.into(), threshold, key_count]); } OpFrame::OpCheckMultiSigFastFail(threshold, key_count) => self.byte_code.extend(&[ Operand::OpCheckMultiSigFastFail.into(), threshold, key_count, ]), } self } }
{ // 1 byte for fn len, 5 bytes for 1 byte id + 4 bytes pointer per fn let header_len = 1 + (self.lookup_table.len() * 5); let total_len = header_len + self.body.len(); if total_len > MAX_SCRIPT_BYTE_SIZE { return Err(total_len); } let mut script = Vec::<u8>::with_capacity(total_len); debug_assert!(self.lookup_table.len() <= u8::max_value() as usize); script.push(self.lookup_table.len() as u8); for fn_ref in self.lookup_table { script.push(fn_ref.0); // Offset the byte pointer by the length of the header script.push_u32(header_len as u32 + fn_ref.1); } script.extend(self.body); debug_assert_eq!( script.len(), total_len, "buffer capacity under utilized, total length is incorrect"
identifier_body