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
regex.rs
// Copyright (c) 2018 The predicates-rs Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
use crate::utils; use crate::Predicate; /// An error that occurred during parsing or compiling a regular expression. pub type RegexError = regex::Error; /// Predicate that uses regex matching /// /// This is created by the `predicate::str::is_match`. #[derive(Debug, Clone)] pub struct RegexPredicate { re: regex::Regex, } impl RegexPredicate { /// Require a specific count of matches. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::str::is_match("T[a-z]*").unwrap().count(3); /// assert_eq!(true, predicate_fn.eval("One Two Three Two One")); /// assert_eq!(false, predicate_fn.eval("One Two Three")); /// ``` pub fn count(self, count: usize) -> RegexMatchesPredicate { RegexMatchesPredicate { re: self.re, count } } } impl Predicate<str> for RegexPredicate { fn eval(&self, variable: &str) -> bool { self.re.is_match(variable) } fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> { utils::default_find_case(self, expected, variable) .map(|case| case.add_product(reflection::Product::new("var", variable.to_owned()))) } } impl reflection::PredicateReflection for RegexPredicate {} impl fmt::Display for RegexPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!( f, "{}.{}({})", palette.var.paint("var"), palette.description.paint("is_match"), palette.expected.paint(&self.re), ) } } /// Predicate that checks for repeated patterns. /// /// This is created by `predicates::str::is_match(...).count`. #[derive(Debug, Clone)] pub struct RegexMatchesPredicate { re: regex::Regex, count: usize, } impl Predicate<str> for RegexMatchesPredicate { fn eval(&self, variable: &str) -> bool { self.re.find_iter(variable).count() == self.count } fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> { let actual_count = self.re.find_iter(variable).count(); let result = self.count == actual_count; if result == expected { Some( reflection::Case::new(Some(self), result) .add_product(reflection::Product::new("var", variable.to_owned())) .add_product(reflection::Product::new("actual count", actual_count)), ) } else { None } } } impl reflection::PredicateReflection for RegexMatchesPredicate { fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> { let params = vec![reflection::Parameter::new("count", &self.count)]; Box::new(params.into_iter()) } } impl fmt::Display for RegexMatchesPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!( f, "{}.{}({})", palette.var.paint("var"), palette.description.paint("is_match"), palette.expected.paint(&self.re), ) } } /// Creates a new `Predicate` that uses a regular expression to match the string. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::str::is_match("^Hello.*$").unwrap(); /// assert_eq!(true, predicate_fn.eval("Hello World")); /// assert_eq!(false, predicate_fn.eval("Food World")); /// ``` pub fn is_match<S>(pattern: S) -> Result<RegexPredicate, RegexError> where S: AsRef<str>, { regex::Regex::new(pattern.as_ref()).map(|re| RegexPredicate { re }) }
// except according to those terms. use std::fmt; use crate::reflection;
random_line_split
packed-struct-vec.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#9116) Bus error use std::mem; #[repr(packed)] #[derive(Copy, PartialEq, Debug)] struct Foo { bar: u8, baz: u64 } pub fn main() { let foos = [Foo { bar: 1, baz: 2 }; 10]; assert_eq!(mem::size_of::<[Foo; 10]>(), 90); for i in 0u..10 { assert_eq!(foos[i], Foo { bar: 1, baz: 2}); } for &foo in &foos { assert_eq!(foo, Foo { bar: 1, baz: 2 }); } }
random_line_split
packed-struct-vec.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#9116) Bus error use std::mem; #[repr(packed)] #[derive(Copy, PartialEq, Debug)] struct Foo { bar: u8, baz: u64 } pub fn
() { let foos = [Foo { bar: 1, baz: 2 }; 10]; assert_eq!(mem::size_of::<[Foo; 10]>(), 90); for i in 0u..10 { assert_eq!(foos[i], Foo { bar: 1, baz: 2}); } for &foo in &foos { assert_eq!(foo, Foo { bar: 1, baz: 2 }); } }
main
identifier_name
mod.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
use core::unicode::property::Pattern_White_Space; use rustc::ty; use syntax_pos::Span; pub mod borrowck_errors; pub mod elaborate_drops; pub mod def_use; pub mod patch; mod alignment; mod graphviz; pub(crate) mod pretty; pub mod liveness; pub mod collect_writes; pub use self::alignment::is_disaligned; pub use self::pretty::{dump_enabled, dump_mir, write_mir_pretty, PassWhere}; pub use self::graphviz::{write_mir_graphviz}; pub use self::graphviz::write_node_label as write_graphviz_node_label; /// If possible, suggest replacing `ref` with `ref mut`. pub fn suggest_ref_mut<'cx, 'gcx, 'tcx>( tcx: ty::TyCtxt<'cx, 'gcx, 'tcx>, binding_span: Span, ) -> Option<(String)> { let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap(); if hi_src.starts_with("ref") && hi_src["ref".len()..].starts_with(Pattern_White_Space) { let replacement = format!("ref mut{}", &hi_src["ref".len()..]); Some(replacement) } else { None } }
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
mod.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::unicode::property::Pattern_White_Space; use rustc::ty; use syntax_pos::Span; pub mod borrowck_errors; pub mod elaborate_drops; pub mod def_use; pub mod patch; mod alignment; mod graphviz; pub(crate) mod pretty; pub mod liveness; pub mod collect_writes; pub use self::alignment::is_disaligned; pub use self::pretty::{dump_enabled, dump_mir, write_mir_pretty, PassWhere}; pub use self::graphviz::{write_mir_graphviz}; pub use self::graphviz::write_node_label as write_graphviz_node_label; /// If possible, suggest replacing `ref` with `ref mut`. pub fn
<'cx, 'gcx, 'tcx>( tcx: ty::TyCtxt<'cx, 'gcx, 'tcx>, binding_span: Span, ) -> Option<(String)> { let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap(); if hi_src.starts_with("ref") && hi_src["ref".len()..].starts_with(Pattern_White_Space) { let replacement = format!("ref mut{}", &hi_src["ref".len()..]); Some(replacement) } else { None } }
suggest_ref_mut
identifier_name
mod.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::unicode::property::Pattern_White_Space; use rustc::ty; use syntax_pos::Span; pub mod borrowck_errors; pub mod elaborate_drops; pub mod def_use; pub mod patch; mod alignment; mod graphviz; pub(crate) mod pretty; pub mod liveness; pub mod collect_writes; pub use self::alignment::is_disaligned; pub use self::pretty::{dump_enabled, dump_mir, write_mir_pretty, PassWhere}; pub use self::graphviz::{write_mir_graphviz}; pub use self::graphviz::write_node_label as write_graphviz_node_label; /// If possible, suggest replacing `ref` with `ref mut`. pub fn suggest_ref_mut<'cx, 'gcx, 'tcx>( tcx: ty::TyCtxt<'cx, 'gcx, 'tcx>, binding_span: Span, ) -> Option<(String)> { let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap(); if hi_src.starts_with("ref") && hi_src["ref".len()..].starts_with(Pattern_White_Space) { let replacement = format!("ref mut{}", &hi_src["ref".len()..]); Some(replacement) } else
}
{ None }
conditional_block
mod.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::unicode::property::Pattern_White_Space; use rustc::ty; use syntax_pos::Span; pub mod borrowck_errors; pub mod elaborate_drops; pub mod def_use; pub mod patch; mod alignment; mod graphviz; pub(crate) mod pretty; pub mod liveness; pub mod collect_writes; pub use self::alignment::is_disaligned; pub use self::pretty::{dump_enabled, dump_mir, write_mir_pretty, PassWhere}; pub use self::graphviz::{write_mir_graphviz}; pub use self::graphviz::write_node_label as write_graphviz_node_label; /// If possible, suggest replacing `ref` with `ref mut`. pub fn suggest_ref_mut<'cx, 'gcx, 'tcx>( tcx: ty::TyCtxt<'cx, 'gcx, 'tcx>, binding_span: Span, ) -> Option<(String)>
{ let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap(); if hi_src.starts_with("ref") && hi_src["ref".len()..].starts_with(Pattern_White_Space) { let replacement = format!("ref mut{}", &hi_src["ref".len()..]); Some(replacement) } else { None } }
identifier_body
block_status.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Block status description module use verification::queue::Status as QueueStatus; /// General block status #[derive(Debug, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub enum
{ /// Part of the blockchain. InChain, /// Queued for import. Queued, /// Known as bad. Bad, /// Unknown. Unknown, } impl From<QueueStatus> for BlockStatus { fn from(status: QueueStatus) -> Self { match status { QueueStatus::Queued => BlockStatus::Queued, QueueStatus::Bad => BlockStatus::Bad, QueueStatus::Unknown => BlockStatus::Unknown, } } }
BlockStatus
identifier_name
block_status.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Block status description module use verification::queue::Status as QueueStatus; /// General block status #[derive(Debug, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub enum BlockStatus { /// Part of the blockchain. InChain, /// Queued for import. Queued, /// Known as bad. Bad, /// Unknown. Unknown, } impl From<QueueStatus> for BlockStatus { fn from(status: QueueStatus) -> Self { match status { QueueStatus::Queued => BlockStatus::Queued, QueueStatus::Bad => BlockStatus::Bad, QueueStatus::Unknown => BlockStatus::Unknown, } } }
// (at your option) any later version. // Parity is distributed in the hope that it will be useful,
random_line_split
config.rs
use std::collections::{HashMap, HashSet, BTreeMap}; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use crate::types::*; use serde_json; use pombase_rc_string::RcString; // configuration for extension display names and for the "Target of" section #[derive(Deserialize, Clone, Debug)] pub struct ExtensionDisplayNames { pub rel_name: RcString, // name of extension relation pub display_name: RcString, // text to display pub if_descendant_of: Option<RcString>, // None if applies to any extension pub reciprocal_display: Option<RcString>, // None if reciprocal shouldn't be displayed } // "interesting parents" are those stored in the JSON in the TermShort structs #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct InterestingParent { pub termid: RcString, pub rel_name: RcString, } // the order of relations within an extension: #[derive(Deserialize, Clone, Debug)] pub struct RelationOrder { // put the relations in this order in the displayed extensions: pub relation_order: Vec<RcString>, // except for these reactions which should always come last: pub always_last: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct AncestorFilterCategory { pub display_name: RcString, // this category matches these terms and their descendants pub ancestors: Vec<TermId>, } #[derive(Deserialize, Clone, Debug)] pub struct FilterConfig { pub filter_name: String, pub display_name: String, #[serde(skip_serializing_if="Vec::is_empty", default)] pub term_categories: Vec<AncestorFilterCategory>, #[serde(skip_serializing_if="Option::is_none", default)] pub slim_name: Option<RcString>, #[serde(skip_serializing_if="Vec::is_empty", default)] pub extension_categories: Vec<AncestorFilterCategory>, } #[derive(Deserialize, Clone, Debug)] pub struct SplitByParentsConfig { pub termids: Vec<RcString>, pub display_name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct ChromosomeConfig { pub name: RcString, // string to use for this chromosome in a file name, eg. "chromosome_II" // or "mitochondrial_chromosome" pub export_file_id: RcString, // string to use within files, eg. "II" or "mitochondrial" pub export_id: RcString, // eg. "Chromosome II" or "Mitochondrial chromosome" pub long_display_name: RcString, // eg. "II" or "Mitochondrial" pub short_display_name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct CvSourceConfig { // a type name for the cvtermprop to display to the user pub display_name_prop: Option<RcString>, // the cvtermprop type name for the ID used for linking // or "ACCESSION" if the accession ID of the term should be used pub id_source: Option<RcString>, } pub type TargetRelationName = String; #[derive(Deserialize, Clone, Debug)] pub struct TargetOfConfig { // these priorities are used to order the list in the "Target of" section // and to filter the "Target of" summary // https://github.com/pombase/website/issues/299 pub relation_priority: HashMap<TargetRelationName, u32>, } #[derive(Deserialize, Clone, Debug)] pub struct CvConfig { pub feature_type: RcString, pub display_name: Option<RcString>, // filtering configured per CV #[serde(skip_serializing_if="Vec::is_empty", default)] pub filters: Vec<FilterConfig>, // config for splitting cv annotation tables into sub-sections // based on ancestry #[serde(skip_serializing_if="Vec::is_empty", default)] pub split_by_parents: Vec<SplitByParentsConfig>, // relations to not show in the summary #[serde(skip_serializing_if="Vec::is_empty", default)] pub summary_relations_to_hide: Vec<RcString>, // relations where the range is a gene ID to display like: // has substrate pom1, cdc1 involved in negative regulation of... // rather than as two lines #[serde(skip_serializing_if="Vec::is_empty", default)] pub summary_relation_ranges_to_collect: Vec<RcString>, #[serde(default="SingleOrMultiLocusConfig::not_applicable")] pub single_or_multi_locus: SingleOrMultiLocusConfig, // the field to sort by #[serde(skip_serializing_if="Option::is_none")] pub sort_details_by: Option<Vec<RcString>>, // This is the configuration for the "Source" column, a map from // source name to config // See Disease association for an example. If there is no config // there will be no Source column will be displayed #[serde(skip_serializing_if="HashMap::is_empty", default)] pub source_config: HashMap<RcString, CvSourceConfig>, } pub type ShortEvidenceCode = RcString; pub type LongEvidenceCode = RcString; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct ConfigOrganism { pub taxonid: OrganismTaxonId, pub genus: RcString, pub species: RcString, pub alternative_names: Vec<RcString>, pub assembly_version: Option<RcString>, } impl ConfigOrganism { pub fn full_name(&self) -> String { self.genus.clone() + "_" + self.species.as_str() } pub fn scientific_name(&self) -> String { self.genus.clone() + " " + self.species.as_str() } } #[derive(Deserialize, Clone, Debug)] pub struct ViabilityTerms { pub viable: RcString, pub inviable: RcString, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct TermAndName { pub termid: RcString, pub name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct ReferencePageConfig { pub triage_status_to_ignore: Vec<String>, } #[derive(Deserialize, Clone, Debug)] pub struct InterPro { pub dbnames_to_filter: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct ServerSubsetConfig { pub prefixes_to_remove: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct ServerConfig { pub subsets: ServerSubsetConfig, pub solr_url: String, pub close_synonym_boost: f32, pub distant_synonym_boost: f32, pub term_definition_boost: f32, pub django_url: String, pub cv_name_for_terms_search: String, pub gene_uniquename_re: String, } #[derive(Deserialize, Clone, Debug)] pub struct EvidenceDetails { pub long: LongEvidenceCode, pub link: Option<RcString>, } pub type DatabaseName = RcString; pub type DatabaseAliases = HashMap<DatabaseName, DatabaseName>; #[derive(Deserialize, Clone, Debug)] pub struct MacromolecularComplexesConfig { pub parent_complex_termid: RcString, pub excluded_terms: HashSet<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct RNAcentralConfig { // SO termids of RNA features to export pub export_so_ids: HashSet<RcString>, } #[derive(Deserialize, Clone, Debug, PartialEq)] pub enum SingleOrMultiLocusConfig { #[serde(rename = "single")] Single, #[serde(rename = "multi")] Multi, #[serde(rename = "na")] NotApplicable } impl SingleOrMultiLocusConfig { pub fn not_applicable() -> SingleOrMultiLocusConfig { SingleOrMultiLocusConfig::NotApplicable } } #[derive(Deserialize, Clone, Debug)] pub struct ExportColumnConfig { pub name: RcString, pub display_name: RcString } #[derive(Deserialize, Clone, Debug)] pub struct AnnotationSubsetConfig { pub term_ids: Vec<TermId>, pub file_name: RcString, pub columns: Vec<ExportColumnConfig>, #[serde(default="SingleOrMultiLocusConfig::not_applicable")] pub single_or_multi_locus: SingleOrMultiLocusConfig, } #[derive(Deserialize, Clone, Debug)] pub struct GpadGpiConfig { // the term IDs of the three GO aspects pub go_aspect_terms: HashMap<String, TermId>, // Map a relation term name to a term ID, unless the term ID is None in // which case we skip writing this extension part pub extension_relation_mappings: HashMap<String, Option<TermId>>, // A map from the SO type of a transcript to the SO type of the gene is // derives from pub transcript_gene_so_term_map: HashMap<String, String>, } #[derive(Deserialize, Clone, Debug)] pub struct FileExportConfig { pub site_map_term_prefixes: Vec<RcString>, pub site_map_reference_prefixes: Vec<RcString>, #[serde(skip_serializing_if="Option::is_none")] pub macromolecular_complexes: Option<MacromolecularComplexesConfig>, #[serde(skip_serializing_if="Option::is_none")] pub rnacentral: Option<RNAcentralConfig>, pub annotation_subsets: Vec<AnnotationSubsetConfig>, pub gpad_gpi: GpadGpiConfig, // the reference to use for ND lines in GPAD/GAF output pub nd_reference: String, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultVisAttrValueConfig { pub termid: Option<RcString>, pub name: RcString, pub bin_start: Option<usize>, pub bin_end: Option<usize>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultVisColumnConfig { #[serde(skip_serializing_if="Vec::is_empty", default)] pub attr_values: Vec<GeneResultVisAttrValueConfig>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultsConfig { pub field_config: HashMap<RcString, GeneResultVisColumnConfig>, pub visualisation_field_names: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct SlimConfig { pub slim_display_name: RcString, pub cv_name: RcString, pub terms: Vec<TermAndName>, } #[derive(Deserialize, Clone, Debug)] pub struct SeqFeaturePageConfig { pub so_types_to_show: Vec<String>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneExDatasetConfig { pub name: RcString, pub pubmed_id: RcString, pub level_type_termid: RcString, pub during_termid: RcString, pub scale: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct GeneExpressionConfig { pub datasets: Vec<GeneExDatasetConfig>, } #[derive(Deserialize, Clone, Debug)] pub struct Config { pub database_name: RcString, pub database_long_name: RcString, pub database_citation: RcString, pub funder: RcString, pub site_description: RcString, pub load_organism_taxonid: Option<OrganismTaxonId>, pub base_url: RcString, pub helpdesk_address: RcString, pub doc_page_aliases: HashMap<String, String>, pub organisms: Vec<ConfigOrganism>, pub api_seq_chunk_sizes: Vec<usize>, pub sequence_feature_page: SeqFeaturePageConfig, pub extension_display_names: Vec<ExtensionDisplayNames>, pub extension_relation_order: RelationOrder, pub evidence_types: HashMap<ShortEvidenceCode, EvidenceDetails>, pub cv_config: HashMap<CvName, CvConfig>, pub target_of_config: TargetOfConfig, // when creating a TermShort struct, for each of these termids if the term has // an "interesting parent" using the given rel_name, we store it in the // interesting_parents field of the TermShort pub interesting_parents: Vec<InterestingParent>, pub viability_terms: ViabilityTerms, // slim sets by slim name: pub slims: HashMap<RcString, SlimConfig>, pub reference_page_config: ReferencePageConfig, pub interpro: InterPro, pub server: ServerConfig, pub extra_database_aliases: DatabaseAliases, pub chromosomes: Vec<ChromosomeConfig>, pub gene_results: GeneResultsConfig, pub ortholog_taxonids: HashSet<u32>, pub file_exports: FileExportConfig, pub gene_expression: GeneExpressionConfig, } impl Config { pub fn read(config_file_name: &str) -> Config { let file = match File::open(config_file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", config_file_name, err) } }; let reader = BufReader::new(file); match serde_json::from_reader(reader) { Ok(config) => config, Err(err) => { panic!("failed to parse {}: {}", config_file_name, err) }, } } pub fn cv_config_by_name(&self, cv_name: &str) -> CvConfig { if let Some(config) = self.cv_config.get(cv_name) { config.clone() } else { let empty_cv_config = CvConfig { feature_type: "".into(), display_name: Some("".into()), single_or_multi_locus: SingleOrMultiLocusConfig::NotApplicable, filters: vec![], split_by_parents: vec![], summary_relations_to_hide: vec![], summary_relation_ranges_to_collect: vec![], sort_details_by: None, source_config: HashMap::new(), }; if cv_name.starts_with("extension:") { if cv_name.ends_with(":gene") { CvConfig { feature_type: "gene".into(), ..empty_cv_config } } else { CvConfig { feature_type: "genotype".into(), ..empty_cv_config } } } else { CvConfig { feature_type: "gene".into(), ..empty_cv_config } } } } pub fn organism_by_taxonid(&self, lookup_taxonid: u32) -> Option<ConfigOrganism> { for org in &self.organisms { if org.taxonid == lookup_taxonid { return Some(org.clone()); } } None } pub fn
(&self) -> Option<ConfigOrganism> { if let Some(load_organism_taxonid) = self.load_organism_taxonid { let org = self.organism_by_taxonid(load_organism_taxonid); if org.is_none() { panic!("can't find configuration for load_organism_taxonid: {}", load_organism_taxonid); } org } else { None } } pub fn find_chromosome_config<'a>(&'a self, chromosome_name: &str) -> &'a ChromosomeConfig { for chr_config in &self.chromosomes { if chr_config.name == chromosome_name { return chr_config; } } panic!("can't find chromosome configuration for {}", &chromosome_name); } } pub const POMBASE_ANN_EXT_TERM_CV_NAME: &str = "PomBase annotation extension terms"; pub const ANNOTATION_EXT_REL_PREFIX: &str = "annotation_extension_relation-"; pub enum FeatureRelAnnotationType { Interaction, Ortholog, Paralog, } pub struct FeatureRelConfig { pub rel_type_name: &'static str, pub annotation_type: FeatureRelAnnotationType, } pub const FEATURE_REL_CONFIGS: [FeatureRelConfig; 4] = [ FeatureRelConfig { rel_type_name: "interacts_physically", annotation_type: FeatureRelAnnotationType::Interaction, }, FeatureRelConfig { rel_type_name: "interacts_genetically", annotation_type: FeatureRelAnnotationType::Interaction, }, FeatureRelConfig { rel_type_name: "orthologous_to", annotation_type: FeatureRelAnnotationType::Ortholog, }, FeatureRelConfig { rel_type_name: "paralogous_to", annotation_type: FeatureRelAnnotationType::Paralog, }, ]; // relations to use when copy annotation to parents (ie. adding the // annotation of child terms to parents) pub const DESCENDANT_REL_NAMES: [&str; 7] = ["is_a", "part_of", "regulates", "positively_regulates", "negatively_regulates", "has_part", "output_of"]; // only consider has_part relations for these ontologies: pub const HAS_PART_CV_NAMES: [&str; 1] = ["fission_yeast_phenotype"]; // number of genes before (and after) to add to the gene_neighbourhood field pub const GENE_NEIGHBOURHOOD_DISTANCE: usize = 5; pub const TRANSCRIPT_FEATURE_TYPES: [&str; 8] = ["snRNA", "rRNA", "mRNA", "snoRNA", "ncRNA", "tRNA", "pseudogenic_transcript", "transcript"]; pub const TRANSCRIPT_PART_TYPES: [&str; 4] = ["five_prime_UTR", "exon", "pseudogenic_exon", "three_prime_UTR"]; // any feature with a type not in this list or in the two TRANSCRIPT lists above // will be stored in the other_features map pub const HANDLED_FEATURE_TYPES: [&str; 7] = ["gene", "pseudogene", "intron", "genotype", "allele", "chromosome", "polypeptide"]; #[derive(Deserialize, Clone, Debug)] pub struct DocConfig { pub pages: BTreeMap<RcString, RcString>, } impl DocConfig { pub fn read(doc_config_file_name: &str) -> DocConfig { let file = match File::open(doc_config_file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", doc_config_file_name, err) } }; let reader = BufReader::new(file); match serde_json::from_reader(reader) { Ok(config) => config, Err(err) => { panic!("failed to parse {}: {}", doc_config_file_name, err) }, } } } pub struct GoEcoMapping { mapping: HashMap<(String, String), String>, } impl GoEcoMapping { pub fn read(file_name: &str) -> Result<GoEcoMapping, std::io::Error> { let file = match File::open(file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", file_name, err) } }; let reader = BufReader::new(file); let mut mapping = HashMap::new(); for line_result in reader.lines() { match line_result { Ok(line) => { if line.starts_with('#') { continue; } let parts: Vec<&str> = line.split('\t').collect(); mapping.insert((String::from(parts[0]), String::from(parts[1])), String::from(parts[2])); }, Err(err) => return Err(err) }; } Ok(GoEcoMapping { mapping }) } pub fn lookup_default(&self, go_evidence_code: &str) -> Option<String> { self.mapping.get(&(String::from(go_evidence_code), String::from("Default"))) .map(String::from) } pub fn lookup_with_go_ref(&self, go_evidence_code: &str, go_ref: &str) -> Option<String> { self.mapping.get(&(String::from(go_evidence_code), String::from(go_ref))) .map(String::from) } }
load_organism
identifier_name
config.rs
use std::collections::{HashMap, HashSet, BTreeMap}; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use crate::types::*; use serde_json; use pombase_rc_string::RcString; // configuration for extension display names and for the "Target of" section #[derive(Deserialize, Clone, Debug)] pub struct ExtensionDisplayNames { pub rel_name: RcString, // name of extension relation pub display_name: RcString, // text to display pub if_descendant_of: Option<RcString>, // None if applies to any extension pub reciprocal_display: Option<RcString>, // None if reciprocal shouldn't be displayed } // "interesting parents" are those stored in the JSON in the TermShort structs #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct InterestingParent { pub termid: RcString, pub rel_name: RcString, } // the order of relations within an extension: #[derive(Deserialize, Clone, Debug)] pub struct RelationOrder { // put the relations in this order in the displayed extensions: pub relation_order: Vec<RcString>, // except for these reactions which should always come last: pub always_last: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct AncestorFilterCategory { pub display_name: RcString, // this category matches these terms and their descendants pub ancestors: Vec<TermId>, } #[derive(Deserialize, Clone, Debug)] pub struct FilterConfig { pub filter_name: String, pub display_name: String, #[serde(skip_serializing_if="Vec::is_empty", default)] pub term_categories: Vec<AncestorFilterCategory>, #[serde(skip_serializing_if="Option::is_none", default)] pub slim_name: Option<RcString>, #[serde(skip_serializing_if="Vec::is_empty", default)] pub extension_categories: Vec<AncestorFilterCategory>, } #[derive(Deserialize, Clone, Debug)] pub struct SplitByParentsConfig { pub termids: Vec<RcString>, pub display_name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct ChromosomeConfig { pub name: RcString, // string to use for this chromosome in a file name, eg. "chromosome_II" // or "mitochondrial_chromosome" pub export_file_id: RcString, // string to use within files, eg. "II" or "mitochondrial" pub export_id: RcString, // eg. "Chromosome II" or "Mitochondrial chromosome" pub long_display_name: RcString, // eg. "II" or "Mitochondrial" pub short_display_name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct CvSourceConfig { // a type name for the cvtermprop to display to the user pub display_name_prop: Option<RcString>, // the cvtermprop type name for the ID used for linking // or "ACCESSION" if the accession ID of the term should be used pub id_source: Option<RcString>, } pub type TargetRelationName = String; #[derive(Deserialize, Clone, Debug)] pub struct TargetOfConfig { // these priorities are used to order the list in the "Target of" section // and to filter the "Target of" summary // https://github.com/pombase/website/issues/299 pub relation_priority: HashMap<TargetRelationName, u32>, } #[derive(Deserialize, Clone, Debug)] pub struct CvConfig { pub feature_type: RcString, pub display_name: Option<RcString>, // filtering configured per CV #[serde(skip_serializing_if="Vec::is_empty", default)] pub filters: Vec<FilterConfig>, // config for splitting cv annotation tables into sub-sections // based on ancestry #[serde(skip_serializing_if="Vec::is_empty", default)] pub split_by_parents: Vec<SplitByParentsConfig>, // relations to not show in the summary #[serde(skip_serializing_if="Vec::is_empty", default)] pub summary_relations_to_hide: Vec<RcString>, // relations where the range is a gene ID to display like: // has substrate pom1, cdc1 involved in negative regulation of... // rather than as two lines #[serde(skip_serializing_if="Vec::is_empty", default)] pub summary_relation_ranges_to_collect: Vec<RcString>, #[serde(default="SingleOrMultiLocusConfig::not_applicable")] pub single_or_multi_locus: SingleOrMultiLocusConfig, // the field to sort by #[serde(skip_serializing_if="Option::is_none")] pub sort_details_by: Option<Vec<RcString>>, // This is the configuration for the "Source" column, a map from // source name to config // See Disease association for an example. If there is no config // there will be no Source column will be displayed #[serde(skip_serializing_if="HashMap::is_empty", default)] pub source_config: HashMap<RcString, CvSourceConfig>, } pub type ShortEvidenceCode = RcString; pub type LongEvidenceCode = RcString; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct ConfigOrganism { pub taxonid: OrganismTaxonId, pub genus: RcString, pub species: RcString, pub alternative_names: Vec<RcString>, pub assembly_version: Option<RcString>, } impl ConfigOrganism { pub fn full_name(&self) -> String { self.genus.clone() + "_" + self.species.as_str() } pub fn scientific_name(&self) -> String { self.genus.clone() + " " + self.species.as_str() } } #[derive(Deserialize, Clone, Debug)] pub struct ViabilityTerms { pub viable: RcString, pub inviable: RcString, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct TermAndName { pub termid: RcString, pub name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct ReferencePageConfig { pub triage_status_to_ignore: Vec<String>, } #[derive(Deserialize, Clone, Debug)] pub struct InterPro { pub dbnames_to_filter: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct ServerSubsetConfig { pub prefixes_to_remove: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct ServerConfig { pub subsets: ServerSubsetConfig, pub solr_url: String, pub close_synonym_boost: f32, pub distant_synonym_boost: f32, pub term_definition_boost: f32, pub django_url: String, pub cv_name_for_terms_search: String, pub gene_uniquename_re: String, } #[derive(Deserialize, Clone, Debug)] pub struct EvidenceDetails { pub long: LongEvidenceCode,
#[derive(Deserialize, Clone, Debug)] pub struct MacromolecularComplexesConfig { pub parent_complex_termid: RcString, pub excluded_terms: HashSet<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct RNAcentralConfig { // SO termids of RNA features to export pub export_so_ids: HashSet<RcString>, } #[derive(Deserialize, Clone, Debug, PartialEq)] pub enum SingleOrMultiLocusConfig { #[serde(rename = "single")] Single, #[serde(rename = "multi")] Multi, #[serde(rename = "na")] NotApplicable } impl SingleOrMultiLocusConfig { pub fn not_applicable() -> SingleOrMultiLocusConfig { SingleOrMultiLocusConfig::NotApplicable } } #[derive(Deserialize, Clone, Debug)] pub struct ExportColumnConfig { pub name: RcString, pub display_name: RcString } #[derive(Deserialize, Clone, Debug)] pub struct AnnotationSubsetConfig { pub term_ids: Vec<TermId>, pub file_name: RcString, pub columns: Vec<ExportColumnConfig>, #[serde(default="SingleOrMultiLocusConfig::not_applicable")] pub single_or_multi_locus: SingleOrMultiLocusConfig, } #[derive(Deserialize, Clone, Debug)] pub struct GpadGpiConfig { // the term IDs of the three GO aspects pub go_aspect_terms: HashMap<String, TermId>, // Map a relation term name to a term ID, unless the term ID is None in // which case we skip writing this extension part pub extension_relation_mappings: HashMap<String, Option<TermId>>, // A map from the SO type of a transcript to the SO type of the gene is // derives from pub transcript_gene_so_term_map: HashMap<String, String>, } #[derive(Deserialize, Clone, Debug)] pub struct FileExportConfig { pub site_map_term_prefixes: Vec<RcString>, pub site_map_reference_prefixes: Vec<RcString>, #[serde(skip_serializing_if="Option::is_none")] pub macromolecular_complexes: Option<MacromolecularComplexesConfig>, #[serde(skip_serializing_if="Option::is_none")] pub rnacentral: Option<RNAcentralConfig>, pub annotation_subsets: Vec<AnnotationSubsetConfig>, pub gpad_gpi: GpadGpiConfig, // the reference to use for ND lines in GPAD/GAF output pub nd_reference: String, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultVisAttrValueConfig { pub termid: Option<RcString>, pub name: RcString, pub bin_start: Option<usize>, pub bin_end: Option<usize>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultVisColumnConfig { #[serde(skip_serializing_if="Vec::is_empty", default)] pub attr_values: Vec<GeneResultVisAttrValueConfig>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultsConfig { pub field_config: HashMap<RcString, GeneResultVisColumnConfig>, pub visualisation_field_names: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct SlimConfig { pub slim_display_name: RcString, pub cv_name: RcString, pub terms: Vec<TermAndName>, } #[derive(Deserialize, Clone, Debug)] pub struct SeqFeaturePageConfig { pub so_types_to_show: Vec<String>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneExDatasetConfig { pub name: RcString, pub pubmed_id: RcString, pub level_type_termid: RcString, pub during_termid: RcString, pub scale: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct GeneExpressionConfig { pub datasets: Vec<GeneExDatasetConfig>, } #[derive(Deserialize, Clone, Debug)] pub struct Config { pub database_name: RcString, pub database_long_name: RcString, pub database_citation: RcString, pub funder: RcString, pub site_description: RcString, pub load_organism_taxonid: Option<OrganismTaxonId>, pub base_url: RcString, pub helpdesk_address: RcString, pub doc_page_aliases: HashMap<String, String>, pub organisms: Vec<ConfigOrganism>, pub api_seq_chunk_sizes: Vec<usize>, pub sequence_feature_page: SeqFeaturePageConfig, pub extension_display_names: Vec<ExtensionDisplayNames>, pub extension_relation_order: RelationOrder, pub evidence_types: HashMap<ShortEvidenceCode, EvidenceDetails>, pub cv_config: HashMap<CvName, CvConfig>, pub target_of_config: TargetOfConfig, // when creating a TermShort struct, for each of these termids if the term has // an "interesting parent" using the given rel_name, we store it in the // interesting_parents field of the TermShort pub interesting_parents: Vec<InterestingParent>, pub viability_terms: ViabilityTerms, // slim sets by slim name: pub slims: HashMap<RcString, SlimConfig>, pub reference_page_config: ReferencePageConfig, pub interpro: InterPro, pub server: ServerConfig, pub extra_database_aliases: DatabaseAliases, pub chromosomes: Vec<ChromosomeConfig>, pub gene_results: GeneResultsConfig, pub ortholog_taxonids: HashSet<u32>, pub file_exports: FileExportConfig, pub gene_expression: GeneExpressionConfig, } impl Config { pub fn read(config_file_name: &str) -> Config { let file = match File::open(config_file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", config_file_name, err) } }; let reader = BufReader::new(file); match serde_json::from_reader(reader) { Ok(config) => config, Err(err) => { panic!("failed to parse {}: {}", config_file_name, err) }, } } pub fn cv_config_by_name(&self, cv_name: &str) -> CvConfig { if let Some(config) = self.cv_config.get(cv_name) { config.clone() } else { let empty_cv_config = CvConfig { feature_type: "".into(), display_name: Some("".into()), single_or_multi_locus: SingleOrMultiLocusConfig::NotApplicable, filters: vec![], split_by_parents: vec![], summary_relations_to_hide: vec![], summary_relation_ranges_to_collect: vec![], sort_details_by: None, source_config: HashMap::new(), }; if cv_name.starts_with("extension:") { if cv_name.ends_with(":gene") { CvConfig { feature_type: "gene".into(), ..empty_cv_config } } else { CvConfig { feature_type: "genotype".into(), ..empty_cv_config } } } else { CvConfig { feature_type: "gene".into(), ..empty_cv_config } } } } pub fn organism_by_taxonid(&self, lookup_taxonid: u32) -> Option<ConfigOrganism> { for org in &self.organisms { if org.taxonid == lookup_taxonid { return Some(org.clone()); } } None } pub fn load_organism(&self) -> Option<ConfigOrganism> { if let Some(load_organism_taxonid) = self.load_organism_taxonid { let org = self.organism_by_taxonid(load_organism_taxonid); if org.is_none() { panic!("can't find configuration for load_organism_taxonid: {}", load_organism_taxonid); } org } else { None } } pub fn find_chromosome_config<'a>(&'a self, chromosome_name: &str) -> &'a ChromosomeConfig { for chr_config in &self.chromosomes { if chr_config.name == chromosome_name { return chr_config; } } panic!("can't find chromosome configuration for {}", &chromosome_name); } } pub const POMBASE_ANN_EXT_TERM_CV_NAME: &str = "PomBase annotation extension terms"; pub const ANNOTATION_EXT_REL_PREFIX: &str = "annotation_extension_relation-"; pub enum FeatureRelAnnotationType { Interaction, Ortholog, Paralog, } pub struct FeatureRelConfig { pub rel_type_name: &'static str, pub annotation_type: FeatureRelAnnotationType, } pub const FEATURE_REL_CONFIGS: [FeatureRelConfig; 4] = [ FeatureRelConfig { rel_type_name: "interacts_physically", annotation_type: FeatureRelAnnotationType::Interaction, }, FeatureRelConfig { rel_type_name: "interacts_genetically", annotation_type: FeatureRelAnnotationType::Interaction, }, FeatureRelConfig { rel_type_name: "orthologous_to", annotation_type: FeatureRelAnnotationType::Ortholog, }, FeatureRelConfig { rel_type_name: "paralogous_to", annotation_type: FeatureRelAnnotationType::Paralog, }, ]; // relations to use when copy annotation to parents (ie. adding the // annotation of child terms to parents) pub const DESCENDANT_REL_NAMES: [&str; 7] = ["is_a", "part_of", "regulates", "positively_regulates", "negatively_regulates", "has_part", "output_of"]; // only consider has_part relations for these ontologies: pub const HAS_PART_CV_NAMES: [&str; 1] = ["fission_yeast_phenotype"]; // number of genes before (and after) to add to the gene_neighbourhood field pub const GENE_NEIGHBOURHOOD_DISTANCE: usize = 5; pub const TRANSCRIPT_FEATURE_TYPES: [&str; 8] = ["snRNA", "rRNA", "mRNA", "snoRNA", "ncRNA", "tRNA", "pseudogenic_transcript", "transcript"]; pub const TRANSCRIPT_PART_TYPES: [&str; 4] = ["five_prime_UTR", "exon", "pseudogenic_exon", "three_prime_UTR"]; // any feature with a type not in this list or in the two TRANSCRIPT lists above // will be stored in the other_features map pub const HANDLED_FEATURE_TYPES: [&str; 7] = ["gene", "pseudogene", "intron", "genotype", "allele", "chromosome", "polypeptide"]; #[derive(Deserialize, Clone, Debug)] pub struct DocConfig { pub pages: BTreeMap<RcString, RcString>, } impl DocConfig { pub fn read(doc_config_file_name: &str) -> DocConfig { let file = match File::open(doc_config_file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", doc_config_file_name, err) } }; let reader = BufReader::new(file); match serde_json::from_reader(reader) { Ok(config) => config, Err(err) => { panic!("failed to parse {}: {}", doc_config_file_name, err) }, } } } pub struct GoEcoMapping { mapping: HashMap<(String, String), String>, } impl GoEcoMapping { pub fn read(file_name: &str) -> Result<GoEcoMapping, std::io::Error> { let file = match File::open(file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", file_name, err) } }; let reader = BufReader::new(file); let mut mapping = HashMap::new(); for line_result in reader.lines() { match line_result { Ok(line) => { if line.starts_with('#') { continue; } let parts: Vec<&str> = line.split('\t').collect(); mapping.insert((String::from(parts[0]), String::from(parts[1])), String::from(parts[2])); }, Err(err) => return Err(err) }; } Ok(GoEcoMapping { mapping }) } pub fn lookup_default(&self, go_evidence_code: &str) -> Option<String> { self.mapping.get(&(String::from(go_evidence_code), String::from("Default"))) .map(String::from) } pub fn lookup_with_go_ref(&self, go_evidence_code: &str, go_ref: &str) -> Option<String> { self.mapping.get(&(String::from(go_evidence_code), String::from(go_ref))) .map(String::from) } }
pub link: Option<RcString>, } pub type DatabaseName = RcString; pub type DatabaseAliases = HashMap<DatabaseName, DatabaseName>;
random_line_split
config.rs
use std::collections::{HashMap, HashSet, BTreeMap}; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use crate::types::*; use serde_json; use pombase_rc_string::RcString; // configuration for extension display names and for the "Target of" section #[derive(Deserialize, Clone, Debug)] pub struct ExtensionDisplayNames { pub rel_name: RcString, // name of extension relation pub display_name: RcString, // text to display pub if_descendant_of: Option<RcString>, // None if applies to any extension pub reciprocal_display: Option<RcString>, // None if reciprocal shouldn't be displayed } // "interesting parents" are those stored in the JSON in the TermShort structs #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct InterestingParent { pub termid: RcString, pub rel_name: RcString, } // the order of relations within an extension: #[derive(Deserialize, Clone, Debug)] pub struct RelationOrder { // put the relations in this order in the displayed extensions: pub relation_order: Vec<RcString>, // except for these reactions which should always come last: pub always_last: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct AncestorFilterCategory { pub display_name: RcString, // this category matches these terms and their descendants pub ancestors: Vec<TermId>, } #[derive(Deserialize, Clone, Debug)] pub struct FilterConfig { pub filter_name: String, pub display_name: String, #[serde(skip_serializing_if="Vec::is_empty", default)] pub term_categories: Vec<AncestorFilterCategory>, #[serde(skip_serializing_if="Option::is_none", default)] pub slim_name: Option<RcString>, #[serde(skip_serializing_if="Vec::is_empty", default)] pub extension_categories: Vec<AncestorFilterCategory>, } #[derive(Deserialize, Clone, Debug)] pub struct SplitByParentsConfig { pub termids: Vec<RcString>, pub display_name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct ChromosomeConfig { pub name: RcString, // string to use for this chromosome in a file name, eg. "chromosome_II" // or "mitochondrial_chromosome" pub export_file_id: RcString, // string to use within files, eg. "II" or "mitochondrial" pub export_id: RcString, // eg. "Chromosome II" or "Mitochondrial chromosome" pub long_display_name: RcString, // eg. "II" or "Mitochondrial" pub short_display_name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct CvSourceConfig { // a type name for the cvtermprop to display to the user pub display_name_prop: Option<RcString>, // the cvtermprop type name for the ID used for linking // or "ACCESSION" if the accession ID of the term should be used pub id_source: Option<RcString>, } pub type TargetRelationName = String; #[derive(Deserialize, Clone, Debug)] pub struct TargetOfConfig { // these priorities are used to order the list in the "Target of" section // and to filter the "Target of" summary // https://github.com/pombase/website/issues/299 pub relation_priority: HashMap<TargetRelationName, u32>, } #[derive(Deserialize, Clone, Debug)] pub struct CvConfig { pub feature_type: RcString, pub display_name: Option<RcString>, // filtering configured per CV #[serde(skip_serializing_if="Vec::is_empty", default)] pub filters: Vec<FilterConfig>, // config for splitting cv annotation tables into sub-sections // based on ancestry #[serde(skip_serializing_if="Vec::is_empty", default)] pub split_by_parents: Vec<SplitByParentsConfig>, // relations to not show in the summary #[serde(skip_serializing_if="Vec::is_empty", default)] pub summary_relations_to_hide: Vec<RcString>, // relations where the range is a gene ID to display like: // has substrate pom1, cdc1 involved in negative regulation of... // rather than as two lines #[serde(skip_serializing_if="Vec::is_empty", default)] pub summary_relation_ranges_to_collect: Vec<RcString>, #[serde(default="SingleOrMultiLocusConfig::not_applicable")] pub single_or_multi_locus: SingleOrMultiLocusConfig, // the field to sort by #[serde(skip_serializing_if="Option::is_none")] pub sort_details_by: Option<Vec<RcString>>, // This is the configuration for the "Source" column, a map from // source name to config // See Disease association for an example. If there is no config // there will be no Source column will be displayed #[serde(skip_serializing_if="HashMap::is_empty", default)] pub source_config: HashMap<RcString, CvSourceConfig>, } pub type ShortEvidenceCode = RcString; pub type LongEvidenceCode = RcString; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct ConfigOrganism { pub taxonid: OrganismTaxonId, pub genus: RcString, pub species: RcString, pub alternative_names: Vec<RcString>, pub assembly_version: Option<RcString>, } impl ConfigOrganism { pub fn full_name(&self) -> String { self.genus.clone() + "_" + self.species.as_str() } pub fn scientific_name(&self) -> String { self.genus.clone() + " " + self.species.as_str() } } #[derive(Deserialize, Clone, Debug)] pub struct ViabilityTerms { pub viable: RcString, pub inviable: RcString, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct TermAndName { pub termid: RcString, pub name: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct ReferencePageConfig { pub triage_status_to_ignore: Vec<String>, } #[derive(Deserialize, Clone, Debug)] pub struct InterPro { pub dbnames_to_filter: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct ServerSubsetConfig { pub prefixes_to_remove: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct ServerConfig { pub subsets: ServerSubsetConfig, pub solr_url: String, pub close_synonym_boost: f32, pub distant_synonym_boost: f32, pub term_definition_boost: f32, pub django_url: String, pub cv_name_for_terms_search: String, pub gene_uniquename_re: String, } #[derive(Deserialize, Clone, Debug)] pub struct EvidenceDetails { pub long: LongEvidenceCode, pub link: Option<RcString>, } pub type DatabaseName = RcString; pub type DatabaseAliases = HashMap<DatabaseName, DatabaseName>; #[derive(Deserialize, Clone, Debug)] pub struct MacromolecularComplexesConfig { pub parent_complex_termid: RcString, pub excluded_terms: HashSet<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct RNAcentralConfig { // SO termids of RNA features to export pub export_so_ids: HashSet<RcString>, } #[derive(Deserialize, Clone, Debug, PartialEq)] pub enum SingleOrMultiLocusConfig { #[serde(rename = "single")] Single, #[serde(rename = "multi")] Multi, #[serde(rename = "na")] NotApplicable } impl SingleOrMultiLocusConfig { pub fn not_applicable() -> SingleOrMultiLocusConfig { SingleOrMultiLocusConfig::NotApplicable } } #[derive(Deserialize, Clone, Debug)] pub struct ExportColumnConfig { pub name: RcString, pub display_name: RcString } #[derive(Deserialize, Clone, Debug)] pub struct AnnotationSubsetConfig { pub term_ids: Vec<TermId>, pub file_name: RcString, pub columns: Vec<ExportColumnConfig>, #[serde(default="SingleOrMultiLocusConfig::not_applicable")] pub single_or_multi_locus: SingleOrMultiLocusConfig, } #[derive(Deserialize, Clone, Debug)] pub struct GpadGpiConfig { // the term IDs of the three GO aspects pub go_aspect_terms: HashMap<String, TermId>, // Map a relation term name to a term ID, unless the term ID is None in // which case we skip writing this extension part pub extension_relation_mappings: HashMap<String, Option<TermId>>, // A map from the SO type of a transcript to the SO type of the gene is // derives from pub transcript_gene_so_term_map: HashMap<String, String>, } #[derive(Deserialize, Clone, Debug)] pub struct FileExportConfig { pub site_map_term_prefixes: Vec<RcString>, pub site_map_reference_prefixes: Vec<RcString>, #[serde(skip_serializing_if="Option::is_none")] pub macromolecular_complexes: Option<MacromolecularComplexesConfig>, #[serde(skip_serializing_if="Option::is_none")] pub rnacentral: Option<RNAcentralConfig>, pub annotation_subsets: Vec<AnnotationSubsetConfig>, pub gpad_gpi: GpadGpiConfig, // the reference to use for ND lines in GPAD/GAF output pub nd_reference: String, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultVisAttrValueConfig { pub termid: Option<RcString>, pub name: RcString, pub bin_start: Option<usize>, pub bin_end: Option<usize>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultVisColumnConfig { #[serde(skip_serializing_if="Vec::is_empty", default)] pub attr_values: Vec<GeneResultVisAttrValueConfig>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneResultsConfig { pub field_config: HashMap<RcString, GeneResultVisColumnConfig>, pub visualisation_field_names: Vec<RcString>, } #[derive(Deserialize, Clone, Debug)] pub struct SlimConfig { pub slim_display_name: RcString, pub cv_name: RcString, pub terms: Vec<TermAndName>, } #[derive(Deserialize, Clone, Debug)] pub struct SeqFeaturePageConfig { pub so_types_to_show: Vec<String>, } #[derive(Deserialize, Clone, Debug)] pub struct GeneExDatasetConfig { pub name: RcString, pub pubmed_id: RcString, pub level_type_termid: RcString, pub during_termid: RcString, pub scale: RcString, } #[derive(Deserialize, Clone, Debug)] pub struct GeneExpressionConfig { pub datasets: Vec<GeneExDatasetConfig>, } #[derive(Deserialize, Clone, Debug)] pub struct Config { pub database_name: RcString, pub database_long_name: RcString, pub database_citation: RcString, pub funder: RcString, pub site_description: RcString, pub load_organism_taxonid: Option<OrganismTaxonId>, pub base_url: RcString, pub helpdesk_address: RcString, pub doc_page_aliases: HashMap<String, String>, pub organisms: Vec<ConfigOrganism>, pub api_seq_chunk_sizes: Vec<usize>, pub sequence_feature_page: SeqFeaturePageConfig, pub extension_display_names: Vec<ExtensionDisplayNames>, pub extension_relation_order: RelationOrder, pub evidence_types: HashMap<ShortEvidenceCode, EvidenceDetails>, pub cv_config: HashMap<CvName, CvConfig>, pub target_of_config: TargetOfConfig, // when creating a TermShort struct, for each of these termids if the term has // an "interesting parent" using the given rel_name, we store it in the // interesting_parents field of the TermShort pub interesting_parents: Vec<InterestingParent>, pub viability_terms: ViabilityTerms, // slim sets by slim name: pub slims: HashMap<RcString, SlimConfig>, pub reference_page_config: ReferencePageConfig, pub interpro: InterPro, pub server: ServerConfig, pub extra_database_aliases: DatabaseAliases, pub chromosomes: Vec<ChromosomeConfig>, pub gene_results: GeneResultsConfig, pub ortholog_taxonids: HashSet<u32>, pub file_exports: FileExportConfig, pub gene_expression: GeneExpressionConfig, } impl Config { pub fn read(config_file_name: &str) -> Config { let file = match File::open(config_file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", config_file_name, err) } }; let reader = BufReader::new(file); match serde_json::from_reader(reader) { Ok(config) => config, Err(err) => { panic!("failed to parse {}: {}", config_file_name, err) }, } } pub fn cv_config_by_name(&self, cv_name: &str) -> CvConfig { if let Some(config) = self.cv_config.get(cv_name) { config.clone() } else { let empty_cv_config = CvConfig { feature_type: "".into(), display_name: Some("".into()), single_or_multi_locus: SingleOrMultiLocusConfig::NotApplicable, filters: vec![], split_by_parents: vec![], summary_relations_to_hide: vec![], summary_relation_ranges_to_collect: vec![], sort_details_by: None, source_config: HashMap::new(), }; if cv_name.starts_with("extension:") { if cv_name.ends_with(":gene") { CvConfig { feature_type: "gene".into(), ..empty_cv_config } } else
} else { CvConfig { feature_type: "gene".into(), ..empty_cv_config } } } } pub fn organism_by_taxonid(&self, lookup_taxonid: u32) -> Option<ConfigOrganism> { for org in &self.organisms { if org.taxonid == lookup_taxonid { return Some(org.clone()); } } None } pub fn load_organism(&self) -> Option<ConfigOrganism> { if let Some(load_organism_taxonid) = self.load_organism_taxonid { let org = self.organism_by_taxonid(load_organism_taxonid); if org.is_none() { panic!("can't find configuration for load_organism_taxonid: {}", load_organism_taxonid); } org } else { None } } pub fn find_chromosome_config<'a>(&'a self, chromosome_name: &str) -> &'a ChromosomeConfig { for chr_config in &self.chromosomes { if chr_config.name == chromosome_name { return chr_config; } } panic!("can't find chromosome configuration for {}", &chromosome_name); } } pub const POMBASE_ANN_EXT_TERM_CV_NAME: &str = "PomBase annotation extension terms"; pub const ANNOTATION_EXT_REL_PREFIX: &str = "annotation_extension_relation-"; pub enum FeatureRelAnnotationType { Interaction, Ortholog, Paralog, } pub struct FeatureRelConfig { pub rel_type_name: &'static str, pub annotation_type: FeatureRelAnnotationType, } pub const FEATURE_REL_CONFIGS: [FeatureRelConfig; 4] = [ FeatureRelConfig { rel_type_name: "interacts_physically", annotation_type: FeatureRelAnnotationType::Interaction, }, FeatureRelConfig { rel_type_name: "interacts_genetically", annotation_type: FeatureRelAnnotationType::Interaction, }, FeatureRelConfig { rel_type_name: "orthologous_to", annotation_type: FeatureRelAnnotationType::Ortholog, }, FeatureRelConfig { rel_type_name: "paralogous_to", annotation_type: FeatureRelAnnotationType::Paralog, }, ]; // relations to use when copy annotation to parents (ie. adding the // annotation of child terms to parents) pub const DESCENDANT_REL_NAMES: [&str; 7] = ["is_a", "part_of", "regulates", "positively_regulates", "negatively_regulates", "has_part", "output_of"]; // only consider has_part relations for these ontologies: pub const HAS_PART_CV_NAMES: [&str; 1] = ["fission_yeast_phenotype"]; // number of genes before (and after) to add to the gene_neighbourhood field pub const GENE_NEIGHBOURHOOD_DISTANCE: usize = 5; pub const TRANSCRIPT_FEATURE_TYPES: [&str; 8] = ["snRNA", "rRNA", "mRNA", "snoRNA", "ncRNA", "tRNA", "pseudogenic_transcript", "transcript"]; pub const TRANSCRIPT_PART_TYPES: [&str; 4] = ["five_prime_UTR", "exon", "pseudogenic_exon", "three_prime_UTR"]; // any feature with a type not in this list or in the two TRANSCRIPT lists above // will be stored in the other_features map pub const HANDLED_FEATURE_TYPES: [&str; 7] = ["gene", "pseudogene", "intron", "genotype", "allele", "chromosome", "polypeptide"]; #[derive(Deserialize, Clone, Debug)] pub struct DocConfig { pub pages: BTreeMap<RcString, RcString>, } impl DocConfig { pub fn read(doc_config_file_name: &str) -> DocConfig { let file = match File::open(doc_config_file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", doc_config_file_name, err) } }; let reader = BufReader::new(file); match serde_json::from_reader(reader) { Ok(config) => config, Err(err) => { panic!("failed to parse {}: {}", doc_config_file_name, err) }, } } } pub struct GoEcoMapping { mapping: HashMap<(String, String), String>, } impl GoEcoMapping { pub fn read(file_name: &str) -> Result<GoEcoMapping, std::io::Error> { let file = match File::open(file_name) { Ok(file) => file, Err(err) => { panic!("Failed to read {}: {}\n", file_name, err) } }; let reader = BufReader::new(file); let mut mapping = HashMap::new(); for line_result in reader.lines() { match line_result { Ok(line) => { if line.starts_with('#') { continue; } let parts: Vec<&str> = line.split('\t').collect(); mapping.insert((String::from(parts[0]), String::from(parts[1])), String::from(parts[2])); }, Err(err) => return Err(err) }; } Ok(GoEcoMapping { mapping }) } pub fn lookup_default(&self, go_evidence_code: &str) -> Option<String> { self.mapping.get(&(String::from(go_evidence_code), String::from("Default"))) .map(String::from) } pub fn lookup_with_go_ref(&self, go_evidence_code: &str, go_ref: &str) -> Option<String> { self.mapping.get(&(String::from(go_evidence_code), String::from(go_ref))) .map(String::from) } }
{ CvConfig { feature_type: "genotype".into(), ..empty_cv_config } }
conditional_block
align_of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of; // pub fn align_of<T>() -> usize { // unsafe { intrinsics::min_align_of::<T>() } // } macro_rules! align_of_test { ($T:ty, $size:expr) => ({ let size: usize = align_of::<$T>(); assert_eq!(size, $size); }) } #[test] fn
() { struct A; align_of_test!( A, 1 ); } #[test] fn align_of_test2() { align_of_test!( u8, 1 ); align_of_test!( u16, 2 ); align_of_test!( u32, 4 ); align_of_test!( u64, 8 ); align_of_test!( i8, 1 ); align_of_test!( i16, 2 ); align_of_test!( i32, 4 ); align_of_test!( i64, 8 ); align_of_test!( f32, 4 ); align_of_test!( f64, 8 ); align_of_test!( [u8; 0], 1 ); align_of_test!( [u8; 68], 1 ); align_of_test!( [u32; 0], 4 ); align_of_test!( [u32; 68], 4 ); align_of_test!( (u8,), 1 ); align_of_test!( (u8, u16), 2 ); align_of_test!( (u8, u16, u32), 4 ); align_of_test!( (u8, u16, u32, u64), 8 ); } }
align_of_test1
identifier_name
align_of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of; // pub fn align_of<T>() -> usize { // unsafe { intrinsics::min_align_of::<T>() } // }
let size: usize = align_of::<$T>(); assert_eq!(size, $size); }) } #[test] fn align_of_test1() { struct A; align_of_test!( A, 1 ); } #[test] fn align_of_test2() { align_of_test!( u8, 1 ); align_of_test!( u16, 2 ); align_of_test!( u32, 4 ); align_of_test!( u64, 8 ); align_of_test!( i8, 1 ); align_of_test!( i16, 2 ); align_of_test!( i32, 4 ); align_of_test!( i64, 8 ); align_of_test!( f32, 4 ); align_of_test!( f64, 8 ); align_of_test!( [u8; 0], 1 ); align_of_test!( [u8; 68], 1 ); align_of_test!( [u32; 0], 4 ); align_of_test!( [u32; 68], 4 ); align_of_test!( (u8,), 1 ); align_of_test!( (u8, u16), 2 ); align_of_test!( (u8, u16, u32), 4 ); align_of_test!( (u8, u16, u32, u64), 8 ); } }
macro_rules! align_of_test { ($T:ty, $size:expr) => ({
random_line_split
align_of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of; // pub fn align_of<T>() -> usize { // unsafe { intrinsics::min_align_of::<T>() } // } macro_rules! align_of_test { ($T:ty, $size:expr) => ({ let size: usize = align_of::<$T>(); assert_eq!(size, $size); }) } #[test] fn align_of_test1()
#[test] fn align_of_test2() { align_of_test!( u8, 1 ); align_of_test!( u16, 2 ); align_of_test!( u32, 4 ); align_of_test!( u64, 8 ); align_of_test!( i8, 1 ); align_of_test!( i16, 2 ); align_of_test!( i32, 4 ); align_of_test!( i64, 8 ); align_of_test!( f32, 4 ); align_of_test!( f64, 8 ); align_of_test!( [u8; 0], 1 ); align_of_test!( [u8; 68], 1 ); align_of_test!( [u32; 0], 4 ); align_of_test!( [u32; 68], 4 ); align_of_test!( (u8,), 1 ); align_of_test!( (u8, u16), 2 ); align_of_test!( (u8, u16, u32), 4 ); align_of_test!( (u8, u16, u32, u64), 8 ); } }
{ struct A; align_of_test!( A, 1 ); }
identifier_body
popstateevent.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/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::window::Window; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_malloc_size_of = "Defined in rust-mozjs"] state: Heap<JSVal>, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(), state: Heap::default(), } } pub fn
(window: &Window) -> DomRoot<PopStateEvent> { reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue, ) -> DomRoot<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>, ) -> Fallible<DomRoot<PopStateEvent>> { Ok(PopStateEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.state.handle(), )) } pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) { let event = PopStateEvent::new(window, atom!("popstate"), false, false, state); event.upcast::<Event>().fire(target); } } impl PopStateEventMethods for PopStateEvent { // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state fn State(&self, _cx: JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
new_uninitialized
identifier_name
popstateevent.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/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::window::Window; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsval::JSVal;
// https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_malloc_size_of = "Defined in rust-mozjs"] state: Heap<JSVal>, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(), state: Heap::default(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<PopStateEvent> { reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue, ) -> DomRoot<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>, ) -> Fallible<DomRoot<PopStateEvent>> { Ok(PopStateEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.state.handle(), )) } pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) { let event = PopStateEvent::new(window, atom!("popstate"), false, false, state); event.upcast::<Event>().fire(target); } } impl PopStateEventMethods for PopStateEvent { // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state fn State(&self, _cx: JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
use js::rust::HandleValue; use servo_atoms::Atom;
random_line_split
popstateevent.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/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::window::Window; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_malloc_size_of = "Defined in rust-mozjs"] state: Heap<JSVal>, } impl PopStateEvent { fn new_inherited() -> PopStateEvent
pub fn new_uninitialized(window: &Window) -> DomRoot<PopStateEvent> { reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue, ) -> DomRoot<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>, ) -> Fallible<DomRoot<PopStateEvent>> { Ok(PopStateEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.state.handle(), )) } pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) { let event = PopStateEvent::new(window, atom!("popstate"), false, false, state); event.upcast::<Event>().fire(target); } } impl PopStateEventMethods for PopStateEvent { // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state fn State(&self, _cx: JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ PopStateEvent { event: Event::new_inherited(), state: Heap::default(), } }
identifier_body
debug.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. use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::PathBuf; use std::ffi::OsString; pub trait IndentedToString { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String; } // indented to string macro_rules! its( {$value:expr, $spaces:expr, $repeat:expr} => { { $value.indented_to_string($spaces, $repeat) } }; ); // default indented to string macro_rules! dits( {$value:expr} => { its!($value, " ", 0) }; ); pub struct IndentedStructFormatter { name: String, fields: Vec<(String, String)>, spaces: String, repeat: usize, } impl IndentedStructFormatter { pub fn new(name: &str, spaces: &str, repeat: usize) -> Self { Self { name: name.to_string(), fields: Vec::new(), spaces: spaces.to_string(), repeat: repeat, } } pub fn add_string(&mut self, field_name: &str, field_value: String) { self.fields.push((field_name.to_string(), field_value)); } pub fn
<T: Debug>(&mut self, field_name: &str, field_value: &T) { self.add_string(field_name, format!("{:?}", field_value)); } pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) { let spaces = self.spaces.to_string(); let repeat = self.repeat + 1; self.add_string(field_name, its!(field_value, &spaces, repeat)); } pub fn fmt(&mut self) -> String { let indent = self.spaces.repeat(self.repeat); let field_indent = self.spaces.repeat(self.repeat + 1); /* 5 - space between name and opening brace, opening brace, newline * after opening brace, closing brace, terminating zero */ let mut capacity = self.name.len() + 5 + indent.len(); for pair in &self.fields { /* 4 - colon after name, space, comma, newline after value */ capacity += field_indent.len() + pair.0.len() + 4 + pair.1.len(); } let mut str = String::with_capacity(capacity); str.push_str(&format!("{} {{\n", self.name,)); for pair in &self.fields { str.push_str(&format!("{}{}: {},\n", field_indent, pair.0, pair.1)); } str.push_str(&format!("{}}}", indent)); str } } impl IndentedToString for u32 { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string() } } impl IndentedToString for PathBuf { fn indented_to_string(&self, _: &str, _: usize) -> String { self.display().to_string() } } impl IndentedToString for OsString { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string_lossy().to_string() } } impl<T: IndentedToString> IndentedToString for Option<T> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { match self { &Some(ref v) => format!("Some({})", its!(v, spaces, repeat)), &None => "None".to_string(), } } } impl<V: IndentedToString> IndentedToString for HashMap<PathBuf, V> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.keys().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{}: {},\n", indent, path.display(), its!(self.get(path).unwrap(), spaces, repeat + 1), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } } impl IndentedToString for HashSet<PathBuf> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.iter().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{},\n", indent, path.display(), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } }
add_debug
identifier_name
debug.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. use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::PathBuf; use std::ffi::OsString; pub trait IndentedToString { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String; } // indented to string macro_rules! its( {$value:expr, $spaces:expr, $repeat:expr} => { { $value.indented_to_string($spaces, $repeat) } }; ); // default indented to string macro_rules! dits( {$value:expr} => {
pub struct IndentedStructFormatter { name: String, fields: Vec<(String, String)>, spaces: String, repeat: usize, } impl IndentedStructFormatter { pub fn new(name: &str, spaces: &str, repeat: usize) -> Self { Self { name: name.to_string(), fields: Vec::new(), spaces: spaces.to_string(), repeat: repeat, } } pub fn add_string(&mut self, field_name: &str, field_value: String) { self.fields.push((field_name.to_string(), field_value)); } pub fn add_debug<T: Debug>(&mut self, field_name: &str, field_value: &T) { self.add_string(field_name, format!("{:?}", field_value)); } pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) { let spaces = self.spaces.to_string(); let repeat = self.repeat + 1; self.add_string(field_name, its!(field_value, &spaces, repeat)); } pub fn fmt(&mut self) -> String { let indent = self.spaces.repeat(self.repeat); let field_indent = self.spaces.repeat(self.repeat + 1); /* 5 - space between name and opening brace, opening brace, newline * after opening brace, closing brace, terminating zero */ let mut capacity = self.name.len() + 5 + indent.len(); for pair in &self.fields { /* 4 - colon after name, space, comma, newline after value */ capacity += field_indent.len() + pair.0.len() + 4 + pair.1.len(); } let mut str = String::with_capacity(capacity); str.push_str(&format!("{} {{\n", self.name,)); for pair in &self.fields { str.push_str(&format!("{}{}: {},\n", field_indent, pair.0, pair.1)); } str.push_str(&format!("{}}}", indent)); str } } impl IndentedToString for u32 { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string() } } impl IndentedToString for PathBuf { fn indented_to_string(&self, _: &str, _: usize) -> String { self.display().to_string() } } impl IndentedToString for OsString { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string_lossy().to_string() } } impl<T: IndentedToString> IndentedToString for Option<T> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { match self { &Some(ref v) => format!("Some({})", its!(v, spaces, repeat)), &None => "None".to_string(), } } } impl<V: IndentedToString> IndentedToString for HashMap<PathBuf, V> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.keys().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{}: {},\n", indent, path.display(), its!(self.get(path).unwrap(), spaces, repeat + 1), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } } impl IndentedToString for HashSet<PathBuf> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.iter().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{},\n", indent, path.display(), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } }
its!($value, " ", 0) }; );
random_line_split
debug.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. use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::PathBuf; use std::ffi::OsString; pub trait IndentedToString { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String; } // indented to string macro_rules! its( {$value:expr, $spaces:expr, $repeat:expr} => { { $value.indented_to_string($spaces, $repeat) } }; ); // default indented to string macro_rules! dits( {$value:expr} => { its!($value, " ", 0) }; ); pub struct IndentedStructFormatter { name: String, fields: Vec<(String, String)>, spaces: String, repeat: usize, } impl IndentedStructFormatter { pub fn new(name: &str, spaces: &str, repeat: usize) -> Self { Self { name: name.to_string(), fields: Vec::new(), spaces: spaces.to_string(), repeat: repeat, } } pub fn add_string(&mut self, field_name: &str, field_value: String) { self.fields.push((field_name.to_string(), field_value)); } pub fn add_debug<T: Debug>(&mut self, field_name: &str, field_value: &T)
pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) { let spaces = self.spaces.to_string(); let repeat = self.repeat + 1; self.add_string(field_name, its!(field_value, &spaces, repeat)); } pub fn fmt(&mut self) -> String { let indent = self.spaces.repeat(self.repeat); let field_indent = self.spaces.repeat(self.repeat + 1); /* 5 - space between name and opening brace, opening brace, newline * after opening brace, closing brace, terminating zero */ let mut capacity = self.name.len() + 5 + indent.len(); for pair in &self.fields { /* 4 - colon after name, space, comma, newline after value */ capacity += field_indent.len() + pair.0.len() + 4 + pair.1.len(); } let mut str = String::with_capacity(capacity); str.push_str(&format!("{} {{\n", self.name,)); for pair in &self.fields { str.push_str(&format!("{}{}: {},\n", field_indent, pair.0, pair.1)); } str.push_str(&format!("{}}}", indent)); str } } impl IndentedToString for u32 { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string() } } impl IndentedToString for PathBuf { fn indented_to_string(&self, _: &str, _: usize) -> String { self.display().to_string() } } impl IndentedToString for OsString { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string_lossy().to_string() } } impl<T: IndentedToString> IndentedToString for Option<T> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { match self { &Some(ref v) => format!("Some({})", its!(v, spaces, repeat)), &None => "None".to_string(), } } } impl<V: IndentedToString> IndentedToString for HashMap<PathBuf, V> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.keys().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{}: {},\n", indent, path.display(), its!(self.get(path).unwrap(), spaces, repeat + 1), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } } impl IndentedToString for HashSet<PathBuf> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.iter().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{},\n", indent, path.display(), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } }
{ self.add_string(field_name, format!("{:?}", field_value)); }
identifier_body
issue_371.rs
//! Checks that `executor.look_ahead().field_name()` is correct in presence of //! multiple query fields. //! See [#371](https://github.com/graphql-rust/juniper/issues/371) for details. //! //! Original author of this test is [@davidpdrsn](https://github.com/davidpdrsn). use juniper::{ graphql_object, graphql_vars, EmptyMutation, EmptySubscription, Executor, LookAheadMethods as _, RootNode, ScalarValue, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[graphql_object(context = Context)] impl Query { fn users<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<User> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "users"); vec![User] } fn countries<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<Country> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "countries"); vec![Country] } } #[derive(Clone)] pub struct User; #[graphql_object(context = Context)] impl User { fn id() -> i32 { 1 } } #[derive(Clone)] pub struct Country; #[graphql_object] impl Country { fn id() -> i32 { 2 } } type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; #[tokio::test] async fn users() { let query = "{ users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn
() { let query = "{ countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both() { let query = "{ countries { id } users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both_in_different_order() { let query = "{ users { id } countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); }
countries
identifier_name
issue_371.rs
//! Checks that `executor.look_ahead().field_name()` is correct in presence of //! multiple query fields. //! See [#371](https://github.com/graphql-rust/juniper/issues/371) for details. //! //! Original author of this test is [@davidpdrsn](https://github.com/davidpdrsn). use juniper::{ graphql_object, graphql_vars, EmptyMutation, EmptySubscription, Executor, LookAheadMethods as _, RootNode, ScalarValue, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[graphql_object(context = Context)] impl Query { fn users<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<User> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "users"); vec![User] } fn countries<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<Country> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "countries"); vec![Country] } } #[derive(Clone)] pub struct User; #[graphql_object(context = Context)] impl User { fn id() -> i32 { 1 } } #[derive(Clone)] pub struct Country; #[graphql_object] impl Country { fn id() -> i32 { 2 } } type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; #[tokio::test] async fn users() { let query = "{ users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap();
#[tokio::test] async fn countries() { let query = "{ countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both() { let query = "{ countries { id } users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both_in_different_order() { let query = "{ users { id } countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); }
assert_eq!(errors.len(), 0); }
random_line_split
colour.rs
use super::request::*; use std::cmp::Ordering; /// HSB colour representation - hue, saturation, brightness (aka value). /// Aka HSV (LIFX terminology) - hue, saturation, value. /// This is not the same as HSL as used in CSS. /// LIFX uses HSB aka HSV, not HSL. #[derive(Debug)] pub struct HSB { pub hue: u16, pub saturation: u8, pub brightness: u8, } /// RGB colour representation - red, green, blue. pub struct RGB { pub red: u8, pub green: u8, pub blue: u8, } /// HSBK colour representation - hue, saturation, brightness, kelvin. /// Kelvin seems to be relevant only to whites - temperature of white. #[derive(Debug)] pub struct HSBK { pub hue: u16, pub saturation: u8, pub brightness: u8, pub kelvin: u16, } impl HSB { pub fn new(h: u16, s: u8, b: u8) -> HSB { HSB { hue: h, saturation: s, brightness: b, } } } impl From<HSBK> for HSB { fn from(c: HSBK) -> HSB { HSB::new(c.hue, c.saturation, c.brightness) } } /// The max value of the two byte representation of colour element as used in the protocol. const WORD_SIZE: usize = 65535; const DEGREES_UBOUND: usize = 360; const PERCENT_UBOUND: usize = 100; // (WORD_SIZE / DEGREES_UBOUND) is ~182.0417 // The two-byte represenation only represents integers, so decimals will be truncated. // This can result in a get_state returning a slightly different result from the // preceding set_state for hue, saturation, and brightness. pub fn hue_degrees_to_word(degrees: u16) -> [u8; 2] { let f = degrees as f64 * WORD_SIZE as f64 / DEGREES_UBOUND as f64; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn hue_word_to_degrees(word: u16) -> u16 { (word as usize * 360 / WORD_SIZE) as u16 } pub fn saturation_percent_to_word(percent: u8) -> [u8; 2] { let f: f64 = percent as f64 * WORD_SIZE as f64 / 100.0; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn saturation_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn brightness_percent_to_word(percent: u8) -> [u8; 2] { saturation_percent_to_word(percent) } pub fn brightness_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn rgb_to_hsv(rgb: RGB) -> HSB { let r1 = rgb.red as f32 / 255.0; let g1 = rgb.green as f32 / 255.0; let b1 = rgb.blue as f32 / 255.0; let mut floats: Vec<f32> = vec![r1, g1, b1]; floats.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); let cmax = floats[2]; let cmin = floats[0]; let d = cmax - cmin; // Hue. let h = match cmax { _ if r1 == cmax => (((g1 - b1) / d) % 6.0) * 60.0, _ if g1 == cmax => (((b1 - r1) / d) + 2.0) * 60.0, _ if b1 == cmax => (((r1 - g1) / d) + 4.0) * 60.0, _ => 0.0, }; // Saturation. let s = match cmax { 0.0 => 0.0, _ => d / cmax, }; // Value / brightness. let v = cmax; HSB { hue: h as u16, saturation: (s * 100.0) as u8, brightness: (v * 100.0) as u8, } } #[cfg(test)] mod tests { use colour::*; #[test] fn test_hue_degrees_to_word() { assert_eq!([0x55, 0x55], hue_degrees_to_word(120)); assert_eq!([0x47, 0x1C], hue_degrees_to_word(100)); assert_eq!([0x44, 0x44], hue_degrees_to_word(96)); assert_eq!([0x43, 0x8E], hue_degrees_to_word(95)); } #[test] fn
() { assert_eq!(360, hue_word_to_degrees(65535)); assert_eq!(0, hue_word_to_degrees(0)); assert_eq!(180, hue_word_to_degrees(32768)); } #[test] fn test_saturation_percent_to_word() { assert_eq!([0x80, 0x00], saturation_percent_to_word(50)); } #[test] fn test_rgb_to_hsv() { struct Test { rgb: RGB, hsb: HSB, }; let tests = vec![ Test { rgb: RGB { // olive red: 128, green: 128, blue: 0, }, hsb: HSB { hue: 60, saturation: 100, brightness: 50, }, }, Test { rgb: RGB { // chartreuse red: 127, green: 255, blue: 0, }, hsb: HSB { hue: 90, saturation: 100, brightness: 100, }, }, ]; for t in tests { let res = rgb_to_hsv(t.rgb); assert_eq!(res.hue, t.hsb.hue); assert_eq!(res.saturation, t.hsb.saturation); assert_eq!(res.brightness, t.hsb.brightness); } } } pub fn named_colours() -> Vec<String> { vec!( "beige".to_string(), "blue".to_string(), "chartreuse".to_string(), "coral".to_string(), "cornflower".to_string(), "crimson".to_string(), "deep_sky_blue".to_string(), "green".to_string(), "red".to_string(), "slate_gray".to_string(), ) } pub fn get_colour(s: &str) -> HSB { let colour: &str = &(s.to_lowercase()); match colour { "beige" => { HSB { hue: 60, saturation: 56, brightness: 91, } } "blue" => { HSB { hue: 240, saturation: 100, brightness: 50, } } "chartreuse" => { HSB { hue: 90, saturation: 100, brightness: 50, } } "coral" => { HSB { hue: 16, saturation: 100, brightness: 66, } } "cornflower" => { HSB { hue: 219, saturation: 79, brightness: 66, } } "crimson" => { HSB { hue: 348, saturation: 83, brightness: 47, } } "deep_sky_blue" => { HSB { hue: 195, saturation: 100, brightness: 50, } } "green" => { HSB { hue: 120, saturation: 100, brightness: 50, } } "red" => { HSB { hue: 0, saturation: 100, brightness: 50, } } "slate_gray" => { HSB { hue: 210, saturation: 13, brightness: 50, } } _ => panic!("no such colour."), } }
test_hue_word_to_degrees
identifier_name
colour.rs
use super::request::*; use std::cmp::Ordering; /// HSB colour representation - hue, saturation, brightness (aka value). /// Aka HSV (LIFX terminology) - hue, saturation, value. /// This is not the same as HSL as used in CSS. /// LIFX uses HSB aka HSV, not HSL. #[derive(Debug)] pub struct HSB { pub hue: u16, pub saturation: u8, pub brightness: u8, } /// RGB colour representation - red, green, blue. pub struct RGB { pub red: u8, pub green: u8, pub blue: u8, } /// HSBK colour representation - hue, saturation, brightness, kelvin. /// Kelvin seems to be relevant only to whites - temperature of white. #[derive(Debug)] pub struct HSBK { pub hue: u16, pub saturation: u8, pub brightness: u8, pub kelvin: u16, } impl HSB { pub fn new(h: u16, s: u8, b: u8) -> HSB { HSB { hue: h, saturation: s, brightness: b, } } } impl From<HSBK> for HSB { fn from(c: HSBK) -> HSB { HSB::new(c.hue, c.saturation, c.brightness) } } /// The max value of the two byte representation of colour element as used in the protocol. const WORD_SIZE: usize = 65535; const DEGREES_UBOUND: usize = 360; const PERCENT_UBOUND: usize = 100; // (WORD_SIZE / DEGREES_UBOUND) is ~182.0417 // The two-byte represenation only represents integers, so decimals will be truncated. // This can result in a get_state returning a slightly different result from the // preceding set_state for hue, saturation, and brightness. pub fn hue_degrees_to_word(degrees: u16) -> [u8; 2] { let f = degrees as f64 * WORD_SIZE as f64 / DEGREES_UBOUND as f64; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn hue_word_to_degrees(word: u16) -> u16 { (word as usize * 360 / WORD_SIZE) as u16 } pub fn saturation_percent_to_word(percent: u8) -> [u8; 2] { let f: f64 = percent as f64 * WORD_SIZE as f64 / 100.0; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn saturation_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn brightness_percent_to_word(percent: u8) -> [u8; 2] { saturation_percent_to_word(percent) } pub fn brightness_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn rgb_to_hsv(rgb: RGB) -> HSB { let r1 = rgb.red as f32 / 255.0; let g1 = rgb.green as f32 / 255.0; let b1 = rgb.blue as f32 / 255.0; let mut floats: Vec<f32> = vec![r1, g1, b1]; floats.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); let cmax = floats[2]; let cmin = floats[0]; let d = cmax - cmin; // Hue. let h = match cmax { _ if r1 == cmax => (((g1 - b1) / d) % 6.0) * 60.0, _ if g1 == cmax => (((b1 - r1) / d) + 2.0) * 60.0, _ if b1 == cmax => (((r1 - g1) / d) + 4.0) * 60.0, _ => 0.0, }; // Saturation. let s = match cmax { 0.0 => 0.0, _ => d / cmax, }; // Value / brightness. let v = cmax; HSB { hue: h as u16, saturation: (s * 100.0) as u8, brightness: (v * 100.0) as u8, } } #[cfg(test)] mod tests { use colour::*; #[test] fn test_hue_degrees_to_word() { assert_eq!([0x55, 0x55], hue_degrees_to_word(120)); assert_eq!([0x47, 0x1C], hue_degrees_to_word(100)); assert_eq!([0x44, 0x44], hue_degrees_to_word(96)); assert_eq!([0x43, 0x8E], hue_degrees_to_word(95)); } #[test] fn test_hue_word_to_degrees() { assert_eq!(360, hue_word_to_degrees(65535)); assert_eq!(0, hue_word_to_degrees(0)); assert_eq!(180, hue_word_to_degrees(32768)); } #[test] fn test_saturation_percent_to_word() { assert_eq!([0x80, 0x00], saturation_percent_to_word(50)); } #[test] fn test_rgb_to_hsv() { struct Test { rgb: RGB, hsb: HSB, }; let tests = vec![ Test { rgb: RGB { // olive red: 128, green: 128, blue: 0, }, hsb: HSB { hue: 60, saturation: 100, brightness: 50, }, }, Test { rgb: RGB { // chartreuse red: 127, green: 255, blue: 0, }, hsb: HSB { hue: 90, saturation: 100, brightness: 100, }, }, ]; for t in tests { let res = rgb_to_hsv(t.rgb); assert_eq!(res.hue, t.hsb.hue); assert_eq!(res.saturation, t.hsb.saturation); assert_eq!(res.brightness, t.hsb.brightness); } } } pub fn named_colours() -> Vec<String> { vec!( "beige".to_string(), "blue".to_string(), "chartreuse".to_string(), "coral".to_string(), "cornflower".to_string(), "crimson".to_string(), "deep_sky_blue".to_string(), "green".to_string(), "red".to_string(), "slate_gray".to_string(), ) } pub fn get_colour(s: &str) -> HSB
saturation: 100, brightness: 50, } } "coral" => { HSB { hue: 16, saturation: 100, brightness: 66, } } "cornflower" => { HSB { hue: 219, saturation: 79, brightness: 66, } } "crimson" => { HSB { hue: 348, saturation: 83, brightness: 47, } } "deep_sky_blue" => { HSB { hue: 195, saturation: 100, brightness: 50, } } "green" => { HSB { hue: 120, saturation: 100, brightness: 50, } } "red" => { HSB { hue: 0, saturation: 100, brightness: 50, } } "slate_gray" => { HSB { hue: 210, saturation: 13, brightness: 50, } } _ => panic!("no such colour."), } }
{ let colour: &str = &(s.to_lowercase()); match colour { "beige" => { HSB { hue: 60, saturation: 56, brightness: 91, } } "blue" => { HSB { hue: 240, saturation: 100, brightness: 50, } } "chartreuse" => { HSB { hue: 90,
identifier_body
colour.rs
use super::request::*; use std::cmp::Ordering; /// HSB colour representation - hue, saturation, brightness (aka value). /// Aka HSV (LIFX terminology) - hue, saturation, value. /// This is not the same as HSL as used in CSS. /// LIFX uses HSB aka HSV, not HSL. #[derive(Debug)] pub struct HSB { pub hue: u16, pub saturation: u8, pub brightness: u8, } /// RGB colour representation - red, green, blue. pub struct RGB { pub red: u8, pub green: u8, pub blue: u8, } /// HSBK colour representation - hue, saturation, brightness, kelvin. /// Kelvin seems to be relevant only to whites - temperature of white. #[derive(Debug)] pub struct HSBK { pub hue: u16, pub saturation: u8, pub brightness: u8, pub kelvin: u16, } impl HSB { pub fn new(h: u16, s: u8, b: u8) -> HSB { HSB { hue: h, saturation: s, brightness: b, } } } impl From<HSBK> for HSB { fn from(c: HSBK) -> HSB { HSB::new(c.hue, c.saturation, c.brightness) } } /// The max value of the two byte representation of colour element as used in the protocol. const WORD_SIZE: usize = 65535; const DEGREES_UBOUND: usize = 360; const PERCENT_UBOUND: usize = 100; // (WORD_SIZE / DEGREES_UBOUND) is ~182.0417 // The two-byte represenation only represents integers, so decimals will be truncated. // This can result in a get_state returning a slightly different result from the // preceding set_state for hue, saturation, and brightness. pub fn hue_degrees_to_word(degrees: u16) -> [u8; 2] { let f = degrees as f64 * WORD_SIZE as f64 / DEGREES_UBOUND as f64; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn hue_word_to_degrees(word: u16) -> u16 { (word as usize * 360 / WORD_SIZE) as u16 } pub fn saturation_percent_to_word(percent: u8) -> [u8; 2] { let f: f64 = percent as f64 * WORD_SIZE as f64 / 100.0; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn saturation_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn brightness_percent_to_word(percent: u8) -> [u8; 2] { saturation_percent_to_word(percent) } pub fn brightness_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn rgb_to_hsv(rgb: RGB) -> HSB { let r1 = rgb.red as f32 / 255.0; let g1 = rgb.green as f32 / 255.0; let b1 = rgb.blue as f32 / 255.0; let mut floats: Vec<f32> = vec![r1, g1, b1]; floats.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); let cmax = floats[2]; let cmin = floats[0]; let d = cmax - cmin; // Hue. let h = match cmax { _ if r1 == cmax => (((g1 - b1) / d) % 6.0) * 60.0, _ if g1 == cmax => (((b1 - r1) / d) + 2.0) * 60.0, _ if b1 == cmax => (((r1 - g1) / d) + 4.0) * 60.0, _ => 0.0, }; // Saturation. let s = match cmax { 0.0 => 0.0, _ => d / cmax, }; // Value / brightness. let v = cmax; HSB { hue: h as u16, saturation: (s * 100.0) as u8, brightness: (v * 100.0) as u8, } } #[cfg(test)] mod tests { use colour::*; #[test] fn test_hue_degrees_to_word() { assert_eq!([0x55, 0x55], hue_degrees_to_word(120)); assert_eq!([0x47, 0x1C], hue_degrees_to_word(100)); assert_eq!([0x44, 0x44], hue_degrees_to_word(96)); assert_eq!([0x43, 0x8E], hue_degrees_to_word(95)); } #[test] fn test_hue_word_to_degrees() { assert_eq!(360, hue_word_to_degrees(65535)); assert_eq!(0, hue_word_to_degrees(0)); assert_eq!(180, hue_word_to_degrees(32768)); } #[test] fn test_saturation_percent_to_word() { assert_eq!([0x80, 0x00], saturation_percent_to_word(50)); } #[test] fn test_rgb_to_hsv() { struct Test { rgb: RGB, hsb: HSB, }; let tests = vec![ Test { rgb: RGB { // olive red: 128, green: 128, blue: 0, }, hsb: HSB { hue: 60, saturation: 100, brightness: 50, }, }, Test { rgb: RGB { // chartreuse red: 127, green: 255, blue: 0, }, hsb: HSB { hue: 90, saturation: 100, brightness: 100, }, }, ]; for t in tests { let res = rgb_to_hsv(t.rgb); assert_eq!(res.hue, t.hsb.hue); assert_eq!(res.saturation, t.hsb.saturation); assert_eq!(res.brightness, t.hsb.brightness); } } } pub fn named_colours() -> Vec<String> { vec!( "beige".to_string(), "blue".to_string(), "chartreuse".to_string(), "coral".to_string(), "cornflower".to_string(), "crimson".to_string(), "deep_sky_blue".to_string(), "green".to_string(), "red".to_string(), "slate_gray".to_string(), ) } pub fn get_colour(s: &str) -> HSB { let colour: &str = &(s.to_lowercase()); match colour { "beige" => { HSB { hue: 60, saturation: 56, brightness: 91, } } "blue" => { HSB { hue: 240, saturation: 100, brightness: 50, } } "chartreuse" => { HSB { hue: 90, saturation: 100, brightness: 50, } } "coral" => { HSB { hue: 16, saturation: 100, brightness: 66, } } "cornflower" => { HSB { hue: 219, saturation: 79, brightness: 66, } } "crimson" => { HSB { hue: 348, saturation: 83, brightness: 47, } } "deep_sky_blue" => { HSB { hue: 195, saturation: 100,
HSB { hue: 120, saturation: 100, brightness: 50, } } "red" => { HSB { hue: 0, saturation: 100, brightness: 50, } } "slate_gray" => { HSB { hue: 210, saturation: 13, brightness: 50, } } _ => panic!("no such colour."), } }
brightness: 50, } } "green" => {
random_line_split
vec_conversion.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 js; use js::conversions::ConversionBehavior; use js::conversions::FromJSValConvertible; use js::conversions::ToJSValConvertible; use js::jsapi::CompartmentOptions; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_Init; use js::jsapi::JS_InitStandardClasses; use js::jsapi::JS_NewGlobalObject; use js::jsapi::OnNewGlobalHookOption; use js::jsapi::Rooted; use js::jsapi::RootedValue; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; #[test] fn vec_conversion() { unsafe { assert!(JS_Init()); let rt = Runtime::new(ptr::null_mut());
ptr::null_mut(), h_option, &c_option); let global_root = Rooted::new(cx, global); let global = global_root.handle(); let _ac = JSAutoCompartment::new(cx, global.get()); assert!(JS_InitStandardClasses(cx, global)); let mut rval = RootedValue::new(cx, UndefinedValue()); let orig_vec: Vec<f32> = vec![1.0, 2.9, 3.0]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<f32>::from_jsval(cx, rval.handle(), ()).unwrap(); assert_eq!(orig_vec, converted); let orig_vec: Vec<i32> = vec![1, 2, 3]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); rt.evaluate_script(global, "new Set([1, 2, 3])", "test", 1, rval.handle_mut()).unwrap(); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); } }
let cx = rt.cx(); let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; let c_option = CompartmentOptions::default(); let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS,
random_line_split
vec_conversion.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 js; use js::conversions::ConversionBehavior; use js::conversions::FromJSValConvertible; use js::conversions::ToJSValConvertible; use js::jsapi::CompartmentOptions; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_Init; use js::jsapi::JS_InitStandardClasses; use js::jsapi::JS_NewGlobalObject; use js::jsapi::OnNewGlobalHookOption; use js::jsapi::Rooted; use js::jsapi::RootedValue; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; #[test] fn vec_conversion()
orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<f32>::from_jsval(cx, rval.handle(), ()).unwrap(); assert_eq!(orig_vec, converted); let orig_vec: Vec<i32> = vec![1, 2, 3]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); rt.evaluate_script(global, "new Set([1, 2, 3])", "test", 1, rval.handle_mut()).unwrap(); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); } }
{ unsafe { assert!(JS_Init()); let rt = Runtime::new(ptr::null_mut()); let cx = rt.cx(); let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; let c_option = CompartmentOptions::default(); let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, ptr::null_mut(), h_option, &c_option); let global_root = Rooted::new(cx, global); let global = global_root.handle(); let _ac = JSAutoCompartment::new(cx, global.get()); assert!(JS_InitStandardClasses(cx, global)); let mut rval = RootedValue::new(cx, UndefinedValue()); let orig_vec: Vec<f32> = vec![1.0, 2.9, 3.0];
identifier_body
vec_conversion.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 js; use js::conversions::ConversionBehavior; use js::conversions::FromJSValConvertible; use js::conversions::ToJSValConvertible; use js::jsapi::CompartmentOptions; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_Init; use js::jsapi::JS_InitStandardClasses; use js::jsapi::JS_NewGlobalObject; use js::jsapi::OnNewGlobalHookOption; use js::jsapi::Rooted; use js::jsapi::RootedValue; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; #[test] fn
() { unsafe { assert!(JS_Init()); let rt = Runtime::new(ptr::null_mut()); let cx = rt.cx(); let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; let c_option = CompartmentOptions::default(); let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, ptr::null_mut(), h_option, &c_option); let global_root = Rooted::new(cx, global); let global = global_root.handle(); let _ac = JSAutoCompartment::new(cx, global.get()); assert!(JS_InitStandardClasses(cx, global)); let mut rval = RootedValue::new(cx, UndefinedValue()); let orig_vec: Vec<f32> = vec![1.0, 2.9, 3.0]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<f32>::from_jsval(cx, rval.handle(), ()).unwrap(); assert_eq!(orig_vec, converted); let orig_vec: Vec<i32> = vec![1, 2, 3]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); rt.evaluate_script(global, "new Set([1, 2, 3])", "test", 1, rval.handle_mut()).unwrap(); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); } }
vec_conversion
identifier_name
writer.rs
use schema::{Schema, Field, Document}; use fastfield::FastFieldSerializer; use std::io; use schema::Value; use DocId; use schema::FieldType; use common; use common::VInt; use common::BinarySerializable; /// The fastfieldswriter regroup all of the fast field writers. pub struct FastFieldsWriter { field_writers: Vec<IntFastFieldWriter>, } impl FastFieldsWriter { /// Create all `FastFieldWriter` required by the schema. pub fn from_schema(schema: &Schema) -> FastFieldsWriter { let field_writers: Vec<IntFastFieldWriter> = schema .fields() .iter() .enumerate() .flat_map(|(field_id, field_entry)| { let field = Field(field_id as u32); match *field_entry.field_type() { FieldType::I64(ref int_options) => { if int_options.is_fast() { let mut fast_field_writer = IntFastFieldWriter::new(field); fast_field_writer.set_val_if_missing(common::i64_to_u64(0i64)); Some(fast_field_writer) } else { None } } FieldType::U64(ref int_options) => { if int_options.is_fast() { Some(IntFastFieldWriter::new(field)) } else { None } } _ => None, } }) .collect(); FastFieldsWriter { field_writers: field_writers } } /// Returns a `FastFieldsWriter` /// with a `IntFastFieldWriter` for each /// of the field given in argument. pub fn new(fields: Vec<Field>) -> FastFieldsWriter { FastFieldsWriter { field_writers: fields.into_iter().map(IntFastFieldWriter::new).collect(), } } /// Get the `FastFieldWriter` associated to a field. pub fn get_field_writer(&mut self, field: Field) -> Option<&mut IntFastFieldWriter> { // TODO optimize self.field_writers .iter_mut() .find(|field_writer| field_writer.field == field) } /// Indexes all of the fastfields of a new document. pub fn add_document(&mut self, doc: &Document) { for field_writer in &mut self.field_writers { field_writer.add_document(doc); } } /// Serializes all of the `FastFieldWriter`s by pushing them in /// order to the fast field serializer. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { for field_writer in &self.field_writers { field_writer.serialize(serializer)?; } Ok(()) } /// Ensures all of the fast field writers have /// reached `doc`. (included) /// /// The missing values will be filled with 0. pub fn fill_val_up_to(&mut self, doc: DocId) { for field_writer in &mut self.field_writers { field_writer.fill_val_up_to(doc); } } } /// Fast field writer for ints.
/// method. /// /// We cannot serialize earlier as the values are /// bitpacked and the number of bits required for bitpacking /// can only been known once we have seen all of the values. /// /// Both u64, and i64 use the same writer. /// i64 are just remapped to the `0..2^64 - 1` /// using `common::i64_to_u64`. pub struct IntFastFieldWriter { field: Field, vals: Vec<u8>, val_count: usize, val_if_missing: u64, val_min: u64, val_max: u64, } impl IntFastFieldWriter { /// Creates a new `IntFastFieldWriter` pub fn new(field: Field) -> IntFastFieldWriter { IntFastFieldWriter { field: field, vals: Vec::new(), val_count: 0, val_if_missing: 0u64, val_min: u64::max_value(), val_max: 0, } } /// Sets the default value. /// /// This default value is recorded for documents if /// a document does not have any value. fn set_val_if_missing(&mut self, val_if_missing: u64) { self.val_if_missing = val_if_missing; } /// Ensures all of the fast field writer have /// reached `doc`. (included) /// /// The missing values will be filled with 0. fn fill_val_up_to(&mut self, doc: DocId) { let target = doc as usize + 1; debug_assert!(self.val_count <= target); let val_if_missing = self.val_if_missing; while self.val_count < target { self.add_val(val_if_missing); } } /// Records a new value. /// /// The n-th value being recorded is implicitely /// associated to the document with the `DocId` n. /// (Well, `n-1` actually because of 0-indexing) pub fn add_val(&mut self, val: u64) { VInt(val) .serialize(&mut self.vals) .expect("unable to serialize VInt to Vec"); if val > self.val_max { self.val_max = val; } if val < self.val_min { self.val_min = val; } self.val_count += 1; } /// Extract the value associated to the fast field for /// this document. /// /// i64 are remapped to u64 using the logic /// in `common::i64_to_u64`. /// /// If the value is missing, then the default value is used /// instead. /// If the document has more than one value for the given field, /// only the first one is taken in account. fn extract_val(&self, doc: &Document) -> u64 { match doc.get_first(self.field) { Some(v) => { match *v { Value::U64(ref val) => *val, Value::I64(ref val) => common::i64_to_u64(*val), _ => panic!("Expected a u64field, got {:?} ", v), } } None => self.val_if_missing, } } /// Extract the fast field value from the document /// (or use the default value) and records it. pub fn add_document(&mut self, doc: &Document) { let val = self.extract_val(doc); self.add_val(val); } /// Push the fast fields value to the `FastFieldWriter`. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { let (min, max) = if self.val_min > self.val_max { (0, 0) } else { (self.val_min, self.val_max) }; serializer.new_u64_fast_field(self.field, min, max)?; let mut cursor = self.vals.as_slice(); while let Ok(VInt(val)) = VInt::deserialize(&mut cursor) { serializer.add_val(val)?; } serializer.close_field() } }
/// The fast field writer just keeps the values in memory. /// /// Only when the segment writer can be closed and /// persisted on disc, the fast field writer is /// sent to a `FastFieldSerializer` via the `.serialize(...)`
random_line_split
writer.rs
use schema::{Schema, Field, Document}; use fastfield::FastFieldSerializer; use std::io; use schema::Value; use DocId; use schema::FieldType; use common; use common::VInt; use common::BinarySerializable; /// The fastfieldswriter regroup all of the fast field writers. pub struct FastFieldsWriter { field_writers: Vec<IntFastFieldWriter>, } impl FastFieldsWriter { /// Create all `FastFieldWriter` required by the schema. pub fn from_schema(schema: &Schema) -> FastFieldsWriter { let field_writers: Vec<IntFastFieldWriter> = schema .fields() .iter() .enumerate() .flat_map(|(field_id, field_entry)| { let field = Field(field_id as u32); match *field_entry.field_type() { FieldType::I64(ref int_options) => { if int_options.is_fast() { let mut fast_field_writer = IntFastFieldWriter::new(field); fast_field_writer.set_val_if_missing(common::i64_to_u64(0i64)); Some(fast_field_writer) } else { None } } FieldType::U64(ref int_options) => { if int_options.is_fast() { Some(IntFastFieldWriter::new(field)) } else { None } } _ => None, } }) .collect(); FastFieldsWriter { field_writers: field_writers } } /// Returns a `FastFieldsWriter` /// with a `IntFastFieldWriter` for each /// of the field given in argument. pub fn new(fields: Vec<Field>) -> FastFieldsWriter { FastFieldsWriter { field_writers: fields.into_iter().map(IntFastFieldWriter::new).collect(), } } /// Get the `FastFieldWriter` associated to a field. pub fn get_field_writer(&mut self, field: Field) -> Option<&mut IntFastFieldWriter> { // TODO optimize self.field_writers .iter_mut() .find(|field_writer| field_writer.field == field) } /// Indexes all of the fastfields of a new document. pub fn add_document(&mut self, doc: &Document) { for field_writer in &mut self.field_writers { field_writer.add_document(doc); } } /// Serializes all of the `FastFieldWriter`s by pushing them in /// order to the fast field serializer. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { for field_writer in &self.field_writers { field_writer.serialize(serializer)?; } Ok(()) } /// Ensures all of the fast field writers have /// reached `doc`. (included) /// /// The missing values will be filled with 0. pub fn fill_val_up_to(&mut self, doc: DocId) { for field_writer in &mut self.field_writers { field_writer.fill_val_up_to(doc); } } } /// Fast field writer for ints. /// The fast field writer just keeps the values in memory. /// /// Only when the segment writer can be closed and /// persisted on disc, the fast field writer is /// sent to a `FastFieldSerializer` via the `.serialize(...)` /// method. /// /// We cannot serialize earlier as the values are /// bitpacked and the number of bits required for bitpacking /// can only been known once we have seen all of the values. /// /// Both u64, and i64 use the same writer. /// i64 are just remapped to the `0..2^64 - 1` /// using `common::i64_to_u64`. pub struct IntFastFieldWriter { field: Field, vals: Vec<u8>, val_count: usize, val_if_missing: u64, val_min: u64, val_max: u64, } impl IntFastFieldWriter { /// Creates a new `IntFastFieldWriter` pub fn new(field: Field) -> IntFastFieldWriter { IntFastFieldWriter { field: field, vals: Vec::new(), val_count: 0, val_if_missing: 0u64, val_min: u64::max_value(), val_max: 0, } } /// Sets the default value. /// /// This default value is recorded for documents if /// a document does not have any value. fn set_val_if_missing(&mut self, val_if_missing: u64) { self.val_if_missing = val_if_missing; } /// Ensures all of the fast field writer have /// reached `doc`. (included) /// /// The missing values will be filled with 0. fn fill_val_up_to(&mut self, doc: DocId) { let target = doc as usize + 1; debug_assert!(self.val_count <= target); let val_if_missing = self.val_if_missing; while self.val_count < target { self.add_val(val_if_missing); } } /// Records a new value. /// /// The n-th value being recorded is implicitely /// associated to the document with the `DocId` n. /// (Well, `n-1` actually because of 0-indexing) pub fn add_val(&mut self, val: u64) { VInt(val) .serialize(&mut self.vals) .expect("unable to serialize VInt to Vec"); if val > self.val_max { self.val_max = val; } if val < self.val_min { self.val_min = val; } self.val_count += 1; } /// Extract the value associated to the fast field for /// this document. /// /// i64 are remapped to u64 using the logic /// in `common::i64_to_u64`. /// /// If the value is missing, then the default value is used /// instead. /// If the document has more than one value for the given field, /// only the first one is taken in account. fn extract_val(&self, doc: &Document) -> u64 { match doc.get_first(self.field) { Some(v) => { match *v { Value::U64(ref val) => *val, Value::I64(ref val) => common::i64_to_u64(*val), _ => panic!("Expected a u64field, got {:?} ", v), } } None => self.val_if_missing, } } /// Extract the fast field value from the document /// (or use the default value) and records it. pub fn
(&mut self, doc: &Document) { let val = self.extract_val(doc); self.add_val(val); } /// Push the fast fields value to the `FastFieldWriter`. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { let (min, max) = if self.val_min > self.val_max { (0, 0) } else { (self.val_min, self.val_max) }; serializer.new_u64_fast_field(self.field, min, max)?; let mut cursor = self.vals.as_slice(); while let Ok(VInt(val)) = VInt::deserialize(&mut cursor) { serializer.add_val(val)?; } serializer.close_field() } }
add_document
identifier_name
body.rs
use std::io::Read; use std::fs::File; use std::fmt; /// Body type for a request. #[derive(Debug)] pub struct Body { reader: Kind, } impl Body { /// Instantiate a `Body` from a reader. /// /// # Note /// /// While allowing for many types to be used, these bodies do not have /// a way to reset to the beginning and be reused. This means that when /// encountering a 307 or 308 status code, instead of repeating the /// request at the new location, the `Response` will be returned with /// the redirect status code set. /// /// A `Body` constructed from a set of bytes, like `String` or `Vec<u8>`, /// are stored differently and can be reused. pub fn new<R: Read + Send +'static>(reader: R) -> Body { Body { reader: Kind::Reader(Box::new(reader), None), } } /// Create a `Body` from a `Reader` where we can predict the size in /// advance, but where we don't want to load the data in memory. This /// is useful if we need to ensure `Content-Length` is passed with the /// request. pub fn sized<R: Read + Send +'static>(reader: R, len: u64) -> Body { Body { reader: Kind::Reader(Box::new(reader), Some(len)), } } /* pub fn chunked(reader: ()) -> Body { unimplemented!() } */ } // useful for tests, but not publicly exposed #[cfg(test)] pub fn read_to_string(mut body: Body) -> ::std::io::Result<String> { let mut s = String::new(); match body.reader { Kind::Reader(ref mut reader, _) => { reader.read_to_string(&mut s) } Kind::Bytes(ref mut bytes) => { (&**bytes).read_to_string(&mut s) } }.map(|_| s) } enum Kind { Reader(Box<Read + Send>, Option<u64>), Bytes(Vec<u8>), } impl From<Vec<u8>> for Body { #[inline] fn from(v: Vec<u8>) -> Body { Body { reader: Kind::Bytes(v), } } } impl From<String> for Body { #[inline] fn from(s: String) -> Body { s.into_bytes().into() } } impl<'a> From<&'a [u8]> for Body { #[inline] fn from(s: &'a [u8]) -> Body { s.to_vec().into() } } impl<'a> From<&'a str> for Body { #[inline] fn from(s: &'a str) -> Body { s.as_bytes().into() } } impl From<File> for Body { #[inline] fn from(f: File) -> Body { let len = f.metadata().map(|m| m.len()).ok(); Body { reader: Kind::Reader(Box::new(f), len), } } } impl fmt::Debug for Kind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(), &Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(), } } } // Wraps a `std::io::Write`. //pub struct Pipe(Kind); pub fn as_hyper_body<'a>(body: &'a mut Body) -> ::hyper::client::Body<'a>
pub fn can_reset(body: &Body) -> bool { match body.reader { Kind::Bytes(_) => true, Kind::Reader(..) => false, } }
{ match body.reader { Kind::Bytes(ref bytes) => { let len = bytes.len(); ::hyper::client::Body::BufBody(bytes, len) } Kind::Reader(ref mut reader, len_opt) => { match len_opt { Some(len) => ::hyper::client::Body::SizedBody(reader, len), None => ::hyper::client::Body::ChunkedBody(reader), } } } }
identifier_body
body.rs
use std::io::Read; use std::fs::File; use std::fmt; /// Body type for a request. #[derive(Debug)] pub struct Body { reader: Kind, } impl Body { /// Instantiate a `Body` from a reader. /// /// # Note /// /// While allowing for many types to be used, these bodies do not have /// a way to reset to the beginning and be reused. This means that when /// encountering a 307 or 308 status code, instead of repeating the /// request at the new location, the `Response` will be returned with /// the redirect status code set. /// /// A `Body` constructed from a set of bytes, like `String` or `Vec<u8>`, /// are stored differently and can be reused. pub fn new<R: Read + Send +'static>(reader: R) -> Body { Body { reader: Kind::Reader(Box::new(reader), None), } } /// Create a `Body` from a `Reader` where we can predict the size in /// advance, but where we don't want to load the data in memory. This /// is useful if we need to ensure `Content-Length` is passed with the /// request. pub fn sized<R: Read + Send +'static>(reader: R, len: u64) -> Body { Body { reader: Kind::Reader(Box::new(reader), Some(len)), } } /* pub fn chunked(reader: ()) -> Body { unimplemented!() } */ } // useful for tests, but not publicly exposed #[cfg(test)] pub fn read_to_string(mut body: Body) -> ::std::io::Result<String> { let mut s = String::new(); match body.reader { Kind::Reader(ref mut reader, _) =>
Kind::Bytes(ref mut bytes) => { (&**bytes).read_to_string(&mut s) } }.map(|_| s) } enum Kind { Reader(Box<Read + Send>, Option<u64>), Bytes(Vec<u8>), } impl From<Vec<u8>> for Body { #[inline] fn from(v: Vec<u8>) -> Body { Body { reader: Kind::Bytes(v), } } } impl From<String> for Body { #[inline] fn from(s: String) -> Body { s.into_bytes().into() } } impl<'a> From<&'a [u8]> for Body { #[inline] fn from(s: &'a [u8]) -> Body { s.to_vec().into() } } impl<'a> From<&'a str> for Body { #[inline] fn from(s: &'a str) -> Body { s.as_bytes().into() } } impl From<File> for Body { #[inline] fn from(f: File) -> Body { let len = f.metadata().map(|m| m.len()).ok(); Body { reader: Kind::Reader(Box::new(f), len), } } } impl fmt::Debug for Kind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(), &Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(), } } } // Wraps a `std::io::Write`. //pub struct Pipe(Kind); pub fn as_hyper_body<'a>(body: &'a mut Body) -> ::hyper::client::Body<'a> { match body.reader { Kind::Bytes(ref bytes) => { let len = bytes.len(); ::hyper::client::Body::BufBody(bytes, len) } Kind::Reader(ref mut reader, len_opt) => { match len_opt { Some(len) => ::hyper::client::Body::SizedBody(reader, len), None => ::hyper::client::Body::ChunkedBody(reader), } } } } pub fn can_reset(body: &Body) -> bool { match body.reader { Kind::Bytes(_) => true, Kind::Reader(..) => false, } }
{ reader.read_to_string(&mut s) }
conditional_block
body.rs
use std::io::Read; use std::fs::File; use std::fmt; /// Body type for a request. #[derive(Debug)] pub struct Body { reader: Kind, } impl Body { /// Instantiate a `Body` from a reader. /// /// # Note /// /// While allowing for many types to be used, these bodies do not have /// a way to reset to the beginning and be reused. This means that when /// encountering a 307 or 308 status code, instead of repeating the /// request at the new location, the `Response` will be returned with /// the redirect status code set. /// /// A `Body` constructed from a set of bytes, like `String` or `Vec<u8>`, /// are stored differently and can be reused. pub fn new<R: Read + Send +'static>(reader: R) -> Body { Body { reader: Kind::Reader(Box::new(reader), None), } } /// Create a `Body` from a `Reader` where we can predict the size in /// advance, but where we don't want to load the data in memory. This /// is useful if we need to ensure `Content-Length` is passed with the /// request. pub fn sized<R: Read + Send +'static>(reader: R, len: u64) -> Body { Body { reader: Kind::Reader(Box::new(reader), Some(len)), } } /* pub fn chunked(reader: ()) -> Body { unimplemented!() } */ } // useful for tests, but not publicly exposed #[cfg(test)] pub fn read_to_string(mut body: Body) -> ::std::io::Result<String> { let mut s = String::new(); match body.reader { Kind::Reader(ref mut reader, _) => { reader.read_to_string(&mut s) } Kind::Bytes(ref mut bytes) => { (&**bytes).read_to_string(&mut s) } }.map(|_| s) } enum Kind { Reader(Box<Read + Send>, Option<u64>), Bytes(Vec<u8>), } impl From<Vec<u8>> for Body { #[inline] fn from(v: Vec<u8>) -> Body { Body { reader: Kind::Bytes(v), } } } impl From<String> for Body { #[inline] fn from(s: String) -> Body { s.into_bytes().into() } } impl<'a> From<&'a [u8]> for Body { #[inline] fn from(s: &'a [u8]) -> Body { s.to_vec().into() } } impl<'a> From<&'a str> for Body { #[inline] fn from(s: &'a str) -> Body { s.as_bytes().into() } } impl From<File> for Body { #[inline] fn from(f: File) -> Body { let len = f.metadata().map(|m| m.len()).ok(); Body { reader: Kind::Reader(Box::new(f), len), } } } impl fmt::Debug for Kind { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(), &Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(), } } } // Wraps a `std::io::Write`. //pub struct Pipe(Kind); pub fn as_hyper_body<'a>(body: &'a mut Body) -> ::hyper::client::Body<'a> { match body.reader { Kind::Bytes(ref bytes) => { let len = bytes.len(); ::hyper::client::Body::BufBody(bytes, len) } Kind::Reader(ref mut reader, len_opt) => { match len_opt { Some(len) => ::hyper::client::Body::SizedBody(reader, len), None => ::hyper::client::Body::ChunkedBody(reader), } } } } pub fn can_reset(body: &Body) -> bool { match body.reader { Kind::Bytes(_) => true, Kind::Reader(..) => false, } }
fmt
identifier_name
body.rs
use std::io::Read; use std::fs::File; use std::fmt; /// Body type for a request. #[derive(Debug)] pub struct Body { reader: Kind, } impl Body { /// Instantiate a `Body` from a reader. /// /// # Note /// /// While allowing for many types to be used, these bodies do not have /// a way to reset to the beginning and be reused. This means that when /// encountering a 307 or 308 status code, instead of repeating the /// request at the new location, the `Response` will be returned with /// the redirect status code set. /// /// A `Body` constructed from a set of bytes, like `String` or `Vec<u8>`, /// are stored differently and can be reused. pub fn new<R: Read + Send +'static>(reader: R) -> Body { Body { reader: Kind::Reader(Box::new(reader), None), } } /// Create a `Body` from a `Reader` where we can predict the size in /// advance, but where we don't want to load the data in memory. This /// is useful if we need to ensure `Content-Length` is passed with the /// request. pub fn sized<R: Read + Send +'static>(reader: R, len: u64) -> Body { Body { reader: Kind::Reader(Box::new(reader), Some(len)), } } /* pub fn chunked(reader: ()) -> Body { unimplemented!() } */ } // useful for tests, but not publicly exposed #[cfg(test)] pub fn read_to_string(mut body: Body) -> ::std::io::Result<String> { let mut s = String::new(); match body.reader { Kind::Reader(ref mut reader, _) => { reader.read_to_string(&mut s) } Kind::Bytes(ref mut bytes) => { (&**bytes).read_to_string(&mut s) } }.map(|_| s) } enum Kind { Reader(Box<Read + Send>, Option<u64>), Bytes(Vec<u8>), } impl From<Vec<u8>> for Body { #[inline] fn from(v: Vec<u8>) -> Body { Body { reader: Kind::Bytes(v), } } } impl From<String> for Body { #[inline] fn from(s: String) -> Body { s.into_bytes().into() } } impl<'a> From<&'a [u8]> for Body { #[inline] fn from(s: &'a [u8]) -> Body { s.to_vec().into() } } impl<'a> From<&'a str> for Body { #[inline] fn from(s: &'a str) -> Body { s.as_bytes().into() } } impl From<File> for Body {
} } } impl fmt::Debug for Kind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(), &Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(), } } } // Wraps a `std::io::Write`. //pub struct Pipe(Kind); pub fn as_hyper_body<'a>(body: &'a mut Body) -> ::hyper::client::Body<'a> { match body.reader { Kind::Bytes(ref bytes) => { let len = bytes.len(); ::hyper::client::Body::BufBody(bytes, len) } Kind::Reader(ref mut reader, len_opt) => { match len_opt { Some(len) => ::hyper::client::Body::SizedBody(reader, len), None => ::hyper::client::Body::ChunkedBody(reader), } } } } pub fn can_reset(body: &Body) -> bool { match body.reader { Kind::Bytes(_) => true, Kind::Reader(..) => false, } }
#[inline] fn from(f: File) -> Body { let len = f.metadata().map(|m| m.len()).ok(); Body { reader: Kind::Reader(Box::new(f), len),
random_line_split
mod.rs
::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ServoParserBinding; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::document::{Document, DocumentSource, IsHTMLDocument}; use dom::globalscope::GlobalScope; use dom::htmlformelement::HTMLFormElement; use dom::htmlimageelement::HTMLImageElement; use dom::htmlscriptelement::HTMLScriptElement; use dom::node::{Node, document_from_node, window_from_node}; use encoding::all::UTF_8; use encoding::types::{DecoderTrap, Encoding}; use html5ever::tokenizer::buffer_queue::BufferQueue; use hyper::header::ContentType; use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper_serde::Serde; use msg::constellation_msg::PipelineId; use net_traits::{FetchMetadata, FetchResponseListener, Metadata, NetworkError}; use network_listener::PreInvoke; use profile_traits::time::{TimerMetadata, TimerMetadataFrameType}; use profile_traits::time::{TimerMetadataReflowType, ProfilerCategory, profile}; use script_thread::ScriptThread; use servo_url::ServoUrl; use std::cell::Cell; use std::mem; use util::resource_files::read_resource_file; mod html; mod xml; #[dom_struct] /// The parser maintains two input streams: one for input from script through /// document.write(), and one for input from network. /// /// There is no concrete representation of the insertion point, instead it /// always points to just before the next character from the network input, /// with all of the script input before itself. /// /// ```text /// ... script input... |... network input... /// ^ /// insertion point /// ``` pub struct ServoParser { reflector: Reflector, /// The document associated with this parser. document: JS<Document>, /// The pipeline associated with this parse, unavailable if this parse /// does not correspond to a page load. pipeline: Option<PipelineId>, /// Input received from network. #[ignore_heap_size_of = "Defined in html5ever"] network_input: DOMRefCell<BufferQueue>, /// Input received from script. Used only to support document.write(). #[ignore_heap_size_of = "Defined in html5ever"] script_input: DOMRefCell<BufferQueue>, /// The tokenizer of this parser. tokenizer: DOMRefCell<Tokenizer>, /// Whether to expect any further input from the associated network request. last_chunk_received: Cell<bool>, /// Whether this parser should avoid passing any further data to the tokenizer. suspended: Cell<bool>, /// https://html.spec.whatwg.org/multipage/#script-nesting-level script_nesting_level: Cell<usize>, } #[derive(PartialEq)] enum LastChunkState { Received, NotReceived, } impl ServoParser { pub fn parse_html_document( document: &Document, input: DOMString, url: ServoUrl, owner: Option<PipelineId>) { let parser = ServoParser::new( document, owner, Tokenizer::Html(self::html::Tokenizer::new(document, url, None)), LastChunkState::NotReceived); parser.parse_chunk(String::from(input)); } // https://html.spec.whatwg.org/multipage/#parsing-html-fragments pub fn parse_html_fragment( context_node: &Node, input: DOMString, output: &Node) { let window = window_from_node(context_node); let context_document = document_from_node(context_node); let url = context_document.url(); // Step 1. let loader = DocumentLoader::new(&*context_document.loader()); let document = Document::new(&window, None, Some(url.clone()), IsHTMLDocument::HTMLDocument, None, None, DocumentSource::FromParser, loader, None, None); // Step 2. document.set_quirks_mode(context_document.quirks_mode()); // Step 11. let form = context_node.inclusive_ancestors() .find(|element| element.is::<HTMLFormElement>()); let fragment_context = FragmentContext { context_elem: context_node, form_elem: form.r(), }; let parser = ServoParser::new( &document, None, Tokenizer::Html( self::html::Tokenizer::new(&document, url.clone(), Some(fragment_context))), LastChunkState::Received); parser.parse_chunk(String::from(input)); // Step 14. let root_element = document.GetDocumentElement().expect("no document element"); for child in root_element.upcast::<Node>().children() { output.AppendChild(&child).unwrap(); } } pub fn parse_xml_document( document: &Document, input: DOMString, url: ServoUrl, owner: Option<PipelineId>) { let parser = ServoParser::new( document, owner, Tokenizer::Xml(self::xml::Tokenizer::new(document, url)), LastChunkState::NotReceived); parser.parse_chunk(String::from(input)); }
} /// Corresponds to the latter part of the "Otherwise" branch of the 'An end /// tag whose tag name is "script"' of /// https://html.spec.whatwg.org/multipage/#parsing-main-incdata /// /// This first moves everything from the script input to the beginning of /// the network input, effectively resetting the insertion point to just /// before the next character to be consumed. /// /// /// ```text /// |... script input... network input... /// ^ /// insertion point /// ``` pub fn resume_with_pending_parsing_blocking_script(&self, script: &HTMLScriptElement) { assert!(self.suspended.get()); self.suspended.set(false); mem::swap(&mut *self.script_input.borrow_mut(), &mut *self.network_input.borrow_mut()); while let Some(chunk) = self.script_input.borrow_mut().pop_front() { self.network_input.borrow_mut().push_back(chunk); } let script_nesting_level = self.script_nesting_level.get(); assert_eq!(script_nesting_level, 0); self.script_nesting_level.set(script_nesting_level + 1); script.execute(); self.script_nesting_level.set(script_nesting_level); if!self.suspended.get() { self.parse_sync(); } } /// Steps 6-8 of https://html.spec.whatwg.org/multipage/#document.write() pub fn write(&self, text: Vec<DOMString>) { assert!(self.script_nesting_level.get() > 0); if self.document.get_pending_parsing_blocking_script().is_some() { // There is already a pending parsing blocking script so the // parser is suspended, we just append everything to the // script input and abort these steps. for chunk in text { self.script_input.borrow_mut().push_back(String::from(chunk).into()); } return; } // There is no pending parsing blocking script, so all previous calls // to document.write() should have seen their entire input tokenized // and process, with nothing pushed to the parser script input. assert!(self.script_input.borrow().is_empty()); let mut input = BufferQueue::new(); for chunk in text { input.push_back(String::from(chunk).into()); } self.tokenize(|tokenizer| tokenizer.feed(&mut input)); if self.suspended.get() { // Parser got suspended, insert remaining input at end of // script input, following anything written by scripts executed // reentrantly during this call. while let Some(chunk) = input.pop_front() { self.script_input.borrow_mut().push_back(chunk); } return; } assert!(input.is_empty()); } #[allow(unrooted_must_root)] fn new_inherited( document: &Document, pipeline: Option<PipelineId>, tokenizer: Tokenizer, last_chunk_state: LastChunkState) -> Self { ServoParser { reflector: Reflector::new(), document: JS::from_ref(document), pipeline: pipeline, network_input: DOMRefCell::new(BufferQueue::new()), script_input: DOMRefCell::new(BufferQueue::new()), tokenizer: DOMRefCell::new(tokenizer), last_chunk_received: Cell::new(last_chunk_state == LastChunkState::Received), suspended: Default::default(), script_nesting_level: Default::default(), } } #[allow(unrooted_must_root)] fn new( document: &Document, pipeline: Option<PipelineId>, tokenizer: Tokenizer, last_chunk_state: LastChunkState) -> Root<Self> { reflect_dom_object( box ServoParser::new_inherited(document, pipeline, tokenizer, last_chunk_state), document.window(), ServoParserBinding::Wrap) } fn push_input_chunk(&self, chunk: String) { self.network_input.borrow_mut().push_back(chunk.into()); } fn parse_sync(&self) { let metadata = TimerMetadata { url: self.document.url().as_str().into(), iframe: TimerMetadataFrameType::RootWindow, incremental: TimerMetadataReflowType::FirstReflow, }; let profiler_category = self.tokenizer.borrow().profiler_category(); profile(profiler_category, Some(metadata), self.document.window().upcast::<GlobalScope>().time_profiler_chan().clone(), || self.do_parse_sync()) } fn do_parse_sync(&self) { assert!(self.script_input.borrow().is_empty()); // This parser will continue to parse while there is either pending input or // the parser remains unsuspended. self.tokenize(|tokenizer| tokenizer.feed(&mut *self.network_input.borrow_mut())); if self.suspended.get() { return; } assert!(self.network_input.borrow().is_empty()); if self.last_chunk_received.get() { self.finish(); } } fn parse_chunk(&self, input: String) { self.document.set_current_parser(Some(self)); self.push_input_chunk(input); if!self.suspended.get() { self.parse_sync(); } } fn tokenize<F>(&self, mut feed: F) where F: FnMut(&mut Tokenizer) -> Result<(), Root<HTMLScriptElement>> { loop { assert!(!self.suspended.get()); self.document.reflow_if_reflow_timer_expired(); let script = match feed(&mut *self.tokenizer.borrow_mut()) { Ok(()) => return, Err(script) => script, }; let script_nesting_level = self.script_nesting_level.get(); self.script_nesting_level.set(script_nesting_level + 1); script.prepare(); self.script_nesting_level.set(script_nesting_level); if self.document.get_pending_parsing_blocking_script().is_some() { self.suspended.set(true); return; } } } fn finish(&self) { assert!(!self.suspended.get()); assert!(self.last_chunk_received.get()); assert!(self.script_input.borrow().is_empty()); assert!(self.network_input.borrow().is_empty()); self.tokenizer.borrow_mut().end(); debug!("finished parsing"); self.document.set_current_parser(None); if let Some(pipeline) = self.pipeline { ScriptThread::parsing_complete(pipeline); } } } #[derive(HeapSizeOf, JSTraceable)] #[must_root] enum Tokenizer { Html(self::html::Tokenizer), Xml(self::xml::Tokenizer), } impl Tokenizer { fn feed(&mut self, input: &mut BufferQueue) -> Result<(), Root<HTMLScriptElement>> { match *self { Tokenizer::Html(ref mut tokenizer) => tokenizer.feed(input), Tokenizer::Xml(ref mut tokenizer) => tokenizer.feed(input), } } fn end(&mut self) { match *self { Tokenizer::Html(ref mut tokenizer) => tokenizer.end(), Tokenizer::Xml(ref mut tokenizer) => tokenizer.end(), } } fn set_plaintext_state(&mut self) { match *self { Tokenizer::Html(ref mut tokenizer) => tokenizer.set_plaintext_state(), Tokenizer::Xml(_) => unimplemented!(), } } fn profiler_category(&self) -> ProfilerCategory { match *self { Tokenizer::Html(_) => ProfilerCategory::ScriptParseHTML, Tokenizer::Xml(_) => ProfilerCategory::ScriptParseXML, } } } /// The context required for asynchronously fetching a document /// and parsing it progressively. pub struct ParserContext { /// The parser that initiated the request. parser: Option<Trusted<ServoParser>>, /// Is this a synthesized document is_synthesized_document: bool, /// The pipeline associated with this document. id: PipelineId, /// The URL for this document. url: ServoUrl, } impl ParserContext { pub fn new(id: PipelineId, url: ServoUrl) -> ParserContext { ParserContext { parser: None, is_synthesized_document: false, id: id, url: url, } } } impl FetchResponseListener for ParserContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, meta_result: Result<FetchMetadata, NetworkError>) { let mut ssl_error = None; let metadata = match meta_result { Ok(meta) => { Some(match meta { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_,.. } => unsafe_ }) }, Err(NetworkError::SslValidation(url, reason)) => { ssl_error = Some(reason); let mut meta = Metadata::default(url); let mime: Option<Mime> = "text/html".parse().ok(); meta.set_content_type(mime.as_ref()); Some(meta) }, Err(_) => None, }; let content_type = metadata.clone().and_then(|meta| meta.content_type).map(Serde::into_inner); let parser = match ScriptThread::page_headers_available(&self.id, metadata) { Some(parser) => parser, None => return, }; self.parser = Some(Trusted::new(&*parser)); match content_type { Some(ContentType(Mime(TopLevel::Image, _, _))) => { self.is_synthesized_document = true; let page = "<html><body></body></html>".into(); parser.push_input_chunk(page); parser.parse_sync(); let doc = &parser.document; let doc_body = Root::upcast::<Node>(doc.GetBody().unwrap()); let img = HTMLImageElement::new(local_name!("img"), None, doc); img.SetSrc(DOMString::from(self.url.to_string())); doc_body.AppendChild(&Root::upcast::<Node>(img)).expect("Appending failed"); }, Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) => { // https://html.spec.whatwg.org/multipage/#read-text let page = "<pre>\n".into(); parser.push_input_chunk(page); parser.parse_sync(); parser.tokenizer.borrow_mut().set_plaintext_state(); }, Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, _))) => { // Handle text/html if let Some(reason) = ssl_error { self.is_synthesized_document = true; let page_bytes = read_resource_file("badcert.html").unwrap(); let page = String::from_utf8(page_bytes).unwrap(); let page = page.replace("${reason}", &reason); parser.push_input_chunk(page); parser.parse_sync(); } }, Some(ContentType(Mime(TopLevel::Text, SubLevel::Xml, _))) => {}, // Handle text/xml Some(ContentType(Mime(toplevel, sublevel, _))) => { if toplevel.as_str() == "application" && sublevel.as_str() == "xhtml+xml" { // Handle xhtml (application/xhtml+xml). return; } // Show warning page for unknown mime types. let page = format!("<html><body><p>Unknown content type ({}/{}).</p></body></html>", toplevel.as_str(), sublevel.as_str()); self.is_synthesized_document = true; parser.push_input_chunk(page); parser.parse_sync(); }, None => { // No content-type header. // Merge with #4212 when fixed. } } } fn process_response_chunk(&mut self, payload: Vec<u8>) { if!self.is_synthesized_document { // FIXME: use Vec<u8> (html5ever #34) let data = UTF_8.decode(&payload, DecoderTrap::Replace).unwrap(); let parser = match self.parser.as_ref() { Some(parser) => parser.root(), None => return, }; parser.parse_chunk(data); } } fn process_response_eof(&mut self, status: Result<(), NetworkError>) { let parser = match self.parser.as_ref() { Some(parser) => parser.root(), None => return, }; if let Err(NetworkError::Internal(ref reason)) = status { // Show an error page for network errors, // certificate errors are handled earlier. self.is_synthesized_document = true; let page_bytes = read_resource_file("neterror.html").unwrap(); let page = String::from_utf8(page_bytes).unwrap(); let page = page.replace("${reason}", reason); parser.push_input_chunk(page); parser.parse_sync(); } else if let Err(err) = status { // TODO(Savago): we
pub fn script_nesting_level(&self) -> usize { self.script_nesting_level.get()
random_line_split
mod.rs
Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ServoParserBinding; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::document::{Document, DocumentSource, IsHTMLDocument}; use dom::globalscope::GlobalScope; use dom::htmlformelement::HTMLFormElement; use dom::htmlimageelement::HTMLImageElement; use dom::htmlscriptelement::HTMLScriptElement; use dom::node::{Node, document_from_node, window_from_node}; use encoding::all::UTF_8; use encoding::types::{DecoderTrap, Encoding}; use html5ever::tokenizer::buffer_queue::BufferQueue; use hyper::header::ContentType; use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper_serde::Serde; use msg::constellation_msg::PipelineId; use net_traits::{FetchMetadata, FetchResponseListener, Metadata, NetworkError}; use network_listener::PreInvoke; use profile_traits::time::{TimerMetadata, TimerMetadataFrameType}; use profile_traits::time::{TimerMetadataReflowType, ProfilerCategory, profile}; use script_thread::ScriptThread; use servo_url::ServoUrl; use std::cell::Cell; use std::mem; use util::resource_files::read_resource_file; mod html; mod xml; #[dom_struct] /// The parser maintains two input streams: one for input from script through /// document.write(), and one for input from network. /// /// There is no concrete representation of the insertion point, instead it /// always points to just before the next character from the network input, /// with all of the script input before itself. /// /// ```text /// ... script input... |... network input... /// ^ /// insertion point /// ``` pub struct ServoParser { reflector: Reflector, /// The document associated with this parser. document: JS<Document>, /// The pipeline associated with this parse, unavailable if this parse /// does not correspond to a page load. pipeline: Option<PipelineId>, /// Input received from network. #[ignore_heap_size_of = "Defined in html5ever"] network_input: DOMRefCell<BufferQueue>, /// Input received from script. Used only to support document.write(). #[ignore_heap_size_of = "Defined in html5ever"] script_input: DOMRefCell<BufferQueue>, /// The tokenizer of this parser. tokenizer: DOMRefCell<Tokenizer>, /// Whether to expect any further input from the associated network request. last_chunk_received: Cell<bool>, /// Whether this parser should avoid passing any further data to the tokenizer. suspended: Cell<bool>, /// https://html.spec.whatwg.org/multipage/#script-nesting-level script_nesting_level: Cell<usize>, } #[derive(PartialEq)] enum
{ Received, NotReceived, } impl ServoParser { pub fn parse_html_document( document: &Document, input: DOMString, url: ServoUrl, owner: Option<PipelineId>) { let parser = ServoParser::new( document, owner, Tokenizer::Html(self::html::Tokenizer::new(document, url, None)), LastChunkState::NotReceived); parser.parse_chunk(String::from(input)); } // https://html.spec.whatwg.org/multipage/#parsing-html-fragments pub fn parse_html_fragment( context_node: &Node, input: DOMString, output: &Node) { let window = window_from_node(context_node); let context_document = document_from_node(context_node); let url = context_document.url(); // Step 1. let loader = DocumentLoader::new(&*context_document.loader()); let document = Document::new(&window, None, Some(url.clone()), IsHTMLDocument::HTMLDocument, None, None, DocumentSource::FromParser, loader, None, None); // Step 2. document.set_quirks_mode(context_document.quirks_mode()); // Step 11. let form = context_node.inclusive_ancestors() .find(|element| element.is::<HTMLFormElement>()); let fragment_context = FragmentContext { context_elem: context_node, form_elem: form.r(), }; let parser = ServoParser::new( &document, None, Tokenizer::Html( self::html::Tokenizer::new(&document, url.clone(), Some(fragment_context))), LastChunkState::Received); parser.parse_chunk(String::from(input)); // Step 14. let root_element = document.GetDocumentElement().expect("no document element"); for child in root_element.upcast::<Node>().children() { output.AppendChild(&child).unwrap(); } } pub fn parse_xml_document( document: &Document, input: DOMString, url: ServoUrl, owner: Option<PipelineId>) { let parser = ServoParser::new( document, owner, Tokenizer::Xml(self::xml::Tokenizer::new(document, url)), LastChunkState::NotReceived); parser.parse_chunk(String::from(input)); } pub fn script_nesting_level(&self) -> usize { self.script_nesting_level.get() } /// Corresponds to the latter part of the "Otherwise" branch of the 'An end /// tag whose tag name is "script"' of /// https://html.spec.whatwg.org/multipage/#parsing-main-incdata /// /// This first moves everything from the script input to the beginning of /// the network input, effectively resetting the insertion point to just /// before the next character to be consumed. /// /// /// ```text /// |... script input... network input... /// ^ /// insertion point /// ``` pub fn resume_with_pending_parsing_blocking_script(&self, script: &HTMLScriptElement) { assert!(self.suspended.get()); self.suspended.set(false); mem::swap(&mut *self.script_input.borrow_mut(), &mut *self.network_input.borrow_mut()); while let Some(chunk) = self.script_input.borrow_mut().pop_front() { self.network_input.borrow_mut().push_back(chunk); } let script_nesting_level = self.script_nesting_level.get(); assert_eq!(script_nesting_level, 0); self.script_nesting_level.set(script_nesting_level + 1); script.execute(); self.script_nesting_level.set(script_nesting_level); if!self.suspended.get() { self.parse_sync(); } } /// Steps 6-8 of https://html.spec.whatwg.org/multipage/#document.write() pub fn write(&self, text: Vec<DOMString>) { assert!(self.script_nesting_level.get() > 0); if self.document.get_pending_parsing_blocking_script().is_some() { // There is already a pending parsing blocking script so the // parser is suspended, we just append everything to the // script input and abort these steps. for chunk in text { self.script_input.borrow_mut().push_back(String::from(chunk).into()); } return; } // There is no pending parsing blocking script, so all previous calls // to document.write() should have seen their entire input tokenized // and process, with nothing pushed to the parser script input. assert!(self.script_input.borrow().is_empty()); let mut input = BufferQueue::new(); for chunk in text { input.push_back(String::from(chunk).into()); } self.tokenize(|tokenizer| tokenizer.feed(&mut input)); if self.suspended.get() { // Parser got suspended, insert remaining input at end of // script input, following anything written by scripts executed // reentrantly during this call. while let Some(chunk) = input.pop_front() { self.script_input.borrow_mut().push_back(chunk); } return; } assert!(input.is_empty()); } #[allow(unrooted_must_root)] fn new_inherited( document: &Document, pipeline: Option<PipelineId>, tokenizer: Tokenizer, last_chunk_state: LastChunkState) -> Self { ServoParser { reflector: Reflector::new(), document: JS::from_ref(document), pipeline: pipeline, network_input: DOMRefCell::new(BufferQueue::new()), script_input: DOMRefCell::new(BufferQueue::new()), tokenizer: DOMRefCell::new(tokenizer), last_chunk_received: Cell::new(last_chunk_state == LastChunkState::Received), suspended: Default::default(), script_nesting_level: Default::default(), } } #[allow(unrooted_must_root)] fn new( document: &Document, pipeline: Option<PipelineId>, tokenizer: Tokenizer, last_chunk_state: LastChunkState) -> Root<Self> { reflect_dom_object( box ServoParser::new_inherited(document, pipeline, tokenizer, last_chunk_state), document.window(), ServoParserBinding::Wrap) } fn push_input_chunk(&self, chunk: String) { self.network_input.borrow_mut().push_back(chunk.into()); } fn parse_sync(&self) { let metadata = TimerMetadata { url: self.document.url().as_str().into(), iframe: TimerMetadataFrameType::RootWindow, incremental: TimerMetadataReflowType::FirstReflow, }; let profiler_category = self.tokenizer.borrow().profiler_category(); profile(profiler_category, Some(metadata), self.document.window().upcast::<GlobalScope>().time_profiler_chan().clone(), || self.do_parse_sync()) } fn do_parse_sync(&self) { assert!(self.script_input.borrow().is_empty()); // This parser will continue to parse while there is either pending input or // the parser remains unsuspended. self.tokenize(|tokenizer| tokenizer.feed(&mut *self.network_input.borrow_mut())); if self.suspended.get() { return; } assert!(self.network_input.borrow().is_empty()); if self.last_chunk_received.get() { self.finish(); } } fn parse_chunk(&self, input: String) { self.document.set_current_parser(Some(self)); self.push_input_chunk(input); if!self.suspended.get() { self.parse_sync(); } } fn tokenize<F>(&self, mut feed: F) where F: FnMut(&mut Tokenizer) -> Result<(), Root<HTMLScriptElement>> { loop { assert!(!self.suspended.get()); self.document.reflow_if_reflow_timer_expired(); let script = match feed(&mut *self.tokenizer.borrow_mut()) { Ok(()) => return, Err(script) => script, }; let script_nesting_level = self.script_nesting_level.get(); self.script_nesting_level.set(script_nesting_level + 1); script.prepare(); self.script_nesting_level.set(script_nesting_level); if self.document.get_pending_parsing_blocking_script().is_some() { self.suspended.set(true); return; } } } fn finish(&self) { assert!(!self.suspended.get()); assert!(self.last_chunk_received.get()); assert!(self.script_input.borrow().is_empty()); assert!(self.network_input.borrow().is_empty()); self.tokenizer.borrow_mut().end(); debug!("finished parsing"); self.document.set_current_parser(None); if let Some(pipeline) = self.pipeline { ScriptThread::parsing_complete(pipeline); } } } #[derive(HeapSizeOf, JSTraceable)] #[must_root] enum Tokenizer { Html(self::html::Tokenizer), Xml(self::xml::Tokenizer), } impl Tokenizer { fn feed(&mut self, input: &mut BufferQueue) -> Result<(), Root<HTMLScriptElement>> { match *self { Tokenizer::Html(ref mut tokenizer) => tokenizer.feed(input), Tokenizer::Xml(ref mut tokenizer) => tokenizer.feed(input), } } fn end(&mut self) { match *self { Tokenizer::Html(ref mut tokenizer) => tokenizer.end(), Tokenizer::Xml(ref mut tokenizer) => tokenizer.end(), } } fn set_plaintext_state(&mut self) { match *self { Tokenizer::Html(ref mut tokenizer) => tokenizer.set_plaintext_state(), Tokenizer::Xml(_) => unimplemented!(), } } fn profiler_category(&self) -> ProfilerCategory { match *self { Tokenizer::Html(_) => ProfilerCategory::ScriptParseHTML, Tokenizer::Xml(_) => ProfilerCategory::ScriptParseXML, } } } /// The context required for asynchronously fetching a document /// and parsing it progressively. pub struct ParserContext { /// The parser that initiated the request. parser: Option<Trusted<ServoParser>>, /// Is this a synthesized document is_synthesized_document: bool, /// The pipeline associated with this document. id: PipelineId, /// The URL for this document. url: ServoUrl, } impl ParserContext { pub fn new(id: PipelineId, url: ServoUrl) -> ParserContext { ParserContext { parser: None, is_synthesized_document: false, id: id, url: url, } } } impl FetchResponseListener for ParserContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, meta_result: Result<FetchMetadata, NetworkError>) { let mut ssl_error = None; let metadata = match meta_result { Ok(meta) => { Some(match meta { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_,.. } => unsafe_ }) }, Err(NetworkError::SslValidation(url, reason)) => { ssl_error = Some(reason); let mut meta = Metadata::default(url); let mime: Option<Mime> = "text/html".parse().ok(); meta.set_content_type(mime.as_ref()); Some(meta) }, Err(_) => None, }; let content_type = metadata.clone().and_then(|meta| meta.content_type).map(Serde::into_inner); let parser = match ScriptThread::page_headers_available(&self.id, metadata) { Some(parser) => parser, None => return, }; self.parser = Some(Trusted::new(&*parser)); match content_type { Some(ContentType(Mime(TopLevel::Image, _, _))) => { self.is_synthesized_document = true; let page = "<html><body></body></html>".into(); parser.push_input_chunk(page); parser.parse_sync(); let doc = &parser.document; let doc_body = Root::upcast::<Node>(doc.GetBody().unwrap()); let img = HTMLImageElement::new(local_name!("img"), None, doc); img.SetSrc(DOMString::from(self.url.to_string())); doc_body.AppendChild(&Root::upcast::<Node>(img)).expect("Appending failed"); }, Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) => { // https://html.spec.whatwg.org/multipage/#read-text let page = "<pre>\n".into(); parser.push_input_chunk(page); parser.parse_sync(); parser.tokenizer.borrow_mut().set_plaintext_state(); }, Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, _))) => { // Handle text/html if let Some(reason) = ssl_error { self.is_synthesized_document = true; let page_bytes = read_resource_file("badcert.html").unwrap(); let page = String::from_utf8(page_bytes).unwrap(); let page = page.replace("${reason}", &reason); parser.push_input_chunk(page); parser.parse_sync(); } }, Some(ContentType(Mime(TopLevel::Text, SubLevel::Xml, _))) => {}, // Handle text/xml Some(ContentType(Mime(toplevel, sublevel, _))) => { if toplevel.as_str() == "application" && sublevel.as_str() == "xhtml+xml" { // Handle xhtml (application/xhtml+xml). return; } // Show warning page for unknown mime types. let page = format!("<html><body><p>Unknown content type ({}/{}).</p></body></html>", toplevel.as_str(), sublevel.as_str()); self.is_synthesized_document = true; parser.push_input_chunk(page); parser.parse_sync(); }, None => { // No content-type header. // Merge with #4212 when fixed. } } } fn process_response_chunk(&mut self, payload: Vec<u8>) { if!self.is_synthesized_document { // FIXME: use Vec<u8> (html5ever #34) let data = UTF_8.decode(&payload, DecoderTrap::Replace).unwrap(); let parser = match self.parser.as_ref() { Some(parser) => parser.root(), None => return, }; parser.parse_chunk(data); } } fn process_response_eof(&mut self, status: Result<(), NetworkError>) { let parser = match self.parser.as_ref() { Some(parser) => parser.root(), None => return, }; if let Err(NetworkError::Internal(ref reason)) = status { // Show an error page for network errors, // certificate errors are handled earlier. self.is_synthesized_document = true; let page_bytes = read_resource_file("neterror.html").unwrap(); let page = String::from_utf8(page_bytes).unwrap(); let page = page.replace("${reason}", reason); parser.push_input_chunk(page); parser.parse_sync(); } else if let Err(err) = status { // TODO(Savago
LastChunkState
identifier_name
handlers.rs
use x11::xlib; use window_system::WindowSystem; use libc::{c_ulong}; pub struct KeyPressedHandler; pub struct MapRequestHandler; fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong { let border_width = 2; unsafe { let border = xlib::XWhitePixel(window_system.display, xlib::XDefaultScreen(window_system.display)); let background = xlib::XBlackPixel(window_system.display, xlib::XDefaultScreen(window_system.display)); let window = xlib::XCreateSimpleWindow(window_system.display, window_system.root,
border_width, border,background); xlib::XSelectInput(window_system.display, window, xlib::SubstructureNotifyMask | xlib::SubstructureRedirectMask); return window; } } impl MapRequestHandler { pub fn new() -> MapRequestHandler { return MapRequestHandler; } pub fn handle(&self, event: xlib::XEvent, window_system: &WindowSystem) { let event = xlib::XMapRequestEvent::from(event); let height: u32; let width: u32; let mut x: i32 = 0; let y: i32 = 0; if window_system.count.get() == 0 { width = window_system.info.width as u32; height = window_system.info.height as u32; } else { width = (window_system.info.width / 2) as u32; height = window_system.info.height as u32; x = width as i32; } // create frame as a new parent for the window to be mapped let frame = create_some_window(window_system, width, height, x, y); unsafe { // resize window to fit parent xlib::XResizeWindow(window_system.display, event.window, width as u32, height as u32); // make frame window parent of window to be mapped xlib::XReparentWindow(window_system.display, event.window, frame, 0, 0); // show frame xlib::XMapWindow(window_system.display, frame); // show window inside frame xlib::XMapWindow(window_system.display, event.window); } window_system.count.set(window_system.count.get() + 1); } } impl KeyPressedHandler { pub fn new() -> KeyPressedHandler { return KeyPressedHandler; } pub fn handle(&self, event: xlib::XEvent) { let event = xlib::XKeyPressedEvent::from(event); println!("KeyPressed {}", event.keycode); } }
x, y, width, height,
random_line_split
handlers.rs
use x11::xlib; use window_system::WindowSystem; use libc::{c_ulong}; pub struct KeyPressedHandler; pub struct MapRequestHandler; fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong { let border_width = 2; unsafe { let border = xlib::XWhitePixel(window_system.display, xlib::XDefaultScreen(window_system.display)); let background = xlib::XBlackPixel(window_system.display, xlib::XDefaultScreen(window_system.display)); let window = xlib::XCreateSimpleWindow(window_system.display, window_system.root, x, y, width, height, border_width, border,background); xlib::XSelectInput(window_system.display, window, xlib::SubstructureNotifyMask | xlib::SubstructureRedirectMask); return window; } } impl MapRequestHandler { pub fn new() -> MapRequestHandler { return MapRequestHandler; } pub fn handle(&self, event: xlib::XEvent, window_system: &WindowSystem) { let event = xlib::XMapRequestEvent::from(event); let height: u32; let width: u32; let mut x: i32 = 0; let y: i32 = 0; if window_system.count.get() == 0
else { width = (window_system.info.width / 2) as u32; height = window_system.info.height as u32; x = width as i32; } // create frame as a new parent for the window to be mapped let frame = create_some_window(window_system, width, height, x, y); unsafe { // resize window to fit parent xlib::XResizeWindow(window_system.display, event.window, width as u32, height as u32); // make frame window parent of window to be mapped xlib::XReparentWindow(window_system.display, event.window, frame, 0, 0); // show frame xlib::XMapWindow(window_system.display, frame); // show window inside frame xlib::XMapWindow(window_system.display, event.window); } window_system.count.set(window_system.count.get() + 1); } } impl KeyPressedHandler { pub fn new() -> KeyPressedHandler { return KeyPressedHandler; } pub fn handle(&self, event: xlib::XEvent) { let event = xlib::XKeyPressedEvent::from(event); println!("KeyPressed {}", event.keycode); } }
{ width = window_system.info.width as u32; height = window_system.info.height as u32; }
conditional_block
handlers.rs
use x11::xlib; use window_system::WindowSystem; use libc::{c_ulong}; pub struct KeyPressedHandler; pub struct
; fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong { let border_width = 2; unsafe { let border = xlib::XWhitePixel(window_system.display, xlib::XDefaultScreen(window_system.display)); let background = xlib::XBlackPixel(window_system.display, xlib::XDefaultScreen(window_system.display)); let window = xlib::XCreateSimpleWindow(window_system.display, window_system.root, x, y, width, height, border_width, border,background); xlib::XSelectInput(window_system.display, window, xlib::SubstructureNotifyMask | xlib::SubstructureRedirectMask); return window; } } impl MapRequestHandler { pub fn new() -> MapRequestHandler { return MapRequestHandler; } pub fn handle(&self, event: xlib::XEvent, window_system: &WindowSystem) { let event = xlib::XMapRequestEvent::from(event); let height: u32; let width: u32; let mut x: i32 = 0; let y: i32 = 0; if window_system.count.get() == 0 { width = window_system.info.width as u32; height = window_system.info.height as u32; } else { width = (window_system.info.width / 2) as u32; height = window_system.info.height as u32; x = width as i32; } // create frame as a new parent for the window to be mapped let frame = create_some_window(window_system, width, height, x, y); unsafe { // resize window to fit parent xlib::XResizeWindow(window_system.display, event.window, width as u32, height as u32); // make frame window parent of window to be mapped xlib::XReparentWindow(window_system.display, event.window, frame, 0, 0); // show frame xlib::XMapWindow(window_system.display, frame); // show window inside frame xlib::XMapWindow(window_system.display, event.window); } window_system.count.set(window_system.count.get() + 1); } } impl KeyPressedHandler { pub fn new() -> KeyPressedHandler { return KeyPressedHandler; } pub fn handle(&self, event: xlib::XEvent) { let event = xlib::XKeyPressedEvent::from(event); println!("KeyPressed {}", event.keycode); } }
MapRequestHandler
identifier_name
main.rs
#![macro_use] extern crate clap; use std::fs; fn main()
} if!p.ends_with(".MP4") { continue; } // 0123456789AB // GX030293.MP4 if p.len()!= 0xc { continue; } let s = match p.to_str() { Some(s) => s, None => continue, } // P (x264) or X (x265) // note: we could probably mix these. let k = s[1]; // GXaa1234 - aa - the index of clip let i = s[2..4]; // GX01bbbb - bbbb - the number of the video (composed of clips) let n = s[4..8]; bases.entry((k, n)). } } println!("Hello, world!"); }
{ let matches = app_from_crate!() .subcommand(SubCommand::with_name("create-combine-lists") .arg(Arg::with_name("DIR") .required(true) .index(1) ) ).get_matches(); if let Some(matches) = matches.subcommand_matches("create-combine-lists") { let mut bases = HashMap::new(); let d = matches.value_of("DIR").unwrap(); let paths = fs::read_dir(d); for p in paths { // check for a pattern match if !p.starts_with("G") { continue;
identifier_body
main.rs
#![macro_use] extern crate clap; use std::fs; fn main() { let matches = app_from_crate!() .subcommand(SubCommand::with_name("create-combine-lists") .arg(Arg::with_name("DIR") .required(true) .index(1) ) ).get_matches(); if let Some(matches) = matches.subcommand_matches("create-combine-lists") { let mut bases = HashMap::new(); let d = matches.value_of("DIR").unwrap(); let paths = fs::read_dir(d); for p in paths { // check for a pattern match if!p.starts_with("G") { continue; } if!p.ends_with(".MP4") { continue; } // 0123456789AB // GX030293.MP4 if p.len()!= 0xc { continue; } let s = match p.to_str() { Some(s) => s, None => continue, } // P (x264) or X (x265)
let n = s[4..8]; bases.entry((k, n)). } } println!("Hello, world!"); }
// note: we could probably mix these. let k = s[1]; // GXaa1234 - aa - the index of clip let i = s[2..4]; // GX01bbbb - bbbb - the number of the video (composed of clips)
random_line_split
main.rs
#![macro_use] extern crate clap; use std::fs; fn
() { let matches = app_from_crate!() .subcommand(SubCommand::with_name("create-combine-lists") .arg(Arg::with_name("DIR") .required(true) .index(1) ) ).get_matches(); if let Some(matches) = matches.subcommand_matches("create-combine-lists") { let mut bases = HashMap::new(); let d = matches.value_of("DIR").unwrap(); let paths = fs::read_dir(d); for p in paths { // check for a pattern match if!p.starts_with("G") { continue; } if!p.ends_with(".MP4") { continue; } // 0123456789AB // GX030293.MP4 if p.len()!= 0xc { continue; } let s = match p.to_str() { Some(s) => s, None => continue, } // P (x264) or X (x265) // note: we could probably mix these. let k = s[1]; // GXaa1234 - aa - the index of clip let i = s[2..4]; // GX01bbbb - bbbb - the number of the video (composed of clips) let n = s[4..8]; bases.entry((k, n)). } } println!("Hello, world!"); }
main
identifier_name
main.rs
#![macro_use] extern crate clap; use std::fs; fn main() { let matches = app_from_crate!() .subcommand(SubCommand::with_name("create-combine-lists") .arg(Arg::with_name("DIR") .required(true) .index(1) ) ).get_matches(); if let Some(matches) = matches.subcommand_matches("create-combine-lists") { let mut bases = HashMap::new(); let d = matches.value_of("DIR").unwrap(); let paths = fs::read_dir(d); for p in paths { // check for a pattern match if!p.starts_with("G") { continue; } if!p.ends_with(".MP4") { continue; } // 0123456789AB // GX030293.MP4 if p.len()!= 0xc
let s = match p.to_str() { Some(s) => s, None => continue, } // P (x264) or X (x265) // note: we could probably mix these. let k = s[1]; // GXaa1234 - aa - the index of clip let i = s[2..4]; // GX01bbbb - bbbb - the number of the video (composed of clips) let n = s[4..8]; bases.entry((k, n)). } } println!("Hello, world!"); }
{ continue; }
conditional_block
mod.rs
use crate::{ commands::CommandHelpers, entity::{EntityRef, Realm}, player_output::PlayerOutput, }; mod enter_room_command; pub use enter_room_command::enter_room; pub fn
<F>( f: F, ) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>> where F: Fn(&mut Realm, EntityRef, CommandHelpers) -> Result<Vec<PlayerOutput>, String> +'static, { Box::new( move |realm, player_ref, helpers| match realm.player(player_ref) { Some(player) if player.is_admin() => match f(realm, player_ref, helpers) { Ok(output) => output, Err(mut message) => { message.push('\n'); let mut output: Vec<PlayerOutput> = Vec::new(); push_output_string!(output, player_ref, message); output } }, _ => { let mut output: Vec<PlayerOutput> = Vec::new(); push_output_str!(output, player_ref, "You are not an admin."); output } }, ) }
wrap_admin_command
identifier_name
mod.rs
use crate::{ commands::CommandHelpers, entity::{EntityRef, Realm}, player_output::PlayerOutput, }; mod enter_room_command; pub use enter_room_command::enter_room; pub fn wrap_admin_command<F>( f: F, ) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>> where F: Fn(&mut Realm, EntityRef, CommandHelpers) -> Result<Vec<PlayerOutput>, String> +'static,
{ Box::new( move |realm, player_ref, helpers| match realm.player(player_ref) { Some(player) if player.is_admin() => match f(realm, player_ref, helpers) { Ok(output) => output, Err(mut message) => { message.push('\n'); let mut output: Vec<PlayerOutput> = Vec::new(); push_output_string!(output, player_ref, message); output } }, _ => { let mut output: Vec<PlayerOutput> = Vec::new(); push_output_str!(output, player_ref, "You are not an admin."); output } }, ) }
identifier_body
mod.rs
use crate::{ commands::CommandHelpers, entity::{EntityRef, Realm}, player_output::PlayerOutput, }; mod enter_room_command; pub use enter_room_command::enter_room; pub fn wrap_admin_command<F>( f: F, ) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>> where F: Fn(&mut Realm, EntityRef, CommandHelpers) -> Result<Vec<PlayerOutput>, String> +'static, { Box::new( move |realm, player_ref, helpers| match realm.player(player_ref) { Some(player) if player.is_admin() => match f(realm, player_ref, helpers) { Ok(output) => output, Err(mut message) => { message.push('\n');
push_output_string!(output, player_ref, message); output } }, _ => { let mut output: Vec<PlayerOutput> = Vec::new(); push_output_str!(output, player_ref, "You are not an admin."); output } }, ) }
let mut output: Vec<PlayerOutput> = Vec::new();
random_line_split
rand_util.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. extern mod std; use std::rand; // random uint less than n fn under(r : rand::rng, n : uint) -> uint { assert!(n!= 0u); r.next() as uint % n } // random choice from a vec fn choice<T:copy>(r : rand::rng, v : ~[T]) -> T { assert!(vec::len(v)!= 0u); v[under(r, vec::len(v))] } // 1 in n chance of being true fn
(r : rand::rng, n : uint) -> bool { under(r, n) == 0u } // shuffle a vec in place fn shuffle<T>(r : rand::rng, &v : ~[T]) { let i = vec::len(v); while i >= 2u { // Loop invariant: elements with index >= i have been locked in place. i -= 1u; vec::swap(v, i, under(r, i + 1u)); // Lock element i in place. } } // create a shuffled copy of a vec fn shuffled<T:copy>(r : rand::rng, v : ~[T]) -> ~[T] { let w = vec::to_mut(v); shuffle(r, w); vec::from_mut(w) // Shouldn't this happen automatically? } // sample from a population without replacement //fn sample<T>(r : rand::rng, pop : ~[T], k : uint) -> ~[T] { fail!() } // Two ways to make a weighted choice. // * weighted_choice is O(number of choices) time // * weighted_vec is O(total weight) space type weighted<T> = { weight: uint, item: T }; fn weighted_choice<T:copy>(r : rand::rng, v : ~[weighted<T>]) -> T { assert!(vec::len(v)!= 0u); let total = 0u; for {weight: weight, item: _} in v { total += weight; } assert!(total >= 0u); let chosen = under(r, total); let so_far = 0u; for {weight: weight, item: item} in v { so_far += weight; if so_far > chosen { return item; } } core::unreachable(); } fn weighted_vec<T:copy>(v : ~[weighted<T>]) -> ~[T] { let r = ~[]; for {weight: weight, item: item} in v { let i = 0u; while i < weight { r.push(item); i += 1u; } } r } fn main() { let r = rand::mk_rng(); log(error, under(r, 5u)); log(error, choice(r, ~[10, 20, 30])); log(error, if unlikely(r, 5u) { "unlikely" } else { "likely" }); let mut a = ~[1, 2, 3]; shuffle(r, a); log(error, a); let i = 0u; let v = ~[ {weight:1u, item:"low"}, {weight:8u, item:"middle"}, {weight:1u, item:"high"} ]; let w = weighted_vec(v); while i < 1000u { log(error, "Immed: " + weighted_choice(r, v)); log(error, "Fast: " + choice(r, w)); i += 1u; } }
unlikely
identifier_name
rand_util.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. extern mod std; use std::rand; // random uint less than n fn under(r : rand::rng, n : uint) -> uint { assert!(n!= 0u); r.next() as uint % n } // random choice from a vec fn choice<T:copy>(r : rand::rng, v : ~[T]) -> T { assert!(vec::len(v)!= 0u); v[under(r, vec::len(v))] } // 1 in n chance of being true fn unlikely(r : rand::rng, n : uint) -> bool { under(r, n) == 0u } // shuffle a vec in place fn shuffle<T>(r : rand::rng, &v : ~[T]) { let i = vec::len(v); while i >= 2u { // Loop invariant: elements with index >= i have been locked in place. i -= 1u; vec::swap(v, i, under(r, i + 1u)); // Lock element i in place. } } // create a shuffled copy of a vec fn shuffled<T:copy>(r : rand::rng, v : ~[T]) -> ~[T] { let w = vec::to_mut(v); shuffle(r, w); vec::from_mut(w) // Shouldn't this happen automatically? } // sample from a population without replacement //fn sample<T>(r : rand::rng, pop : ~[T], k : uint) -> ~[T] { fail!() } // Two ways to make a weighted choice. // * weighted_choice is O(number of choices) time // * weighted_vec is O(total weight) space type weighted<T> = { weight: uint, item: T }; fn weighted_choice<T:copy>(r : rand::rng, v : ~[weighted<T>]) -> T { assert!(vec::len(v)!= 0u); let total = 0u; for {weight: weight, item: _} in v { total += weight; } assert!(total >= 0u); let chosen = under(r, total); let so_far = 0u; for {weight: weight, item: item} in v { so_far += weight; if so_far > chosen { return item; } } core::unreachable(); } fn weighted_vec<T:copy>(v : ~[weighted<T>]) -> ~[T] { let r = ~[]; for {weight: weight, item: item} in v { let i = 0u; while i < weight { r.push(item); i += 1u; } } r } fn main() { let r = rand::mk_rng(); log(error, under(r, 5u)); log(error, choice(r, ~[10, 20, 30])); log(error, if unlikely(r, 5u) { "unlikely" } else
); let mut a = ~[1, 2, 3]; shuffle(r, a); log(error, a); let i = 0u; let v = ~[ {weight:1u, item:"low"}, {weight:8u, item:"middle"}, {weight:1u, item:"high"} ]; let w = weighted_vec(v); while i < 1000u { log(error, "Immed: " + weighted_choice(r, v)); log(error, "Fast: " + choice(r, w)); i += 1u; } }
{ "likely" }
conditional_block
rand_util.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. extern mod std; use std::rand; // random uint less than n fn under(r : rand::rng, n : uint) -> uint { assert!(n!= 0u); r.next() as uint % n } // random choice from a vec fn choice<T:copy>(r : rand::rng, v : ~[T]) -> T { assert!(vec::len(v)!= 0u); v[under(r, vec::len(v))] } // 1 in n chance of being true fn unlikely(r : rand::rng, n : uint) -> bool { under(r, n) == 0u } // shuffle a vec in place fn shuffle<T>(r : rand::rng, &v : ~[T]) { let i = vec::len(v); while i >= 2u { // Loop invariant: elements with index >= i have been locked in place. i -= 1u; vec::swap(v, i, under(r, i + 1u)); // Lock element i in place. } } // create a shuffled copy of a vec fn shuffled<T:copy>(r : rand::rng, v : ~[T]) -> ~[T] { let w = vec::to_mut(v); shuffle(r, w); vec::from_mut(w) // Shouldn't this happen automatically? } // sample from a population without replacement //fn sample<T>(r : rand::rng, pop : ~[T], k : uint) -> ~[T] { fail!() } // Two ways to make a weighted choice. // * weighted_choice is O(number of choices) time
assert!(vec::len(v)!= 0u); let total = 0u; for {weight: weight, item: _} in v { total += weight; } assert!(total >= 0u); let chosen = under(r, total); let so_far = 0u; for {weight: weight, item: item} in v { so_far += weight; if so_far > chosen { return item; } } core::unreachable(); } fn weighted_vec<T:copy>(v : ~[weighted<T>]) -> ~[T] { let r = ~[]; for {weight: weight, item: item} in v { let i = 0u; while i < weight { r.push(item); i += 1u; } } r } fn main() { let r = rand::mk_rng(); log(error, under(r, 5u)); log(error, choice(r, ~[10, 20, 30])); log(error, if unlikely(r, 5u) { "unlikely" } else { "likely" }); let mut a = ~[1, 2, 3]; shuffle(r, a); log(error, a); let i = 0u; let v = ~[ {weight:1u, item:"low"}, {weight:8u, item:"middle"}, {weight:1u, item:"high"} ]; let w = weighted_vec(v); while i < 1000u { log(error, "Immed: " + weighted_choice(r, v)); log(error, "Fast: " + choice(r, w)); i += 1u; } }
// * weighted_vec is O(total weight) space type weighted<T> = { weight: uint, item: T }; fn weighted_choice<T:copy>(r : rand::rng, v : ~[weighted<T>]) -> T {
random_line_split
rand_util.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. extern mod std; use std::rand; // random uint less than n fn under(r : rand::rng, n : uint) -> uint { assert!(n!= 0u); r.next() as uint % n } // random choice from a vec fn choice<T:copy>(r : rand::rng, v : ~[T]) -> T { assert!(vec::len(v)!= 0u); v[under(r, vec::len(v))] } // 1 in n chance of being true fn unlikely(r : rand::rng, n : uint) -> bool { under(r, n) == 0u } // shuffle a vec in place fn shuffle<T>(r : rand::rng, &v : ~[T]) { let i = vec::len(v); while i >= 2u { // Loop invariant: elements with index >= i have been locked in place. i -= 1u; vec::swap(v, i, under(r, i + 1u)); // Lock element i in place. } } // create a shuffled copy of a vec fn shuffled<T:copy>(r : rand::rng, v : ~[T]) -> ~[T] { let w = vec::to_mut(v); shuffle(r, w); vec::from_mut(w) // Shouldn't this happen automatically? } // sample from a population without replacement //fn sample<T>(r : rand::rng, pop : ~[T], k : uint) -> ~[T] { fail!() } // Two ways to make a weighted choice. // * weighted_choice is O(number of choices) time // * weighted_vec is O(total weight) space type weighted<T> = { weight: uint, item: T }; fn weighted_choice<T:copy>(r : rand::rng, v : ~[weighted<T>]) -> T { assert!(vec::len(v)!= 0u); let total = 0u; for {weight: weight, item: _} in v { total += weight; } assert!(total >= 0u); let chosen = under(r, total); let so_far = 0u; for {weight: weight, item: item} in v { so_far += weight; if so_far > chosen { return item; } } core::unreachable(); } fn weighted_vec<T:copy>(v : ~[weighted<T>]) -> ~[T] { let r = ~[]; for {weight: weight, item: item} in v { let i = 0u; while i < weight { r.push(item); i += 1u; } } r } fn main()
log(error, "Immed: " + weighted_choice(r, v)); log(error, "Fast: " + choice(r, w)); i += 1u; } }
{ let r = rand::mk_rng(); log(error, under(r, 5u)); log(error, choice(r, ~[10, 20, 30])); log(error, if unlikely(r, 5u) { "unlikely" } else { "likely" }); let mut a = ~[1, 2, 3]; shuffle(r, a); log(error, a); let i = 0u; let v = ~[ {weight:1u, item:"low"}, {weight:8u, item:"middle"}, {weight:1u, item:"high"} ]; let w = weighted_vec(v); while i < 1000u {
identifier_body
lib.rs
#![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")] extern crate phf_shared; extern crate rand; use phf_shared::PhfHash; use rand::{SeedableRng, XorShiftRng, Rng}; const DEFAULT_LAMBDA: usize = 5; const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841]; pub struct
{ pub key: u64, pub disps: Vec<(u32, u32)>, pub map: Vec<usize>, } pub fn generate_hash<H: PhfHash>(entries: &[H]) -> HashState { let mut rng = XorShiftRng::from_seed(FIXED_SEED); loop { if let Some(s) = try_generate_hash(entries, &mut rng) { return s; } } } fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> { struct Bucket { idx: usize, keys: Vec<usize>, } struct Hashes { g: u32, f1: u32, f2: u32, } let key = rng.gen(); let hashes: Vec<_> = entries.iter() .map(|entry| { let hash = phf_shared::hash(entry, key); let (g, f1, f2) = phf_shared::split(hash); Hashes { g: g, f1: f1, f2: f2, } }) .collect(); let buckets_len = (entries.len() + DEFAULT_LAMBDA - 1) / DEFAULT_LAMBDA; let mut buckets = (0..buckets_len) .map(|i| { Bucket { idx: i, keys: vec![], } }) .collect::<Vec<_>>(); for (i, hash) in hashes.iter().enumerate() { buckets[(hash.g % (buckets_len as u32)) as usize].keys.push(i); } // Sort descending buckets.sort_by(|a, b| a.keys.len().cmp(&b.keys.len()).reverse()); let table_len = entries.len(); let mut map = vec![None; table_len]; let mut disps = vec![(0u32, 0u32); buckets_len]; // store whether an element from the bucket being placed is // located at a certain position, to allow for efficient overlap // checks. It works by storing the generation in each cell and // each new placement-attempt is a new generation, so you can tell // if this is legitimately full by checking that the generations // are equal. (A u64 is far too large to overflow in a reasonable // time for current hardware.) let mut try_map = vec![0u64; table_len]; let mut generation = 0u64; // the actual values corresponding to the markers above, as // (index, key) pairs, for adding to the main map once we've // chosen the right disps. let mut values_to_add = vec![]; 'buckets: for bucket in &buckets { for d1 in 0..(table_len as u32) { 'disps: for d2 in 0..(table_len as u32) { values_to_add.clear(); generation += 1; for &key in &bucket.keys { let idx = (phf_shared::displace(hashes[key].f1, hashes[key].f2, d1, d2) % (table_len as u32)) as usize; if map[idx].is_some() || try_map[idx] == generation { continue 'disps; } try_map[idx] = generation; values_to_add.push((idx, key)); } // We've picked a good set of disps disps[bucket.idx] = (d1, d2); for &(idx, key) in &values_to_add { map[idx] = Some(key); } continue 'buckets; } } // Unable to find displacements for a bucket return None; } Some(HashState { key: key, disps: disps, map: map.into_iter().map(|i| i.unwrap()).collect(), }) }
HashState
identifier_name
lib.rs
#![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")] extern crate phf_shared; extern crate rand; use phf_shared::PhfHash; use rand::{SeedableRng, XorShiftRng, Rng}; const DEFAULT_LAMBDA: usize = 5; const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841]; pub struct HashState { pub key: u64, pub disps: Vec<(u32, u32)>, pub map: Vec<usize>, } pub fn generate_hash<H: PhfHash>(entries: &[H]) -> HashState
fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> { struct Bucket { idx: usize, keys: Vec<usize>, } struct Hashes { g: u32, f1: u32, f2: u32, } let key = rng.gen(); let hashes: Vec<_> = entries.iter() .map(|entry| { let hash = phf_shared::hash(entry, key); let (g, f1, f2) = phf_shared::split(hash); Hashes { g: g, f1: f1, f2: f2, } }) .collect(); let buckets_len = (entries.len() + DEFAULT_LAMBDA - 1) / DEFAULT_LAMBDA; let mut buckets = (0..buckets_len) .map(|i| { Bucket { idx: i, keys: vec![], } }) .collect::<Vec<_>>(); for (i, hash) in hashes.iter().enumerate() { buckets[(hash.g % (buckets_len as u32)) as usize].keys.push(i); } // Sort descending buckets.sort_by(|a, b| a.keys.len().cmp(&b.keys.len()).reverse()); let table_len = entries.len(); let mut map = vec![None; table_len]; let mut disps = vec![(0u32, 0u32); buckets_len]; // store whether an element from the bucket being placed is // located at a certain position, to allow for efficient overlap // checks. It works by storing the generation in each cell and // each new placement-attempt is a new generation, so you can tell // if this is legitimately full by checking that the generations // are equal. (A u64 is far too large to overflow in a reasonable // time for current hardware.) let mut try_map = vec![0u64; table_len]; let mut generation = 0u64; // the actual values corresponding to the markers above, as // (index, key) pairs, for adding to the main map once we've // chosen the right disps. let mut values_to_add = vec![]; 'buckets: for bucket in &buckets { for d1 in 0..(table_len as u32) { 'disps: for d2 in 0..(table_len as u32) { values_to_add.clear(); generation += 1; for &key in &bucket.keys { let idx = (phf_shared::displace(hashes[key].f1, hashes[key].f2, d1, d2) % (table_len as u32)) as usize; if map[idx].is_some() || try_map[idx] == generation { continue 'disps; } try_map[idx] = generation; values_to_add.push((idx, key)); } // We've picked a good set of disps disps[bucket.idx] = (d1, d2); for &(idx, key) in &values_to_add { map[idx] = Some(key); } continue 'buckets; } } // Unable to find displacements for a bucket return None; } Some(HashState { key: key, disps: disps, map: map.into_iter().map(|i| i.unwrap()).collect(), }) }
{ let mut rng = XorShiftRng::from_seed(FIXED_SEED); loop { if let Some(s) = try_generate_hash(entries, &mut rng) { return s; } } }
identifier_body
lib.rs
#![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")] extern crate phf_shared; extern crate rand; use phf_shared::PhfHash; use rand::{SeedableRng, XorShiftRng, Rng}; const DEFAULT_LAMBDA: usize = 5; const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841]; pub struct HashState { pub key: u64, pub disps: Vec<(u32, u32)>, pub map: Vec<usize>, } pub fn generate_hash<H: PhfHash>(entries: &[H]) -> HashState { let mut rng = XorShiftRng::from_seed(FIXED_SEED); loop { if let Some(s) = try_generate_hash(entries, &mut rng) { return s; } } } fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> { struct Bucket { idx: usize, keys: Vec<usize>, } struct Hashes { g: u32, f1: u32, f2: u32, } let key = rng.gen(); let hashes: Vec<_> = entries.iter() .map(|entry| { let hash = phf_shared::hash(entry, key); let (g, f1, f2) = phf_shared::split(hash); Hashes { g: g, f1: f1, f2: f2, } }) .collect(); let buckets_len = (entries.len() + DEFAULT_LAMBDA - 1) / DEFAULT_LAMBDA; let mut buckets = (0..buckets_len) .map(|i| { Bucket { idx: i, keys: vec![], }
} // Sort descending buckets.sort_by(|a, b| a.keys.len().cmp(&b.keys.len()).reverse()); let table_len = entries.len(); let mut map = vec![None; table_len]; let mut disps = vec![(0u32, 0u32); buckets_len]; // store whether an element from the bucket being placed is // located at a certain position, to allow for efficient overlap // checks. It works by storing the generation in each cell and // each new placement-attempt is a new generation, so you can tell // if this is legitimately full by checking that the generations // are equal. (A u64 is far too large to overflow in a reasonable // time for current hardware.) let mut try_map = vec![0u64; table_len]; let mut generation = 0u64; // the actual values corresponding to the markers above, as // (index, key) pairs, for adding to the main map once we've // chosen the right disps. let mut values_to_add = vec![]; 'buckets: for bucket in &buckets { for d1 in 0..(table_len as u32) { 'disps: for d2 in 0..(table_len as u32) { values_to_add.clear(); generation += 1; for &key in &bucket.keys { let idx = (phf_shared::displace(hashes[key].f1, hashes[key].f2, d1, d2) % (table_len as u32)) as usize; if map[idx].is_some() || try_map[idx] == generation { continue 'disps; } try_map[idx] = generation; values_to_add.push((idx, key)); } // We've picked a good set of disps disps[bucket.idx] = (d1, d2); for &(idx, key) in &values_to_add { map[idx] = Some(key); } continue 'buckets; } } // Unable to find displacements for a bucket return None; } Some(HashState { key: key, disps: disps, map: map.into_iter().map(|i| i.unwrap()).collect(), }) }
}) .collect::<Vec<_>>(); for (i, hash) in hashes.iter().enumerate() { buckets[(hash.g % (buckets_len as u32)) as usize].keys.push(i);
random_line_split
lib.rs
#![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")] extern crate phf_shared; extern crate rand; use phf_shared::PhfHash; use rand::{SeedableRng, XorShiftRng, Rng}; const DEFAULT_LAMBDA: usize = 5; const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841]; pub struct HashState { pub key: u64, pub disps: Vec<(u32, u32)>, pub map: Vec<usize>, } pub fn generate_hash<H: PhfHash>(entries: &[H]) -> HashState { let mut rng = XorShiftRng::from_seed(FIXED_SEED); loop { if let Some(s) = try_generate_hash(entries, &mut rng)
} } fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> { struct Bucket { idx: usize, keys: Vec<usize>, } struct Hashes { g: u32, f1: u32, f2: u32, } let key = rng.gen(); let hashes: Vec<_> = entries.iter() .map(|entry| { let hash = phf_shared::hash(entry, key); let (g, f1, f2) = phf_shared::split(hash); Hashes { g: g, f1: f1, f2: f2, } }) .collect(); let buckets_len = (entries.len() + DEFAULT_LAMBDA - 1) / DEFAULT_LAMBDA; let mut buckets = (0..buckets_len) .map(|i| { Bucket { idx: i, keys: vec![], } }) .collect::<Vec<_>>(); for (i, hash) in hashes.iter().enumerate() { buckets[(hash.g % (buckets_len as u32)) as usize].keys.push(i); } // Sort descending buckets.sort_by(|a, b| a.keys.len().cmp(&b.keys.len()).reverse()); let table_len = entries.len(); let mut map = vec![None; table_len]; let mut disps = vec![(0u32, 0u32); buckets_len]; // store whether an element from the bucket being placed is // located at a certain position, to allow for efficient overlap // checks. It works by storing the generation in each cell and // each new placement-attempt is a new generation, so you can tell // if this is legitimately full by checking that the generations // are equal. (A u64 is far too large to overflow in a reasonable // time for current hardware.) let mut try_map = vec![0u64; table_len]; let mut generation = 0u64; // the actual values corresponding to the markers above, as // (index, key) pairs, for adding to the main map once we've // chosen the right disps. let mut values_to_add = vec![]; 'buckets: for bucket in &buckets { for d1 in 0..(table_len as u32) { 'disps: for d2 in 0..(table_len as u32) { values_to_add.clear(); generation += 1; for &key in &bucket.keys { let idx = (phf_shared::displace(hashes[key].f1, hashes[key].f2, d1, d2) % (table_len as u32)) as usize; if map[idx].is_some() || try_map[idx] == generation { continue 'disps; } try_map[idx] = generation; values_to_add.push((idx, key)); } // We've picked a good set of disps disps[bucket.idx] = (d1, d2); for &(idx, key) in &values_to_add { map[idx] = Some(key); } continue 'buckets; } } // Unable to find displacements for a bucket return None; } Some(HashState { key: key, disps: disps, map: map.into_iter().map(|i| i.unwrap()).collect(), }) }
{ return s; }
conditional_block
dropck_vec_cycle_checked.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Reject mixing cyclic structure and Drop when using Vec. // // (Compare against compile-fail/dropck_arr_cycle_checked.rs) use std::cell::Cell; use id::Id; mod s { #![allow(unstable)] use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static S_COUNT: AtomicUsize = ATOMIC_USIZE_INIT; pub fn next_count() -> usize { S_COUNT.fetch_add(1, Ordering::SeqCst) + 1 } } mod id { use s; #[derive(Debug)] pub struct Id { orig_count: usize, count: usize, } impl Id { pub fn new() -> Id { let c = s::next_count(); println!("building Id {}", c); Id { orig_count: c, count: c } } pub fn count(&self) -> usize { println!("Id::count on {} returns {}", self.orig_count, self.count); self.count } } impl Drop for Id { fn drop(&mut self) { println!("dropping Id {}", self.count); self.count = 0; } } } trait HasId { fn count(&self) -> usize; } #[derive(Debug)] struct CheckId<T:HasId> { v: T } #[allow(non_snake_case)] fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } } impl<T:HasId> Drop for CheckId<T> {
} #[derive(Debug)] struct C<'a> { id: Id, v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>, } impl<'a> HasId for Cell<Option<&'a C<'a>>> { fn count(&self) -> usize { match self.get() { None => 1, Some(c) => c.id.count(), } } } impl<'a> C<'a> { fn new() -> C<'a> { C { id: Id::new(), v: Vec::new() } } } fn f() { let (mut c1, mut c2, mut c3); c1 = C::new(); c2 = C::new(); c3 = C::new(); c1.v.push(CheckId(Cell::new(None))); c1.v.push(CheckId(Cell::new(None))); c2.v.push(CheckId(Cell::new(None))); c2.v.push(CheckId(Cell::new(None))); c3.v.push(CheckId(Cell::new(None))); c3.v.push(CheckId(Cell::new(None))); c1.v[0].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough c1.v[1].v.set(Some(&c3)); //~ ERROR `c3` does not live long enough c2.v[0].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough c2.v[1].v.set(Some(&c3)); //~ ERROR `c3` does not live long enough c3.v[0].v.set(Some(&c1)); //~ ERROR `c1` does not live long enough c3.v[1].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough } fn main() { f(); }
fn drop(&mut self) { assert!(self.v.count() > 0); }
random_line_split
dropck_vec_cycle_checked.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Reject mixing cyclic structure and Drop when using Vec. // // (Compare against compile-fail/dropck_arr_cycle_checked.rs) use std::cell::Cell; use id::Id; mod s { #![allow(unstable)] use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static S_COUNT: AtomicUsize = ATOMIC_USIZE_INIT; pub fn next_count() -> usize { S_COUNT.fetch_add(1, Ordering::SeqCst) + 1 } } mod id { use s; #[derive(Debug)] pub struct Id { orig_count: usize, count: usize, } impl Id { pub fn
() -> Id { let c = s::next_count(); println!("building Id {}", c); Id { orig_count: c, count: c } } pub fn count(&self) -> usize { println!("Id::count on {} returns {}", self.orig_count, self.count); self.count } } impl Drop for Id { fn drop(&mut self) { println!("dropping Id {}", self.count); self.count = 0; } } } trait HasId { fn count(&self) -> usize; } #[derive(Debug)] struct CheckId<T:HasId> { v: T } #[allow(non_snake_case)] fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } } impl<T:HasId> Drop for CheckId<T> { fn drop(&mut self) { assert!(self.v.count() > 0); } } #[derive(Debug)] struct C<'a> { id: Id, v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>, } impl<'a> HasId for Cell<Option<&'a C<'a>>> { fn count(&self) -> usize { match self.get() { None => 1, Some(c) => c.id.count(), } } } impl<'a> C<'a> { fn new() -> C<'a> { C { id: Id::new(), v: Vec::new() } } } fn f() { let (mut c1, mut c2, mut c3); c1 = C::new(); c2 = C::new(); c3 = C::new(); c1.v.push(CheckId(Cell::new(None))); c1.v.push(CheckId(Cell::new(None))); c2.v.push(CheckId(Cell::new(None))); c2.v.push(CheckId(Cell::new(None))); c3.v.push(CheckId(Cell::new(None))); c3.v.push(CheckId(Cell::new(None))); c1.v[0].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough c1.v[1].v.set(Some(&c3)); //~ ERROR `c3` does not live long enough c2.v[0].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough c2.v[1].v.set(Some(&c3)); //~ ERROR `c3` does not live long enough c3.v[0].v.set(Some(&c1)); //~ ERROR `c1` does not live long enough c3.v[1].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough } fn main() { f(); }
new
identifier_name
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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. /// Parse and re-serialize a HTML5 document. /// /// This is meant to produce the exact same output (ignoring stderr) as /// /// java -classpath htmlparser-1.4.jar nu.validator.htmlparser.tools.HTML2HTML /// /// where htmlparser-1.4.jar comes from http://about.validator.nu/htmlparser/ extern crate html5ever; use std::io;
use html5ever::driver::ParseOpts; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse, one_input, serialize}; fn main() { let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a doctype at the very beginning. io::stdout().write_str("<!DOCTYPE html>\n") .ok().expect("writing DOCTYPE failed"); serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
use std::default::Default; use html5ever::sink::rcdom::RcDom;
random_line_split
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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. /// Parse and re-serialize a HTML5 document. /// /// This is meant to produce the exact same output (ignoring stderr) as /// /// java -classpath htmlparser-1.4.jar nu.validator.htmlparser.tools.HTML2HTML /// /// where htmlparser-1.4.jar comes from http://about.validator.nu/htmlparser/ extern crate html5ever; use std::io; use std::default::Default; use html5ever::sink::rcdom::RcDom; use html5ever::driver::ParseOpts; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse, one_input, serialize}; fn main()
{ let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a doctype at the very beginning. io::stdout().write_str("<!DOCTYPE html>\n") .ok().expect("writing DOCTYPE failed"); serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
identifier_body
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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. /// Parse and re-serialize a HTML5 document. /// /// This is meant to produce the exact same output (ignoring stderr) as /// /// java -classpath htmlparser-1.4.jar nu.validator.htmlparser.tools.HTML2HTML /// /// where htmlparser-1.4.jar comes from http://about.validator.nu/htmlparser/ extern crate html5ever; use std::io; use std::default::Default; use html5ever::sink::rcdom::RcDom; use html5ever::driver::ParseOpts; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse, one_input, serialize}; fn
() { let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a doctype at the very beginning. io::stdout().write_str("<!DOCTYPE html>\n") .ok().expect("writing DOCTYPE failed"); serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
main
identifier_name
lib.rs
#![feature(no_std,core_intrinsics)] #![no_std] #[macro_export] macro_rules! impl_fmt { (@as_item $($i:item)*) => {$($i)*}; ($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t { fn fmt(&$s, $f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { $( $code )* } } })+ }; } #[macro_export] macro_rules! impl_conv {
$(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::From<$src> for $t { fn from($v: $src) -> $t { $($code)* } } })+ }; (@match_ $( $(<($($params:tt)+)>)* Into<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::Into<$dst> for $t { fn into($self_) -> $dst { $($code)* } } })+ }; (@match_ $( $(<($($params:tt)+)>)* AsRef<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::AsRef<$dst> for $t { fn as_ref($self_) -> &$dst { $($code)* } } })+ }; ($( $(<($($params:tt)+)>)* $name:ident<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_conv!{ @match_ $(<($($params:tt)+)>)* $name<$src>($v) for $t { $($code)* } })+ }; } #[macro_export] macro_rules! impl_from { (@as_item $($i:item)*) => {$($i)*}; ($( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::From<$src> for $t { fn from($v: $src) -> $t { $($code)* } } })+ }; } pub fn type_name<T:?::core::marker::Sized>() -> &'static str { // SAFE: Intrinsic with no sideeffect unsafe { ::core::intrinsics::type_name::<T>() } } #[macro_export] macro_rules! type_name { ($t:ty) => ( $crate::type_name::<$t>() ); } #[macro_export] macro_rules! todo { ( $s:expr ) => ( panic!( concat!("TODO: ",$s) ) ); ( $s:expr, $($v:tt)* ) => ( panic!( concat!("TODO: ",$s), $($v)* ) ); } /// Override libcore's `try!` macro with one that backs onto `From` #[macro_export] macro_rules! try { ($e:expr) => ( match $e { Ok(v) => v, Err(e) => return Err(From::from(e)), } ); }
(@as_item $($i:item)*) => {$($i)*}; (@match_ $( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => {
random_line_split
lib.rs
#![feature(no_std,core_intrinsics)] #![no_std] #[macro_export] macro_rules! impl_fmt { (@as_item $($i:item)*) => {$($i)*}; ($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t { fn fmt(&$s, $f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { $( $code )* } } })+ }; } #[macro_export] macro_rules! impl_conv { (@as_item $($i:item)*) => {$($i)*}; (@match_ $( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::From<$src> for $t { fn from($v: $src) -> $t { $($code)* } } })+ }; (@match_ $( $(<($($params:tt)+)>)* Into<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::Into<$dst> for $t { fn into($self_) -> $dst { $($code)* } } })+ }; (@match_ $( $(<($($params:tt)+)>)* AsRef<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::AsRef<$dst> for $t { fn as_ref($self_) -> &$dst { $($code)* } } })+ }; ($( $(<($($params:tt)+)>)* $name:ident<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_conv!{ @match_ $(<($($params:tt)+)>)* $name<$src>($v) for $t { $($code)* } })+ }; } #[macro_export] macro_rules! impl_from { (@as_item $($i:item)*) => {$($i)*}; ($( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::From<$src> for $t { fn from($v: $src) -> $t { $($code)* } } })+ }; } pub fn type_name<T:?::core::marker::Sized>() -> &'static str
#[macro_export] macro_rules! type_name { ($t:ty) => ( $crate::type_name::<$t>() ); } #[macro_export] macro_rules! todo { ( $s:expr ) => ( panic!( concat!("TODO: ",$s) ) ); ( $s:expr, $($v:tt)* ) => ( panic!( concat!("TODO: ",$s), $($v)* ) ); } /// Override libcore's `try!` macro with one that backs onto `From` #[macro_export] macro_rules! try { ($e:expr) => ( match $e { Ok(v) => v, Err(e) => return Err(From::from(e)), } ); }
{ // SAFE: Intrinsic with no sideeffect unsafe { ::core::intrinsics::type_name::<T>() } }
identifier_body
lib.rs
#![feature(no_std,core_intrinsics)] #![no_std] #[macro_export] macro_rules! impl_fmt { (@as_item $($i:item)*) => {$($i)*}; ($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t { fn fmt(&$s, $f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { $( $code )* } } })+ }; } #[macro_export] macro_rules! impl_conv { (@as_item $($i:item)*) => {$($i)*}; (@match_ $( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::From<$src> for $t { fn from($v: $src) -> $t { $($code)* } } })+ }; (@match_ $( $(<($($params:tt)+)>)* Into<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::Into<$dst> for $t { fn into($self_) -> $dst { $($code)* } } })+ }; (@match_ $( $(<($($params:tt)+)>)* AsRef<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::AsRef<$dst> for $t { fn as_ref($self_) -> &$dst { $($code)* } } })+ }; ($( $(<($($params:tt)+)>)* $name:ident<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_conv!{ @match_ $(<($($params:tt)+)>)* $name<$src>($v) for $t { $($code)* } })+ }; } #[macro_export] macro_rules! impl_from { (@as_item $($i:item)*) => {$($i)*}; ($( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { $(impl_from!{ @as_item impl$(<$($params)+>)* ::std::convert::From<$src> for $t { fn from($v: $src) -> $t { $($code)* } } })+ }; } pub fn
<T:?::core::marker::Sized>() -> &'static str { // SAFE: Intrinsic with no sideeffect unsafe { ::core::intrinsics::type_name::<T>() } } #[macro_export] macro_rules! type_name { ($t:ty) => ( $crate::type_name::<$t>() ); } #[macro_export] macro_rules! todo { ( $s:expr ) => ( panic!( concat!("TODO: ",$s) ) ); ( $s:expr, $($v:tt)* ) => ( panic!( concat!("TODO: ",$s), $($v)* ) ); } /// Override libcore's `try!` macro with one that backs onto `From` #[macro_export] macro_rules! try { ($e:expr) => ( match $e { Ok(v) => v, Err(e) => return Err(From::from(e)), } ); }
type_name
identifier_name
msgsend-pipes.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. #![feature(std_misc)] use std::sync::mpsc::{channel, Sender, Receiver}; use std::env; use std::thread; use std::time::Duration; enum request { get_count, bytes(usize), stop } fn server(requests: &Receiver<request>, responses: &Sender<usize>)
fn run(args: &[String]) { let (to_parent, from_child) = channel(); let size = args[1].parse::<usize>().unwrap(); let workers = args[2].parse::<usize>().unwrap(); let num_bytes = 100; let mut result = None; let mut to_parent = Some(to_parent); let dur = Duration::span(|| { let to_parent = to_parent.take().unwrap(); let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); worker_results.push(thread::spawn(move|| { for _ in 0..size / workers { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); } //println!("worker {} exiting", i); })); from_parent } else { let (to_child, from_parent) = channel(); for _ in 0..workers { let to_child = to_child.clone(); worker_results.push(thread::spawn(move|| { for _ in 0..size / workers { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); } //println!("worker {} exiting", i); })); } from_parent }; thread::spawn(move|| { server(&from_parent, &to_parent); }); for r in worker_results { let _ = r.join(); } //println!("sending stop message"); //to_child.send(stop); //move_out(to_child); result = Some(from_child.recv().unwrap()); }); let result = result.unwrap(); print!("Count is {}\n", result); print!("Test took {} ms\n", dur.num_milliseconds()); let thruput = ((size / workers * workers) as f64) / (dur.num_milliseconds() as f64); print!("Throughput={} per sec\n", thruput / 1000.0); assert_eq!(result, num_bytes * size); } fn main() { let args = env::args(); let args = if env::var_os("RUST_BENCH").is_some() { vec!("".to_string(), "1000000".to_string(), "8".to_string()) } else if args.len() <= 1 { vec!("".to_string(), "10000".to_string(), "4".to_string()) } else { args.map(|x| x.to_string()).collect() }; println!("{:?}", args); run(&args); }
{ let mut count: usize = 0; let mut done = false; while !done { match requests.recv() { Ok(request::get_count) => { responses.send(count.clone()); } Ok(request::bytes(b)) => { //println!("server: received {} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count).unwrap(); //println!("server exiting"); }
identifier_body
msgsend-pipes.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. // A port of the simplistic benchmark from
// // I *think* it's the same, more or less. #![feature(std_misc)] use std::sync::mpsc::{channel, Sender, Receiver}; use std::env; use std::thread; use std::time::Duration; enum request { get_count, bytes(usize), stop } fn server(requests: &Receiver<request>, responses: &Sender<usize>) { let mut count: usize = 0; let mut done = false; while!done { match requests.recv() { Ok(request::get_count) => { responses.send(count.clone()); } Ok(request::bytes(b)) => { //println!("server: received {} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count).unwrap(); //println!("server exiting"); } fn run(args: &[String]) { let (to_parent, from_child) = channel(); let size = args[1].parse::<usize>().unwrap(); let workers = args[2].parse::<usize>().unwrap(); let num_bytes = 100; let mut result = None; let mut to_parent = Some(to_parent); let dur = Duration::span(|| { let to_parent = to_parent.take().unwrap(); let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); worker_results.push(thread::spawn(move|| { for _ in 0..size / workers { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); } //println!("worker {} exiting", i); })); from_parent } else { let (to_child, from_parent) = channel(); for _ in 0..workers { let to_child = to_child.clone(); worker_results.push(thread::spawn(move|| { for _ in 0..size / workers { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); } //println!("worker {} exiting", i); })); } from_parent }; thread::spawn(move|| { server(&from_parent, &to_parent); }); for r in worker_results { let _ = r.join(); } //println!("sending stop message"); //to_child.send(stop); //move_out(to_child); result = Some(from_child.recv().unwrap()); }); let result = result.unwrap(); print!("Count is {}\n", result); print!("Test took {} ms\n", dur.num_milliseconds()); let thruput = ((size / workers * workers) as f64) / (dur.num_milliseconds() as f64); print!("Throughput={} per sec\n", thruput / 1000.0); assert_eq!(result, num_bytes * size); } fn main() { let args = env::args(); let args = if env::var_os("RUST_BENCH").is_some() { vec!("".to_string(), "1000000".to_string(), "8".to_string()) } else if args.len() <= 1 { vec!("".to_string(), "10000".to_string(), "4".to_string()) } else { args.map(|x| x.to_string()).collect() }; println!("{:?}", args); run(&args); }
// // http://github.com/PaulKeeble/ScalaVErlangAgents
random_line_split
msgsend-pipes.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. #![feature(std_misc)] use std::sync::mpsc::{channel, Sender, Receiver}; use std::env; use std::thread; use std::time::Duration; enum request { get_count, bytes(usize), stop } fn
(requests: &Receiver<request>, responses: &Sender<usize>) { let mut count: usize = 0; let mut done = false; while!done { match requests.recv() { Ok(request::get_count) => { responses.send(count.clone()); } Ok(request::bytes(b)) => { //println!("server: received {} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count).unwrap(); //println!("server exiting"); } fn run(args: &[String]) { let (to_parent, from_child) = channel(); let size = args[1].parse::<usize>().unwrap(); let workers = args[2].parse::<usize>().unwrap(); let num_bytes = 100; let mut result = None; let mut to_parent = Some(to_parent); let dur = Duration::span(|| { let to_parent = to_parent.take().unwrap(); let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); worker_results.push(thread::spawn(move|| { for _ in 0..size / workers { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); } //println!("worker {} exiting", i); })); from_parent } else { let (to_child, from_parent) = channel(); for _ in 0..workers { let to_child = to_child.clone(); worker_results.push(thread::spawn(move|| { for _ in 0..size / workers { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); } //println!("worker {} exiting", i); })); } from_parent }; thread::spawn(move|| { server(&from_parent, &to_parent); }); for r in worker_results { let _ = r.join(); } //println!("sending stop message"); //to_child.send(stop); //move_out(to_child); result = Some(from_child.recv().unwrap()); }); let result = result.unwrap(); print!("Count is {}\n", result); print!("Test took {} ms\n", dur.num_milliseconds()); let thruput = ((size / workers * workers) as f64) / (dur.num_milliseconds() as f64); print!("Throughput={} per sec\n", thruput / 1000.0); assert_eq!(result, num_bytes * size); } fn main() { let args = env::args(); let args = if env::var_os("RUST_BENCH").is_some() { vec!("".to_string(), "1000000".to_string(), "8".to_string()) } else if args.len() <= 1 { vec!("".to_string(), "10000".to_string(), "4".to_string()) } else { args.map(|x| x.to_string()).collect() }; println!("{:?}", args); run(&args); }
server
identifier_name
mod.rs
// Copyright (c) 2019, Ben Boeckel // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of this project nor the names of its contributors
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //! The test structure here comes from the structure in libkeyutils. pub(crate) mod utils; mod add; mod clear; mod describe; mod instantiate; mod invalidate; mod keytype; mod link; mod newring; mod permitting; mod reading; mod revoke; mod search; mod timeout; mod unlink; mod update;
// may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
random_line_split
fs_helpers.rs
#![allow(non_camel_case_types)] #![allow(unused_unsafe)] use crate::ctx::WasiCtx; use crate::host; use lucet_runtime::vmctx::Vmctx; use nix::libc::{self, c_long}; use std::ffi::{OsStr, OsString}; use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd}; #[cfg(target_os = "linux")] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_RSYNC; #[cfg(not(target_os = "linux"))] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_SYNC; /// Normalizes a path to ensure that the target path is located under the directory provided. /// /// This is a workaround for not having Capsicum support in the OS. pub fn path_get<P: AsRef<OsStr>>( vmctx: &Vmctx, dirfd: host::__wasi_fd_t, dirflags: host::__wasi_lookupflags_t, path: P, needed_base: host::__wasi_rights_t, needed_inheriting: host::__wasi_rights_t, needs_final_component: bool, ) -> Result<(RawFd, OsString), host::__wasi_errno_t>
/// close all file descriptors other than the base directory, and return the errno for /// convenience with `return` fn ret_error( dir_stack: &mut Vec<RawFd>, errno: host::__wasi_errno_t, ) -> Result<(RawFd, OsString), host::__wasi_errno_t> { if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } Err(errno) } let ctx = vmctx.get_embed_ctx::<WasiCtx>(); let dirfe = ctx.get_fd_entry(dirfd, needed_base, needed_inheriting)?; // Stack of directory file descriptors. Index 0 always corresponds with the directory provided // to this function. Entering a directory causes a file descriptor to be pushed, while handling // ".." entries causes an entry to be popped. Index 0 cannot be popped, as this would imply // escaping the base directory. let mut dir_stack = vec![dirfe.fd_object.rawfd]; // Stack of paths left to process. This is initially the `path` argument to this function, but // any symlinks we encounter are processed by pushing them on the stack. let mut path_stack = vec![path.as_ref().to_owned().into_vec()]; // Track the number of symlinks we've expanded, so we can return `ELOOP` after too many. let mut symlink_expansions = 0; // Buffer to read links into; defined outside of the loop so we don't reallocate it constantly. let mut readlink_buf = vec![0u8; libc::PATH_MAX as usize + 1]; // TODO: rewrite this using a custom posix path type, with a component iterator that respects // trailing slashes. This version does way too much allocation, and is way too fiddly. loop { let component = if let Some(cur_path) = path_stack.pop() { // eprintln!( // "cur_path = {:?}", // std::str::from_utf8(cur_path.as_slice()).unwrap() // ); let mut split = cur_path.splitn(2, |&c| c == b'/'); let head = split.next(); let tail = split.next(); match (head, tail) { (None, _) => { // split always returns at least a singleton iterator with an empty slice panic!("unreachable"); } // path is empty (Some([]), None) => { return ret_error(&mut dir_stack, host::__WASI_ENOENT as host::__wasi_errno_t); } // path starts with `/`, is absolute (Some([]), Some(_)) => { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } // the final component of the path with no trailing slash (Some(component), None) => component.to_vec(), (Some(component), Some(rest)) => { if rest.iter().all(|&c| c == b'/') { // the final component of the path with trailing slashes; put one trailing // slash back on let mut component = component.to_vec(); component.push('/' as u8); component } else { // non-final component; push the rest back on the stack path_stack.push(rest.to_vec()); component.to_vec() } } } } else { // if the path stack is ever empty, we return rather than going through the loop again panic!("unreachable"); }; // eprintln!( // "component = {:?}", // std::str::from_utf8(component.as_slice()).unwrap() // ); match component.as_slice() { b"." => { // skip component } b".." => { // pop a directory let dirfd = dir_stack.pop().expect("dir_stack is never empty"); // we're not allowed to pop past the original directory if dir_stack.is_empty() { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } else { nix::unistd::close(dirfd).unwrap_or_else(|e| { dbg!(e); }); } } // should the component be a directory? it should if there is more path left to process, or // if it has a trailing slash and `needs_final_component` is not set component if!path_stack.is_empty() || (component.ends_with(b"/") &&!needs_final_component) => { match openat( *dir_stack.last().expect("dir_stack is never empty"), component, OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW, Mode::empty(), ) { Ok(new_dir) => { dir_stack.push(new_dir); continue; } Err(e) // Check to see if it was a symlink. Linux indicates // this with ENOTDIR because of the O_DIRECTORY flag. if e.as_errno() == Some(Errno::ELOOP) || e.as_errno() == Some(Errno::EMLINK) || e.as_errno() == Some(Errno::ENOTDIR) => { // attempt symlink expansion match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } // the final component component => { // if there's a trailing slash, or if `LOOKUP_SYMLINK_FOLLOW` is set, attempt // symlink expansion if component.ends_with(b"/") || (dirflags & host::__WASI_LOOKUP_SYMLINK_FOLLOW)!= 0 { match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { let errno = e.as_errno().unwrap(); if errno!= Errno::EINVAL && errno!= Errno::ENOENT { // only return an error if this path is not actually a symlink return ret_error(&mut dir_stack, host::errno_from_nix(errno)); } } } } // not a symlink, so we're done; return Ok(( ret_dir_success(&mut dir_stack), OsStr::from_bytes(component).to_os_string(), )); } } if path_stack.is_empty() { // no further components to process. means we've hit a case like "." or "a/..", or if the // input path has trailing slashes and `needs_final_component` is not set return Ok(( ret_dir_success(&mut dir_stack), OsStr::new(".").to_os_string(), )); } else { continue; } } } #[cfg(not(target_os = "macos"))] pub fn utime_now() -> c_long { libc::UTIME_NOW } #[cfg(target_os = "macos")] pub fn utime_now() -> c_long { -1 } #[cfg(not(target_os = "macos"))] pub fn utime_omit() -> c_long { libc::UTIME_OMIT } #[cfg(target_os = "macos")] pub fn utime_omit() -> c_long { -2 }
{ use nix::errno::Errno; use nix::fcntl::{openat, readlinkat, OFlag}; use nix::sys::stat::Mode; const MAX_SYMLINK_EXPANSIONS: usize = 128; /// close all the intermediate file descriptors, but make sure not to drop either the original /// dirfd or the one we return (which may be the same dirfd) fn ret_dir_success(dir_stack: &mut Vec<RawFd>) -> RawFd { let ret_dir = dir_stack.pop().expect("there is always a dirfd to return"); if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } ret_dir }
identifier_body
fs_helpers.rs
#![allow(non_camel_case_types)] #![allow(unused_unsafe)] use crate::ctx::WasiCtx; use crate::host; use lucet_runtime::vmctx::Vmctx; use nix::libc::{self, c_long}; use std::ffi::{OsStr, OsString}; use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd}; #[cfg(target_os = "linux")] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_RSYNC; #[cfg(not(target_os = "linux"))] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_SYNC; /// Normalizes a path to ensure that the target path is located under the directory provided. /// /// This is a workaround for not having Capsicum support in the OS. pub fn path_get<P: AsRef<OsStr>>( vmctx: &Vmctx, dirfd: host::__wasi_fd_t, dirflags: host::__wasi_lookupflags_t, path: P, needed_base: host::__wasi_rights_t, needed_inheriting: host::__wasi_rights_t, needs_final_component: bool, ) -> Result<(RawFd, OsString), host::__wasi_errno_t> { use nix::errno::Errno; use nix::fcntl::{openat, readlinkat, OFlag}; use nix::sys::stat::Mode; const MAX_SYMLINK_EXPANSIONS: usize = 128; /// close all the intermediate file descriptors, but make sure not to drop either the original /// dirfd or the one we return (which may be the same dirfd) fn ret_dir_success(dir_stack: &mut Vec<RawFd>) -> RawFd { let ret_dir = dir_stack.pop().expect("there is always a dirfd to return"); if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } ret_dir } /// close all file descriptors other than the base directory, and return the errno for /// convenience with `return` fn ret_error( dir_stack: &mut Vec<RawFd>, errno: host::__wasi_errno_t, ) -> Result<(RawFd, OsString), host::__wasi_errno_t> { if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } Err(errno) } let ctx = vmctx.get_embed_ctx::<WasiCtx>(); let dirfe = ctx.get_fd_entry(dirfd, needed_base, needed_inheriting)?; // Stack of directory file descriptors. Index 0 always corresponds with the directory provided // to this function. Entering a directory causes a file descriptor to be pushed, while handling // ".." entries causes an entry to be popped. Index 0 cannot be popped, as this would imply // escaping the base directory. let mut dir_stack = vec![dirfe.fd_object.rawfd]; // Stack of paths left to process. This is initially the `path` argument to this function, but // any symlinks we encounter are processed by pushing them on the stack. let mut path_stack = vec![path.as_ref().to_owned().into_vec()]; // Track the number of symlinks we've expanded, so we can return `ELOOP` after too many. let mut symlink_expansions = 0; // Buffer to read links into; defined outside of the loop so we don't reallocate it constantly. let mut readlink_buf = vec![0u8; libc::PATH_MAX as usize + 1]; // TODO: rewrite this using a custom posix path type, with a component iterator that respects // trailing slashes. This version does way too much allocation, and is way too fiddly. loop { let component = if let Some(cur_path) = path_stack.pop() { // eprintln!( // "cur_path = {:?}", // std::str::from_utf8(cur_path.as_slice()).unwrap() // ); let mut split = cur_path.splitn(2, |&c| c == b'/'); let head = split.next(); let tail = split.next(); match (head, tail) { (None, _) => { // split always returns at least a singleton iterator with an empty slice panic!("unreachable"); } // path is empty (Some([]), None) => { return ret_error(&mut dir_stack, host::__WASI_ENOENT as host::__wasi_errno_t); } // path starts with `/`, is absolute (Some([]), Some(_)) => { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } // the final component of the path with no trailing slash (Some(component), None) => component.to_vec(), (Some(component), Some(rest)) => { if rest.iter().all(|&c| c == b'/') { // the final component of the path with trailing slashes; put one trailing // slash back on let mut component = component.to_vec(); component.push('/' as u8); component } else { // non-final component; push the rest back on the stack path_stack.push(rest.to_vec()); component.to_vec() } } } } else { // if the path stack is ever empty, we return rather than going through the loop again panic!("unreachable"); }; // eprintln!( // "component = {:?}", // std::str::from_utf8(component.as_slice()).unwrap() // ); match component.as_slice() { b"." => { // skip component } b".." => { // pop a directory let dirfd = dir_stack.pop().expect("dir_stack is never empty"); // we're not allowed to pop past the original directory if dir_stack.is_empty() { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } else { nix::unistd::close(dirfd).unwrap_or_else(|e| { dbg!(e); }); } } // should the component be a directory? it should if there is more path left to process, or // if it has a trailing slash and `needs_final_component` is not set component if!path_stack.is_empty() || (component.ends_with(b"/") &&!needs_final_component) => { match openat( *dir_stack.last().expect("dir_stack is never empty"), component, OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW, Mode::empty(), ) { Ok(new_dir) => { dir_stack.push(new_dir); continue; } Err(e) // Check to see if it was a symlink. Linux indicates // this with ENOTDIR because of the O_DIRECTORY flag. if e.as_errno() == Some(Errno::ELOOP) || e.as_errno() == Some(Errno::EMLINK) || e.as_errno() == Some(Errno::ENOTDIR) => { // attempt symlink expansion match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } // the final component component => { // if there's a trailing slash, or if `LOOKUP_SYMLINK_FOLLOW` is set, attempt // symlink expansion if component.ends_with(b"/") || (dirflags & host::__WASI_LOOKUP_SYMLINK_FOLLOW)!= 0 { match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { let errno = e.as_errno().unwrap(); if errno!= Errno::EINVAL && errno!= Errno::ENOENT { // only return an error if this path is not actually a symlink return ret_error(&mut dir_stack, host::errno_from_nix(errno)); } } } } // not a symlink, so we're done; return Ok(( ret_dir_success(&mut dir_stack), OsStr::from_bytes(component).to_os_string(), )); } } if path_stack.is_empty() { // no further components to process. means we've hit a case like "." or "a/..", or if the // input path has trailing slashes and `needs_final_component` is not set return Ok(( ret_dir_success(&mut dir_stack), OsStr::new(".").to_os_string(), )); } else { continue; } } } #[cfg(not(target_os = "macos"))] pub fn utime_now() -> c_long { libc::UTIME_NOW } #[cfg(target_os = "macos")] pub fn
() -> c_long { -1 } #[cfg(not(target_os = "macos"))] pub fn utime_omit() -> c_long { libc::UTIME_OMIT } #[cfg(target_os = "macos")] pub fn utime_omit() -> c_long { -2 }
utime_now
identifier_name
fs_helpers.rs
#![allow(non_camel_case_types)] #![allow(unused_unsafe)] use crate::ctx::WasiCtx; use crate::host; use lucet_runtime::vmctx::Vmctx; use nix::libc::{self, c_long}; use std::ffi::{OsStr, OsString}; use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd}; #[cfg(target_os = "linux")] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_RSYNC; #[cfg(not(target_os = "linux"))] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_SYNC; /// Normalizes a path to ensure that the target path is located under the directory provided. /// /// This is a workaround for not having Capsicum support in the OS. pub fn path_get<P: AsRef<OsStr>>( vmctx: &Vmctx, dirfd: host::__wasi_fd_t, dirflags: host::__wasi_lookupflags_t, path: P, needed_base: host::__wasi_rights_t, needed_inheriting: host::__wasi_rights_t, needs_final_component: bool, ) -> Result<(RawFd, OsString), host::__wasi_errno_t> { use nix::errno::Errno; use nix::fcntl::{openat, readlinkat, OFlag}; use nix::sys::stat::Mode; const MAX_SYMLINK_EXPANSIONS: usize = 128; /// close all the intermediate file descriptors, but make sure not to drop either the original /// dirfd or the one we return (which may be the same dirfd) fn ret_dir_success(dir_stack: &mut Vec<RawFd>) -> RawFd { let ret_dir = dir_stack.pop().expect("there is always a dirfd to return"); if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } ret_dir } /// close all file descriptors other than the base directory, and return the errno for /// convenience with `return` fn ret_error( dir_stack: &mut Vec<RawFd>, errno: host::__wasi_errno_t, ) -> Result<(RawFd, OsString), host::__wasi_errno_t> { if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } Err(errno) } let ctx = vmctx.get_embed_ctx::<WasiCtx>(); let dirfe = ctx.get_fd_entry(dirfd, needed_base, needed_inheriting)?; // Stack of directory file descriptors. Index 0 always corresponds with the directory provided // to this function. Entering a directory causes a file descriptor to be pushed, while handling // ".." entries causes an entry to be popped. Index 0 cannot be popped, as this would imply // escaping the base directory. let mut dir_stack = vec![dirfe.fd_object.rawfd]; // Stack of paths left to process. This is initially the `path` argument to this function, but // any symlinks we encounter are processed by pushing them on the stack. let mut path_stack = vec![path.as_ref().to_owned().into_vec()]; // Track the number of symlinks we've expanded, so we can return `ELOOP` after too many. let mut symlink_expansions = 0; // Buffer to read links into; defined outside of the loop so we don't reallocate it constantly. let mut readlink_buf = vec![0u8; libc::PATH_MAX as usize + 1]; // TODO: rewrite this using a custom posix path type, with a component iterator that respects // trailing slashes. This version does way too much allocation, and is way too fiddly. loop { let component = if let Some(cur_path) = path_stack.pop() { // eprintln!( // "cur_path = {:?}", // std::str::from_utf8(cur_path.as_slice()).unwrap() // ); let mut split = cur_path.splitn(2, |&c| c == b'/'); let head = split.next(); let tail = split.next(); match (head, tail) { (None, _) => { // split always returns at least a singleton iterator with an empty slice panic!("unreachable"); } // path is empty (Some([]), None) => { return ret_error(&mut dir_stack, host::__WASI_ENOENT as host::__wasi_errno_t); } // path starts with `/`, is absolute (Some([]), Some(_)) => { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } // the final component of the path with no trailing slash (Some(component), None) => component.to_vec(), (Some(component), Some(rest)) => { if rest.iter().all(|&c| c == b'/') { // the final component of the path with trailing slashes; put one trailing // slash back on let mut component = component.to_vec(); component.push('/' as u8); component } else { // non-final component; push the rest back on the stack path_stack.push(rest.to_vec()); component.to_vec() } } } } else { // if the path stack is ever empty, we return rather than going through the loop again panic!("unreachable"); }; // eprintln!( // "component = {:?}", // std::str::from_utf8(component.as_slice()).unwrap() // ); match component.as_slice() { b"." => { // skip component } b".." => { // pop a directory let dirfd = dir_stack.pop().expect("dir_stack is never empty"); // we're not allowed to pop past the original directory if dir_stack.is_empty() { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } else { nix::unistd::close(dirfd).unwrap_or_else(|e| { dbg!(e); }); } } // should the component be a directory? it should if there is more path left to process, or // if it has a trailing slash and `needs_final_component` is not set component if!path_stack.is_empty() || (component.ends_with(b"/") &&!needs_final_component) => { match openat( *dir_stack.last().expect("dir_stack is never empty"), component, OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW, Mode::empty(), ) { Ok(new_dir) => { dir_stack.push(new_dir); continue; } Err(e) // Check to see if it was a symlink. Linux indicates // this with ENOTDIR because of the O_DIRECTORY flag. if e.as_errno() == Some(Errno::ELOOP) || e.as_errno() == Some(Errno::EMLINK) || e.as_errno() == Some(Errno::ENOTDIR) => { // attempt symlink expansion match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } // the final component component => { // if there's a trailing slash, or if `LOOKUP_SYMLINK_FOLLOW` is set, attempt // symlink expansion if component.ends_with(b"/") || (dirflags & host::__WASI_LOOKUP_SYMLINK_FOLLOW)!= 0 { match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { let errno = e.as_errno().unwrap(); if errno!= Errno::EINVAL && errno!= Errno::ENOENT { // only return an error if this path is not actually a symlink return ret_error(&mut dir_stack, host::errno_from_nix(errno)); } } } }
// not a symlink, so we're done; return Ok(( ret_dir_success(&mut dir_stack), OsStr::from_bytes(component).to_os_string(), )); } } if path_stack.is_empty() { // no further components to process. means we've hit a case like "." or "a/..", or if the // input path has trailing slashes and `needs_final_component` is not set return Ok(( ret_dir_success(&mut dir_stack), OsStr::new(".").to_os_string(), )); } else { continue; } } } #[cfg(not(target_os = "macos"))] pub fn utime_now() -> c_long { libc::UTIME_NOW } #[cfg(target_os = "macos")] pub fn utime_now() -> c_long { -1 } #[cfg(not(target_os = "macos"))] pub fn utime_omit() -> c_long { libc::UTIME_OMIT } #[cfg(target_os = "macos")] pub fn utime_omit() -> c_long { -2 }
random_line_split
fs_helpers.rs
#![allow(non_camel_case_types)] #![allow(unused_unsafe)] use crate::ctx::WasiCtx; use crate::host; use lucet_runtime::vmctx::Vmctx; use nix::libc::{self, c_long}; use std::ffi::{OsStr, OsString}; use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd}; #[cfg(target_os = "linux")] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_RSYNC; #[cfg(not(target_os = "linux"))] pub const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_SYNC; /// Normalizes a path to ensure that the target path is located under the directory provided. /// /// This is a workaround for not having Capsicum support in the OS. pub fn path_get<P: AsRef<OsStr>>( vmctx: &Vmctx, dirfd: host::__wasi_fd_t, dirflags: host::__wasi_lookupflags_t, path: P, needed_base: host::__wasi_rights_t, needed_inheriting: host::__wasi_rights_t, needs_final_component: bool, ) -> Result<(RawFd, OsString), host::__wasi_errno_t> { use nix::errno::Errno; use nix::fcntl::{openat, readlinkat, OFlag}; use nix::sys::stat::Mode; const MAX_SYMLINK_EXPANSIONS: usize = 128; /// close all the intermediate file descriptors, but make sure not to drop either the original /// dirfd or the one we return (which may be the same dirfd) fn ret_dir_success(dir_stack: &mut Vec<RawFd>) -> RawFd { let ret_dir = dir_stack.pop().expect("there is always a dirfd to return"); if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } ret_dir } /// close all file descriptors other than the base directory, and return the errno for /// convenience with `return` fn ret_error( dir_stack: &mut Vec<RawFd>, errno: host::__wasi_errno_t, ) -> Result<(RawFd, OsString), host::__wasi_errno_t> { if let Some(dirfds) = dir_stack.get(1..) { for dirfd in dirfds { nix::unistd::close(*dirfd).unwrap_or_else(|e| { dbg!(e); }); } } Err(errno) } let ctx = vmctx.get_embed_ctx::<WasiCtx>(); let dirfe = ctx.get_fd_entry(dirfd, needed_base, needed_inheriting)?; // Stack of directory file descriptors. Index 0 always corresponds with the directory provided // to this function. Entering a directory causes a file descriptor to be pushed, while handling // ".." entries causes an entry to be popped. Index 0 cannot be popped, as this would imply // escaping the base directory. let mut dir_stack = vec![dirfe.fd_object.rawfd]; // Stack of paths left to process. This is initially the `path` argument to this function, but // any symlinks we encounter are processed by pushing them on the stack. let mut path_stack = vec![path.as_ref().to_owned().into_vec()]; // Track the number of symlinks we've expanded, so we can return `ELOOP` after too many. let mut symlink_expansions = 0; // Buffer to read links into; defined outside of the loop so we don't reallocate it constantly. let mut readlink_buf = vec![0u8; libc::PATH_MAX as usize + 1]; // TODO: rewrite this using a custom posix path type, with a component iterator that respects // trailing slashes. This version does way too much allocation, and is way too fiddly. loop { let component = if let Some(cur_path) = path_stack.pop() { // eprintln!( // "cur_path = {:?}", // std::str::from_utf8(cur_path.as_slice()).unwrap() // ); let mut split = cur_path.splitn(2, |&c| c == b'/'); let head = split.next(); let tail = split.next(); match (head, tail) { (None, _) => { // split always returns at least a singleton iterator with an empty slice panic!("unreachable"); } // path is empty (Some([]), None) => { return ret_error(&mut dir_stack, host::__WASI_ENOENT as host::__wasi_errno_t); } // path starts with `/`, is absolute (Some([]), Some(_)) => { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } // the final component of the path with no trailing slash (Some(component), None) => component.to_vec(), (Some(component), Some(rest)) => { if rest.iter().all(|&c| c == b'/') { // the final component of the path with trailing slashes; put one trailing // slash back on let mut component = component.to_vec(); component.push('/' as u8); component } else { // non-final component; push the rest back on the stack path_stack.push(rest.to_vec()); component.to_vec() } } } } else { // if the path stack is ever empty, we return rather than going through the loop again panic!("unreachable"); }; // eprintln!( // "component = {:?}", // std::str::from_utf8(component.as_slice()).unwrap() // ); match component.as_slice() { b"." => { // skip component } b".." => { // pop a directory let dirfd = dir_stack.pop().expect("dir_stack is never empty"); // we're not allowed to pop past the original directory if dir_stack.is_empty() { return ret_error( &mut dir_stack, host::__WASI_ENOTCAPABLE as host::__wasi_errno_t, ); } else { nix::unistd::close(dirfd).unwrap_or_else(|e| { dbg!(e); }); } } // should the component be a directory? it should if there is more path left to process, or // if it has a trailing slash and `needs_final_component` is not set component if!path_stack.is_empty() || (component.ends_with(b"/") &&!needs_final_component) => { match openat( *dir_stack.last().expect("dir_stack is never empty"), component, OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW, Mode::empty(), ) { Ok(new_dir) =>
Err(e) // Check to see if it was a symlink. Linux indicates // this with ENOTDIR because of the O_DIRECTORY flag. if e.as_errno() == Some(Errno::ELOOP) || e.as_errno() == Some(Errno::EMLINK) || e.as_errno() == Some(Errno::ENOTDIR) => { // attempt symlink expansion match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } Err(e) => { return ret_error( &mut dir_stack, host::errno_from_nix(e.as_errno().unwrap()), ); } } } // the final component component => { // if there's a trailing slash, or if `LOOKUP_SYMLINK_FOLLOW` is set, attempt // symlink expansion if component.ends_with(b"/") || (dirflags & host::__WASI_LOOKUP_SYMLINK_FOLLOW)!= 0 { match readlinkat( *dir_stack.last().expect("dir_stack is never empty"), component, readlink_buf.as_mut_slice(), ) { Ok(link_path) => { symlink_expansions += 1; if symlink_expansions > MAX_SYMLINK_EXPANSIONS { return ret_error( &mut dir_stack, host::__WASI_ELOOP as host::__wasi_errno_t, ); } let mut link_path = link_path.as_bytes().to_vec(); // append a trailing slash if the component leading to it has one, so // that we preserve any ENOTDIR that might come from trying to open a // non-directory if component.ends_with(b"/") { link_path.push(b'/'); } path_stack.push(link_path); continue; } Err(e) => { let errno = e.as_errno().unwrap(); if errno!= Errno::EINVAL && errno!= Errno::ENOENT { // only return an error if this path is not actually a symlink return ret_error(&mut dir_stack, host::errno_from_nix(errno)); } } } } // not a symlink, so we're done; return Ok(( ret_dir_success(&mut dir_stack), OsStr::from_bytes(component).to_os_string(), )); } } if path_stack.is_empty() { // no further components to process. means we've hit a case like "." or "a/..", or if the // input path has trailing slashes and `needs_final_component` is not set return Ok(( ret_dir_success(&mut dir_stack), OsStr::new(".").to_os_string(), )); } else { continue; } } } #[cfg(not(target_os = "macos"))] pub fn utime_now() -> c_long { libc::UTIME_NOW } #[cfg(target_os = "macos")] pub fn utime_now() -> c_long { -1 } #[cfg(not(target_os = "macos"))] pub fn utime_omit() -> c_long { libc::UTIME_OMIT } #[cfg(target_os = "macos")] pub fn utime_omit() -> c_long { -2 }
{ dir_stack.push(new_dir); continue; }
conditional_block
tydecode.rs
://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Type decoding // tjc note: Would be great to have a `match check` macro equivalent // for some of these use core::prelude::*; use middle::ty; use core::str; use core::uint; use core::vec; use syntax::abi::AbiSet; use syntax::abi; use syntax::ast; use syntax::ast::*; use syntax::codemap::dummy_sp; use syntax::opt_vec; // Compact string representation for ty::t values. API ty_str & // parse_from_str. Extra parameters are for converting to/from def_ids in the // data buffer. Whatever format you choose should not contain pipe characters. // Def id conversion: when we encounter def-ids, they have to be translated. // For example, the crate number must be converted from the crate number used // in the library we are reading from into the local crate numbers in use // here. To perform this translation, the type decoder is supplied with a // conversion function of type `conv_did`. // // Sometimes, particularly when inlining, the correct translation of the // def-id will depend on where it originated from. Therefore, the conversion // function is given an indicator of the source of the def-id. See // astencode.rs for more information. pub enum DefIdSource { // Identifies a struct, trait, enum, etc. NominalType, // Identifies a type alias (`type X =...`). TypeWithId, // Identifies a type parameter (`fn foo<X>() {... }`). TypeParameter } type conv_did<'self> = &'self fn(source: DefIdSource, ast::def_id) -> ast::def_id; pub struct PState { data: @~[u8], crate: int, pos: uint, tcx: ty::ctxt } fn peek(st: @mut PState) -> char { st.data[st.pos] as char } fn next(st: @mut PState) -> char { let ch = st.data[st.pos] as char; st.pos = st.pos + 1u; return ch; } fn next_byte(st: @mut PState) -> u8 { let b = st.data[st.pos]; st.pos = st.pos + 1u; return b; } fn scan<R>(st: &mut PState, is_last: &fn(char) -> bool, op: &fn(&[u8]) -> R) -> R { let start_pos = st.pos; debug!("scan: '%c' (start)", st.data[st.pos] as char); while!is_last(st.data[st.pos] as char) { st.pos += 1; debug!("scan: '%c'", st.data[st.pos] as char); } let end_pos = st.pos; st.pos += 1; return op(st.data.slice(start_pos, end_pos)); } pub fn parse_ident(st: @mut PState, last: char) -> ast::ident { fn is_last(b: char, c: char) -> bool { return c == b; } return parse_ident_(st, |a| is_last(last, a) ); } fn
(st: @mut PState, is_last: @fn(char) -> bool) -> ast::ident { let rslt = scan(st, is_last, str::from_bytes); return st.tcx.sess.ident_of(rslt); } pub fn parse_state_from_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt) -> @mut PState { @mut PState { data: data, crate: crate_num, pos: pos, tcx: tcx } } pub fn parse_ty_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt, conv: conv_did) -> ty::t { let st = parse_state_from_data(data, crate_num, pos, tcx); parse_ty(st, conv) } pub fn parse_arg_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt, conv: conv_did) -> ty::arg { let st = parse_state_from_data(data, crate_num, pos, tcx); parse_arg(st, conv) } fn parse_path(st: @mut PState) -> @ast::path { let mut idents: ~[ast::ident] = ~[]; fn is_last(c: char) -> bool { return c == '(' || c == ':'; } idents.push(parse_ident_(st, is_last)); loop { match peek(st) { ':' => { next(st); next(st); } c => { if c == '(' { return @ast::path { span: dummy_sp(), global: false, idents: idents, rp: None, types: ~[] }; } else { idents.push(parse_ident_(st, is_last)); } } } }; } fn parse_sigil(st: @mut PState) -> ast::Sigil { match next(st) { '@' => ast::ManagedSigil, '~' => ast::OwnedSigil, '&' => ast::BorrowedSigil, c => st.tcx.sess.bug(fmt!("parse_sigil(): bad input '%c'", c)) } } fn parse_vstore(st: @mut PState) -> ty::vstore { assert!(next(st) == '/'); let c = peek(st); if '0' <= c && c <= '9' { let n = parse_int(st) as uint; assert!(next(st) == '|'); return ty::vstore_fixed(n); } match next(st) { '~' => ty::vstore_uniq, '@' => ty::vstore_box, '&' => ty::vstore_slice(parse_region(st)), c => st.tcx.sess.bug(fmt!("parse_vstore(): bad input '%c'", c)) } } fn parse_trait_store(st: @mut PState) -> ty::TraitStore { match next(st) { '~' => ty::UniqTraitStore, '@' => ty::BoxTraitStore, '&' => ty::RegionTraitStore(parse_region(st)), '.' => ty::BareTraitStore, c => st.tcx.sess.bug(fmt!("parse_trait_store(): bad input '%c'", c)) } } fn parse_substs(st: @mut PState, conv: conv_did) -> ty::substs { let self_r = parse_opt(st, || parse_region(st) ); let self_ty = parse_opt(st, || parse_ty(st, conv) ); assert!(next(st) == '['); let mut params: ~[ty::t] = ~[]; while peek(st)!= ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; return ty::substs { self_r: self_r, self_ty: self_ty, tps: params }; } fn parse_bound_region(st: @mut PState) -> ty::bound_region { match next(st) { 's' => ty::br_self, 'a' => { let id = parse_int(st) as uint; assert!(next(st) == '|'); ty::br_anon(id) } '[' => ty::br_named(st.tcx.sess.ident_of(parse_str(st, ']'))), 'c' => { let id = parse_int(st); assert!(next(st) == '|'); ty::br_cap_avoid(id, @parse_bound_region(st)) }, _ => fail!(~"parse_bound_region: bad input") } } fn parse_region(st: @mut PState) -> ty::Region { match next(st) { 'b' => { ty::re_bound(parse_bound_region(st)) } 'f' => { assert!(next(st) == '['); let id = parse_int(st); assert!(next(st) == '|'); let br = parse_bound_region(st); assert!(next(st) == ']'); ty::re_free(id, br) } 's' => { let id = parse_int(st); assert!(next(st) == '|'); ty::re_scope(id) } 't' => { ty::re_static } _ => fail!(~"parse_region: bad input") } } fn parse_opt<T>(st: @mut PState, f: &fn() -> T) -> Option<T> { match next(st) { 'n' => None, 's' => Some(f()), _ => fail!(~"parse_opt: bad input") } } fn parse_str(st: @mut PState, term: char) -> ~str { let mut result = ~""; while peek(st)!= term { result += str::from_byte(next_byte(st)); } next(st); return result; } fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t { match next(st) { 'n' => return ty::mk_nil(st.tcx), 'z' => return ty::mk_bot(st.tcx), 'b' => return ty::mk_bool(st.tcx), 'i' => return ty::mk_int(st.tcx), 'u' => return ty::mk_uint(st.tcx), 'l' => return ty::mk_float(st.tcx), 'M' => { match next(st) { 'b' => return ty::mk_mach_uint(st.tcx, ast::ty_u8), 'w' => return ty::mk_mach_uint(st.tcx, ast::ty_u16), 'l' => return ty::mk_mach_uint(st.tcx, ast::ty_u32), 'd' => return ty::mk_mach_uint(st.tcx, ast::ty_u64), 'B' => return ty::mk_mach_int(st.tcx, ast::ty_i8), 'W' => return ty::mk_mach_int(st.tcx, ast::ty_i16), 'L' => return ty::mk_mach_int(st.tcx, ast::ty_i32), 'D' => return ty::mk_mach_int(st.tcx, ast::ty_i64), 'f' => return ty::mk_mach_float(st.tcx, ast::ty_f32), 'F' => return ty::mk_mach_float(st.tcx, ast::ty_f64), _ => fail!(~"parse_ty: bad numeric type") } } 'c' => return ty::mk_char(st.tcx), 't' => { assert!((next(st) == '[')); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); assert!(next(st) == ']'); return ty::mk_enum(st.tcx, def, substs); } 'x' => { assert!(next(st) == '['); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); let store = parse_trait_store(st); assert!(next(st) == ']'); return ty::mk_trait(st.tcx, def, substs, store); } 'p' => { let did = parse_def(st, TypeParameter, conv); debug!("parsed ty_param: did=%?", did); return ty::mk_param(st.tcx, parse_int(st) as uint, did); } 's' => { let did = parse_def(st, TypeParameter, conv); return ty::mk_self(st.tcx, did); } '@' => return ty::mk_box(st.tcx, parse_mt(st, conv)), '~' => return ty::mk_uniq(st.tcx, parse_mt(st, conv)), '*' => return ty::mk_ptr(st.tcx, parse_mt(st, conv)), '&' => { let r = parse_region(st); let mt = parse_mt(st, conv); return ty::mk_rptr(st.tcx, r, mt); } 'U' => return ty::mk_unboxed_vec(st.tcx, parse_mt(st, conv)), 'V' => { let mt = parse_mt(st, conv); let v = parse_vstore(st); return ty::mk_evec(st.tcx, mt, v); } 'v' => { let v = parse_vstore(st); return ty::mk_estr(st.tcx, v); } 'T' => { assert!((next(st) == '[')); let mut params = ~[]; while peek(st)!= ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; return ty::mk_tup(st.tcx, params); } 'f' => { return ty::mk_closure(st.tcx, parse_closure_ty(st, conv)); } 'F' => { return ty::mk_bare_fn(st.tcx, parse_bare_fn_ty(st, conv)); } 'Y' => return ty::mk_type(st.tcx), 'C' => { let sigil = parse_sigil(st); return ty::mk_opaque_closure_ptr(st.tcx, sigil); } '#' => { let pos = parse_hex(st); assert!((next(st) == ':')); let len = parse_hex(st); assert!((next(st) == '#')); let key = ty::creader_cache_key {cnum: st.crate, pos: pos, len: len }; match st.tcx.rcache.find(&key) { Some(&tt) => return tt, None => { let ps = @mut PState {pos: pos,.. copy *st}; let tt = parse_ty(ps, conv); st.tcx.rcache.insert(key, tt); return tt; } } } '"' => { let def = parse_def(st, TypeWithId, conv); let inner = parse_ty(st, conv); ty::mk_with_id(st.tcx, inner, def) } 'B' => ty::mk_opaque_box(st.tcx), 'a' => { assert!((next(st) == '[')); let did = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); assert!((next(st) == ']')); return ty::mk_struct(st.tcx, did, substs); } c => { error!("unexpected char in type string: %c", c); fail!();} } } fn parse_mt(st: @mut PState, conv: conv_did) -> ty::mt { let mut m; match peek(st) { 'm' => { next(st); m = ast::m_mutbl; } '?' => { next(st); m = ast::m_const; } _ => { m = ast::m_imm; } } ty::mt { ty: parse_ty(st, conv), mutbl: m } } fn parse_def(st: @mut PState, source: DefIdSource, conv: conv_did) -> ast::def_id { let mut def = ~[]; while peek(st)!= '|' { def.push(next_byte(st)); } st.pos = st.pos + 1u; return conv(source, parse_def_id(def)); } fn parse_int(st: @mut PState) -> int { let mut n = 0; loop { let cur = peek(st); if cur < '0' || cur > '9' { return n; } st.pos = st.pos + 1u; n *= 10; n += (cur as int) - ('0' as int); }; } fn parse_hex(st: @mut PState) -> uint { let mut n = 0u; loop { let cur = peek(st); if (cur < '0' || cur > '9') && (cur < 'a' || cur > 'f') { return n; } st.pos = st.pos + 1u; n *= 16u; if '0' <= cur && cur <= '9' { n += (cur as uint) - ('0' as uint); } else { n += 10u + (cur as uint) - ('a' as uint); } }; } fn parse_purity(c: char) -> purity { match c { 'u' => unsafe_fn, 'p' => pure_fn, 'i' => impure_fn, 'c' => extern_fn, _ => fail!(~"parse_purity: bad purity") } } fn parse_abi_set(st: @mut PState) -> AbiSet { assert!(next(st) == '['); let mut abis = AbiSet::empty(); while peek(st)!= ']' { // FIXME(#5422) str API should not force this copy let abi_str = scan(st, |c| c == ',', str::from_bytes); let abi = abi::lookup(abi_str).expect(abi_str); abis.add(abi); } assert!(next(st) == ']'); return abis; } fn parse_onceness(c: char) -> ast::Onceness { match c { 'o' => ast::Once, 'm' => ast::Many, _ => fail!(~"parse_onceness: bad onceness") } } fn parse_arg(st: @mut PState, conv: conv_did) -> ty::arg { ty::arg { mode: parse_mode(st), ty: parse_ty(st, conv) } } fn parse_mode(st: @mut PState) -> ast::mode { let m = ast::expl(match next(st) { '+' => ast::by_copy, '=' => ast::by_ref, _ => fail!(~"bad mode") }); return m; } fn parse_closure_ty(st: @mut PState, conv: conv_did) -> ty::ClosureTy { let sigil = parse_sigil(st); let purity = parse_purity(next(st)); let onceness = parse_onceness(next(st)); let region = parse_region(st); let sig = parse_sig(st, conv); ty::ClosureTy { purity: purity, sigil: sigil, onceness: onceness, region: region, sig: sig } } fn parse_bare_fn_ty(st: @mut PState, conv: conv_did) -> ty::BareFnTy { let purity = parse_purity(next(st)); let abi = parse_abi_set(st); let sig = parse_sig(st, conv); ty::BareFnTy { purity: purity, abis: abi, sig: sig } } fn parse_sig(st: @mut PState, conv: conv_did) -> ty::FnSig { assert!((next(st) == '[')); let mut inputs: ~[ty::arg] = ~[]; while peek(st)!= ']' { let mode = parse_mode(st); inputs.push(ty::arg { mode: mode, ty: parse_ty(st, conv) }); } st.pos += 1u; // eat the ']' let ret_ty = parse_ty(st, conv); ty::FnSig {bound_lifetime_names: opt_vec::Empty, // FIXME(#4846) inputs: inputs, output: ret_ty} } // Rust metadata parsing pub fn parse_def_id(buf: &[u8]) -> ast::def_id { let mut colon_idx = 0u; let len = vec::len(buf); while colon_idx < len && buf[colon_idx]!= ':' as u8 { colon_idx += 1u; } if colon_idx == len { error!("didn't find ':' when parsing def id"); fail!(); } let crate_part = vec::slice(buf, 0u, colon_idx); let def_part = vec::slice(buf, colon_idx + 1u, len); let crate_num = match uint::parse_bytes(crate_part, 10u) { Some(cn) => cn as int, None => fail!(fmt!("internal error: parse_def_id: crate number \ expected, but found %?", crate_part)) }; let def_num = match uint::parse_bytes(def_part, 10u) { Some(dn) => dn as int, None => fail!(fmt!("internal error: parse_def_id: id expected, but \ found %?", def_part)) }; ast::def_id { crate: crate_num, node: def_num } } pub fn parse_bounds_data(data: @~[u8], start: uint, crate_num: int, tcx: ty::ctxt, conv: conv_did) -> @~[ty::param_bound] { let st = parse_state_from_data(data, crate_num, start, tcx); parse_bounds(st, conv) } fn parse_bounds(st: @mut PState, conv: conv_did) -> @~[ty::param_bound] { let mut bounds = ~[]; loop { bounds.push(match next(st) { 'S' => ty::bound_owned, 'C' => ty::bound_copy, 'K' => ty::bound_const, 'O' => ty::bound_durable, 'I' => ty::bound_trait(parse_ty(st, conv)), '.' => break, _ => fail!(~"parse_bounds: bad bounds") }); }
parse_ident_
identifier_name
tydecode.rs
://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Type decoding // tjc note: Would be great to have a `match check` macro equivalent // for some of these use core::prelude::*; use middle::ty; use core::str; use core::uint; use core::vec; use syntax::abi::AbiSet; use syntax::abi; use syntax::ast; use syntax::ast::*; use syntax::codemap::dummy_sp; use syntax::opt_vec; // Compact string representation for ty::t values. API ty_str & // parse_from_str. Extra parameters are for converting to/from def_ids in the // data buffer. Whatever format you choose should not contain pipe characters. // Def id conversion: when we encounter def-ids, they have to be translated. // For example, the crate number must be converted from the crate number used // in the library we are reading from into the local crate numbers in use // here. To perform this translation, the type decoder is supplied with a // conversion function of type `conv_did`. // // Sometimes, particularly when inlining, the correct translation of the // def-id will depend on where it originated from. Therefore, the conversion // function is given an indicator of the source of the def-id. See // astencode.rs for more information. pub enum DefIdSource { // Identifies a struct, trait, enum, etc. NominalType, // Identifies a type alias (`type X =...`). TypeWithId, // Identifies a type parameter (`fn foo<X>() {... }`). TypeParameter } type conv_did<'self> = &'self fn(source: DefIdSource, ast::def_id) -> ast::def_id; pub struct PState { data: @~[u8], crate: int, pos: uint, tcx: ty::ctxt } fn peek(st: @mut PState) -> char { st.data[st.pos] as char } fn next(st: @mut PState) -> char { let ch = st.data[st.pos] as char; st.pos = st.pos + 1u; return ch; } fn next_byte(st: @mut PState) -> u8 { let b = st.data[st.pos]; st.pos = st.pos + 1u; return b; } fn scan<R>(st: &mut PState, is_last: &fn(char) -> bool, op: &fn(&[u8]) -> R) -> R { let start_pos = st.pos; debug!("scan: '%c' (start)", st.data[st.pos] as char); while!is_last(st.data[st.pos] as char) { st.pos += 1; debug!("scan: '%c'", st.data[st.pos] as char); } let end_pos = st.pos; st.pos += 1; return op(st.data.slice(start_pos, end_pos)); } pub fn parse_ident(st: @mut PState, last: char) -> ast::ident { fn is_last(b: char, c: char) -> bool { return c == b; } return parse_ident_(st, |a| is_last(last, a) ); } fn parse_ident_(st: @mut PState, is_last: @fn(char) -> bool) -> ast::ident { let rslt = scan(st, is_last, str::from_bytes); return st.tcx.sess.ident_of(rslt); } pub fn parse_state_from_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt) -> @mut PState { @mut PState { data: data, crate: crate_num, pos: pos, tcx: tcx } } pub fn parse_ty_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt, conv: conv_did) -> ty::t
pub fn parse_arg_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt, conv: conv_did) -> ty::arg { let st = parse_state_from_data(data, crate_num, pos, tcx); parse_arg(st, conv) } fn parse_path(st: @mut PState) -> @ast::path { let mut idents: ~[ast::ident] = ~[]; fn is_last(c: char) -> bool { return c == '(' || c == ':'; } idents.push(parse_ident_(st, is_last)); loop { match peek(st) { ':' => { next(st); next(st); } c => { if c == '(' { return @ast::path { span: dummy_sp(), global: false, idents: idents, rp: None, types: ~[] }; } else { idents.push(parse_ident_(st, is_last)); } } } }; } fn parse_sigil(st: @mut PState) -> ast::Sigil { match next(st) { '@' => ast::ManagedSigil, '~' => ast::OwnedSigil, '&' => ast::BorrowedSigil, c => st.tcx.sess.bug(fmt!("parse_sigil(): bad input '%c'", c)) } } fn parse_vstore(st: @mut PState) -> ty::vstore { assert!(next(st) == '/'); let c = peek(st); if '0' <= c && c <= '9' { let n = parse_int(st) as uint; assert!(next(st) == '|'); return ty::vstore_fixed(n); } match next(st) { '~' => ty::vstore_uniq, '@' => ty::vstore_box, '&' => ty::vstore_slice(parse_region(st)), c => st.tcx.sess.bug(fmt!("parse_vstore(): bad input '%c'", c)) } } fn parse_trait_store(st: @mut PState) -> ty::TraitStore { match next(st) { '~' => ty::UniqTraitStore, '@' => ty::BoxTraitStore, '&' => ty::RegionTraitStore(parse_region(st)), '.' => ty::BareTraitStore, c => st.tcx.sess.bug(fmt!("parse_trait_store(): bad input '%c'", c)) } } fn parse_substs(st: @mut PState, conv: conv_did) -> ty::substs { let self_r = parse_opt(st, || parse_region(st) ); let self_ty = parse_opt(st, || parse_ty(st, conv) ); assert!(next(st) == '['); let mut params: ~[ty::t] = ~[]; while peek(st)!= ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; return ty::substs { self_r: self_r, self_ty: self_ty, tps: params }; } fn parse_bound_region(st: @mut PState) -> ty::bound_region { match next(st) { 's' => ty::br_self, 'a' => { let id = parse_int(st) as uint; assert!(next(st) == '|'); ty::br_anon(id) } '[' => ty::br_named(st.tcx.sess.ident_of(parse_str(st, ']'))), 'c' => { let id = parse_int(st); assert!(next(st) == '|'); ty::br_cap_avoid(id, @parse_bound_region(st)) }, _ => fail!(~"parse_bound_region: bad input") } } fn parse_region(st: @mut PState) -> ty::Region { match next(st) { 'b' => { ty::re_bound(parse_bound_region(st)) } 'f' => { assert!(next(st) == '['); let id = parse_int(st); assert!(next(st) == '|'); let br = parse_bound_region(st); assert!(next(st) == ']'); ty::re_free(id, br) } 's' => { let id = parse_int(st); assert!(next(st) == '|'); ty::re_scope(id) } 't' => { ty::re_static } _ => fail!(~"parse_region: bad input") } } fn parse_opt<T>(st: @mut PState, f: &fn() -> T) -> Option<T> { match next(st) { 'n' => None, 's' => Some(f()), _ => fail!(~"parse_opt: bad input") } } fn parse_str(st: @mut PState, term: char) -> ~str { let mut result = ~""; while peek(st)!= term { result += str::from_byte(next_byte(st)); } next(st); return result; } fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t { match next(st) { 'n' => return ty::mk_nil(st.tcx), 'z' => return ty::mk_bot(st.tcx), 'b' => return ty::mk_bool(st.tcx), 'i' => return ty::mk_int(st.tcx), 'u' => return ty::mk_uint(st.tcx), 'l' => return ty::mk_float(st.tcx), 'M' => { match next(st) { 'b' => return ty::mk_mach_uint(st.tcx, ast::ty_u8), 'w' => return ty::mk_mach_uint(st.tcx, ast::ty_u16), 'l' => return ty::mk_mach_uint(st.tcx, ast::ty_u32), 'd' => return ty::mk_mach_uint(st.tcx, ast::ty_u64), 'B' => return ty::mk_mach_int(st.tcx, ast::ty_i8), 'W' => return ty::mk_mach_int(st.tcx, ast::ty_i16), 'L' => return ty::mk_mach_int(st.tcx, ast::ty_i32), 'D' => return ty::mk_mach_int(st.tcx, ast::ty_i64), 'f' => return ty::mk_mach_float(st.tcx, ast::ty_f32), 'F' => return ty::mk_mach_float(st.tcx, ast::ty_f64), _ => fail!(~"parse_ty: bad numeric type") } } 'c' => return ty::mk_char(st.tcx), 't' => { assert!((next(st) == '[')); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); assert!(next(st) == ']'); return ty::mk_enum(st.tcx, def, substs); } 'x' => { assert!(next(st) == '['); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); let store = parse_trait_store(st); assert!(next(st) == ']'); return ty::mk_trait(st.tcx, def, substs, store); } 'p' => { let did = parse_def(st, TypeParameter, conv); debug!("parsed ty_param: did=%?", did); return ty::mk_param(st.tcx, parse_int(st) as uint, did); } 's' => { let did = parse_def(st, TypeParameter, conv); return ty::mk_self(st.tcx, did); } '@' => return ty::mk_box(st.tcx, parse_mt(st, conv)), '~' => return ty::mk_uniq(st.tcx, parse_mt(st, conv)), '*' => return ty::mk_ptr(st.tcx, parse_mt(st, conv)), '&' => { let r = parse_region(st); let mt = parse_mt(st, conv); return ty::mk_rptr(st.tcx, r, mt); } 'U' => return ty::mk_unboxed_vec(st.tcx, parse_mt(st, conv)), 'V' => { let mt = parse_mt(st, conv); let v = parse_vstore(st); return ty::mk_evec(st.tcx, mt, v); } 'v' => { let v = parse_vstore(st); return ty::mk_estr(st.tcx, v); } 'T' => { assert!((next(st) == '[')); let mut params = ~[]; while peek(st)!= ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; return ty::mk_tup(st.tcx, params); } 'f' => { return ty::mk_closure(st.tcx, parse_closure_ty(st, conv)); } 'F' => { return ty::mk_bare_fn(st.tcx, parse_bare_fn_ty(st, conv)); } 'Y' => return ty::mk_type(st.tcx), 'C' => { let sigil = parse_sigil(st); return ty::mk_opaque_closure_ptr(st.tcx, sigil); } '#' => { let pos = parse_hex(st); assert!((next(st) == ':')); let len = parse_hex(st); assert!((next(st) == '#')); let key = ty::creader_cache_key {cnum: st.crate, pos: pos, len: len }; match st.tcx.rcache.find(&key) { Some(&tt) => return tt, None => { let ps = @mut PState {pos: pos,.. copy *st}; let tt = parse_ty(ps, conv); st.tcx.rcache.insert(key, tt); return tt; } } } '"' => { let def = parse_def(st, TypeWithId, conv); let inner = parse_ty(st, conv); ty::mk_with_id(st.tcx, inner, def) } 'B' => ty::mk_opaque_box(st.tcx), 'a' => { assert!((next(st) == '[')); let did = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); assert!((next(st) == ']')); return ty::mk_struct(st.tcx, did, substs); } c => { error!("unexpected char in type string: %c", c); fail!();} } } fn parse_mt(st: @mut PState, conv: conv_did) -> ty::mt { let mut m; match peek(st) { 'm' => { next(st); m = ast::m_mutbl; } '?' => { next(st); m = ast::m_const; } _ => { m = ast::m_imm; } } ty::mt { ty: parse_ty(st, conv), mutbl: m } } fn parse_def(st: @mut PState, source: DefIdSource, conv: conv_did) -> ast::def_id { let mut def = ~[]; while peek(st)!= '|' { def.push(next_byte(st)); } st.pos = st.pos + 1u; return conv(source, parse_def_id(def)); } fn parse_int(st: @mut PState) -> int { let mut n = 0; loop { let cur = peek(st); if cur < '0' || cur > '9' { return n; } st.pos = st.pos + 1u; n *= 10; n += (cur as int) - ('0' as int); }; } fn parse_hex(st: @mut PState) -> uint { let mut n = 0u; loop { let cur = peek(st); if (cur < '0' || cur > '9') && (cur < 'a' || cur > 'f') { return n; } st.pos = st.pos + 1u; n *= 16u; if '0' <= cur && cur <= '9' { n += (cur as uint) - ('0' as uint); } else { n += 10u + (cur as uint) - ('a' as uint); } }; } fn parse_purity(c: char) -> purity { match c { 'u' => unsafe_fn, 'p' => pure_fn, 'i' => impure_fn, 'c' => extern_fn, _ => fail!(~"parse_purity: bad purity") } } fn parse_abi_set(st: @mut PState) -> AbiSet { assert!(next(st) == '['); let mut abis = AbiSet::empty(); while peek(st)!= ']' { // FIXME(#5422) str API should not force this copy let abi_str = scan(st, |c| c == ',', str::from_bytes); let abi = abi::lookup(abi_str).expect(abi_str); abis.add(abi); } assert!(next(st) == ']'); return abis; } fn parse_onceness(c: char) -> ast::Onceness { match c { 'o' => ast::Once, 'm' => ast::Many, _ => fail!(~"parse_onceness: bad onceness") } } fn parse_arg(st: @mut PState, conv: conv_did) -> ty::arg { ty::arg { mode: parse_mode(st), ty: parse_ty(st, conv) } } fn parse_mode(st: @mut PState) -> ast::mode { let m = ast::expl(match next(st) { '+' => ast::by_copy, '=' => ast::by_ref, _ => fail!(~"bad mode") }); return m; } fn parse_closure_ty(st: @mut PState, conv: conv_did) -> ty::ClosureTy { let sigil = parse_sigil(st); let purity = parse_purity(next(st)); let onceness = parse_onceness(next(st)); let region = parse_region(st); let sig = parse_sig(st, conv); ty::ClosureTy { purity: purity, sigil: sigil, onceness: onceness, region: region, sig: sig } } fn parse_bare_fn_ty(st: @mut PState, conv: conv_did) -> ty::BareFnTy { let purity = parse_purity(next(st)); let abi = parse_abi_set(st); let sig = parse_sig(st, conv); ty::BareFnTy { purity: purity, abis: abi, sig: sig } } fn parse_sig(st: @mut PState, conv: conv_did) -> ty::FnSig { assert!((next(st) == '[')); let mut inputs: ~[ty::arg] = ~[]; while peek(st)!= ']' { let mode = parse_mode(st); inputs.push(ty::arg { mode: mode, ty: parse_ty(st, conv) }); } st.pos += 1u; // eat the ']' let ret_ty = parse_ty(st, conv); ty::FnSig {bound_lifetime_names: opt_vec::Empty, // FIXME(#4846) inputs: inputs, output: ret_ty} } // Rust metadata parsing pub fn parse_def_id(buf: &[u8]) -> ast::def_id { let mut colon_idx = 0u; let len = vec::len(buf); while colon_idx < len && buf[colon_idx]!= ':' as u8 { colon_idx += 1u; } if colon_idx == len { error!("didn't find ':' when parsing def id"); fail!(); } let crate_part = vec::slice(buf, 0u, colon_idx); let def_part = vec::slice(buf, colon_idx + 1u, len); let crate_num = match uint::parse_bytes(crate_part, 10u) { Some(cn) => cn as int, None => fail!(fmt!("internal error: parse_def_id: crate number \ expected, but found %?", crate_part)) }; let def_num = match uint::parse_bytes(def_part, 10u) { Some(dn) => dn as int, None => fail!(fmt!("internal error: parse_def_id: id expected, but \ found %?", def_part)) }; ast::def_id { crate: crate_num, node: def_num } } pub fn parse_bounds_data(data: @~[u8], start: uint, crate_num: int, tcx: ty::ctxt, conv: conv_did) -> @~[ty::param_bound] { let st = parse_state_from_data(data, crate_num, start, tcx); parse_bounds(st, conv) } fn parse_bounds(st: @mut PState, conv: conv_did) -> @~[ty::param_bound] { let mut bounds = ~[]; loop { bounds.push(match next(st) { 'S' => ty::bound_owned, 'C' => ty::bound_copy, 'K' => ty::bound_const, 'O' => ty::bound_durable, 'I' => ty::bound_trait(parse_ty(st, conv)), '.' => break, _ => fail!(~"parse_bounds: bad bounds") }); }
{ let st = parse_state_from_data(data, crate_num, pos, tcx); parse_ty(st, conv) }
identifier_body
tydecode.rs
http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Type decoding // tjc note: Would be great to have a `match check` macro equivalent // for some of these use core::prelude::*; use middle::ty; use core::str; use core::uint; use core::vec; use syntax::abi::AbiSet; use syntax::abi; use syntax::ast; use syntax::ast::*; use syntax::codemap::dummy_sp; use syntax::opt_vec; // Compact string representation for ty::t values. API ty_str & // parse_from_str. Extra parameters are for converting to/from def_ids in the // data buffer. Whatever format you choose should not contain pipe characters. // Def id conversion: when we encounter def-ids, they have to be translated. // For example, the crate number must be converted from the crate number used // in the library we are reading from into the local crate numbers in use // here. To perform this translation, the type decoder is supplied with a // conversion function of type `conv_did`. // // Sometimes, particularly when inlining, the correct translation of the // def-id will depend on where it originated from. Therefore, the conversion // function is given an indicator of the source of the def-id. See // astencode.rs for more information. pub enum DefIdSource { // Identifies a struct, trait, enum, etc. NominalType, // Identifies a type alias (`type X =...`). TypeWithId, // Identifies a type parameter (`fn foo<X>() {... }`). TypeParameter } type conv_did<'self> = &'self fn(source: DefIdSource, ast::def_id) -> ast::def_id; pub struct PState { data: @~[u8], crate: int, pos: uint, tcx: ty::ctxt } fn peek(st: @mut PState) -> char { st.data[st.pos] as char } fn next(st: @mut PState) -> char { let ch = st.data[st.pos] as char; st.pos = st.pos + 1u; return ch; } fn next_byte(st: @mut PState) -> u8 { let b = st.data[st.pos]; st.pos = st.pos + 1u; return b; } fn scan<R>(st: &mut PState, is_last: &fn(char) -> bool, op: &fn(&[u8]) -> R) -> R { let start_pos = st.pos; debug!("scan: '%c' (start)", st.data[st.pos] as char); while!is_last(st.data[st.pos] as char) { st.pos += 1; debug!("scan: '%c'", st.data[st.pos] as char); } let end_pos = st.pos; st.pos += 1; return op(st.data.slice(start_pos, end_pos)); } pub fn parse_ident(st: @mut PState, last: char) -> ast::ident { fn is_last(b: char, c: char) -> bool { return c == b; } return parse_ident_(st, |a| is_last(last, a) ); } fn parse_ident_(st: @mut PState, is_last: @fn(char) -> bool) -> ast::ident { let rslt = scan(st, is_last, str::from_bytes); return st.tcx.sess.ident_of(rslt); } pub fn parse_state_from_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt) -> @mut PState { @mut PState { data: data, crate: crate_num, pos: pos, tcx: tcx } } pub fn parse_ty_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt, conv: conv_did) -> ty::t { let st = parse_state_from_data(data, crate_num, pos, tcx); parse_ty(st, conv) } pub fn parse_arg_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt, conv: conv_did) -> ty::arg { let st = parse_state_from_data(data, crate_num, pos, tcx); parse_arg(st, conv) } fn parse_path(st: @mut PState) -> @ast::path { let mut idents: ~[ast::ident] = ~[]; fn is_last(c: char) -> bool { return c == '(' || c == ':'; } idents.push(parse_ident_(st, is_last)); loop { match peek(st) { ':' => { next(st); next(st); } c => { if c == '(' { return @ast::path { span: dummy_sp(), global: false, idents: idents, rp: None, types: ~[] }; } else { idents.push(parse_ident_(st, is_last)); } } } }; } fn parse_sigil(st: @mut PState) -> ast::Sigil { match next(st) { '@' => ast::ManagedSigil, '~' => ast::OwnedSigil, '&' => ast::BorrowedSigil, c => st.tcx.sess.bug(fmt!("parse_sigil(): bad input '%c'", c)) } } fn parse_vstore(st: @mut PState) -> ty::vstore { assert!(next(st) == '/'); let c = peek(st); if '0' <= c && c <= '9' { let n = parse_int(st) as uint; assert!(next(st) == '|'); return ty::vstore_fixed(n); } match next(st) { '~' => ty::vstore_uniq, '@' => ty::vstore_box, '&' => ty::vstore_slice(parse_region(st)), c => st.tcx.sess.bug(fmt!("parse_vstore(): bad input '%c'", c)) } } fn parse_trait_store(st: @mut PState) -> ty::TraitStore { match next(st) { '~' => ty::UniqTraitStore, '@' => ty::BoxTraitStore, '&' => ty::RegionTraitStore(parse_region(st)), '.' => ty::BareTraitStore, c => st.tcx.sess.bug(fmt!("parse_trait_store(): bad input '%c'", c)) } } fn parse_substs(st: @mut PState, conv: conv_did) -> ty::substs { let self_r = parse_opt(st, || parse_region(st) ); let self_ty = parse_opt(st, || parse_ty(st, conv) ); assert!(next(st) == '['); let mut params: ~[ty::t] = ~[]; while peek(st)!= ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; return ty::substs { self_r: self_r, self_ty: self_ty, tps: params }; } fn parse_bound_region(st: @mut PState) -> ty::bound_region { match next(st) { 's' => ty::br_self, 'a' => { let id = parse_int(st) as uint; assert!(next(st) == '|'); ty::br_anon(id) } '[' => ty::br_named(st.tcx.sess.ident_of(parse_str(st, ']'))), 'c' => { let id = parse_int(st); assert!(next(st) == '|'); ty::br_cap_avoid(id, @parse_bound_region(st)) }, _ => fail!(~"parse_bound_region: bad input") } } fn parse_region(st: @mut PState) -> ty::Region { match next(st) { 'b' => { ty::re_bound(parse_bound_region(st)) } 'f' => { assert!(next(st) == '['); let id = parse_int(st); assert!(next(st) == '|'); let br = parse_bound_region(st); assert!(next(st) == ']'); ty::re_free(id, br) } 's' => { let id = parse_int(st); assert!(next(st) == '|'); ty::re_scope(id) } 't' => { ty::re_static } _ => fail!(~"parse_region: bad input") } } fn parse_opt<T>(st: @mut PState, f: &fn() -> T) -> Option<T> { match next(st) { 'n' => None, 's' => Some(f()), _ => fail!(~"parse_opt: bad input") } } fn parse_str(st: @mut PState, term: char) -> ~str { let mut result = ~""; while peek(st)!= term { result += str::from_byte(next_byte(st)); } next(st); return result; } fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t { match next(st) { 'n' => return ty::mk_nil(st.tcx), 'z' => return ty::mk_bot(st.tcx), 'b' => return ty::mk_bool(st.tcx), 'i' => return ty::mk_int(st.tcx), 'u' => return ty::mk_uint(st.tcx), 'l' => return ty::mk_float(st.tcx), 'M' => { match next(st) { 'b' => return ty::mk_mach_uint(st.tcx, ast::ty_u8), 'w' => return ty::mk_mach_uint(st.tcx, ast::ty_u16), 'l' => return ty::mk_mach_uint(st.tcx, ast::ty_u32), 'd' => return ty::mk_mach_uint(st.tcx, ast::ty_u64), 'B' => return ty::mk_mach_int(st.tcx, ast::ty_i8), 'W' => return ty::mk_mach_int(st.tcx, ast::ty_i16), 'L' => return ty::mk_mach_int(st.tcx, ast::ty_i32), 'D' => return ty::mk_mach_int(st.tcx, ast::ty_i64), 'f' => return ty::mk_mach_float(st.tcx, ast::ty_f32), 'F' => return ty::mk_mach_float(st.tcx, ast::ty_f64), _ => fail!(~"parse_ty: bad numeric type") } } 'c' => return ty::mk_char(st.tcx), 't' => { assert!((next(st) == '[')); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); assert!(next(st) == ']'); return ty::mk_enum(st.tcx, def, substs); } 'x' => { assert!(next(st) == '['); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); let store = parse_trait_store(st); assert!(next(st) == ']'); return ty::mk_trait(st.tcx, def, substs, store); } 'p' => { let did = parse_def(st, TypeParameter, conv); debug!("parsed ty_param: did=%?", did); return ty::mk_param(st.tcx, parse_int(st) as uint, did); } 's' => { let did = parse_def(st, TypeParameter, conv); return ty::mk_self(st.tcx, did); } '@' => return ty::mk_box(st.tcx, parse_mt(st, conv)), '~' => return ty::mk_uniq(st.tcx, parse_mt(st, conv)), '*' => return ty::mk_ptr(st.tcx, parse_mt(st, conv)), '&' => { let r = parse_region(st); let mt = parse_mt(st, conv); return ty::mk_rptr(st.tcx, r, mt); } 'U' => return ty::mk_unboxed_vec(st.tcx, parse_mt(st, conv)), 'V' => { let mt = parse_mt(st, conv); let v = parse_vstore(st); return ty::mk_evec(st.tcx, mt, v); } 'v' => { let v = parse_vstore(st); return ty::mk_estr(st.tcx, v);
} 'T' => { assert!((next(st) == '[')); let mut params = ~[]; while peek(st)!= ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; return ty::mk_tup(st.tcx, params); } 'f' => { return ty::mk_closure(st.tcx, parse_closure_ty(st, conv)); } 'F' => { return ty::mk_bare_fn(st.tcx, parse_bare_fn_ty(st, conv)); } 'Y' => return ty::mk_type(st.tcx), 'C' => { let sigil = parse_sigil(st); return ty::mk_opaque_closure_ptr(st.tcx, sigil); } '#' => { let pos = parse_hex(st); assert!((next(st) == ':')); let len = parse_hex(st); assert!((next(st) == '#')); let key = ty::creader_cache_key {cnum: st.crate, pos: pos, len: len }; match st.tcx.rcache.find(&key) { Some(&tt) => return tt, None => { let ps = @mut PState {pos: pos,.. copy *st}; let tt = parse_ty(ps, conv); st.tcx.rcache.insert(key, tt); return tt; } } } '"' => { let def = parse_def(st, TypeWithId, conv); let inner = parse_ty(st, conv); ty::mk_with_id(st.tcx, inner, def) } 'B' => ty::mk_opaque_box(st.tcx), 'a' => { assert!((next(st) == '[')); let did = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); assert!((next(st) == ']')); return ty::mk_struct(st.tcx, did, substs); } c => { error!("unexpected char in type string: %c", c); fail!();} } } fn parse_mt(st: @mut PState, conv: conv_did) -> ty::mt { let mut m; match peek(st) { 'm' => { next(st); m = ast::m_mutbl; } '?' => { next(st); m = ast::m_const; } _ => { m = ast::m_imm; } } ty::mt { ty: parse_ty(st, conv), mutbl: m } } fn parse_def(st: @mut PState, source: DefIdSource, conv: conv_did) -> ast::def_id { let mut def = ~[]; while peek(st)!= '|' { def.push(next_byte(st)); } st.pos = st.pos + 1u; return conv(source, parse_def_id(def)); } fn parse_int(st: @mut PState) -> int { let mut n = 0; loop { let cur = peek(st); if cur < '0' || cur > '9' { return n; } st.pos = st.pos + 1u; n *= 10; n += (cur as int) - ('0' as int); }; } fn parse_hex(st: @mut PState) -> uint { let mut n = 0u; loop { let cur = peek(st); if (cur < '0' || cur > '9') && (cur < 'a' || cur > 'f') { return n; } st.pos = st.pos + 1u; n *= 16u; if '0' <= cur && cur <= '9' { n += (cur as uint) - ('0' as uint); } else { n += 10u + (cur as uint) - ('a' as uint); } }; } fn parse_purity(c: char) -> purity { match c { 'u' => unsafe_fn, 'p' => pure_fn, 'i' => impure_fn, 'c' => extern_fn, _ => fail!(~"parse_purity: bad purity") } } fn parse_abi_set(st: @mut PState) -> AbiSet { assert!(next(st) == '['); let mut abis = AbiSet::empty(); while peek(st)!= ']' { // FIXME(#5422) str API should not force this copy let abi_str = scan(st, |c| c == ',', str::from_bytes); let abi = abi::lookup(abi_str).expect(abi_str); abis.add(abi); } assert!(next(st) == ']'); return abis; } fn parse_onceness(c: char) -> ast::Onceness { match c { 'o' => ast::Once, 'm' => ast::Many, _ => fail!(~"parse_onceness: bad onceness") } } fn parse_arg(st: @mut PState, conv: conv_did) -> ty::arg { ty::arg { mode: parse_mode(st), ty: parse_ty(st, conv) } } fn parse_mode(st: @mut PState) -> ast::mode { let m = ast::expl(match next(st) { '+' => ast::by_copy, '=' => ast::by_ref, _ => fail!(~"bad mode") }); return m; } fn parse_closure_ty(st: @mut PState, conv: conv_did) -> ty::ClosureTy { let sigil = parse_sigil(st); let purity = parse_purity(next(st)); let onceness = parse_onceness(next(st)); let region = parse_region(st); let sig = parse_sig(st, conv); ty::ClosureTy { purity: purity, sigil: sigil, onceness: onceness, region: region, sig: sig } } fn parse_bare_fn_ty(st: @mut PState, conv: conv_did) -> ty::BareFnTy { let purity = parse_purity(next(st)); let abi = parse_abi_set(st); let sig = parse_sig(st, conv); ty::BareFnTy { purity: purity, abis: abi, sig: sig } } fn parse_sig(st: @mut PState, conv: conv_did) -> ty::FnSig { assert!((next(st) == '[')); let mut inputs: ~[ty::arg] = ~[]; while peek(st)!= ']' { let mode = parse_mode(st); inputs.push(ty::arg { mode: mode, ty: parse_ty(st, conv) }); } st.pos += 1u; // eat the ']' let ret_ty = parse_ty(st, conv); ty::FnSig {bound_lifetime_names: opt_vec::Empty, // FIXME(#4846) inputs: inputs, output: ret_ty} } // Rust metadata parsing pub fn parse_def_id(buf: &[u8]) -> ast::def_id { let mut colon_idx = 0u; let len = vec::len(buf); while colon_idx < len && buf[colon_idx]!= ':' as u8 { colon_idx += 1u; } if colon_idx == len { error!("didn't find ':' when parsing def id"); fail!(); } let crate_part = vec::slice(buf, 0u, colon_idx); let def_part = vec::slice(buf, colon_idx + 1u, len); let crate_num = match uint::parse_bytes(crate_part, 10u) { Some(cn) => cn as int, None => fail!(fmt!("internal error: parse_def_id: crate number \ expected, but found %?", crate_part)) }; let def_num = match uint::parse_bytes(def_part, 10u) { Some(dn) => dn as int, None => fail!(fmt!("internal error: parse_def_id: id expected, but \ found %?", def_part)) }; ast::def_id { crate: crate_num, node: def_num } } pub fn parse_bounds_data(data: @~[u8], start: uint, crate_num: int, tcx: ty::ctxt, conv: conv_did) -> @~[ty::param_bound] { let st = parse_state_from_data(data, crate_num, start, tcx); parse_bounds(st, conv) } fn parse_bounds(st: @mut PState, conv: conv_did) -> @~[ty::param_bound] { let mut bounds = ~[]; loop { bounds.push(match next(st) { 'S' => ty::bound_owned, 'C' => ty::bound_copy, 'K' => ty::bound_const, 'O' => ty::bound_durable, 'I' => ty::bound_trait(parse_ty(st, conv)), '.' => break, _ => fail!(~"parse_bounds: bad bounds") }); }
random_line_split
mock.rs
use std::{ io::{self, Cursor, Read, Write}, pin::Pin, task::{Context, Poll}, }; use tokio::io::{AsyncRead, AsyncWrite}; /// A fake stream for testing network applications backed by buffers. #[derive(Clone, Debug)] pub struct MockStream { written: Cursor<Vec<u8>>, received: Cursor<Vec<u8>>, } impl MockStream { /// Creates a new mock stream with nothing to read. pub fn empty() -> MockStream { MockStream::new(&[]) } /// Creates a new mock stream with the specified bytes to read. pub fn new(initial: &[u8]) -> MockStream { MockStream { written: Cursor::new(vec![]), received: Cursor::new(initial.to_owned()), } } /// Gets a slice of bytes representing the data that has been written. pub fn written(&self) -> &[u8] { self.written.get_ref() } /// Gets a slice of bytes representing the data that has been received. pub fn
(&self) -> &[u8] { self.received.get_ref() } } impl AsyncRead for MockStream { fn poll_read( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { Poll::Ready(self.as_mut().received.read(buf)) } } impl AsyncWrite for MockStream { fn poll_write( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { Poll::Ready(self.as_mut().written.write(buf)) } fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Poll::Ready(self.as_mut().written.flush()) } fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Poll::Ready(Ok(())) } }
received
identifier_name
mock.rs
use std::{ io::{self, Cursor, Read, Write}, pin::Pin, task::{Context, Poll}, }; use tokio::io::{AsyncRead, AsyncWrite}; /// A fake stream for testing network applications backed by buffers. #[derive(Clone, Debug)] pub struct MockStream { written: Cursor<Vec<u8>>, received: Cursor<Vec<u8>>, } impl MockStream { /// Creates a new mock stream with nothing to read. pub fn empty() -> MockStream { MockStream::new(&[]) } /// Creates a new mock stream with the specified bytes to read. pub fn new(initial: &[u8]) -> MockStream { MockStream { written: Cursor::new(vec![]), received: Cursor::new(initial.to_owned()), } } /// Gets a slice of bytes representing the data that has been written. pub fn written(&self) -> &[u8] { self.written.get_ref() } /// Gets a slice of bytes representing the data that has been received. pub fn received(&self) -> &[u8] { self.received.get_ref() }
fn poll_read( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { Poll::Ready(self.as_mut().received.read(buf)) } } impl AsyncWrite for MockStream { fn poll_write( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { Poll::Ready(self.as_mut().written.write(buf)) } fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Poll::Ready(self.as_mut().written.flush()) } fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Poll::Ready(Ok(())) } }
} impl AsyncRead for MockStream {
random_line_split
mock.rs
use std::{ io::{self, Cursor, Read, Write}, pin::Pin, task::{Context, Poll}, }; use tokio::io::{AsyncRead, AsyncWrite}; /// A fake stream for testing network applications backed by buffers. #[derive(Clone, Debug)] pub struct MockStream { written: Cursor<Vec<u8>>, received: Cursor<Vec<u8>>, } impl MockStream { /// Creates a new mock stream with nothing to read. pub fn empty() -> MockStream { MockStream::new(&[]) } /// Creates a new mock stream with the specified bytes to read. pub fn new(initial: &[u8]) -> MockStream { MockStream { written: Cursor::new(vec![]), received: Cursor::new(initial.to_owned()), } } /// Gets a slice of bytes representing the data that has been written. pub fn written(&self) -> &[u8] { self.written.get_ref() } /// Gets a slice of bytes representing the data that has been received. pub fn received(&self) -> &[u8] { self.received.get_ref() } } impl AsyncRead for MockStream { fn poll_read( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { Poll::Ready(self.as_mut().received.read(buf)) } } impl AsyncWrite for MockStream { fn poll_write( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { Poll::Ready(self.as_mut().written.write(buf)) } fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> { Poll::Ready(self.as_mut().written.flush()) } fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>>
}
{ Poll::Ready(Ok(())) }
identifier_body
sync-send-iterators-in-libcore.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![feature(collections)] fn is_sync<T>(_: T) where T: Sync
fn is_send<T>(_: T) where T: Send {} macro_rules! all_sync_send { ($ctor:expr, $($iter:ident),+) => ({ $( let mut x = $ctor; is_sync(x.$iter()); let mut y = $ctor; is_send(y.$iter()); )+ }) } fn main() { // for char.rs all_sync_send!("Я", escape_default, escape_unicode); // for iter.rs // FIXME // for option.rs // FIXME // for result.rs // FIXME // for slice.rs // FIXME // for str/mod.rs // FIXME }
{}
identifier_body
sync-send-iterators-in-libcore.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![feature(collections)] fn
<T>(_: T) where T: Sync {} fn is_send<T>(_: T) where T: Send {} macro_rules! all_sync_send { ($ctor:expr, $($iter:ident),+) => ({ $( let mut x = $ctor; is_sync(x.$iter()); let mut y = $ctor; is_send(y.$iter()); )+ }) } fn main() { // for char.rs all_sync_send!("Я", escape_default, escape_unicode); // for iter.rs // FIXME // for option.rs // FIXME // for result.rs // FIXME // for slice.rs // FIXME // for str/mod.rs // FIXME }
is_sync
identifier_name
sync-send-iterators-in-libcore.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// pretty-expanded FIXME #23616 #![feature(collections)] fn is_sync<T>(_: T) where T: Sync {} fn is_send<T>(_: T) where T: Send {} macro_rules! all_sync_send { ($ctor:expr, $($iter:ident),+) => ({ $( let mut x = $ctor; is_sync(x.$iter()); let mut y = $ctor; is_send(y.$iter()); )+ }) } fn main() { // for char.rs all_sync_send!("Я", escape_default, escape_unicode); // for iter.rs // FIXME // for option.rs // FIXME // for result.rs // FIXME // for slice.rs // FIXME // for str/mod.rs // FIXME }
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
cipher.rs
//! Implements the basic XTEA cipher routines as described in the //! paper (http://en.wikipedia.org/wiki/XTEA). These functions only //! deal with a single 64-bit block of data at a time. static NUM_ROUNDS: u32 = 32; use super::{Key, Block}; /// Encrypts 64 bits of `input` using the `key`. /// /// # Example: /// ``` /// use tea::cipher; /// /// let key = [5, 6, 7, 8]; /// let plaintext = [128, 256]; /// assert!(cipher::encipher(&key, &plaintext)!= plaintext); /// ``` pub fn encipher(key: &Key, input: &Block) -> Block { let [mut v0, mut v1] = *input; let delta = 0x9E3779B9; let mut sum: u32 = 0; for _ in 0..NUM_ROUNDS { v0 = v0.wrapping_add((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize]))); sum = sum.wrapping_add(delta); v1 = v1.wrapping_add((((v0 << 4) ^ (v0 >> 5)).wrapping_add(v0)) ^ (sum.wrapping_add(key[((sum>>11) & 3) as usize]))) } [v0, v1] } /// Decrypts 64 bits of `input` using the `key`. /// /// # Example: /// ``` /// use tea::cipher; /// /// let key = [5, 6, 7, 8]; /// let plaintext = [128, 256]; /// let crypted = cipher::encipher(&key, &plaintext); /// assert_eq!(cipher::decipher(&key, &crypted), plaintext); /// ``` pub fn decipher(key: &Key, input: &Block) -> Block { let [mut v0, mut v1] = *input; let delta = 0x9E3779B9; let mut sum = delta.wrapping_mul(NUM_ROUNDS); for _ in 0..NUM_ROUNDS { v1 = v1.wrapping_sub((((v0 << 4) ^ (v0 >> 5)).wrapping_add(v0)) ^ (sum.wrapping_add(key[((sum>>11) & 3) as usize]))); sum = sum.wrapping_sub(delta); v0 = v0.wrapping_sub((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize]))); } [v0, v1] } #[test] fn it_works()
{ let key: Key = [10, 20, 30, 42]; let plaintext: Block = [300, 400]; let ciphertext = encipher(&key, &plaintext); assert!(plaintext != ciphertext); assert_eq!(plaintext, decipher(&key, &ciphertext)); }
identifier_body
cipher.rs
//! Implements the basic XTEA cipher routines as described in the //! paper (http://en.wikipedia.org/wiki/XTEA). These functions only //! deal with a single 64-bit block of data at a time. static NUM_ROUNDS: u32 = 32; use super::{Key, Block}; /// Encrypts 64 bits of `input` using the `key`. /// /// # Example: /// ``` /// use tea::cipher; /// /// let key = [5, 6, 7, 8]; /// let plaintext = [128, 256]; /// assert!(cipher::encipher(&key, &plaintext)!= plaintext); /// ``` pub fn encipher(key: &Key, input: &Block) -> Block { let [mut v0, mut v1] = *input; let delta = 0x9E3779B9; let mut sum: u32 = 0; for _ in 0..NUM_ROUNDS { v0 = v0.wrapping_add((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize]))); sum = sum.wrapping_add(delta); v1 = v1.wrapping_add((((v0 << 4) ^ (v0 >> 5)).wrapping_add(v0)) ^ (sum.wrapping_add(key[((sum>>11) & 3) as usize]))) } [v0, v1] } /// Decrypts 64 bits of `input` using the `key`. /// /// # Example: /// ``` /// use tea::cipher; /// /// let key = [5, 6, 7, 8]; /// let plaintext = [128, 256]; /// let crypted = cipher::encipher(&key, &plaintext); /// assert_eq!(cipher::decipher(&key, &crypted), plaintext); /// ``` pub fn decipher(key: &Key, input: &Block) -> Block { let [mut v0, mut v1] = *input; let delta = 0x9E3779B9; let mut sum = delta.wrapping_mul(NUM_ROUNDS); for _ in 0..NUM_ROUNDS { v1 = v1.wrapping_sub((((v0 << 4) ^ (v0 >> 5)).wrapping_add(v0)) ^ (sum.wrapping_add(key[((sum>>11) & 3) as usize]))); sum = sum.wrapping_sub(delta); v0 = v0.wrapping_sub((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize])));
#[test] fn it_works() { let key: Key = [10, 20, 30, 42]; let plaintext: Block = [300, 400]; let ciphertext = encipher(&key, &plaintext); assert!(plaintext!= ciphertext); assert_eq!(plaintext, decipher(&key, &ciphertext)); }
} [v0, v1] }
random_line_split
cipher.rs
//! Implements the basic XTEA cipher routines as described in the //! paper (http://en.wikipedia.org/wiki/XTEA). These functions only //! deal with a single 64-bit block of data at a time. static NUM_ROUNDS: u32 = 32; use super::{Key, Block}; /// Encrypts 64 bits of `input` using the `key`. /// /// # Example: /// ``` /// use tea::cipher; /// /// let key = [5, 6, 7, 8]; /// let plaintext = [128, 256]; /// assert!(cipher::encipher(&key, &plaintext)!= plaintext); /// ``` pub fn
(key: &Key, input: &Block) -> Block { let [mut v0, mut v1] = *input; let delta = 0x9E3779B9; let mut sum: u32 = 0; for _ in 0..NUM_ROUNDS { v0 = v0.wrapping_add((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize]))); sum = sum.wrapping_add(delta); v1 = v1.wrapping_add((((v0 << 4) ^ (v0 >> 5)).wrapping_add(v0)) ^ (sum.wrapping_add(key[((sum>>11) & 3) as usize]))) } [v0, v1] } /// Decrypts 64 bits of `input` using the `key`. /// /// # Example: /// ``` /// use tea::cipher; /// /// let key = [5, 6, 7, 8]; /// let plaintext = [128, 256]; /// let crypted = cipher::encipher(&key, &plaintext); /// assert_eq!(cipher::decipher(&key, &crypted), plaintext); /// ``` pub fn decipher(key: &Key, input: &Block) -> Block { let [mut v0, mut v1] = *input; let delta = 0x9E3779B9; let mut sum = delta.wrapping_mul(NUM_ROUNDS); for _ in 0..NUM_ROUNDS { v1 = v1.wrapping_sub((((v0 << 4) ^ (v0 >> 5)).wrapping_add(v0)) ^ (sum.wrapping_add(key[((sum>>11) & 3) as usize]))); sum = sum.wrapping_sub(delta); v0 = v0.wrapping_sub((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize]))); } [v0, v1] } #[test] fn it_works() { let key: Key = [10, 20, 30, 42]; let plaintext: Block = [300, 400]; let ciphertext = encipher(&key, &plaintext); assert!(plaintext!= ciphertext); assert_eq!(plaintext, decipher(&key, &ciphertext)); }
encipher
identifier_name
server.rs
use enums::*; use serde_json as json; use std::fmt; #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct PublicChannel { pub name: String, pub mode: ChannelMode, pub characters: i32, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct ORSDetails { pub name: String, pub characters: i32, pub title: String, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct UserObject { pub identity: String, } #[derive(Deserialize, Debug, Clone, PartialEq)] pub enum Message { ADL { ops: Vec<String> }, AOP { character: String }, BRO { message: String }, CDS { channel: String, description: String, }, CHA { channels: Vec<String> }, CIU { sender: String, title: String, name: String, }, CBU { operator: String, channel: String, character: String, }, CKU { operator: String, channel: String, character: String, }, COA { character: String, channel: String }, COL { channel: String, oplist: Vec<String>, }, CON { count: i32 }, COR { character: String, channel: String }, CSO { character: String, channel: String }, CTU { operator: String, channel: String, length: i32, character: String, }, DOP { character: String }, ERR { number: i32, message: String }, FKS { characters: Vec<String>, kinks: Vec<i32>, }, FLN { character: String }, HLO { message: String }, ICH { users: Vec<UserObject>, channel: String, mode: ChannelMode, }, IDN { character: String }, JCH { channel: String, character: UserObject, title: String, }, KID(json::Value), LCH { channel: String, character: String }, LIS { characters: Vec<Vec<String>> }, NLN { identity: String, gender: Gender, status: CharacterStatus, }, IGN(json::Value), FRL { characters: Vec<String> }, ORS { channels: Vec<ORSDetails> }, PIN, PRD(json::Value), PRI { character: String, message: String }, MSG { character: String, message: String, channel: String, }, LRP { character: String, message: String, channel: String, }, RLL(json::Value), RMO { mode: ChannelMode, channel: String }, RTB { #[serde(rename = "type")] _type: String, character: String, }, SFC(json::Value), STA { status: CharacterStatus, character: String, statusmsg: String, }, SYS { message: String, channel: Option<String>, }, TPN { character: String, status: TypingStatus, }, UPT { time: i64, starttime: i64, startstring: String, accepted: i64, channels: i64, users: i64, maxusers: i64, }, VAR { variable: String, value: json::Value, }, } #[derive(Debug)] pub enum ParseError { Json(json::Error), InvalidMessage, } impl ::std::convert::From<json::Error> for ParseError { fn from(error: json::Error) -> ParseError { ParseError::Json(error) } } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ParseError::*; match *self { Json(ref err) => err.fmt(f), InvalidMessage => "Invalid F-Chat message received.".fmt(f), } } } impl ::std::error::Error for ParseError { fn description(&self) -> &str { "Error parsing F-Chat message." } } impl Message { // TODO: Find a way to deserialize without allocating a BTreeMap fn deserialize(variant: &[u8], text: &[u8]) -> Result<Self, ParseError> { let mut map = json::Map::new(); let variant = String::from_utf8(Vec::from(variant)).map_err(|_| ParseError::InvalidMessage)?; if text!= b"" { let data = json::from_slice(text)?; map.insert(variant, data); } else { map.insert(variant, json::Value::Null); } Ok(json::from_value(json::Value::Object(map))?) } pub fn from_slice(message: &[u8]) -> Result<Self, ParseError> { if message.len() < 3 { Err(ParseError::InvalidMessage) } else { let text = if message.len() >= 4 { &message[4..] } else {
&[] }; Message::deserialize(&message[..3], text) } } }
random_line_split
server.rs
use enums::*; use serde_json as json; use std::fmt; #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct PublicChannel { pub name: String, pub mode: ChannelMode, pub characters: i32, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct ORSDetails { pub name: String, pub characters: i32, pub title: String, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct
{ pub identity: String, } #[derive(Deserialize, Debug, Clone, PartialEq)] pub enum Message { ADL { ops: Vec<String> }, AOP { character: String }, BRO { message: String }, CDS { channel: String, description: String, }, CHA { channels: Vec<String> }, CIU { sender: String, title: String, name: String, }, CBU { operator: String, channel: String, character: String, }, CKU { operator: String, channel: String, character: String, }, COA { character: String, channel: String }, COL { channel: String, oplist: Vec<String>, }, CON { count: i32 }, COR { character: String, channel: String }, CSO { character: String, channel: String }, CTU { operator: String, channel: String, length: i32, character: String, }, DOP { character: String }, ERR { number: i32, message: String }, FKS { characters: Vec<String>, kinks: Vec<i32>, }, FLN { character: String }, HLO { message: String }, ICH { users: Vec<UserObject>, channel: String, mode: ChannelMode, }, IDN { character: String }, JCH { channel: String, character: UserObject, title: String, }, KID(json::Value), LCH { channel: String, character: String }, LIS { characters: Vec<Vec<String>> }, NLN { identity: String, gender: Gender, status: CharacterStatus, }, IGN(json::Value), FRL { characters: Vec<String> }, ORS { channels: Vec<ORSDetails> }, PIN, PRD(json::Value), PRI { character: String, message: String }, MSG { character: String, message: String, channel: String, }, LRP { character: String, message: String, channel: String, }, RLL(json::Value), RMO { mode: ChannelMode, channel: String }, RTB { #[serde(rename = "type")] _type: String, character: String, }, SFC(json::Value), STA { status: CharacterStatus, character: String, statusmsg: String, }, SYS { message: String, channel: Option<String>, }, TPN { character: String, status: TypingStatus, }, UPT { time: i64, starttime: i64, startstring: String, accepted: i64, channels: i64, users: i64, maxusers: i64, }, VAR { variable: String, value: json::Value, }, } #[derive(Debug)] pub enum ParseError { Json(json::Error), InvalidMessage, } impl ::std::convert::From<json::Error> for ParseError { fn from(error: json::Error) -> ParseError { ParseError::Json(error) } } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ParseError::*; match *self { Json(ref err) => err.fmt(f), InvalidMessage => "Invalid F-Chat message received.".fmt(f), } } } impl ::std::error::Error for ParseError { fn description(&self) -> &str { "Error parsing F-Chat message." } } impl Message { // TODO: Find a way to deserialize without allocating a BTreeMap fn deserialize(variant: &[u8], text: &[u8]) -> Result<Self, ParseError> { let mut map = json::Map::new(); let variant = String::from_utf8(Vec::from(variant)).map_err(|_| ParseError::InvalidMessage)?; if text!= b"" { let data = json::from_slice(text)?; map.insert(variant, data); } else { map.insert(variant, json::Value::Null); } Ok(json::from_value(json::Value::Object(map))?) } pub fn from_slice(message: &[u8]) -> Result<Self, ParseError> { if message.len() < 3 { Err(ParseError::InvalidMessage) } else { let text = if message.len() >= 4 { &message[4..] } else { &[] }; Message::deserialize(&message[..3], text) } } }
UserObject
identifier_name
server.rs
use enums::*; use serde_json as json; use std::fmt; #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct PublicChannel { pub name: String, pub mode: ChannelMode, pub characters: i32, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct ORSDetails { pub name: String, pub characters: i32, pub title: String, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct UserObject { pub identity: String, } #[derive(Deserialize, Debug, Clone, PartialEq)] pub enum Message { ADL { ops: Vec<String> }, AOP { character: String }, BRO { message: String }, CDS { channel: String, description: String, }, CHA { channels: Vec<String> }, CIU { sender: String, title: String, name: String, }, CBU { operator: String, channel: String, character: String, }, CKU { operator: String, channel: String, character: String, }, COA { character: String, channel: String }, COL { channel: String, oplist: Vec<String>, }, CON { count: i32 }, COR { character: String, channel: String }, CSO { character: String, channel: String }, CTU { operator: String, channel: String, length: i32, character: String, }, DOP { character: String }, ERR { number: i32, message: String }, FKS { characters: Vec<String>, kinks: Vec<i32>, }, FLN { character: String }, HLO { message: String }, ICH { users: Vec<UserObject>, channel: String, mode: ChannelMode, }, IDN { character: String }, JCH { channel: String, character: UserObject, title: String, }, KID(json::Value), LCH { channel: String, character: String }, LIS { characters: Vec<Vec<String>> }, NLN { identity: String, gender: Gender, status: CharacterStatus, }, IGN(json::Value), FRL { characters: Vec<String> }, ORS { channels: Vec<ORSDetails> }, PIN, PRD(json::Value), PRI { character: String, message: String }, MSG { character: String, message: String, channel: String, }, LRP { character: String, message: String, channel: String, }, RLL(json::Value), RMO { mode: ChannelMode, channel: String }, RTB { #[serde(rename = "type")] _type: String, character: String, }, SFC(json::Value), STA { status: CharacterStatus, character: String, statusmsg: String, }, SYS { message: String, channel: Option<String>, }, TPN { character: String, status: TypingStatus, }, UPT { time: i64, starttime: i64, startstring: String, accepted: i64, channels: i64, users: i64, maxusers: i64, }, VAR { variable: String, value: json::Value, }, } #[derive(Debug)] pub enum ParseError { Json(json::Error), InvalidMessage, } impl ::std::convert::From<json::Error> for ParseError { fn from(error: json::Error) -> ParseError
} impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ParseError::*; match *self { Json(ref err) => err.fmt(f), InvalidMessage => "Invalid F-Chat message received.".fmt(f), } } } impl ::std::error::Error for ParseError { fn description(&self) -> &str { "Error parsing F-Chat message." } } impl Message { // TODO: Find a way to deserialize without allocating a BTreeMap fn deserialize(variant: &[u8], text: &[u8]) -> Result<Self, ParseError> { let mut map = json::Map::new(); let variant = String::from_utf8(Vec::from(variant)).map_err(|_| ParseError::InvalidMessage)?; if text!= b"" { let data = json::from_slice(text)?; map.insert(variant, data); } else { map.insert(variant, json::Value::Null); } Ok(json::from_value(json::Value::Object(map))?) } pub fn from_slice(message: &[u8]) -> Result<Self, ParseError> { if message.len() < 3 { Err(ParseError::InvalidMessage) } else { let text = if message.len() >= 4 { &message[4..] } else { &[] }; Message::deserialize(&message[..3], text) } } }
{ ParseError::Json(error) }
identifier_body
server.rs
use enums::*; use serde_json as json; use std::fmt; #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct PublicChannel { pub name: String, pub mode: ChannelMode, pub characters: i32, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct ORSDetails { pub name: String, pub characters: i32, pub title: String, } #[derive(Deserialize, Debug, Clone, PartialEq, Eq)] pub struct UserObject { pub identity: String, } #[derive(Deserialize, Debug, Clone, PartialEq)] pub enum Message { ADL { ops: Vec<String> }, AOP { character: String }, BRO { message: String }, CDS { channel: String, description: String, }, CHA { channels: Vec<String> }, CIU { sender: String, title: String, name: String, }, CBU { operator: String, channel: String, character: String, }, CKU { operator: String, channel: String, character: String, }, COA { character: String, channel: String }, COL { channel: String, oplist: Vec<String>, }, CON { count: i32 }, COR { character: String, channel: String }, CSO { character: String, channel: String }, CTU { operator: String, channel: String, length: i32, character: String, }, DOP { character: String }, ERR { number: i32, message: String }, FKS { characters: Vec<String>, kinks: Vec<i32>, }, FLN { character: String }, HLO { message: String }, ICH { users: Vec<UserObject>, channel: String, mode: ChannelMode, }, IDN { character: String }, JCH { channel: String, character: UserObject, title: String, }, KID(json::Value), LCH { channel: String, character: String }, LIS { characters: Vec<Vec<String>> }, NLN { identity: String, gender: Gender, status: CharacterStatus, }, IGN(json::Value), FRL { characters: Vec<String> }, ORS { channels: Vec<ORSDetails> }, PIN, PRD(json::Value), PRI { character: String, message: String }, MSG { character: String, message: String, channel: String, }, LRP { character: String, message: String, channel: String, }, RLL(json::Value), RMO { mode: ChannelMode, channel: String }, RTB { #[serde(rename = "type")] _type: String, character: String, }, SFC(json::Value), STA { status: CharacterStatus, character: String, statusmsg: String, }, SYS { message: String, channel: Option<String>, }, TPN { character: String, status: TypingStatus, }, UPT { time: i64, starttime: i64, startstring: String, accepted: i64, channels: i64, users: i64, maxusers: i64, }, VAR { variable: String, value: json::Value, }, } #[derive(Debug)] pub enum ParseError { Json(json::Error), InvalidMessage, } impl ::std::convert::From<json::Error> for ParseError { fn from(error: json::Error) -> ParseError { ParseError::Json(error) } } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ParseError::*; match *self { Json(ref err) => err.fmt(f), InvalidMessage => "Invalid F-Chat message received.".fmt(f), } } } impl ::std::error::Error for ParseError { fn description(&self) -> &str { "Error parsing F-Chat message." } } impl Message { // TODO: Find a way to deserialize without allocating a BTreeMap fn deserialize(variant: &[u8], text: &[u8]) -> Result<Self, ParseError> { let mut map = json::Map::new(); let variant = String::from_utf8(Vec::from(variant)).map_err(|_| ParseError::InvalidMessage)?; if text!= b"" { let data = json::from_slice(text)?; map.insert(variant, data); } else { map.insert(variant, json::Value::Null); } Ok(json::from_value(json::Value::Object(map))?) } pub fn from_slice(message: &[u8]) -> Result<Self, ParseError> { if message.len() < 3 { Err(ParseError::InvalidMessage) } else
} }
{ let text = if message.len() >= 4 { &message[4..] } else { &[] }; Message::deserialize(&message[..3], text) }
conditional_block
text_info.rs
use std::ops::{Add, AddAssign, Sub, SubAssign}; use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates}; use crate::tree::Count; #[derive(Debug, Copy, Clone, PartialEq)] pub struct TextInfo { pub(crate) bytes: Count, pub(crate) chars: Count, pub(crate) utf16_surrogates: Count, pub(crate) line_breaks: Count, }
impl TextInfo { #[inline] pub fn new() -> TextInfo { TextInfo { bytes: 0, chars: 0, utf16_surrogates: 0, line_breaks: 0, } } #[inline] pub fn from_str(text: &str) -> TextInfo { TextInfo { bytes: text.len() as Count, chars: count_chars(text) as Count, utf16_surrogates: count_utf16_surrogates(text) as Count, line_breaks: count_line_breaks(text) as Count, } } } impl Add for TextInfo { type Output = Self; #[inline] fn add(self, rhs: TextInfo) -> TextInfo { TextInfo { bytes: self.bytes + rhs.bytes, chars: self.chars + rhs.chars, utf16_surrogates: self.utf16_surrogates + rhs.utf16_surrogates, line_breaks: self.line_breaks + rhs.line_breaks, } } } impl AddAssign for TextInfo { #[inline] fn add_assign(&mut self, other: TextInfo) { *self = *self + other; } } impl Sub for TextInfo { type Output = Self; #[inline] fn sub(self, rhs: TextInfo) -> TextInfo { TextInfo { bytes: self.bytes - rhs.bytes, chars: self.chars - rhs.chars, utf16_surrogates: self.utf16_surrogates - rhs.utf16_surrogates, line_breaks: self.line_breaks - rhs.line_breaks, } } } impl SubAssign for TextInfo { #[inline] fn sub_assign(&mut self, other: TextInfo) { *self = *self - other; } }
random_line_split
text_info.rs
use std::ops::{Add, AddAssign, Sub, SubAssign}; use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates}; use crate::tree::Count; #[derive(Debug, Copy, Clone, PartialEq)] pub struct TextInfo { pub(crate) bytes: Count, pub(crate) chars: Count, pub(crate) utf16_surrogates: Count, pub(crate) line_breaks: Count, } impl TextInfo { #[inline] pub fn new() -> TextInfo { TextInfo { bytes: 0, chars: 0, utf16_surrogates: 0, line_breaks: 0, } } #[inline] pub fn from_str(text: &str) -> TextInfo
} impl Add for TextInfo { type Output = Self; #[inline] fn add(self, rhs: TextInfo) -> TextInfo { TextInfo { bytes: self.bytes + rhs.bytes, chars: self.chars + rhs.chars, utf16_surrogates: self.utf16_surrogates + rhs.utf16_surrogates, line_breaks: self.line_breaks + rhs.line_breaks, } } } impl AddAssign for TextInfo { #[inline] fn add_assign(&mut self, other: TextInfo) { *self = *self + other; } } impl Sub for TextInfo { type Output = Self; #[inline] fn sub(self, rhs: TextInfo) -> TextInfo { TextInfo { bytes: self.bytes - rhs.bytes, chars: self.chars - rhs.chars, utf16_surrogates: self.utf16_surrogates - rhs.utf16_surrogates, line_breaks: self.line_breaks - rhs.line_breaks, } } } impl SubAssign for TextInfo { #[inline] fn sub_assign(&mut self, other: TextInfo) { *self = *self - other; } }
{ TextInfo { bytes: text.len() as Count, chars: count_chars(text) as Count, utf16_surrogates: count_utf16_surrogates(text) as Count, line_breaks: count_line_breaks(text) as Count, } }
identifier_body
text_info.rs
use std::ops::{Add, AddAssign, Sub, SubAssign}; use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates}; use crate::tree::Count; #[derive(Debug, Copy, Clone, PartialEq)] pub struct TextInfo { pub(crate) bytes: Count, pub(crate) chars: Count, pub(crate) utf16_surrogates: Count, pub(crate) line_breaks: Count, } impl TextInfo { #[inline] pub fn new() -> TextInfo { TextInfo { bytes: 0, chars: 0, utf16_surrogates: 0, line_breaks: 0, } } #[inline] pub fn from_str(text: &str) -> TextInfo { TextInfo { bytes: text.len() as Count, chars: count_chars(text) as Count, utf16_surrogates: count_utf16_surrogates(text) as Count, line_breaks: count_line_breaks(text) as Count, } } } impl Add for TextInfo { type Output = Self; #[inline] fn add(self, rhs: TextInfo) -> TextInfo { TextInfo { bytes: self.bytes + rhs.bytes, chars: self.chars + rhs.chars, utf16_surrogates: self.utf16_surrogates + rhs.utf16_surrogates, line_breaks: self.line_breaks + rhs.line_breaks, } } } impl AddAssign for TextInfo { #[inline] fn
(&mut self, other: TextInfo) { *self = *self + other; } } impl Sub for TextInfo { type Output = Self; #[inline] fn sub(self, rhs: TextInfo) -> TextInfo { TextInfo { bytes: self.bytes - rhs.bytes, chars: self.chars - rhs.chars, utf16_surrogates: self.utf16_surrogates - rhs.utf16_surrogates, line_breaks: self.line_breaks - rhs.line_breaks, } } } impl SubAssign for TextInfo { #[inline] fn sub_assign(&mut self, other: TextInfo) { *self = *self - other; } }
add_assign
identifier_name
issue-15381.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. fn main()
{ let values: Vec<u8> = vec![1,2,3,4,5,6,7,8]; for [x,y,z] //~^ ERROR refutable pattern in `for` loop binding: `[]` not covered in values.as_slice().chunks(3).filter(|&xs| xs.len() == 3) { println!("y={}", y); } }
identifier_body
issue-15381.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. fn
() { let values: Vec<u8> = vec![1,2,3,4,5,6,7,8]; for [x,y,z] //~^ ERROR refutable pattern in `for` loop binding: `[]` not covered in values.as_slice().chunks(3).filter(|&xs| xs.len() == 3) { println!("y={}", y); } }
main
identifier_name
issue-15381.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. fn main() { let values: Vec<u8> = vec![1,2,3,4,5,6,7,8];
println!("y={}", y); } }
for [x,y,z] //~^ ERROR refutable pattern in `for` loop binding: `[]` not covered in values.as_slice().chunks(3).filter(|&xs| xs.len() == 3) {
random_line_split
mod.rs
pub use self::manager::ContextManager; pub use self::manager::ViewContext; pub use self::manager::ViewContextMut; mod manager; //mod proxies; //use mopa; use std::collections::HashMap; use store::StoreValueStatic; use { Store, StoreValue, AttributeGetResult, AttributeMutResult, AttributeSetResult }; use lookup::PropertyAccessor; /// This trait is used to provide a possible interface for Context /// objects managed by the `ContextManager`. It is implemented by /// the `AmbientModel` to give an example of such a `Context`. /// **Note:** /// If the "Context" type for the `ContextManager` implement this trait, /// then those function can be used also on the `ContextManager`. pub trait Context { /// Register a single value at the key fn register_value<V: Into<StoreValueStatic>>(&mut self, key: String, value: V); /// Register a store: fn register_store<S: Store>(&mut self, key: String, store: S); /// Return a previously registered store: /// This can be useful when you want to modify an existing store but without /// retaining a reference to it. fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store +'static>>; } /// Default version of the `ContextManager` where the template /// parameter is set to `AmbientModel`. pub type DefaultContextManager = ContextManager<AmbientModel, AmbientModel>; /// An `AmbientModel` instance is a root object that is used /// by the `DefaultContextManager`. /// Internally it use a HashMap for single `StoreValue`s /// and an other HashMap for boxed type implementing the trait `Store`. #[derive(Default)] pub struct AmbientModel { values: HashMap<String, StoreValueStatic>, stores: HashMap<String, Box<Store>>, } /// Minimal contraint to be used in a `ContextManager`: /// implement the trait `Store`. impl Store for AmbientModel { fn get_attribute<'a>(&'a self, k: PropertyAccessor) -> AttributeGetResult<'a> { let value = self.stores.get_attribute(k.clone()); if value.is_found() { value } else { self.values.get_attribute(k) } } fn get_attribute_mut<'a>(&'a mut self, k: PropertyAccessor) -> AttributeMutResult<'a> { let value = self.stores.get_attribute_mut(k.clone()); if value.is_found() { value } else { self.values.get_attribute_mut(k) } } fn set_attribute<'a>(&mut self, k: PropertyAccessor, value: StoreValue<'a>) -> AttributeSetResult<'a> { match self.stores.set_attribute(k.clone(), value) { AttributeSetResult::NoSuchProperty(v) => { self.values.set_attribute(k, v) } _ => AttributeSetResult::Stored } } } // Context implementation impl Context for AmbientModel { fn register_value<V: Into<StoreValueStatic>>(&mut self, key: String, value: V) { self.values.insert(key, value.into()); } fn register_store<S: Store +'static>(&mut self, key: String, store: S) { self.stores.insert(key, Box::new(store) as Box<Store>); }
} }
fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store + 'static>> { self.stores.get_mut(&key)
random_line_split
mod.rs
pub use self::manager::ContextManager; pub use self::manager::ViewContext; pub use self::manager::ViewContextMut; mod manager; //mod proxies; //use mopa; use std::collections::HashMap; use store::StoreValueStatic; use { Store, StoreValue, AttributeGetResult, AttributeMutResult, AttributeSetResult }; use lookup::PropertyAccessor; /// This trait is used to provide a possible interface for Context /// objects managed by the `ContextManager`. It is implemented by /// the `AmbientModel` to give an example of such a `Context`. /// **Note:** /// If the "Context" type for the `ContextManager` implement this trait, /// then those function can be used also on the `ContextManager`. pub trait Context { /// Register a single value at the key fn register_value<V: Into<StoreValueStatic>>(&mut self, key: String, value: V); /// Register a store: fn register_store<S: Store>(&mut self, key: String, store: S); /// Return a previously registered store: /// This can be useful when you want to modify an existing store but without /// retaining a reference to it. fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store +'static>>; } /// Default version of the `ContextManager` where the template /// parameter is set to `AmbientModel`. pub type DefaultContextManager = ContextManager<AmbientModel, AmbientModel>; /// An `AmbientModel` instance is a root object that is used /// by the `DefaultContextManager`. /// Internally it use a HashMap for single `StoreValue`s /// and an other HashMap for boxed type implementing the trait `Store`. #[derive(Default)] pub struct AmbientModel { values: HashMap<String, StoreValueStatic>, stores: HashMap<String, Box<Store>>, } /// Minimal contraint to be used in a `ContextManager`: /// implement the trait `Store`. impl Store for AmbientModel { fn get_attribute<'a>(&'a self, k: PropertyAccessor) -> AttributeGetResult<'a> { let value = self.stores.get_attribute(k.clone()); if value.is_found() { value } else { self.values.get_attribute(k) } } fn get_attribute_mut<'a>(&'a mut self, k: PropertyAccessor) -> AttributeMutResult<'a> { let value = self.stores.get_attribute_mut(k.clone()); if value.is_found() { value } else { self.values.get_attribute_mut(k) } } fn set_attribute<'a>(&mut self, k: PropertyAccessor, value: StoreValue<'a>) -> AttributeSetResult<'a>
} // Context implementation impl Context for AmbientModel { fn register_value<V: Into<StoreValueStatic>>(&mut self, key: String, value: V) { self.values.insert(key, value.into()); } fn register_store<S: Store +'static>(&mut self, key: String, store: S) { self.stores.insert(key, Box::new(store) as Box<Store>); } fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store +'static>> { self.stores.get_mut(&key) } }
{ match self.stores.set_attribute(k.clone(), value) { AttributeSetResult::NoSuchProperty(v) => { self.values.set_attribute(k, v) } _ => AttributeSetResult::Stored } }
identifier_body
mod.rs
pub use self::manager::ContextManager; pub use self::manager::ViewContext; pub use self::manager::ViewContextMut; mod manager; //mod proxies; //use mopa; use std::collections::HashMap; use store::StoreValueStatic; use { Store, StoreValue, AttributeGetResult, AttributeMutResult, AttributeSetResult }; use lookup::PropertyAccessor; /// This trait is used to provide a possible interface for Context /// objects managed by the `ContextManager`. It is implemented by /// the `AmbientModel` to give an example of such a `Context`. /// **Note:** /// If the "Context" type for the `ContextManager` implement this trait, /// then those function can be used also on the `ContextManager`. pub trait Context { /// Register a single value at the key fn register_value<V: Into<StoreValueStatic>>(&mut self, key: String, value: V); /// Register a store: fn register_store<S: Store>(&mut self, key: String, store: S); /// Return a previously registered store: /// This can be useful when you want to modify an existing store but without /// retaining a reference to it. fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store +'static>>; } /// Default version of the `ContextManager` where the template /// parameter is set to `AmbientModel`. pub type DefaultContextManager = ContextManager<AmbientModel, AmbientModel>; /// An `AmbientModel` instance is a root object that is used /// by the `DefaultContextManager`. /// Internally it use a HashMap for single `StoreValue`s /// and an other HashMap for boxed type implementing the trait `Store`. #[derive(Default)] pub struct AmbientModel { values: HashMap<String, StoreValueStatic>, stores: HashMap<String, Box<Store>>, } /// Minimal contraint to be used in a `ContextManager`: /// implement the trait `Store`. impl Store for AmbientModel { fn get_attribute<'a>(&'a self, k: PropertyAccessor) -> AttributeGetResult<'a> { let value = self.stores.get_attribute(k.clone()); if value.is_found() { value } else { self.values.get_attribute(k) } } fn get_attribute_mut<'a>(&'a mut self, k: PropertyAccessor) -> AttributeMutResult<'a> { let value = self.stores.get_attribute_mut(k.clone()); if value.is_found() { value } else { self.values.get_attribute_mut(k) } } fn set_attribute<'a>(&mut self, k: PropertyAccessor, value: StoreValue<'a>) -> AttributeSetResult<'a> { match self.stores.set_attribute(k.clone(), value) { AttributeSetResult::NoSuchProperty(v) => { self.values.set_attribute(k, v) } _ => AttributeSetResult::Stored } } } // Context implementation impl Context for AmbientModel { fn register_value<V: Into<StoreValueStatic>>(&mut self, key: String, value: V) { self.values.insert(key, value.into()); } fn
<S: Store +'static>(&mut self, key: String, store: S) { self.stores.insert(key, Box::new(store) as Box<Store>); } fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store +'static>> { self.stores.get_mut(&key) } }
register_store
identifier_name
object.rs
use std::sync::Arc; use ::types::{Vec3f, Mat4f}; use ::Material; use ::ray::Ray; pub struct
{ ray: Ray, // Ray that intersected pub time: f64, normal: Vec3f, object: Arc<Object> } pub struct ObjectData { // texture transformation: Mat4f, inv_trans: Mat4f } pub trait Object { /// Return whether ray intersected object fn intersection(&self, ray: &Ray) -> Option<Intersection> { let internal = self.internal(); // 1. Transform the ray by the inverse transformation let transformed = ray.transform(internal.inv_trans); // if let Some(intersection) = self.inters None } /// Return whether point is inside object fn is_inside(&self, point: &Vec3f) -> bool; fn internal(&self) -> &ObjectData; // A world coordinate bounding box computed for the object // fn bounding_box(&self, transformation: Mat4f) -> AABB; // fn texture // fn interior // fn transformation // fn children // pre computed // trans_inverse // aabb }
Intersection
identifier_name
object.rs
use std::sync::Arc; use ::types::{Vec3f, Mat4f}; use ::Material; use ::ray::Ray; pub struct Intersection { ray: Ray, // Ray that intersected pub time: f64, normal: Vec3f, object: Arc<Object> } pub struct ObjectData { // texture transformation: Mat4f, inv_trans: Mat4f } pub trait Object { /// Return whether ray intersected object fn intersection(&self, ray: &Ray) -> Option<Intersection> { let internal = self.internal(); // 1. Transform the ray by the inverse transformation let transformed = ray.transform(internal.inv_trans); // if let Some(intersection) = self.inters None } /// Return whether point is inside object fn is_inside(&self, point: &Vec3f) -> bool; fn internal(&self) -> &ObjectData; // A world coordinate bounding box computed for the object // fn bounding_box(&self, transformation: Mat4f) -> AABB; // fn texture // fn interior // fn transformation
// fn children // pre computed // trans_inverse // aabb }
random_line_split
grabbing.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use glutin::{Event, ElementState}; mod support; #[cfg(target_os = "android")] android_start!(main); fn main() { let window = glutin::WindowBuilder::new().build().unwrap(); window.set_title("glutin - Cursor grabbing test"); let _ = unsafe { window.make_current() }; let context = support::load(&window); let mut grabbed = false; for event in window.wait_events() { match event { Event::KeyboardInput(ElementState::Pressed, _, _) => { if grabbed
else { grabbed = true; window.set_cursor_state(glutin::CursorState::Grab) .ok().expect("could not grab mouse cursor"); } }, Event::Closed => break, a @ Event::MouseMoved(_, _) => { println!("{:?}", a); }, _ => (), } context.draw_frame((0.0, 1.0, 0.0, 1.0)); let _ = window.swap_buffers(); } }
{ grabbed = false; window.set_cursor_state(glutin::CursorState::Normal) .ok().expect("could not ungrab mouse cursor"); }
conditional_block
grabbing.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use glutin::{Event, ElementState}; mod support; #[cfg(target_os = "android")]
window.set_title("glutin - Cursor grabbing test"); let _ = unsafe { window.make_current() }; let context = support::load(&window); let mut grabbed = false; for event in window.wait_events() { match event { Event::KeyboardInput(ElementState::Pressed, _, _) => { if grabbed { grabbed = false; window.set_cursor_state(glutin::CursorState::Normal) .ok().expect("could not ungrab mouse cursor"); } else { grabbed = true; window.set_cursor_state(glutin::CursorState::Grab) .ok().expect("could not grab mouse cursor"); } }, Event::Closed => break, a @ Event::MouseMoved(_, _) => { println!("{:?}", a); }, _ => (), } context.draw_frame((0.0, 1.0, 0.0, 1.0)); let _ = window.swap_buffers(); } }
android_start!(main); fn main() { let window = glutin::WindowBuilder::new().build().unwrap();
random_line_split