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
offsets.rs
use byteorder::{BigEndian, ReadBytesExt}; use futures::Stream; use rdkafka::config::{ClientConfig, TopicConfig}; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::consumer::{Consumer, EmptyConsumerContext}; use rdkafka::error::KafkaError; use rdkafka::{Message, Offset, TopicPartitionList}; use cache::{Cache, OffsetsCache}; use config::{ClusterConfig, Config}; use error::*; use metadata::{ClusterId, TopicName}; use utils::{insert_at, read_string}; use std::cmp; use std::collections::HashMap; use std::io::Cursor; use std::str; use std::thread; use std::time::{Duration, Instant}; #[derive(Debug)] enum ConsumerUpdate { Metadata, OffsetCommit { group: String, topic: String, partition: i32, offset: i64, }, OffsetTombstone { group: String, topic: String, partition: i32, }, } fn parse_group_offset( key_rdr: &mut Cursor<&[u8]>, payload_rdr: &mut Cursor<&[u8]>, ) -> Result<ConsumerUpdate> { let group = read_string(key_rdr).chain_err(|| "Failed to parse group name from key")?; let topic = read_string(key_rdr).chain_err(|| "Failed to parse topic name from key")?; let partition = key_rdr .read_i32::<BigEndian>() .chain_err(|| "Failed to parse partition from key")?; if!payload_rdr.get_ref().is_empty() { // payload is not empty let _version = payload_rdr .read_i16::<BigEndian>() .chain_err(|| "Failed to parse value version")?; let offset = payload_rdr .read_i64::<BigEndian>() .chain_err(|| "Failed to parse offset from value")?; Ok(ConsumerUpdate::OffsetCommit { group, topic, partition, offset, }) } else { Ok(ConsumerUpdate::OffsetTombstone { group, topic, partition, }) } } fn parse_message(key: &[u8], payload: &[u8]) -> Result<ConsumerUpdate> { let mut key_rdr = Cursor::new(key); let key_version = key_rdr .read_i16::<BigEndian>() .chain_err(|| "Failed to parse key version")?; match key_version { 0 | 1 => parse_group_offset(&mut key_rdr, &mut Cursor::new(payload)) .chain_err(|| "Failed to parse group offset update"), 2 => Ok(ConsumerUpdate::Metadata), _ => bail!("Key version not recognized"), } } fn create_consumer( brokers: &str, group_id: &str, start_offsets: Option<Vec<i64>>, ) -> Result<StreamConsumer<EmptyConsumerContext>> { let consumer = ClientConfig::new() .set("group.id", group_id) .set("bootstrap.servers", brokers) .set("enable.partition.eof", "false") .set("enable.auto.commit", "false") .set("session.timeout.ms", "30000") .set("api.version.request", "true") //.set("fetch.message.max.bytes", "1024000") // Reduce memory usage .set("queued.min.messages", "10000") // Reduce memory usage .set("message.max.bytes", "10485760") .set_default_topic_config( TopicConfig::new() .set("auto.offset.reset", "smallest") .finalize(), ) .create::<StreamConsumer<_>>() .chain_err(|| format!("Consumer creation failed: {}", brokers))?; match start_offsets { Some(pos) => { let mut tp_list = TopicPartitionList::new(); for (partition, &offset) in pos.iter().enumerate() { tp_list.add_partition_offset( "__consumer_offsets", partition as i32, Offset::Offset(offset), ); } debug!( "Previous offsets found, assigning offsets explicitly: {:?}", tp_list ); consumer .assign(&tp_list) .chain_err(|| "Failure during consumer assignment")?; } None => { debug!("No previous offsets found, subscribing to topic"); consumer.subscribe(&["__consumer_offsets"]).chain_err(|| { format!("Can't subscribe to offset __consumer_offsets ({})", brokers) })?; } } Ok(consumer) } // we should really have some tests here fn update_global_cache( cluster_id: &ClusterId, local_cache: &HashMap<(String, String), Vec<i64>>, cache: &OffsetsCache, ) { for (&(ref group, ref topic), new_offsets) in local_cache { // Consider a consuming iterator // This logic is not needed if i store the consumer offset, right? wrong! if new_offsets.iter().any(|&offset| offset == -1) { if let Some(mut existing_offsets) = cache.get(&(cluster_id.to_owned(), group.to_owned(), topic.to_owned())) { // If the new offset is not complete and i have an old one, do the merge vec_merge_in_place(&mut existing_offsets, &new_offsets, -1, cmp::max); // for i in 0..(cmp::max(offsets.len(), existing_offsets.len())) { // let new_offset = cmp::max( // offsets.get(i).cloned().unwrap_or(-1), // existing_offsets.get(i).cloned().unwrap_or(-1)); // insert_at(&mut existing_offsets, i, new_offset, -1); // } let _ = cache.insert( (cluster_id.to_owned(), group.to_owned(), topic.to_owned()), existing_offsets, ); continue; } } // TODO: log errors let _ = cache.insert( (cluster_id.to_owned(), group.to_owned(), topic.to_owned()), new_offsets.clone(), ); } } fn commit_offset_position_to_array(tp_list: TopicPartitionList) -> Vec<i64>
fn consume_offset_topic( cluster_id: ClusterId, consumer: StreamConsumer<EmptyConsumerContext>, cache: &Cache, ) -> Result<()> { let mut local_cache = HashMap::new(); let mut last_dump = Instant::now(); debug!("Starting offset consumer loop for {:?}", cluster_id); for message in consumer.start_with(Duration::from_millis(200), true).wait() { match message { Ok(Ok(m)) => { let key = m.key().unwrap_or(&[]); let payload = m.payload().unwrap_or(&[]); match parse_message(key, payload) { Ok(ConsumerUpdate::OffsetCommit { group, topic, partition, offset, }) => { let mut offsets = local_cache .entry((group.to_owned(), topic.to_owned())) .or_insert_with(Vec::new); insert_at(&mut offsets, partition as usize, offset, -1); } Ok(_) => {} Err(e) => format_error_chain!(e), }; } Ok(Err(KafkaError::NoMessageReceived)) => {} Ok(Err(e)) => warn!("Kafka error: {} {:?}", cluster_id, e), Err(e) => warn!("Can't receive data from stream: {:?}", e), }; // Update the cache if needed if (Instant::now() - last_dump) > Duration::from_secs(10) { trace!( "Dumping local offset cache ({}: {} updates)", cluster_id, local_cache.len() ); update_global_cache(&cluster_id, &local_cache, &cache.offsets); // Consumer position is not up to date after start, so we have to merge with the // existing offsets and take the largest. let res = consumer .position() .map(|current_position| { let previous_position_vec = cache .internal_offsets .get(&cluster_id) .unwrap_or_else(Vec::new); let mut current_position_vec = commit_offset_position_to_array(current_position); vec_merge_in_place( &mut current_position_vec, &previous_position_vec, Offset::Invalid.to_raw(), cmp::max, ); cache .internal_offsets .insert(cluster_id.clone(), current_position_vec) }) .chain_err(|| "Failed to store consumer offset position")?; if let Err(e) = res { format_error_chain!(e); } local_cache = HashMap::with_capacity(local_cache.len()); last_dump = Instant::now(); } } Ok(()) } pub fn vec_merge_in_place<F, T: Copy>(vec1: &mut Vec<T>, vec2: &[T], default: T, merge_fn: F) where F: Fn(T, T) -> T, { let new_len = cmp::max(vec1.len(), vec2.len()); vec1.resize(new_len, default); for i in 0..vec1.len() { vec1[i] = merge_fn( vec1.get(i).unwrap_or(&default).to_owned(), vec2.get(i).unwrap_or(&default).to_owned(), ); } } //pub fn vec_merge<F, T: Clone>(vec1: Vec<T>, vec2: Vec<T>, default: T, merge: F) -> Vec<T> // where F: Fn(T, T) -> T //{ // (0..cmp::max(vec1.len(), vec2.len())) // .map(|index| // merge( // vec1.get(index).unwrap_or(&default).to_owned(), // vec2.get(index).unwrap_or(&default).to_owned())) // .collect::<Vec<T>>() //} pub fn run_offset_consumer( cluster_id: &ClusterId, cluster_config: &ClusterConfig, config: &Config, cache: &Cache, ) -> Result<()> { let start_position = cache.internal_offsets.get(cluster_id); let consumer = create_consumer( &cluster_config.bootstrap_servers(), &config.consumer_offsets_group_id, start_position, ) .chain_err(|| format!("Failed to create offset consumer for {}", cluster_id))?; let cluster_id_clone = cluster_id.clone(); let cache_alias = cache.alias(); let _ = thread::Builder::new() .name("offset-consumer".to_owned()) .spawn(move || { if let Err(e) = consume_offset_topic(cluster_id_clone, consumer, &cache_alias) { format_error_chain!(e); } }) .chain_err(|| "Failed to start offset consumer thread")?; Ok(()) } pub trait OffsetStore { fn offsets_by_cluster( &self, cluster_id: &ClusterId, ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>; fn offsets_by_cluster_topic( &self, cluster_id: &ClusterId, topic_name: &str, ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>; fn offsets_by_cluster_group( &self, cluster_id: &ClusterId, group_name: &str, ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>; } impl OffsetStore for Cache { fn offsets_by_cluster( &self, cluster: &ClusterId, ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> { self.offsets.filter_clone(|&(ref c, _, _)| c == cluster) } fn offsets_by_cluster_topic( &self, cluster: &ClusterId, topic: &str, ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> { self.offsets .filter_clone(|&(ref c, _, ref t)| c == cluster && t == topic) } fn offsets_by_cluster_group( &self, cluster: &ClusterId, group: &str, ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> { self.offsets .filter_clone(|&(ref c, ref g, _)| c == cluster && g == group) } }
{ let tp_elements = tp_list.elements_for_topic("__consumer_offsets"); let mut offsets = vec![0; tp_elements.len()]; for tp in &tp_elements { offsets[tp.partition() as usize] = tp.offset().to_raw(); } offsets }
identifier_body
movmskpd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn
() { run_test(&Instruction { mnemonic: Mnemonic::MOVMSKPD, operand1: Some(Direct(ESP)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 80, 225], OperandSize::Dword) } fn movmskpd_2() { run_test(&Instruction { mnemonic: Mnemonic::MOVMSKPD, operand1: Some(Direct(RDX)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 80, 209], OperandSize::Qword) }
movmskpd_1
identifier_name
movmskpd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn movmskpd_1() { run_test(&Instruction { mnemonic: Mnemonic::MOVMSKPD, operand1: Some(Direct(ESP)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 80, 225], OperandSize::Dword) } fn movmskpd_2() { run_test(&Instruction { mnemonic: Mnemonic::MOVMSKPD, operand1: Some(Direct(RDX)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 80, 209], OperandSize::Qword)
}
random_line_split
movmskpd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn movmskpd_1()
fn movmskpd_2() { run_test(&Instruction { mnemonic: Mnemonic::MOVMSKPD, operand1: Some(Direct(RDX)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 80, 209], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::MOVMSKPD, operand1: Some(Direct(ESP)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 80, 225], OperandSize::Dword) }
identifier_body
cssrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::cssfontfacerule::CSSFontFaceRule; use crate::dom::cssimportrule::CSSImportRule; use crate::dom::csskeyframerule::CSSKeyframeRule; use crate::dom::csskeyframesrule::CSSKeyframesRule; use crate::dom::cssmediarule::CSSMediaRule; use crate::dom::cssnamespacerule::CSSNamespaceRule; use crate::dom::cssstylerule::CSSStyleRule; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::csssupportsrule::CSSSupportsRule; use crate::dom::cssviewportrule::CSSViewportRule; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::CssRule as StyleCssRule; #[dom_struct] pub struct CSSRule { reflector_: Reflector, parent_stylesheet: Dom<CSSStyleSheet>, /// Whether the parentStyleSheet attribute should return null. /// We keep parent_stylesheet in that case because insertRule needs it /// for the stylesheet’s base URL and namespace prefixes. parent_stylesheet_removed: Cell<bool>, } impl CSSRule { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet) -> CSSRule { CSSRule { reflector_: Reflector::new(), parent_stylesheet: Dom::from_ref(parent_stylesheet), parent_stylesheet_removed: Cell::new(false), } } pub fn as_specific(&self) -> &dyn SpecificCSSRule { if let Some(rule) = self.downcast::<CSSStyleRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSFontFaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframesRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSMediaRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSNamespaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSViewportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframeRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSImportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSSupportsRule>() {
lse { unreachable!() } } // Given a StyleCssRule, create a new instance of a derived class of // CSSRule based on which rule it is pub fn new_specific( window: &Window, parent_stylesheet: &CSSStyleSheet, rule: StyleCssRule, ) -> DomRoot<CSSRule> { // be sure to update the match in as_specific when this is updated match rule { StyleCssRule::Import(s) => { DomRoot::upcast(CSSImportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Style(s) => { DomRoot::upcast(CSSStyleRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFace(s) => { DomRoot::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFeatureValues(_) => unimplemented!(), StyleCssRule::CounterStyle(_) => unimplemented!(), StyleCssRule::Keyframes(s) => { DomRoot::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Media(s) => { DomRoot::upcast(CSSMediaRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Namespace(s) => { DomRoot::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Viewport(s) => { DomRoot::upcast(CSSViewportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Supports(s) => { DomRoot::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Page(_) => unreachable!(), StyleCssRule::Document(_) => unimplemented!(), // TODO } } /// Sets owner sheet/rule to null pub fn detach(&self) { self.deparent(); // should set parent rule to None when we add parent rule support } /// Sets owner sheet to null (and does the same for all children) pub fn deparent(&self) { self.parent_stylesheet_removed.set(true); // https://github.com/w3c/csswg-drafts/issues/722 // Spec doesn't ask us to do this, but it makes sense // and browsers implement this behavior self.as_specific().deparent_children(); } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { &self.parent_stylesheet } pub fn shared_lock(&self) -> &SharedRwLock { &self.parent_stylesheet.style_stylesheet().shared_lock } } impl CSSRuleMethods for CSSRule { // https://drafts.csswg.org/cssom/#dom-cssrule-type fn Type(&self) -> u16 { self.as_specific().ty() } // https://drafts.csswg.org/cssom/#dom-cssrule-parentstylesheet fn GetParentStyleSheet(&self) -> Option<DomRoot<CSSStyleSheet>> { if self.parent_stylesheet_removed.get() { None } else { Some(DomRoot::from_ref(&*self.parent_stylesheet)) } } // https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn CssText(&self) -> DOMString { self.as_specific().get_css() } // https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn SetCssText(&self, _: DOMString) { // do nothing } } pub trait SpecificCSSRule { fn ty(&self) -> u16; fn get_css(&self) -> DOMString; /// Remove parentStylesheet from all transitive children fn deparent_children(&self) { // most CSSRules do nothing here } }
rule as &dyn SpecificCSSRule } e
conditional_block
cssrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::cssfontfacerule::CSSFontFaceRule; use crate::dom::cssimportrule::CSSImportRule; use crate::dom::csskeyframerule::CSSKeyframeRule; use crate::dom::csskeyframesrule::CSSKeyframesRule; use crate::dom::cssmediarule::CSSMediaRule; use crate::dom::cssnamespacerule::CSSNamespaceRule; use crate::dom::cssstylerule::CSSStyleRule; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::csssupportsrule::CSSSupportsRule; use crate::dom::cssviewportrule::CSSViewportRule; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::CssRule as StyleCssRule; #[dom_struct] pub struct CSSRule { reflector_: Reflector, parent_stylesheet: Dom<CSSStyleSheet>, /// Whether the parentStyleSheet attribute should return null. /// We keep parent_stylesheet in that case because insertRule needs it /// for the stylesheet’s base URL and namespace prefixes. parent_stylesheet_removed: Cell<bool>, } impl CSSRule { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet) -> CSSRule { CSSRule { reflector_: Reflector::new(), parent_stylesheet: Dom::from_ref(parent_stylesheet), parent_stylesheet_removed: Cell::new(false), } } pub fn as_specific(&self) -> &dyn SpecificCSSRule { if let Some(rule) = self.downcast::<CSSStyleRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSFontFaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframesRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSMediaRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSNamespaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSViewportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframeRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSImportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule as &dyn SpecificCSSRule } else { unreachable!() } } // Given a StyleCssRule, create a new instance of a derived class of // CSSRule based on which rule it is pub fn new_specific( window: &Window, parent_stylesheet: &CSSStyleSheet, rule: StyleCssRule, ) -> DomRoot<CSSRule> { // be sure to update the match in as_specific when this is updated match rule { StyleCssRule::Import(s) => { DomRoot::upcast(CSSImportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Style(s) => { DomRoot::upcast(CSSStyleRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFace(s) => { DomRoot::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFeatureValues(_) => unimplemented!(), StyleCssRule::CounterStyle(_) => unimplemented!(), StyleCssRule::Keyframes(s) => { DomRoot::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Media(s) => { DomRoot::upcast(CSSMediaRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Namespace(s) => { DomRoot::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Viewport(s) => { DomRoot::upcast(CSSViewportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Supports(s) => { DomRoot::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Page(_) => unreachable!(), StyleCssRule::Document(_) => unimplemented!(), // TODO } } /// Sets owner sheet/rule to null pub fn detach(&self) { self.deparent(); // should set parent rule to None when we add parent rule support } /// Sets owner sheet to null (and does the same for all children) pub fn deparent(&self) { self.parent_stylesheet_removed.set(true); // https://github.com/w3c/csswg-drafts/issues/722 // Spec doesn't ask us to do this, but it makes sense // and browsers implement this behavior self.as_specific().deparent_children(); } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { &self.parent_stylesheet } pub fn shared_lock(&self) -> &SharedRwLock { &self.parent_stylesheet.style_stylesheet().shared_lock } } impl CSSRuleMethods for CSSRule { // https://drafts.csswg.org/cssom/#dom-cssrule-type fn Type(&self) -> u16 { self.as_specific().ty() } // https://drafts.csswg.org/cssom/#dom-cssrule-parentstylesheet fn GetParentStyleSheet(&self) -> Option<DomRoot<CSSStyleSheet>> {
// https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn CssText(&self) -> DOMString { self.as_specific().get_css() } // https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn SetCssText(&self, _: DOMString) { // do nothing } } pub trait SpecificCSSRule { fn ty(&self) -> u16; fn get_css(&self) -> DOMString; /// Remove parentStylesheet from all transitive children fn deparent_children(&self) { // most CSSRules do nothing here } }
if self.parent_stylesheet_removed.get() { None } else { Some(DomRoot::from_ref(&*self.parent_stylesheet)) } }
identifier_body
cssrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::cssfontfacerule::CSSFontFaceRule; use crate::dom::cssimportrule::CSSImportRule; use crate::dom::csskeyframerule::CSSKeyframeRule; use crate::dom::csskeyframesrule::CSSKeyframesRule; use crate::dom::cssmediarule::CSSMediaRule; use crate::dom::cssnamespacerule::CSSNamespaceRule; use crate::dom::cssstylerule::CSSStyleRule; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::csssupportsrule::CSSSupportsRule; use crate::dom::cssviewportrule::CSSViewportRule; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::CssRule as StyleCssRule; #[dom_struct] pub struct CSSRule { reflector_: Reflector, parent_stylesheet: Dom<CSSStyleSheet>, /// Whether the parentStyleSheet attribute should return null. /// We keep parent_stylesheet in that case because insertRule needs it /// for the stylesheet’s base URL and namespace prefixes. parent_stylesheet_removed: Cell<bool>, } impl CSSRule { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet) -> CSSRule { CSSRule { reflector_: Reflector::new(), parent_stylesheet: Dom::from_ref(parent_stylesheet), parent_stylesheet_removed: Cell::new(false), } } pub fn as
self) -> &dyn SpecificCSSRule { if let Some(rule) = self.downcast::<CSSStyleRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSFontFaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframesRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSMediaRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSNamespaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSViewportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframeRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSImportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule as &dyn SpecificCSSRule } else { unreachable!() } } // Given a StyleCssRule, create a new instance of a derived class of // CSSRule based on which rule it is pub fn new_specific( window: &Window, parent_stylesheet: &CSSStyleSheet, rule: StyleCssRule, ) -> DomRoot<CSSRule> { // be sure to update the match in as_specific when this is updated match rule { StyleCssRule::Import(s) => { DomRoot::upcast(CSSImportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Style(s) => { DomRoot::upcast(CSSStyleRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFace(s) => { DomRoot::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFeatureValues(_) => unimplemented!(), StyleCssRule::CounterStyle(_) => unimplemented!(), StyleCssRule::Keyframes(s) => { DomRoot::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Media(s) => { DomRoot::upcast(CSSMediaRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Namespace(s) => { DomRoot::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Viewport(s) => { DomRoot::upcast(CSSViewportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Supports(s) => { DomRoot::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Page(_) => unreachable!(), StyleCssRule::Document(_) => unimplemented!(), // TODO } } /// Sets owner sheet/rule to null pub fn detach(&self) { self.deparent(); // should set parent rule to None when we add parent rule support } /// Sets owner sheet to null (and does the same for all children) pub fn deparent(&self) { self.parent_stylesheet_removed.set(true); // https://github.com/w3c/csswg-drafts/issues/722 // Spec doesn't ask us to do this, but it makes sense // and browsers implement this behavior self.as_specific().deparent_children(); } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { &self.parent_stylesheet } pub fn shared_lock(&self) -> &SharedRwLock { &self.parent_stylesheet.style_stylesheet().shared_lock } } impl CSSRuleMethods for CSSRule { // https://drafts.csswg.org/cssom/#dom-cssrule-type fn Type(&self) -> u16 { self.as_specific().ty() } // https://drafts.csswg.org/cssom/#dom-cssrule-parentstylesheet fn GetParentStyleSheet(&self) -> Option<DomRoot<CSSStyleSheet>> { if self.parent_stylesheet_removed.get() { None } else { Some(DomRoot::from_ref(&*self.parent_stylesheet)) } } // https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn CssText(&self) -> DOMString { self.as_specific().get_css() } // https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn SetCssText(&self, _: DOMString) { // do nothing } } pub trait SpecificCSSRule { fn ty(&self) -> u16; fn get_css(&self) -> DOMString; /// Remove parentStylesheet from all transitive children fn deparent_children(&self) { // most CSSRules do nothing here } }
_specific(&
identifier_name
cssrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::cssfontfacerule::CSSFontFaceRule; use crate::dom::cssimportrule::CSSImportRule; use crate::dom::csskeyframerule::CSSKeyframeRule; use crate::dom::csskeyframesrule::CSSKeyframesRule; use crate::dom::cssmediarule::CSSMediaRule; use crate::dom::cssnamespacerule::CSSNamespaceRule; use crate::dom::cssstylerule::CSSStyleRule; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::csssupportsrule::CSSSupportsRule; use crate::dom::cssviewportrule::CSSViewportRule; use crate::dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::CssRule as StyleCssRule; #[dom_struct] pub struct CSSRule { reflector_: Reflector, parent_stylesheet: Dom<CSSStyleSheet>, /// Whether the parentStyleSheet attribute should return null. /// We keep parent_stylesheet in that case because insertRule needs it /// for the stylesheet’s base URL and namespace prefixes. parent_stylesheet_removed: Cell<bool>, } impl CSSRule { #[allow(unrooted_must_root)] pub fn new_inherited(parent_stylesheet: &CSSStyleSheet) -> CSSRule { CSSRule { reflector_: Reflector::new(), parent_stylesheet: Dom::from_ref(parent_stylesheet), parent_stylesheet_removed: Cell::new(false), } } pub fn as_specific(&self) -> &dyn SpecificCSSRule { if let Some(rule) = self.downcast::<CSSStyleRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSFontFaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframesRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSMediaRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSNamespaceRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSViewportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSKeyframeRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSImportRule>() { rule as &dyn SpecificCSSRule } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule as &dyn SpecificCSSRule } else { unreachable!() } }
// CSSRule based on which rule it is pub fn new_specific( window: &Window, parent_stylesheet: &CSSStyleSheet, rule: StyleCssRule, ) -> DomRoot<CSSRule> { // be sure to update the match in as_specific when this is updated match rule { StyleCssRule::Import(s) => { DomRoot::upcast(CSSImportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Style(s) => { DomRoot::upcast(CSSStyleRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFace(s) => { DomRoot::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::FontFeatureValues(_) => unimplemented!(), StyleCssRule::CounterStyle(_) => unimplemented!(), StyleCssRule::Keyframes(s) => { DomRoot::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Media(s) => { DomRoot::upcast(CSSMediaRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Namespace(s) => { DomRoot::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Viewport(s) => { DomRoot::upcast(CSSViewportRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Supports(s) => { DomRoot::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)) }, StyleCssRule::Page(_) => unreachable!(), StyleCssRule::Document(_) => unimplemented!(), // TODO } } /// Sets owner sheet/rule to null pub fn detach(&self) { self.deparent(); // should set parent rule to None when we add parent rule support } /// Sets owner sheet to null (and does the same for all children) pub fn deparent(&self) { self.parent_stylesheet_removed.set(true); // https://github.com/w3c/csswg-drafts/issues/722 // Spec doesn't ask us to do this, but it makes sense // and browsers implement this behavior self.as_specific().deparent_children(); } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { &self.parent_stylesheet } pub fn shared_lock(&self) -> &SharedRwLock { &self.parent_stylesheet.style_stylesheet().shared_lock } } impl CSSRuleMethods for CSSRule { // https://drafts.csswg.org/cssom/#dom-cssrule-type fn Type(&self) -> u16 { self.as_specific().ty() } // https://drafts.csswg.org/cssom/#dom-cssrule-parentstylesheet fn GetParentStyleSheet(&self) -> Option<DomRoot<CSSStyleSheet>> { if self.parent_stylesheet_removed.get() { None } else { Some(DomRoot::from_ref(&*self.parent_stylesheet)) } } // https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn CssText(&self) -> DOMString { self.as_specific().get_css() } // https://drafts.csswg.org/cssom/#dom-cssrule-csstext fn SetCssText(&self, _: DOMString) { // do nothing } } pub trait SpecificCSSRule { fn ty(&self) -> u16; fn get_css(&self) -> DOMString; /// Remove parentStylesheet from all transitive children fn deparent_children(&self) { // most CSSRules do nothing here } }
// Given a StyleCssRule, create a new instance of a derived class of
random_line_split
stream_blob00.rs
#![cfg(all(test, feature = "test_e2e"))] use azure_sdk_core::prelude::*; use azure_sdk_core::{range::Range, DeleteSnapshotsMethod}; use azure_sdk_storage_blob::prelude::*; use azure_sdk_storage_core::prelude::*; use futures::stream::StreamExt; #[tokio::test] async fn create_blob_and_stream_back() { code().await.unwrap(); } async fn code() -> Result<(), Box<dyn std::error::Error>> { let container_name = "azuresdkforrust"; let file_name = "azure_sdk_for_rust_stream_test.txt"; // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let client = client::with_access_key(&account, &master_key); if client .list_containers() .finalize() .await? .incomplete_vector .iter() .find(|x| x.name == container_name) .is_none() { client .create_container() .with_container_name(container_name) .with_public_access(PublicAccess::Blob) .finalize() .await?; } let string = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; client .put_block_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_content_type("text/plain") .with_body(string.as_ref()) .finalize() .await?; println!("{}/{} blob created!", container_name, file_name); for dropped_suffix_len in &[3usize, 2, 1, 0] { // this is how you stream data from azure blob. Notice that you have // to specify the range requested. Also make sure to specify how big // a chunk is going to be. Bigger chunks are of course more efficient as the // http overhead will be less but it also means you will have to wait for more // time before receiving anything. In this example we use an awkward value // just to make the test worthwile. let slice_range = 0..(string.len() - dropped_suffix_len); let expected_string = &string[slice_range.clone()]; let range: Range = slice_range.into(); let chunk_size: usize = 4; let mut stream = Box::pin( client .stream_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_range(&range) .with_chunk_size(chunk_size as u64) .finalize(), ); let result = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); { let mut res_closure = result.borrow_mut(); while let Some(value) = stream.next().await { let mut value = value?; assert!(value.len() <= chunk_size); println!("received {:?} bytes", value.len()); res_closure.append(&mut value); } } let returned_string = { let rlock = result.borrow(); String::from_utf8(rlock.to_vec())? }; println!( "dropped_suffix_len == {} returned_string == {}", dropped_suffix_len, returned_string ); assert_eq!(expected_string, returned_string); } client .delete_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_delete_snapshots_method(DeleteSnapshotsMethod::Include)
println!("{}/{} blob deleted!", container_name, file_name); Ok(()) }
.finalize() .await?;
random_line_split
stream_blob00.rs
#![cfg(all(test, feature = "test_e2e"))] use azure_sdk_core::prelude::*; use azure_sdk_core::{range::Range, DeleteSnapshotsMethod}; use azure_sdk_storage_blob::prelude::*; use azure_sdk_storage_core::prelude::*; use futures::stream::StreamExt; #[tokio::test] async fn create_blob_and_stream_back()
async fn code() -> Result<(), Box<dyn std::error::Error>> { let container_name = "azuresdkforrust"; let file_name = "azure_sdk_for_rust_stream_test.txt"; // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let client = client::with_access_key(&account, &master_key); if client .list_containers() .finalize() .await? .incomplete_vector .iter() .find(|x| x.name == container_name) .is_none() { client .create_container() .with_container_name(container_name) .with_public_access(PublicAccess::Blob) .finalize() .await?; } let string = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; client .put_block_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_content_type("text/plain") .with_body(string.as_ref()) .finalize() .await?; println!("{}/{} blob created!", container_name, file_name); for dropped_suffix_len in &[3usize, 2, 1, 0] { // this is how you stream data from azure blob. Notice that you have // to specify the range requested. Also make sure to specify how big // a chunk is going to be. Bigger chunks are of course more efficient as the // http overhead will be less but it also means you will have to wait for more // time before receiving anything. In this example we use an awkward value // just to make the test worthwile. let slice_range = 0..(string.len() - dropped_suffix_len); let expected_string = &string[slice_range.clone()]; let range: Range = slice_range.into(); let chunk_size: usize = 4; let mut stream = Box::pin( client .stream_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_range(&range) .with_chunk_size(chunk_size as u64) .finalize(), ); let result = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); { let mut res_closure = result.borrow_mut(); while let Some(value) = stream.next().await { let mut value = value?; assert!(value.len() <= chunk_size); println!("received {:?} bytes", value.len()); res_closure.append(&mut value); } } let returned_string = { let rlock = result.borrow(); String::from_utf8(rlock.to_vec())? }; println!( "dropped_suffix_len == {} returned_string == {}", dropped_suffix_len, returned_string ); assert_eq!(expected_string, returned_string); } client .delete_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_delete_snapshots_method(DeleteSnapshotsMethod::Include) .finalize() .await?; println!("{}/{} blob deleted!", container_name, file_name); Ok(()) }
{ code().await.unwrap(); }
identifier_body
stream_blob00.rs
#![cfg(all(test, feature = "test_e2e"))] use azure_sdk_core::prelude::*; use azure_sdk_core::{range::Range, DeleteSnapshotsMethod}; use azure_sdk_storage_blob::prelude::*; use azure_sdk_storage_core::prelude::*; use futures::stream::StreamExt; #[tokio::test] async fn create_blob_and_stream_back() { code().await.unwrap(); } async fn
() -> Result<(), Box<dyn std::error::Error>> { let container_name = "azuresdkforrust"; let file_name = "azure_sdk_for_rust_stream_test.txt"; // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let client = client::with_access_key(&account, &master_key); if client .list_containers() .finalize() .await? .incomplete_vector .iter() .find(|x| x.name == container_name) .is_none() { client .create_container() .with_container_name(container_name) .with_public_access(PublicAccess::Blob) .finalize() .await?; } let string = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; client .put_block_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_content_type("text/plain") .with_body(string.as_ref()) .finalize() .await?; println!("{}/{} blob created!", container_name, file_name); for dropped_suffix_len in &[3usize, 2, 1, 0] { // this is how you stream data from azure blob. Notice that you have // to specify the range requested. Also make sure to specify how big // a chunk is going to be. Bigger chunks are of course more efficient as the // http overhead will be less but it also means you will have to wait for more // time before receiving anything. In this example we use an awkward value // just to make the test worthwile. let slice_range = 0..(string.len() - dropped_suffix_len); let expected_string = &string[slice_range.clone()]; let range: Range = slice_range.into(); let chunk_size: usize = 4; let mut stream = Box::pin( client .stream_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_range(&range) .with_chunk_size(chunk_size as u64) .finalize(), ); let result = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); { let mut res_closure = result.borrow_mut(); while let Some(value) = stream.next().await { let mut value = value?; assert!(value.len() <= chunk_size); println!("received {:?} bytes", value.len()); res_closure.append(&mut value); } } let returned_string = { let rlock = result.borrow(); String::from_utf8(rlock.to_vec())? }; println!( "dropped_suffix_len == {} returned_string == {}", dropped_suffix_len, returned_string ); assert_eq!(expected_string, returned_string); } client .delete_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_delete_snapshots_method(DeleteSnapshotsMethod::Include) .finalize() .await?; println!("{}/{} blob deleted!", container_name, file_name); Ok(()) }
code
identifier_name
stream_blob00.rs
#![cfg(all(test, feature = "test_e2e"))] use azure_sdk_core::prelude::*; use azure_sdk_core::{range::Range, DeleteSnapshotsMethod}; use azure_sdk_storage_blob::prelude::*; use azure_sdk_storage_core::prelude::*; use futures::stream::StreamExt; #[tokio::test] async fn create_blob_and_stream_back() { code().await.unwrap(); } async fn code() -> Result<(), Box<dyn std::error::Error>> { let container_name = "azuresdkforrust"; let file_name = "azure_sdk_for_rust_stream_test.txt"; // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let client = client::with_access_key(&account, &master_key); if client .list_containers() .finalize() .await? .incomplete_vector .iter() .find(|x| x.name == container_name) .is_none()
let string = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; client .put_block_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_content_type("text/plain") .with_body(string.as_ref()) .finalize() .await?; println!("{}/{} blob created!", container_name, file_name); for dropped_suffix_len in &[3usize, 2, 1, 0] { // this is how you stream data from azure blob. Notice that you have // to specify the range requested. Also make sure to specify how big // a chunk is going to be. Bigger chunks are of course more efficient as the // http overhead will be less but it also means you will have to wait for more // time before receiving anything. In this example we use an awkward value // just to make the test worthwile. let slice_range = 0..(string.len() - dropped_suffix_len); let expected_string = &string[slice_range.clone()]; let range: Range = slice_range.into(); let chunk_size: usize = 4; let mut stream = Box::pin( client .stream_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_range(&range) .with_chunk_size(chunk_size as u64) .finalize(), ); let result = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); { let mut res_closure = result.borrow_mut(); while let Some(value) = stream.next().await { let mut value = value?; assert!(value.len() <= chunk_size); println!("received {:?} bytes", value.len()); res_closure.append(&mut value); } } let returned_string = { let rlock = result.borrow(); String::from_utf8(rlock.to_vec())? }; println!( "dropped_suffix_len == {} returned_string == {}", dropped_suffix_len, returned_string ); assert_eq!(expected_string, returned_string); } client .delete_blob() .with_container_name(&container_name) .with_blob_name(file_name) .with_delete_snapshots_method(DeleteSnapshotsMethod::Include) .finalize() .await?; println!("{}/{} blob deleted!", container_name, file_name); Ok(()) }
{ client .create_container() .with_container_name(container_name) .with_public_access(PublicAccess::Blob) .finalize() .await?; }
conditional_block
fsm.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::mailbox::BasicMailbox; use std::borrow::Cow; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use std::{ptr, usize}; // The FSM is notified. const NOTIFYSTATE_NOTIFIED: usize = 0; // The FSM is idle. const NOTIFYSTATE_IDLE: usize = 1; // The FSM is expected to be dropped. const NOTIFYSTATE_DROP: usize = 2; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Priority { Low, Normal, } /// `FsmScheduler` schedules `Fsm` for later handles. pub trait FsmScheduler { type Fsm: Fsm; /// Schedule a Fsm for later handles. fn schedule(&self, fsm: Box<Self::Fsm>); /// Shutdown the scheduler, which indicates that resources like /// background thread pool should be released. fn shutdown(&self); } /// A Fsm is a finite state machine. It should be able to be notified for /// updating internal state according to incoming messages. pub trait Fsm { type Message: Send; fn is_stopped(&self) -> bool; /// Set a mailbox to Fsm, which should be used to send message to itself. fn set_mailbox(&mut self, _mailbox: Cow<'_, BasicMailbox<Self>>) where Self: Sized, { } /// Take the mailbox from Fsm. Implementation should ensure there will be /// no reference to mailbox after calling this method. fn take_mailbox(&mut self) -> Option<BasicMailbox<Self>> where Self: Sized, { None } fn get_priority(&self) -> Priority { Priority::Normal } } pub struct FsmState<N> { status: AtomicUsize, data: AtomicPtr<N>, } impl<N: Fsm> FsmState<N> { pub fn new(data: Box<N>) -> FsmState<N> { FsmState { status: AtomicUsize::new(NOTIFYSTATE_IDLE), data: AtomicPtr::new(Box::into_raw(data)), } } /// Take the fsm if it's IDLE. pub fn take_fsm(&self) -> Option<Box<N>> { let res = self.status.compare_exchange( NOTIFYSTATE_IDLE, NOTIFYSTATE_NOTIFIED, Ordering::AcqRel, Ordering::Acquire, ); if res.is_err()
let p = self.data.swap(ptr::null_mut(), Ordering::AcqRel); if!p.is_null() { Some(unsafe { Box::from_raw(p) }) } else { panic!("inconsistent status and data, something should be wrong."); } } /// Notify fsm via a `FsmScheduler`. #[inline] pub fn notify<S: FsmScheduler<Fsm = N>>( &self, scheduler: &S, mailbox: Cow<'_, BasicMailbox<N>>, ) { match self.take_fsm() { None => {} Some(mut n) => { n.set_mailbox(mailbox); scheduler.schedule(n); } } } /// Put the owner back to the state. /// /// It's not required that all messages should be consumed before /// releasing a fsm. However, a fsm is guaranteed to be notified only /// when new messages arrives after it's released. #[inline] pub fn release(&self, fsm: Box<N>) { let previous = self.data.swap(Box::into_raw(fsm), Ordering::AcqRel); let mut previous_status = NOTIFYSTATE_NOTIFIED; if previous.is_null() { let res = self.status.compare_exchange( NOTIFYSTATE_NOTIFIED, NOTIFYSTATE_IDLE, Ordering::AcqRel, Ordering::Acquire, ); previous_status = match res { Ok(_) => return, Err(NOTIFYSTATE_DROP) => { let ptr = self.data.swap(ptr::null_mut(), Ordering::AcqRel); unsafe { Box::from_raw(ptr) }; return; } Err(s) => s, }; } panic!("invalid release state: {:?} {}", previous, previous_status); } /// Clear the fsm. #[inline] pub fn clear(&self) { match self.status.swap(NOTIFYSTATE_DROP, Ordering::AcqRel) { NOTIFYSTATE_NOTIFIED | NOTIFYSTATE_DROP => return, _ => {} } let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr); } } } } impl<N> Drop for FsmState<N> { fn drop(&mut self) { let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr) }; } } }
{ return None; }
conditional_block
fsm.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::mailbox::BasicMailbox; use std::borrow::Cow; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use std::{ptr, usize}; // The FSM is notified. const NOTIFYSTATE_NOTIFIED: usize = 0; // The FSM is idle. const NOTIFYSTATE_IDLE: usize = 1; // The FSM is expected to be dropped. const NOTIFYSTATE_DROP: usize = 2; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Priority { Low, Normal, } /// `FsmScheduler` schedules `Fsm` for later handles. pub trait FsmScheduler { type Fsm: Fsm; /// Schedule a Fsm for later handles. fn schedule(&self, fsm: Box<Self::Fsm>); /// Shutdown the scheduler, which indicates that resources like /// background thread pool should be released. fn shutdown(&self); } /// A Fsm is a finite state machine. It should be able to be notified for /// updating internal state according to incoming messages. pub trait Fsm { type Message: Send; fn is_stopped(&self) -> bool; /// Set a mailbox to Fsm, which should be used to send message to itself. fn set_mailbox(&mut self, _mailbox: Cow<'_, BasicMailbox<Self>>) where Self: Sized, { } /// Take the mailbox from Fsm. Implementation should ensure there will be /// no reference to mailbox after calling this method. fn take_mailbox(&mut self) -> Option<BasicMailbox<Self>> where Self: Sized, { None } fn get_priority(&self) -> Priority { Priority::Normal } } pub struct FsmState<N> { status: AtomicUsize, data: AtomicPtr<N>, } impl<N: Fsm> FsmState<N> { pub fn new(data: Box<N>) -> FsmState<N> { FsmState { status: AtomicUsize::new(NOTIFYSTATE_IDLE), data: AtomicPtr::new(Box::into_raw(data)), } } /// Take the fsm if it's IDLE. pub fn take_fsm(&self) -> Option<Box<N>> { let res = self.status.compare_exchange( NOTIFYSTATE_IDLE, NOTIFYSTATE_NOTIFIED, Ordering::AcqRel, Ordering::Acquire, ); if res.is_err() { return None; } let p = self.data.swap(ptr::null_mut(), Ordering::AcqRel); if!p.is_null() { Some(unsafe { Box::from_raw(p) }) } else { panic!("inconsistent status and data, something should be wrong."); } } /// Notify fsm via a `FsmScheduler`. #[inline] pub fn notify<S: FsmScheduler<Fsm = N>>( &self, scheduler: &S, mailbox: Cow<'_, BasicMailbox<N>>, ) { match self.take_fsm() { None => {} Some(mut n) => { n.set_mailbox(mailbox); scheduler.schedule(n); } } } /// Put the owner back to the state. /// /// It's not required that all messages should be consumed before /// releasing a fsm. However, a fsm is guaranteed to be notified only /// when new messages arrives after it's released. #[inline] pub fn release(&self, fsm: Box<N>) { let previous = self.data.swap(Box::into_raw(fsm), Ordering::AcqRel); let mut previous_status = NOTIFYSTATE_NOTIFIED; if previous.is_null() { let res = self.status.compare_exchange( NOTIFYSTATE_NOTIFIED, NOTIFYSTATE_IDLE, Ordering::AcqRel, Ordering::Acquire, ); previous_status = match res { Ok(_) => return, Err(NOTIFYSTATE_DROP) => { let ptr = self.data.swap(ptr::null_mut(), Ordering::AcqRel); unsafe { Box::from_raw(ptr) }; return; } Err(s) => s, }; } panic!("invalid release state: {:?} {}", previous, previous_status); } /// Clear the fsm. #[inline] pub fn
(&self) { match self.status.swap(NOTIFYSTATE_DROP, Ordering::AcqRel) { NOTIFYSTATE_NOTIFIED | NOTIFYSTATE_DROP => return, _ => {} } let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr); } } } } impl<N> Drop for FsmState<N> { fn drop(&mut self) { let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr) }; } } }
clear
identifier_name
fsm.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::mailbox::BasicMailbox; use std::borrow::Cow; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use std::{ptr, usize}; // The FSM is notified. const NOTIFYSTATE_NOTIFIED: usize = 0; // The FSM is idle. const NOTIFYSTATE_IDLE: usize = 1; // The FSM is expected to be dropped. const NOTIFYSTATE_DROP: usize = 2; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Priority { Low, Normal, } /// `FsmScheduler` schedules `Fsm` for later handles. pub trait FsmScheduler { type Fsm: Fsm; /// Schedule a Fsm for later handles. fn schedule(&self, fsm: Box<Self::Fsm>); /// Shutdown the scheduler, which indicates that resources like /// background thread pool should be released. fn shutdown(&self); } /// A Fsm is a finite state machine. It should be able to be notified for /// updating internal state according to incoming messages. pub trait Fsm { type Message: Send; fn is_stopped(&self) -> bool; /// Set a mailbox to Fsm, which should be used to send message to itself. fn set_mailbox(&mut self, _mailbox: Cow<'_, BasicMailbox<Self>>) where Self: Sized, { } /// Take the mailbox from Fsm. Implementation should ensure there will be /// no reference to mailbox after calling this method. fn take_mailbox(&mut self) -> Option<BasicMailbox<Self>> where Self: Sized,
fn get_priority(&self) -> Priority { Priority::Normal } } pub struct FsmState<N> { status: AtomicUsize, data: AtomicPtr<N>, } impl<N: Fsm> FsmState<N> { pub fn new(data: Box<N>) -> FsmState<N> { FsmState { status: AtomicUsize::new(NOTIFYSTATE_IDLE), data: AtomicPtr::new(Box::into_raw(data)), } } /// Take the fsm if it's IDLE. pub fn take_fsm(&self) -> Option<Box<N>> { let res = self.status.compare_exchange( NOTIFYSTATE_IDLE, NOTIFYSTATE_NOTIFIED, Ordering::AcqRel, Ordering::Acquire, ); if res.is_err() { return None; } let p = self.data.swap(ptr::null_mut(), Ordering::AcqRel); if!p.is_null() { Some(unsafe { Box::from_raw(p) }) } else { panic!("inconsistent status and data, something should be wrong."); } } /// Notify fsm via a `FsmScheduler`. #[inline] pub fn notify<S: FsmScheduler<Fsm = N>>( &self, scheduler: &S, mailbox: Cow<'_, BasicMailbox<N>>, ) { match self.take_fsm() { None => {} Some(mut n) => { n.set_mailbox(mailbox); scheduler.schedule(n); } } } /// Put the owner back to the state. /// /// It's not required that all messages should be consumed before /// releasing a fsm. However, a fsm is guaranteed to be notified only /// when new messages arrives after it's released. #[inline] pub fn release(&self, fsm: Box<N>) { let previous = self.data.swap(Box::into_raw(fsm), Ordering::AcqRel); let mut previous_status = NOTIFYSTATE_NOTIFIED; if previous.is_null() { let res = self.status.compare_exchange( NOTIFYSTATE_NOTIFIED, NOTIFYSTATE_IDLE, Ordering::AcqRel, Ordering::Acquire, ); previous_status = match res { Ok(_) => return, Err(NOTIFYSTATE_DROP) => { let ptr = self.data.swap(ptr::null_mut(), Ordering::AcqRel); unsafe { Box::from_raw(ptr) }; return; } Err(s) => s, }; } panic!("invalid release state: {:?} {}", previous, previous_status); } /// Clear the fsm. #[inline] pub fn clear(&self) { match self.status.swap(NOTIFYSTATE_DROP, Ordering::AcqRel) { NOTIFYSTATE_NOTIFIED | NOTIFYSTATE_DROP => return, _ => {} } let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr); } } } } impl<N> Drop for FsmState<N> { fn drop(&mut self) { let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr) }; } } }
{ None }
identifier_body
fsm.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::mailbox::BasicMailbox; use std::borrow::Cow; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use std::{ptr, usize}; // The FSM is notified. const NOTIFYSTATE_NOTIFIED: usize = 0; // The FSM is idle. const NOTIFYSTATE_IDLE: usize = 1;
#[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Priority { Low, Normal, } /// `FsmScheduler` schedules `Fsm` for later handles. pub trait FsmScheduler { type Fsm: Fsm; /// Schedule a Fsm for later handles. fn schedule(&self, fsm: Box<Self::Fsm>); /// Shutdown the scheduler, which indicates that resources like /// background thread pool should be released. fn shutdown(&self); } /// A Fsm is a finite state machine. It should be able to be notified for /// updating internal state according to incoming messages. pub trait Fsm { type Message: Send; fn is_stopped(&self) -> bool; /// Set a mailbox to Fsm, which should be used to send message to itself. fn set_mailbox(&mut self, _mailbox: Cow<'_, BasicMailbox<Self>>) where Self: Sized, { } /// Take the mailbox from Fsm. Implementation should ensure there will be /// no reference to mailbox after calling this method. fn take_mailbox(&mut self) -> Option<BasicMailbox<Self>> where Self: Sized, { None } fn get_priority(&self) -> Priority { Priority::Normal } } pub struct FsmState<N> { status: AtomicUsize, data: AtomicPtr<N>, } impl<N: Fsm> FsmState<N> { pub fn new(data: Box<N>) -> FsmState<N> { FsmState { status: AtomicUsize::new(NOTIFYSTATE_IDLE), data: AtomicPtr::new(Box::into_raw(data)), } } /// Take the fsm if it's IDLE. pub fn take_fsm(&self) -> Option<Box<N>> { let res = self.status.compare_exchange( NOTIFYSTATE_IDLE, NOTIFYSTATE_NOTIFIED, Ordering::AcqRel, Ordering::Acquire, ); if res.is_err() { return None; } let p = self.data.swap(ptr::null_mut(), Ordering::AcqRel); if!p.is_null() { Some(unsafe { Box::from_raw(p) }) } else { panic!("inconsistent status and data, something should be wrong."); } } /// Notify fsm via a `FsmScheduler`. #[inline] pub fn notify<S: FsmScheduler<Fsm = N>>( &self, scheduler: &S, mailbox: Cow<'_, BasicMailbox<N>>, ) { match self.take_fsm() { None => {} Some(mut n) => { n.set_mailbox(mailbox); scheduler.schedule(n); } } } /// Put the owner back to the state. /// /// It's not required that all messages should be consumed before /// releasing a fsm. However, a fsm is guaranteed to be notified only /// when new messages arrives after it's released. #[inline] pub fn release(&self, fsm: Box<N>) { let previous = self.data.swap(Box::into_raw(fsm), Ordering::AcqRel); let mut previous_status = NOTIFYSTATE_NOTIFIED; if previous.is_null() { let res = self.status.compare_exchange( NOTIFYSTATE_NOTIFIED, NOTIFYSTATE_IDLE, Ordering::AcqRel, Ordering::Acquire, ); previous_status = match res { Ok(_) => return, Err(NOTIFYSTATE_DROP) => { let ptr = self.data.swap(ptr::null_mut(), Ordering::AcqRel); unsafe { Box::from_raw(ptr) }; return; } Err(s) => s, }; } panic!("invalid release state: {:?} {}", previous, previous_status); } /// Clear the fsm. #[inline] pub fn clear(&self) { match self.status.swap(NOTIFYSTATE_DROP, Ordering::AcqRel) { NOTIFYSTATE_NOTIFIED | NOTIFYSTATE_DROP => return, _ => {} } let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr); } } } } impl<N> Drop for FsmState<N> { fn drop(&mut self) { let ptr = self.data.swap(ptr::null_mut(), Ordering::SeqCst); if!ptr.is_null() { unsafe { Box::from_raw(ptr) }; } } }
// The FSM is expected to be dropped. const NOTIFYSTATE_DROP: usize = 2;
random_line_split
htmlsourceelement.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
use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::htmlmediaelement::HTMLMediaElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement } impl HTMLSourceElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLSourceElement> { Node::reflect_node(Box::new(HTMLSourceElement::new_inherited(local_name, prefix, document)), document, HTMLSourceElementBinding::Wrap) } } impl VirtualMethods for HTMLSourceElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>() { media.handle_source_child_insertion(); } } }
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods;
random_line_split
htmlsourceelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::htmlmediaelement::HTMLMediaElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement } impl HTMLSourceElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLSourceElement> { Node::reflect_node(Box::new(HTMLSourceElement::new_inherited(local_name, prefix, document)), document, HTMLSourceElementBinding::Wrap) } } impl VirtualMethods for HTMLSourceElement { fn
(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>() { media.handle_source_child_insertion(); } } }
super_type
identifier_name
htmlsourceelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::htmlmediaelement::HTMLMediaElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement } impl HTMLSourceElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLSourceElement> { Node::reflect_node(Box::new(HTMLSourceElement::new_inherited(local_name, prefix, document)), document, HTMLSourceElementBinding::Wrap) } } impl VirtualMethods for HTMLSourceElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>()
} }
{ media.handle_source_child_insertion(); }
conditional_block
htmlsourceelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::htmlmediaelement::HTMLMediaElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement } impl HTMLSourceElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLSourceElement>
} impl VirtualMethods for HTMLSourceElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>() { media.handle_source_child_insertion(); } } }
{ Node::reflect_node(Box::new(HTMLSourceElement::new_inherited(local_name, prefix, document)), document, HTMLSourceElementBinding::Wrap) }
identifier_body
problem4.rs
fn is_palindrome(num: i64) -> bool { let num_str = num.to_string(); let chars_to_check = num_str.len()/2; let mut iter = num_str.as_bytes().iter().take(chars_to_check); let mut rev_iter = num_str.as_bytes().iter().rev().take(chars_to_check); // HACK: In future rust versions, this can probably be replaced by // "return iter == rev_iter" loop { match (iter.next(), rev_iter.next()) { (Some(x), Some(y)) => if x!= y { return false }, _ => return true, } } } fn largest_palindrome_product(max_digits: u32) -> i64 { let mut highest_found = 0; for a in 1..10i64.pow(max_digits) { for b in 1..10i64.pow(max_digits) { let prod = a*b; if prod > highest_found && is_palindrome(prod) { highest_found = prod } } } return highest_found } pub fn main() { let answer = largest_palindrome_product(2); if answer!= 9009 { panic!("error: wrong answer"); } let answer = largest_palindrome_product(3); println!("largest palindrome made from the product of two 3-digit integers is {}", answer); } #[cfg(test)] mod test { use super::{is_palindrome, largest_palindrome_product};
assert_eq!(is_palindrome(10), false); assert_eq!(is_palindrome(11), true); assert_eq!(is_palindrome(12), false); assert_eq!(is_palindrome(22), true); assert_eq!(is_palindrome(33), true); assert_eq!(is_palindrome(333), true); assert_eq!(is_palindrome(131), true); assert_eq!(is_palindrome(1331), true); assert_eq!(is_palindrome(1231), false); assert_eq!(largest_palindrome_product(2), 9009); } }
#[test] fn tests() { assert_eq!(is_palindrome(0), true); assert_eq!(is_palindrome(1), true);
random_line_split
problem4.rs
fn is_palindrome(num: i64) -> bool { let num_str = num.to_string(); let chars_to_check = num_str.len()/2; let mut iter = num_str.as_bytes().iter().take(chars_to_check); let mut rev_iter = num_str.as_bytes().iter().rev().take(chars_to_check); // HACK: In future rust versions, this can probably be replaced by // "return iter == rev_iter" loop { match (iter.next(), rev_iter.next()) { (Some(x), Some(y)) => if x!= y { return false }, _ => return true, } } } fn largest_palindrome_product(max_digits: u32) -> i64 { let mut highest_found = 0; for a in 1..10i64.pow(max_digits) { for b in 1..10i64.pow(max_digits) { let prod = a*b; if prod > highest_found && is_palindrome(prod) { highest_found = prod } } } return highest_found } pub fn main() { let answer = largest_palindrome_product(2); if answer!= 9009 { panic!("error: wrong answer"); } let answer = largest_palindrome_product(3); println!("largest palindrome made from the product of two 3-digit integers is {}", answer); } #[cfg(test)] mod test { use super::{is_palindrome, largest_palindrome_product}; #[test] fn tests()
}
{ assert_eq!(is_palindrome(0), true); assert_eq!(is_palindrome(1), true); assert_eq!(is_palindrome(10), false); assert_eq!(is_palindrome(11), true); assert_eq!(is_palindrome(12), false); assert_eq!(is_palindrome(22), true); assert_eq!(is_palindrome(33), true); assert_eq!(is_palindrome(333), true); assert_eq!(is_palindrome(131), true); assert_eq!(is_palindrome(1331), true); assert_eq!(is_palindrome(1231), false); assert_eq!(largest_palindrome_product(2), 9009); }
identifier_body
problem4.rs
fn is_palindrome(num: i64) -> bool { let num_str = num.to_string(); let chars_to_check = num_str.len()/2; let mut iter = num_str.as_bytes().iter().take(chars_to_check); let mut rev_iter = num_str.as_bytes().iter().rev().take(chars_to_check); // HACK: In future rust versions, this can probably be replaced by // "return iter == rev_iter" loop { match (iter.next(), rev_iter.next()) { (Some(x), Some(y)) => if x!= y { return false }, _ => return true, } } } fn
(max_digits: u32) -> i64 { let mut highest_found = 0; for a in 1..10i64.pow(max_digits) { for b in 1..10i64.pow(max_digits) { let prod = a*b; if prod > highest_found && is_palindrome(prod) { highest_found = prod } } } return highest_found } pub fn main() { let answer = largest_palindrome_product(2); if answer!= 9009 { panic!("error: wrong answer"); } let answer = largest_palindrome_product(3); println!("largest palindrome made from the product of two 3-digit integers is {}", answer); } #[cfg(test)] mod test { use super::{is_palindrome, largest_palindrome_product}; #[test] fn tests() { assert_eq!(is_palindrome(0), true); assert_eq!(is_palindrome(1), true); assert_eq!(is_palindrome(10), false); assert_eq!(is_palindrome(11), true); assert_eq!(is_palindrome(12), false); assert_eq!(is_palindrome(22), true); assert_eq!(is_palindrome(33), true); assert_eq!(is_palindrome(333), true); assert_eq!(is_palindrome(131), true); assert_eq!(is_palindrome(1331), true); assert_eq!(is_palindrome(1231), false); assert_eq!(largest_palindrome_product(2), 9009); } }
largest_palindrome_product
identifier_name
oestexturehalffloat.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::{self, OESTextureHalfFloatConstants}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; use super::{constants as webgl, ext_constants as gl, WebGLExtension, WebGLExtensions}; #[dom_struct] pub struct OESTextureHalfFloat { reflector_: Reflector, } impl OESTextureHalfFloat { fn new_inherited() -> OESTextureHalfFloat { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for OESTextureHalfFloat { type Extension = OESTextureHalfFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureHalfFloat> { reflect_dom_object(Box::new(OESTextureHalfFloat::new_inherited()), &*ctx.global(), OESTextureHalfFloatBinding::Wrap) } fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&["GL_OES_texture_half_float", "GL_ARB_half_float_pixel", "GL_NV_half_float", "GL_EXT_color_buffer_half_float"]) } fn enable(ext: &WebGLExtensions) { // Enable FLOAT text data type let hf = OESTextureHalfFloatConstants::HALF_FLOAT_OES; ext.enable_tex_type(hf); let needs_replace =!ext.supports_gl_extension("GL_OES_texture_float"); if needs_replace
} fn name() -> &'static str { "OES_texture_half_float" } }
{ // Special internal formats must be used to avoid clamped float values ext.add_effective_tex_internal_format(webgl::RGBA, hf, gl::RGBA16F); ext.add_effective_tex_internal_format(webgl::RGB, hf, gl::RGB16F); ext.add_effective_tex_internal_format(webgl::LUMINANCE, hf, gl::LUMINANCE16F_ARB); ext.add_effective_tex_internal_format(webgl::ALPHA, hf, gl::ALPHA16F_ARB); ext.add_effective_tex_internal_format(webgl::LUMINANCE_ALPHA, hf, gl::LUMINANCE_ALPHA16F_ARB); }
conditional_block
oestexturehalffloat.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::{self, OESTextureHalfFloatConstants}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; use super::{constants as webgl, ext_constants as gl, WebGLExtension, WebGLExtensions}; #[dom_struct] pub struct OESTextureHalfFloat { reflector_: Reflector, } impl OESTextureHalfFloat { fn new_inherited() -> OESTextureHalfFloat { Self { reflector_: Reflector::new(),
} } } impl WebGLExtension for OESTextureHalfFloat { type Extension = OESTextureHalfFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureHalfFloat> { reflect_dom_object(Box::new(OESTextureHalfFloat::new_inherited()), &*ctx.global(), OESTextureHalfFloatBinding::Wrap) } fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&["GL_OES_texture_half_float", "GL_ARB_half_float_pixel", "GL_NV_half_float", "GL_EXT_color_buffer_half_float"]) } fn enable(ext: &WebGLExtensions) { // Enable FLOAT text data type let hf = OESTextureHalfFloatConstants::HALF_FLOAT_OES; ext.enable_tex_type(hf); let needs_replace =!ext.supports_gl_extension("GL_OES_texture_float"); if needs_replace { // Special internal formats must be used to avoid clamped float values ext.add_effective_tex_internal_format(webgl::RGBA, hf, gl::RGBA16F); ext.add_effective_tex_internal_format(webgl::RGB, hf, gl::RGB16F); ext.add_effective_tex_internal_format(webgl::LUMINANCE, hf, gl::LUMINANCE16F_ARB); ext.add_effective_tex_internal_format(webgl::ALPHA, hf, gl::ALPHA16F_ARB); ext.add_effective_tex_internal_format(webgl::LUMINANCE_ALPHA, hf, gl::LUMINANCE_ALPHA16F_ARB); } } fn name() -> &'static str { "OES_texture_half_float" } }
random_line_split
oestexturehalffloat.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::{self, OESTextureHalfFloatConstants}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; use super::{constants as webgl, ext_constants as gl, WebGLExtension, WebGLExtensions}; #[dom_struct] pub struct OESTextureHalfFloat { reflector_: Reflector, } impl OESTextureHalfFloat { fn new_inherited() -> OESTextureHalfFloat { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for OESTextureHalfFloat { type Extension = OESTextureHalfFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureHalfFloat>
fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&["GL_OES_texture_half_float", "GL_ARB_half_float_pixel", "GL_NV_half_float", "GL_EXT_color_buffer_half_float"]) } fn enable(ext: &WebGLExtensions) { // Enable FLOAT text data type let hf = OESTextureHalfFloatConstants::HALF_FLOAT_OES; ext.enable_tex_type(hf); let needs_replace =!ext.supports_gl_extension("GL_OES_texture_float"); if needs_replace { // Special internal formats must be used to avoid clamped float values ext.add_effective_tex_internal_format(webgl::RGBA, hf, gl::RGBA16F); ext.add_effective_tex_internal_format(webgl::RGB, hf, gl::RGB16F); ext.add_effective_tex_internal_format(webgl::LUMINANCE, hf, gl::LUMINANCE16F_ARB); ext.add_effective_tex_internal_format(webgl::ALPHA, hf, gl::ALPHA16F_ARB); ext.add_effective_tex_internal_format(webgl::LUMINANCE_ALPHA, hf, gl::LUMINANCE_ALPHA16F_ARB); } } fn name() -> &'static str { "OES_texture_half_float" } }
{ reflect_dom_object(Box::new(OESTextureHalfFloat::new_inherited()), &*ctx.global(), OESTextureHalfFloatBinding::Wrap) }
identifier_body
oestexturehalffloat.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::{self, OESTextureHalfFloatConstants}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; use super::{constants as webgl, ext_constants as gl, WebGLExtension, WebGLExtensions}; #[dom_struct] pub struct OESTextureHalfFloat { reflector_: Reflector, } impl OESTextureHalfFloat { fn new_inherited() -> OESTextureHalfFloat { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for OESTextureHalfFloat { type Extension = OESTextureHalfFloat; fn
(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureHalfFloat> { reflect_dom_object(Box::new(OESTextureHalfFloat::new_inherited()), &*ctx.global(), OESTextureHalfFloatBinding::Wrap) } fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&["GL_OES_texture_half_float", "GL_ARB_half_float_pixel", "GL_NV_half_float", "GL_EXT_color_buffer_half_float"]) } fn enable(ext: &WebGLExtensions) { // Enable FLOAT text data type let hf = OESTextureHalfFloatConstants::HALF_FLOAT_OES; ext.enable_tex_type(hf); let needs_replace =!ext.supports_gl_extension("GL_OES_texture_float"); if needs_replace { // Special internal formats must be used to avoid clamped float values ext.add_effective_tex_internal_format(webgl::RGBA, hf, gl::RGBA16F); ext.add_effective_tex_internal_format(webgl::RGB, hf, gl::RGB16F); ext.add_effective_tex_internal_format(webgl::LUMINANCE, hf, gl::LUMINANCE16F_ARB); ext.add_effective_tex_internal_format(webgl::ALPHA, hf, gl::ALPHA16F_ARB); ext.add_effective_tex_internal_format(webgl::LUMINANCE_ALPHA, hf, gl::LUMINANCE_ALPHA16F_ARB); } } fn name() -> &'static str { "OES_texture_half_float" } }
new
identifier_name
deriving-eq-ord-boxed-slice.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
struct Foo(Box<[u8]>); pub fn main() { let a = Foo(Box::new([0, 1, 2])); let b = Foo(Box::new([0, 1, 2])); assert_eq!(a, b); println!("{}", a!= b); println!("{}", a < b); println!("{}", a <= b); println!("{}", a == b); println!("{}", a > b); println!("{}", a >= b); }
// except according to those terms. // run-pass #[derive(PartialEq, PartialOrd, Eq, Ord, Debug)]
random_line_split
deriving-eq-ord-boxed-slice.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. // run-pass #[derive(PartialEq, PartialOrd, Eq, Ord, Debug)] struct Foo(Box<[u8]>); pub fn
() { let a = Foo(Box::new([0, 1, 2])); let b = Foo(Box::new([0, 1, 2])); assert_eq!(a, b); println!("{}", a!= b); println!("{}", a < b); println!("{}", a <= b); println!("{}", a == b); println!("{}", a > b); println!("{}", a >= b); }
main
identifier_name
deriving-eq-ord-boxed-slice.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. // run-pass #[derive(PartialEq, PartialOrd, Eq, Ord, Debug)] struct Foo(Box<[u8]>); pub fn main()
{ let a = Foo(Box::new([0, 1, 2])); let b = Foo(Box::new([0, 1, 2])); assert_eq!(a, b); println!("{}", a != b); println!("{}", a < b); println!("{}", a <= b); println!("{}", a == b); println!("{}", a > b); println!("{}", a >= b); }
identifier_body
request.rs
//! The module that contains the request code. use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::io::Error; use std::str; use std::sync::mpsc::channel; use std::time::Duration; use Method; use curl::easy::{Easy, List}; use futures::{BoxFuture, failed, Future}; use response::Response; use tokio_core::reactor::Handle; use tokio_curl::Session; use url::Url; #[cfg(feature = "rustc-serialization")] use rustc_serialize; #[cfg(feature = "serde-serialization")] use serde; #[cfg(feature = "serde-serialization")] use serde_json; /// The default low byte rate threshold. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_LIMIT: u32 = 10; /// The default low speed time threshold in seconds. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_TIME: u32 = 10; /// The default redirect threshold for a single request. /// /// cURL will follow this many redirects by default before aborting /// the request. See [`Request::max_redirects`](struct.Request.html#method.max_redirects) /// for more information. pub const MAX_REDIRECTS: u32 = 10; /// Represents an HTTP request. /// /// While this can be used directly (and _must_ be for special HTTP verbs, it is /// preferred to use the [`get`](fn.get.html), [`post`](fn.post.html), etc. functions /// since they are shorter. pub struct Request { body: Option<Vec<u8>>, follow_redirects: bool, handle: Option<Easy>, headers: Vec<(String, String)>, lowspeed_limits: Option<(u32, Duration)>, max_redirects: u32, method: Method, params: Vec<(String, String)>, timeout: Option<Duration>, url: Url } impl Request { /// Creates a new instance of `Request`. pub fn new(url: &Url, method: Method) -> Self { Request { body: None, follow_redirects: true, handle: None, headers: Vec::new(), lowspeed_limits: Some((LOW_SPEED_LIMIT, Duration::from_secs(LOW_SPEED_TIME as u64))), max_redirects: MAX_REDIRECTS, method: method, params: Vec::new(), timeout: None, url: url.clone() } } /// Sets the body of the request as raw byte array. pub fn body<B: Into<Vec<u8>>>(mut self, body: B) -> Self { self.body = Some(body.into()); self } /// Sets the option whether to follow 3xx-redirects or not. /// /// Defaults to `true`. pub fn follow_redirects(mut self, follow: bool) -> Self { self.follow_redirects = follow; self } /// Adds an HTTP header to the request. pub fn header(mut self, name: &str, value: &str) -> Self { self.headers.push((name.to_owned(), value.to_owned())); self } /// Sets the given request headers. /// /// This overwrites all previously set headers. pub fn headers(mut self, headers: Vec<(String, String)>) -> Self { self.headers = headers; self } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "rustc-serialization")] pub fn json<T: rustc_serialize::Encodable>(self, body: &T) -> Self { self.set_json(rustc_serialize::json::encode(body).unwrap().into_bytes()) } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "serde-serialization")] pub fn json<T: serde::Serialize>(self, body: &T) -> Self { self.set_json(serde_json::to_vec(body).unwrap()) } /// Sets the thresholds which, when reached, aborts a download due to too /// low speeds. /// /// Pass 0 for either parameter to disable lowspeed limiting. /// /// ## Remarks /// `bytes` sets the minimum average amount of bytes transferred in `per_duration` /// time. If this number is not reached, cURL will abort the transfer because the transfer /// speed is too low. /// /// The values here default to [`LOW_SPEED_LIMIT`](constant.LOW_SPEED_LIMIT.html) and /// [`LOW_SPEED_TIME`](constant.LOW_SPEED_TIME.html). pub fn lowspeed_limit(mut self, bytes: u32, per_duration: Duration) -> Self { self.lowspeed_limits = if bytes > 0 && per_duration > Duration::from_secs(0) { Some((bytes, per_duration)) } else { None }; self } /// Sets the maximum amount of redirects cURL will follow when /// [`Request::follow_redirects`](#method.follow_redirects) is /// enabled. pub fn
(mut self, max_redirects: u32) -> Self { self.max_redirects = max_redirects; self } /// Adds a URL parameter to the request. pub fn param(mut self, name: &str, value: &str) -> Self { self.params.push((name.to_owned(), value.to_owned())); self } /// Sets the given request URL parameters. /// /// This overwrites all previously set parameters. pub fn params(mut self, params: Vec<(String, String)>) -> Self { self.params = params; self } /// Creates a new `Session` on the specified event loop to send the HTTP request through /// and returns a future that fires off the request, parses the response and resolves to /// a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send(self, h: Handle) -> BoxFuture<Response, Error> { self.send_with_session(&Session::new(h)) } /// Uses the given `Session` to send the HTTP request through and returns a future that /// fires off the request, parses the response and resolves to a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send_with_session(mut self, session: &Session) -> BoxFuture<Response, Error> { { let mut query_pairs = self.url.query_pairs_mut(); for (key, value) in self.params { query_pairs.append_pair(key.trim(), value.trim()); } } let headers = { let mut list = List::new(); for (key, value) in self.headers { list.append(&format!("{}: {}", key.trim(), value.trim())).expect("Failed to append header value to (native cURL) header list."); } list }; let mut easy = self.handle.unwrap_or_else(|| Easy::new()); let (header_tx, header_rx) = channel(); let (body_tx, body_rx) = channel(); let config_res = { // Make the borrow checker happy let body = self.body; let follow_redirects = self.follow_redirects; let lowspeed_limits = self.lowspeed_limits; let max_redirects = self.max_redirects; let method = self.method; let timeout = self.timeout; let url = self.url; let mut first_header = true; // We cannot use try! here, since we're dealing with futures, not with Results Ok(()) .and_then(|_| easy.accept_encoding("")) .and_then(|_| easy.custom_request(method.as_ref())) .and_then(|_| if follow_redirects { easy.follow_location(true) .and_then(|_| easy.max_redirections(max_redirects)) } else { Ok(()) }) .and_then(|_| easy.header_function(move |header| { match str::from_utf8(header) { Ok(s) => { let s = s.trim(); // Headers are \n-separated if!first_header && s.len() > 0 { // First header is HTTP status line, don't want that let _ = header_tx.send(s.to_owned()); } first_header = false; true }, Err(_) => false } })) .and_then(|_| easy.http_headers(headers)) .and_then(|_| if let Some((bytes, per_time)) = lowspeed_limits { easy.low_speed_limit(bytes) .and_then(|_| easy.low_speed_time(per_time)) } else { Ok(()) }) .and_then(|_| if method == Method::Head { easy.nobody(true) } else { Ok(()) }) .and_then(|_| if let Some(ref body) = body { easy.post_fields_copy(body) } else { Ok(()) }) .and_then(|_| if let Some(timeout) = timeout { easy.timeout(timeout) } else { Ok(()) }) .and_then(|_| easy.url(url.as_str())) .and_then(|_| easy.write_function(move |data| { let _ = body_tx.send(Vec::from(data)); Ok(data.len()) })) }; match config_res { Ok(_) => session.perform(easy) .map_err(|err| err.into_error()) .map(move |ez| { // In an ideal world where receiver_try_iter is stable // we could shorten this code to two lines. let body = { let mut b = Vec::new(); while let Ok(item) = body_rx.try_recv() { b.extend(item); } b }; let headers = { let mut h = Vec::new(); while let Ok(hdr) = header_rx.try_recv() { h.push(hdr); } h }; Response::new(ez, headers, body) }) .boxed(), Err(error) => failed(error.into()).boxed() } } /// Set the maximum time the request is allowed to take. /// /// Disabled by default in favor of [`lowspeed_limit`] pub fn timeout(mut self, duration: Duration) -> Self { self.timeout = Some(duration); self } /// Uses the given cURL handle in the request process reusing its resources /// and improving performance. /// /// This is solely a way to improve performance, it is not necessary to call /// this method prior to firing off the request. The easy handle will be created /// automatically if necessary. pub fn use_handle(mut self, handle: Easy) -> Self { self.handle = Some(handle); self } #[cfg(any(feature = "rustc-serialization", feature = "serde-serialization"))] fn set_json(mut self, body: Vec<u8>) -> Self { self.body = Some(body); self.header("Content-Type", "application/json") } } impl Debug for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let len = if let Some(ref body) = self.body { body.len() as isize } else { -1isize }; fmt.debug_struct(stringify!(Request)) .field("body_len", &len) .field("follow_redirects", &self.follow_redirects) .field("headers", &self.headers) .field("method", &self.method) .field("params", &self.params) .field("reuses_handle", &self.handle.is_some()) .field("url", &self.url) .finish() } } impl Display for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { write!(fmt, "{} {}", self.method, self.url) } }
max_redirects
identifier_name
request.rs
//! The module that contains the request code. use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::io::Error; use std::str; use std::sync::mpsc::channel; use std::time::Duration; use Method; use curl::easy::{Easy, List}; use futures::{BoxFuture, failed, Future}; use response::Response; use tokio_core::reactor::Handle; use tokio_curl::Session; use url::Url; #[cfg(feature = "rustc-serialization")] use rustc_serialize; #[cfg(feature = "serde-serialization")] use serde; #[cfg(feature = "serde-serialization")] use serde_json; /// The default low byte rate threshold. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_LIMIT: u32 = 10; /// The default low speed time threshold in seconds. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_TIME: u32 = 10; /// The default redirect threshold for a single request. /// /// cURL will follow this many redirects by default before aborting /// the request. See [`Request::max_redirects`](struct.Request.html#method.max_redirects) /// for more information. pub const MAX_REDIRECTS: u32 = 10; /// Represents an HTTP request. /// /// While this can be used directly (and _must_ be for special HTTP verbs, it is /// preferred to use the [`get`](fn.get.html), [`post`](fn.post.html), etc. functions /// since they are shorter. pub struct Request { body: Option<Vec<u8>>, follow_redirects: bool, handle: Option<Easy>, headers: Vec<(String, String)>, lowspeed_limits: Option<(u32, Duration)>, max_redirects: u32, method: Method, params: Vec<(String, String)>, timeout: Option<Duration>, url: Url } impl Request { /// Creates a new instance of `Request`. pub fn new(url: &Url, method: Method) -> Self { Request { body: None, follow_redirects: true, handle: None, headers: Vec::new(), lowspeed_limits: Some((LOW_SPEED_LIMIT, Duration::from_secs(LOW_SPEED_TIME as u64))), max_redirects: MAX_REDIRECTS, method: method, params: Vec::new(), timeout: None, url: url.clone() } } /// Sets the body of the request as raw byte array. pub fn body<B: Into<Vec<u8>>>(mut self, body: B) -> Self { self.body = Some(body.into()); self } /// Sets the option whether to follow 3xx-redirects or not. /// /// Defaults to `true`. pub fn follow_redirects(mut self, follow: bool) -> Self { self.follow_redirects = follow; self } /// Adds an HTTP header to the request. pub fn header(mut self, name: &str, value: &str) -> Self { self.headers.push((name.to_owned(), value.to_owned())); self } /// Sets the given request headers. /// /// This overwrites all previously set headers. pub fn headers(mut self, headers: Vec<(String, String)>) -> Self { self.headers = headers; self } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "rustc-serialization")] pub fn json<T: rustc_serialize::Encodable>(self, body: &T) -> Self { self.set_json(rustc_serialize::json::encode(body).unwrap().into_bytes()) } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "serde-serialization")] pub fn json<T: serde::Serialize>(self, body: &T) -> Self { self.set_json(serde_json::to_vec(body).unwrap()) } /// Sets the thresholds which, when reached, aborts a download due to too /// low speeds. /// /// Pass 0 for either parameter to disable lowspeed limiting. /// /// ## Remarks /// `bytes` sets the minimum average amount of bytes transferred in `per_duration` /// time. If this number is not reached, cURL will abort the transfer because the transfer /// speed is too low. /// /// The values here default to [`LOW_SPEED_LIMIT`](constant.LOW_SPEED_LIMIT.html) and /// [`LOW_SPEED_TIME`](constant.LOW_SPEED_TIME.html). pub fn lowspeed_limit(mut self, bytes: u32, per_duration: Duration) -> Self { self.lowspeed_limits = if bytes > 0 && per_duration > Duration::from_secs(0) { Some((bytes, per_duration)) } else { None }; self } /// Sets the maximum amount of redirects cURL will follow when /// [`Request::follow_redirects`](#method.follow_redirects) is /// enabled. pub fn max_redirects(mut self, max_redirects: u32) -> Self { self.max_redirects = max_redirects; self } /// Adds a URL parameter to the request. pub fn param(mut self, name: &str, value: &str) -> Self { self.params.push((name.to_owned(), value.to_owned())); self } /// Sets the given request URL parameters. /// /// This overwrites all previously set parameters. pub fn params(mut self, params: Vec<(String, String)>) -> Self { self.params = params; self } /// Creates a new `Session` on the specified event loop to send the HTTP request through /// and returns a future that fires off the request, parses the response and resolves to /// a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send(self, h: Handle) -> BoxFuture<Response, Error> { self.send_with_session(&Session::new(h)) } /// Uses the given `Session` to send the HTTP request through and returns a future that /// fires off the request, parses the response and resolves to a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send_with_session(mut self, session: &Session) -> BoxFuture<Response, Error> { { let mut query_pairs = self.url.query_pairs_mut(); for (key, value) in self.params { query_pairs.append_pair(key.trim(), value.trim()); } } let headers = { let mut list = List::new(); for (key, value) in self.headers { list.append(&format!("{}: {}", key.trim(), value.trim())).expect("Failed to append header value to (native cURL) header list."); } list }; let mut easy = self.handle.unwrap_or_else(|| Easy::new()); let (header_tx, header_rx) = channel(); let (body_tx, body_rx) = channel(); let config_res = { // Make the borrow checker happy let body = self.body; let follow_redirects = self.follow_redirects; let lowspeed_limits = self.lowspeed_limits; let max_redirects = self.max_redirects; let method = self.method; let timeout = self.timeout; let url = self.url; let mut first_header = true; // We cannot use try! here, since we're dealing with futures, not with Results Ok(()) .and_then(|_| easy.accept_encoding("")) .and_then(|_| easy.custom_request(method.as_ref())) .and_then(|_| if follow_redirects { easy.follow_location(true) .and_then(|_| easy.max_redirections(max_redirects)) } else { Ok(()) }) .and_then(|_| easy.header_function(move |header| { match str::from_utf8(header) { Ok(s) => { let s = s.trim(); // Headers are \n-separated if!first_header && s.len() > 0 { // First header is HTTP status line, don't want that let _ = header_tx.send(s.to_owned()); } first_header = false; true }, Err(_) => false } })) .and_then(|_| easy.http_headers(headers)) .and_then(|_| if let Some((bytes, per_time)) = lowspeed_limits { easy.low_speed_limit(bytes) .and_then(|_| easy.low_speed_time(per_time)) } else { Ok(()) }) .and_then(|_| if method == Method::Head { easy.nobody(true) } else { Ok(()) }) .and_then(|_| if let Some(ref body) = body { easy.post_fields_copy(body) } else { Ok(()) }) .and_then(|_| if let Some(timeout) = timeout
else { Ok(()) }) .and_then(|_| easy.url(url.as_str())) .and_then(|_| easy.write_function(move |data| { let _ = body_tx.send(Vec::from(data)); Ok(data.len()) })) }; match config_res { Ok(_) => session.perform(easy) .map_err(|err| err.into_error()) .map(move |ez| { // In an ideal world where receiver_try_iter is stable // we could shorten this code to two lines. let body = { let mut b = Vec::new(); while let Ok(item) = body_rx.try_recv() { b.extend(item); } b }; let headers = { let mut h = Vec::new(); while let Ok(hdr) = header_rx.try_recv() { h.push(hdr); } h }; Response::new(ez, headers, body) }) .boxed(), Err(error) => failed(error.into()).boxed() } } /// Set the maximum time the request is allowed to take. /// /// Disabled by default in favor of [`lowspeed_limit`] pub fn timeout(mut self, duration: Duration) -> Self { self.timeout = Some(duration); self } /// Uses the given cURL handle in the request process reusing its resources /// and improving performance. /// /// This is solely a way to improve performance, it is not necessary to call /// this method prior to firing off the request. The easy handle will be created /// automatically if necessary. pub fn use_handle(mut self, handle: Easy) -> Self { self.handle = Some(handle); self } #[cfg(any(feature = "rustc-serialization", feature = "serde-serialization"))] fn set_json(mut self, body: Vec<u8>) -> Self { self.body = Some(body); self.header("Content-Type", "application/json") } } impl Debug for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let len = if let Some(ref body) = self.body { body.len() as isize } else { -1isize }; fmt.debug_struct(stringify!(Request)) .field("body_len", &len) .field("follow_redirects", &self.follow_redirects) .field("headers", &self.headers) .field("method", &self.method) .field("params", &self.params) .field("reuses_handle", &self.handle.is_some()) .field("url", &self.url) .finish() } } impl Display for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { write!(fmt, "{} {}", self.method, self.url) } }
{ easy.timeout(timeout) }
conditional_block
request.rs
//! The module that contains the request code. use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::io::Error; use std::str; use std::sync::mpsc::channel; use std::time::Duration; use Method; use curl::easy::{Easy, List}; use futures::{BoxFuture, failed, Future}; use response::Response; use tokio_core::reactor::Handle; use tokio_curl::Session; use url::Url; #[cfg(feature = "rustc-serialization")] use rustc_serialize; #[cfg(feature = "serde-serialization")] use serde; #[cfg(feature = "serde-serialization")] use serde_json; /// The default low byte rate threshold. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_LIMIT: u32 = 10; /// The default low speed time threshold in seconds. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_TIME: u32 = 10; /// The default redirect threshold for a single request. /// /// cURL will follow this many redirects by default before aborting /// the request. See [`Request::max_redirects`](struct.Request.html#method.max_redirects) /// for more information. pub const MAX_REDIRECTS: u32 = 10; /// Represents an HTTP request. /// /// While this can be used directly (and _must_ be for special HTTP verbs, it is /// preferred to use the [`get`](fn.get.html), [`post`](fn.post.html), etc. functions /// since they are shorter. pub struct Request { body: Option<Vec<u8>>, follow_redirects: bool, handle: Option<Easy>, headers: Vec<(String, String)>, lowspeed_limits: Option<(u32, Duration)>, max_redirects: u32, method: Method, params: Vec<(String, String)>, timeout: Option<Duration>, url: Url } impl Request { /// Creates a new instance of `Request`. pub fn new(url: &Url, method: Method) -> Self { Request { body: None, follow_redirects: true, handle: None, headers: Vec::new(), lowspeed_limits: Some((LOW_SPEED_LIMIT, Duration::from_secs(LOW_SPEED_TIME as u64))), max_redirects: MAX_REDIRECTS, method: method, params: Vec::new(), timeout: None, url: url.clone() } } /// Sets the body of the request as raw byte array. pub fn body<B: Into<Vec<u8>>>(mut self, body: B) -> Self { self.body = Some(body.into()); self } /// Sets the option whether to follow 3xx-redirects or not. /// /// Defaults to `true`. pub fn follow_redirects(mut self, follow: bool) -> Self { self.follow_redirects = follow; self } /// Adds an HTTP header to the request. pub fn header(mut self, name: &str, value: &str) -> Self { self.headers.push((name.to_owned(), value.to_owned())); self } /// Sets the given request headers. /// /// This overwrites all previously set headers. pub fn headers(mut self, headers: Vec<(String, String)>) -> Self { self.headers = headers; self } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "rustc-serialization")] pub fn json<T: rustc_serialize::Encodable>(self, body: &T) -> Self { self.set_json(rustc_serialize::json::encode(body).unwrap().into_bytes()) } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "serde-serialization")] pub fn json<T: serde::Serialize>(self, body: &T) -> Self
/// Sets the thresholds which, when reached, aborts a download due to too /// low speeds. /// /// Pass 0 for either parameter to disable lowspeed limiting. /// /// ## Remarks /// `bytes` sets the minimum average amount of bytes transferred in `per_duration` /// time. If this number is not reached, cURL will abort the transfer because the transfer /// speed is too low. /// /// The values here default to [`LOW_SPEED_LIMIT`](constant.LOW_SPEED_LIMIT.html) and /// [`LOW_SPEED_TIME`](constant.LOW_SPEED_TIME.html). pub fn lowspeed_limit(mut self, bytes: u32, per_duration: Duration) -> Self { self.lowspeed_limits = if bytes > 0 && per_duration > Duration::from_secs(0) { Some((bytes, per_duration)) } else { None }; self } /// Sets the maximum amount of redirects cURL will follow when /// [`Request::follow_redirects`](#method.follow_redirects) is /// enabled. pub fn max_redirects(mut self, max_redirects: u32) -> Self { self.max_redirects = max_redirects; self } /// Adds a URL parameter to the request. pub fn param(mut self, name: &str, value: &str) -> Self { self.params.push((name.to_owned(), value.to_owned())); self } /// Sets the given request URL parameters. /// /// This overwrites all previously set parameters. pub fn params(mut self, params: Vec<(String, String)>) -> Self { self.params = params; self } /// Creates a new `Session` on the specified event loop to send the HTTP request through /// and returns a future that fires off the request, parses the response and resolves to /// a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send(self, h: Handle) -> BoxFuture<Response, Error> { self.send_with_session(&Session::new(h)) } /// Uses the given `Session` to send the HTTP request through and returns a future that /// fires off the request, parses the response and resolves to a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send_with_session(mut self, session: &Session) -> BoxFuture<Response, Error> { { let mut query_pairs = self.url.query_pairs_mut(); for (key, value) in self.params { query_pairs.append_pair(key.trim(), value.trim()); } } let headers = { let mut list = List::new(); for (key, value) in self.headers { list.append(&format!("{}: {}", key.trim(), value.trim())).expect("Failed to append header value to (native cURL) header list."); } list }; let mut easy = self.handle.unwrap_or_else(|| Easy::new()); let (header_tx, header_rx) = channel(); let (body_tx, body_rx) = channel(); let config_res = { // Make the borrow checker happy let body = self.body; let follow_redirects = self.follow_redirects; let lowspeed_limits = self.lowspeed_limits; let max_redirects = self.max_redirects; let method = self.method; let timeout = self.timeout; let url = self.url; let mut first_header = true; // We cannot use try! here, since we're dealing with futures, not with Results Ok(()) .and_then(|_| easy.accept_encoding("")) .and_then(|_| easy.custom_request(method.as_ref())) .and_then(|_| if follow_redirects { easy.follow_location(true) .and_then(|_| easy.max_redirections(max_redirects)) } else { Ok(()) }) .and_then(|_| easy.header_function(move |header| { match str::from_utf8(header) { Ok(s) => { let s = s.trim(); // Headers are \n-separated if!first_header && s.len() > 0 { // First header is HTTP status line, don't want that let _ = header_tx.send(s.to_owned()); } first_header = false; true }, Err(_) => false } })) .and_then(|_| easy.http_headers(headers)) .and_then(|_| if let Some((bytes, per_time)) = lowspeed_limits { easy.low_speed_limit(bytes) .and_then(|_| easy.low_speed_time(per_time)) } else { Ok(()) }) .and_then(|_| if method == Method::Head { easy.nobody(true) } else { Ok(()) }) .and_then(|_| if let Some(ref body) = body { easy.post_fields_copy(body) } else { Ok(()) }) .and_then(|_| if let Some(timeout) = timeout { easy.timeout(timeout) } else { Ok(()) }) .and_then(|_| easy.url(url.as_str())) .and_then(|_| easy.write_function(move |data| { let _ = body_tx.send(Vec::from(data)); Ok(data.len()) })) }; match config_res { Ok(_) => session.perform(easy) .map_err(|err| err.into_error()) .map(move |ez| { // In an ideal world where receiver_try_iter is stable // we could shorten this code to two lines. let body = { let mut b = Vec::new(); while let Ok(item) = body_rx.try_recv() { b.extend(item); } b }; let headers = { let mut h = Vec::new(); while let Ok(hdr) = header_rx.try_recv() { h.push(hdr); } h }; Response::new(ez, headers, body) }) .boxed(), Err(error) => failed(error.into()).boxed() } } /// Set the maximum time the request is allowed to take. /// /// Disabled by default in favor of [`lowspeed_limit`] pub fn timeout(mut self, duration: Duration) -> Self { self.timeout = Some(duration); self } /// Uses the given cURL handle in the request process reusing its resources /// and improving performance. /// /// This is solely a way to improve performance, it is not necessary to call /// this method prior to firing off the request. The easy handle will be created /// automatically if necessary. pub fn use_handle(mut self, handle: Easy) -> Self { self.handle = Some(handle); self } #[cfg(any(feature = "rustc-serialization", feature = "serde-serialization"))] fn set_json(mut self, body: Vec<u8>) -> Self { self.body = Some(body); self.header("Content-Type", "application/json") } } impl Debug for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let len = if let Some(ref body) = self.body { body.len() as isize } else { -1isize }; fmt.debug_struct(stringify!(Request)) .field("body_len", &len) .field("follow_redirects", &self.follow_redirects) .field("headers", &self.headers) .field("method", &self.method) .field("params", &self.params) .field("reuses_handle", &self.handle.is_some()) .field("url", &self.url) .finish() } } impl Display for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { write!(fmt, "{} {}", self.method, self.url) } }
{ self.set_json(serde_json::to_vec(body).unwrap()) }
identifier_body
request.rs
//! The module that contains the request code. use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::io::Error; use std::str; use std::sync::mpsc::channel; use std::time::Duration; use Method; use curl::easy::{Easy, List}; use futures::{BoxFuture, failed, Future}; use response::Response; use tokio_core::reactor::Handle; use tokio_curl::Session; use url::Url; #[cfg(feature = "rustc-serialization")] use rustc_serialize; #[cfg(feature = "serde-serialization")] use serde; #[cfg(feature = "serde-serialization")] use serde_json; /// The default low byte rate threshold. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_LIMIT: u32 = 10; /// The default low speed time threshold in seconds. /// /// See [`Request::lowspeed_limit`](struct.Request.html#method.lowspeed_limit) /// for more information. pub const LOW_SPEED_TIME: u32 = 10; /// The default redirect threshold for a single request. /// /// cURL will follow this many redirects by default before aborting /// the request. See [`Request::max_redirects`](struct.Request.html#method.max_redirects) /// for more information. pub const MAX_REDIRECTS: u32 = 10; /// Represents an HTTP request. /// /// While this can be used directly (and _must_ be for special HTTP verbs, it is /// preferred to use the [`get`](fn.get.html), [`post`](fn.post.html), etc. functions /// since they are shorter. pub struct Request { body: Option<Vec<u8>>, follow_redirects: bool, handle: Option<Easy>, headers: Vec<(String, String)>, lowspeed_limits: Option<(u32, Duration)>, max_redirects: u32, method: Method, params: Vec<(String, String)>, timeout: Option<Duration>, url: Url } impl Request { /// Creates a new instance of `Request`. pub fn new(url: &Url, method: Method) -> Self { Request { body: None, follow_redirects: true, handle: None, headers: Vec::new(), lowspeed_limits: Some((LOW_SPEED_LIMIT, Duration::from_secs(LOW_SPEED_TIME as u64))), max_redirects: MAX_REDIRECTS, method: method, params: Vec::new(), timeout: None, url: url.clone() } } /// Sets the body of the request as raw byte array. pub fn body<B: Into<Vec<u8>>>(mut self, body: B) -> Self { self.body = Some(body.into()); self } /// Sets the option whether to follow 3xx-redirects or not. /// /// Defaults to `true`. pub fn follow_redirects(mut self, follow: bool) -> Self { self.follow_redirects = follow; self } /// Adds an HTTP header to the request. pub fn header(mut self, name: &str, value: &str) -> Self { self.headers.push((name.to_owned(), value.to_owned())); self } /// Sets the given request headers. /// /// This overwrites all previously set headers. pub fn headers(mut self, headers: Vec<(String, String)>) -> Self { self.headers = headers; self } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "rustc-serialization")] pub fn json<T: rustc_serialize::Encodable>(self, body: &T) -> Self { self.set_json(rustc_serialize::json::encode(body).unwrap().into_bytes()) } /// Serializes the given object to JSON and uses that as the request body. /// Also automatically sets the `Content-Type` to `application/json`. /// /// ## Panics /// Panics if serialization is not successful. #[cfg(feature = "serde-serialization")] pub fn json<T: serde::Serialize>(self, body: &T) -> Self { self.set_json(serde_json::to_vec(body).unwrap()) } /// Sets the thresholds which, when reached, aborts a download due to too /// low speeds. /// /// Pass 0 for either parameter to disable lowspeed limiting. /// /// ## Remarks /// `bytes` sets the minimum average amount of bytes transferred in `per_duration` /// time. If this number is not reached, cURL will abort the transfer because the transfer /// speed is too low. /// /// The values here default to [`LOW_SPEED_LIMIT`](constant.LOW_SPEED_LIMIT.html) and /// [`LOW_SPEED_TIME`](constant.LOW_SPEED_TIME.html). pub fn lowspeed_limit(mut self, bytes: u32, per_duration: Duration) -> Self { self.lowspeed_limits = if bytes > 0 && per_duration > Duration::from_secs(0) { Some((bytes, per_duration)) } else { None }; self } /// Sets the maximum amount of redirects cURL will follow when /// [`Request::follow_redirects`](#method.follow_redirects) is /// enabled. pub fn max_redirects(mut self, max_redirects: u32) -> Self { self.max_redirects = max_redirects; self } /// Adds a URL parameter to the request. pub fn param(mut self, name: &str, value: &str) -> Self { self.params.push((name.to_owned(), value.to_owned())); self } /// Sets the given request URL parameters. /// /// This overwrites all previously set parameters. pub fn params(mut self, params: Vec<(String, String)>) -> Self { self.params = params; self } /// Creates a new `Session` on the specified event loop to send the HTTP request through /// and returns a future that fires off the request, parses the response and resolves to /// a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send(self, h: Handle) -> BoxFuture<Response, Error> { self.send_with_session(&Session::new(h)) } /// Uses the given `Session` to send the HTTP request through and returns a future that /// fires off the request, parses the response and resolves to a `Response`-struct on success. /// /// ## Panics /// Panics in case of native exceptions in cURL. pub fn send_with_session(mut self, session: &Session) -> BoxFuture<Response, Error> { { let mut query_pairs = self.url.query_pairs_mut(); for (key, value) in self.params { query_pairs.append_pair(key.trim(), value.trim()); } } let headers = { let mut list = List::new(); for (key, value) in self.headers { list.append(&format!("{}: {}", key.trim(), value.trim())).expect("Failed to append header value to (native cURL) header list."); } list }; let mut easy = self.handle.unwrap_or_else(|| Easy::new()); let (header_tx, header_rx) = channel(); let (body_tx, body_rx) = channel(); let config_res = { // Make the borrow checker happy let body = self.body; let follow_redirects = self.follow_redirects; let lowspeed_limits = self.lowspeed_limits; let max_redirects = self.max_redirects; let method = self.method; let timeout = self.timeout; let url = self.url; let mut first_header = true; // We cannot use try! here, since we're dealing with futures, not with Results Ok(()) .and_then(|_| easy.accept_encoding(""))
.and_then(|_| if follow_redirects { easy.follow_location(true) .and_then(|_| easy.max_redirections(max_redirects)) } else { Ok(()) }) .and_then(|_| easy.header_function(move |header| { match str::from_utf8(header) { Ok(s) => { let s = s.trim(); // Headers are \n-separated if!first_header && s.len() > 0 { // First header is HTTP status line, don't want that let _ = header_tx.send(s.to_owned()); } first_header = false; true }, Err(_) => false } })) .and_then(|_| easy.http_headers(headers)) .and_then(|_| if let Some((bytes, per_time)) = lowspeed_limits { easy.low_speed_limit(bytes) .and_then(|_| easy.low_speed_time(per_time)) } else { Ok(()) }) .and_then(|_| if method == Method::Head { easy.nobody(true) } else { Ok(()) }) .and_then(|_| if let Some(ref body) = body { easy.post_fields_copy(body) } else { Ok(()) }) .and_then(|_| if let Some(timeout) = timeout { easy.timeout(timeout) } else { Ok(()) }) .and_then(|_| easy.url(url.as_str())) .and_then(|_| easy.write_function(move |data| { let _ = body_tx.send(Vec::from(data)); Ok(data.len()) })) }; match config_res { Ok(_) => session.perform(easy) .map_err(|err| err.into_error()) .map(move |ez| { // In an ideal world where receiver_try_iter is stable // we could shorten this code to two lines. let body = { let mut b = Vec::new(); while let Ok(item) = body_rx.try_recv() { b.extend(item); } b }; let headers = { let mut h = Vec::new(); while let Ok(hdr) = header_rx.try_recv() { h.push(hdr); } h }; Response::new(ez, headers, body) }) .boxed(), Err(error) => failed(error.into()).boxed() } } /// Set the maximum time the request is allowed to take. /// /// Disabled by default in favor of [`lowspeed_limit`] pub fn timeout(mut self, duration: Duration) -> Self { self.timeout = Some(duration); self } /// Uses the given cURL handle in the request process reusing its resources /// and improving performance. /// /// This is solely a way to improve performance, it is not necessary to call /// this method prior to firing off the request. The easy handle will be created /// automatically if necessary. pub fn use_handle(mut self, handle: Easy) -> Self { self.handle = Some(handle); self } #[cfg(any(feature = "rustc-serialization", feature = "serde-serialization"))] fn set_json(mut self, body: Vec<u8>) -> Self { self.body = Some(body); self.header("Content-Type", "application/json") } } impl Debug for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let len = if let Some(ref body) = self.body { body.len() as isize } else { -1isize }; fmt.debug_struct(stringify!(Request)) .field("body_len", &len) .field("follow_redirects", &self.follow_redirects) .field("headers", &self.headers) .field("method", &self.method) .field("params", &self.params) .field("reuses_handle", &self.handle.is_some()) .field("url", &self.url) .finish() } } impl Display for Request { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { write!(fmt, "{} {}", self.method, self.url) } }
.and_then(|_| easy.custom_request(method.as_ref()))
random_line_split
rc_slice.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 std::fmt; use std::ops::Deref; use std::rc::Rc; use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult, HashStable}; #[derive(Clone)] pub struct RcSlice<T> { data: Rc<Box<[T]>>, offset: u32, len: u32, } impl<T> RcSlice<T> { pub fn
(vec: Vec<T>) -> Self { RcSlice { offset: 0, len: vec.len() as u32, data: Rc::new(vec.into_boxed_slice()), } } } impl<T> Deref for RcSlice<T> { type Target = [T]; fn deref(&self) -> &[T] { &self.data[self.offset as usize.. (self.offset + self.len) as usize] } } impl<T: fmt::Debug> fmt::Debug for RcSlice<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.deref(), f) } } impl<CTX, T> HashStable<CTX> for RcSlice<T> where T: HashStable<CTX> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut CTX, hasher: &mut StableHasher<W>) { (**self).hash_stable(hcx, hasher); } }
new
identifier_name
rc_slice.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 std::fmt; use std::ops::Deref; use std::rc::Rc; use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult, HashStable}; #[derive(Clone)] pub struct RcSlice<T> { data: Rc<Box<[T]>>, offset: u32, len: u32, } impl<T> RcSlice<T> { pub fn new(vec: Vec<T>) -> Self { RcSlice { offset: 0, len: vec.len() as u32, data: Rc::new(vec.into_boxed_slice()), } } } impl<T> Deref for RcSlice<T> { type Target = [T]; fn deref(&self) -> &[T] { &self.data[self.offset as usize.. (self.offset + self.len) as usize] } } impl<T: fmt::Debug> fmt::Debug for RcSlice<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.deref(), f)
{ fn hash_stable<W: StableHasherResult>(&self, hcx: &mut CTX, hasher: &mut StableHasher<W>) { (**self).hash_stable(hcx, hasher); } }
} } impl<CTX, T> HashStable<CTX> for RcSlice<T> where T: HashStable<CTX>
random_line_split
rc_slice.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 std::fmt; use std::ops::Deref; use std::rc::Rc; use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult, HashStable}; #[derive(Clone)] pub struct RcSlice<T> { data: Rc<Box<[T]>>, offset: u32, len: u32, } impl<T> RcSlice<T> { pub fn new(vec: Vec<T>) -> Self { RcSlice { offset: 0, len: vec.len() as u32, data: Rc::new(vec.into_boxed_slice()), } } } impl<T> Deref for RcSlice<T> { type Target = [T]; fn deref(&self) -> &[T] { &self.data[self.offset as usize.. (self.offset + self.len) as usize] } } impl<T: fmt::Debug> fmt::Debug for RcSlice<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} impl<CTX, T> HashStable<CTX> for RcSlice<T> where T: HashStable<CTX> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut CTX, hasher: &mut StableHasher<W>) { (**self).hash_stable(hcx, hasher); } }
{ fmt::Debug::fmt(self.deref(), f) }
identifier_body
regions-fn-subtyping.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn of<'a,T>() -> |T|:'a { fail!(); } fn subtype<T>(x: |T|)
fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::< <'a>|&'a T|>( of::< <'a>|&'a T|>()); subtype::< <'a>|&'a T|>( of::< <'b>|&'b T|>()); subtype::< <'b>|&'b T|>( of::<|&'x T|>()); subtype::<|&'x T|>( of::< <'b>|&'b T|>()); //~ ERROR mismatched types subtype::< <'a,'b>|&'a T, &'b T|>( of::< <'a>|&'a T, &'a T|>()); subtype::< <'a>|&'a T, &'a T|>( of::< <'a,'b>|&'a T, &'b T|>()); //~ ERROR mismatched types subtype::< <'a,'b>|&'a T, &'b T|>( of::<|&'x T, &'y T|>()); subtype::<|&'x T, &'y T|>( of::< <'a,'b>|&'a T, &'b T|>()); //~ ERROR mismatched types } fn main() {}
{ fail!(); }
identifier_body
regions-fn-subtyping.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn
<'a,T>() -> |T|:'a { fail!(); } fn subtype<T>(x: |T|) { fail!(); } fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::< <'a>|&'a T|>( of::< <'a>|&'a T|>()); subtype::< <'a>|&'a T|>( of::< <'b>|&'b T|>()); subtype::< <'b>|&'b T|>( of::<|&'x T|>()); subtype::<|&'x T|>( of::< <'b>|&'b T|>()); //~ ERROR mismatched types subtype::< <'a,'b>|&'a T, &'b T|>( of::< <'a>|&'a T, &'a T|>()); subtype::< <'a>|&'a T, &'a T|>( of::< <'a,'b>|&'a T, &'b T|>()); //~ ERROR mismatched types subtype::< <'a,'b>|&'a T, &'b T|>( of::<|&'x T, &'y T|>()); subtype::<|&'x T, &'y T|>( of::< <'a,'b>|&'a T, &'b T|>()); //~ ERROR mismatched types } fn main() {}
of
identifier_name
regions-fn-subtyping.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::< <'a>|&'a T|>( of::< <'a>|&'a T|>()); subtype::< <'a>|&'a T|>( of::< <'b>|&'b T|>()); subtype::< <'b>|&'b T|>( of::<|&'x T|>()); subtype::<|&'x T|>( of::< <'b>|&'b T|>()); //~ ERROR mismatched types subtype::< <'a,'b>|&'a T, &'b T|>( of::< <'a>|&'a T, &'a T|>()); subtype::< <'a>|&'a T, &'a T|>( of::< <'a,'b>|&'a T, &'b T|>()); //~ ERROR mismatched types subtype::< <'a,'b>|&'a T, &'b T|>( of::<|&'x T, &'y T|>()); subtype::<|&'x T, &'y T|>( of::< <'a,'b>|&'a T, &'b T|>()); //~ ERROR mismatched types } fn main() {}
fn of<'a,T>() -> |T|:'a { fail!(); } fn subtype<T>(x: |T|) { fail!(); }
random_line_split
size.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/. */ //! Generic type for CSS properties that are composed by two dimensions. use crate::parser::ParserContext; use crate::Zero; use cssparser::Parser; use std::fmt::{self, Write}; use style_traits::{CssWriter, ParseError, ToCss}; /// A generic size, for `border-*-radius` longhand properties, or /// `border-spacing`. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToAnimatedValue, ToComputedValue, ToResolvedValue, ToShmem, )] #[allow(missing_docs)] #[repr(C)] pub struct Size2D<L> { pub width: L, pub height: L, } impl<L> Size2D<L> { #[inline] /// Create a new `Size2D` for an area of given width and height. pub fn new(width: L, height: L) -> Self { Self { width, height } } /// Returns the width component. pub fn width(&self) -> &L { &self.width } /// Returns the height component. pub fn height(&self) -> &L { &self.height } /// Parse a `Size2D` with a given parsing function. pub fn parse_with<'i, 't, F>( context: &ParserContext, input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Self, ParseError<'i>> where L: Clone, F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<L, ParseError<'i>>,
} impl<L> ToCss for Size2D<L> where L: ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.width.to_css(dest)?; if self.height!= self.width { dest.write_str(" ")?; self.height.to_css(dest)?; } Ok(()) } } impl<L: Zero> Zero for Size2D<L> { fn zero() -> Self { Self::new(L::zero(), L::zero()) } fn is_zero(&self) -> bool { self.width.is_zero() && self.height.is_zero() } }
{ let first = parse_one(context, input)?; let second = input .try_parse(|i| parse_one(context, i)) .unwrap_or_else(|_| first.clone()); Ok(Self::new(first, second)) }
identifier_body
size.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/. */ //! Generic type for CSS properties that are composed by two dimensions. use crate::parser::ParserContext; use crate::Zero; use cssparser::Parser; use std::fmt::{self, Write}; use style_traits::{CssWriter, ParseError, ToCss}; /// A generic size, for `border-*-radius` longhand properties, or /// `border-spacing`. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToAnimatedValue, ToComputedValue, ToResolvedValue, ToShmem, )] #[allow(missing_docs)] #[repr(C)] pub struct Size2D<L> { pub width: L, pub height: L, } impl<L> Size2D<L> { #[inline] /// Create a new `Size2D` for an area of given width and height. pub fn new(width: L, height: L) -> Self { Self { width, height } } /// Returns the width component. pub fn width(&self) -> &L { &self.width } /// Returns the height component. pub fn height(&self) -> &L { &self.height } /// Parse a `Size2D` with a given parsing function. pub fn parse_with<'i, 't, F>( context: &ParserContext, input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Self, ParseError<'i>> where L: Clone, F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<L, ParseError<'i>>, { let first = parse_one(context, input)?; let second = input .try_parse(|i| parse_one(context, i)) .unwrap_or_else(|_| first.clone()); Ok(Self::new(first, second)) } } impl<L> ToCss for Size2D<L> where L: ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.width.to_css(dest)?; if self.height!= self.width
Ok(()) } } impl<L: Zero> Zero for Size2D<L> { fn zero() -> Self { Self::new(L::zero(), L::zero()) } fn is_zero(&self) -> bool { self.width.is_zero() && self.height.is_zero() } }
{ dest.write_str(" ")?; self.height.to_css(dest)?; }
conditional_block
size.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/. */ //! Generic type for CSS properties that are composed by two dimensions. use crate::parser::ParserContext; use crate::Zero; use cssparser::Parser; use std::fmt::{self, Write}; use style_traits::{CssWriter, ParseError, ToCss}; /// A generic size, for `border-*-radius` longhand properties, or /// `border-spacing`. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToAnimatedValue, ToComputedValue, ToResolvedValue, ToShmem, )] #[allow(missing_docs)] #[repr(C)] pub struct Size2D<L> { pub width: L, pub height: L, } impl<L> Size2D<L> { #[inline] /// Create a new `Size2D` for an area of given width and height. pub fn new(width: L, height: L) -> Self { Self { width, height } } /// Returns the width component. pub fn width(&self) -> &L { &self.width } /// Returns the height component. pub fn height(&self) -> &L { &self.height } /// Parse a `Size2D` with a given parsing function. pub fn parse_with<'i, 't, F>( context: &ParserContext, input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Self, ParseError<'i>> where L: Clone, F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<L, ParseError<'i>>, { let first = parse_one(context, input)?; let second = input .try_parse(|i| parse_one(context, i)) .unwrap_or_else(|_| first.clone()); Ok(Self::new(first, second)) } } impl<L> ToCss for Size2D<L> where L: ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.width.to_css(dest)?; if self.height!= self.width { dest.write_str(" ")?; self.height.to_css(dest)?; } Ok(()) } } impl<L: Zero> Zero for Size2D<L> { fn
() -> Self { Self::new(L::zero(), L::zero()) } fn is_zero(&self) -> bool { self.width.is_zero() && self.height.is_zero() } }
zero
identifier_name
size.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/. */ //! Generic type for CSS properties that are composed by two dimensions. use crate::parser::ParserContext; use crate::Zero; use cssparser::Parser; use std::fmt::{self, Write}; use style_traits::{CssWriter, ParseError, ToCss}; /// A generic size, for `border-*-radius` longhand properties, or /// `border-spacing`. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToAnimatedValue, ToComputedValue, ToResolvedValue, ToShmem, )] #[allow(missing_docs)] #[repr(C)] pub struct Size2D<L> { pub width: L, pub height: L, } impl<L> Size2D<L> { #[inline] /// Create a new `Size2D` for an area of given width and height. pub fn new(width: L, height: L) -> Self { Self { width, height } } /// Returns the width component. pub fn width(&self) -> &L { &self.width } /// Returns the height component. pub fn height(&self) -> &L { &self.height } /// Parse a `Size2D` with a given parsing function. pub fn parse_with<'i, 't, F>( context: &ParserContext, input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Self, ParseError<'i>> where L: Clone, F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<L, ParseError<'i>>,
Ok(Self::new(first, second)) } } impl<L> ToCss for Size2D<L> where L: ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.width.to_css(dest)?; if self.height!= self.width { dest.write_str(" ")?; self.height.to_css(dest)?; } Ok(()) } } impl<L: Zero> Zero for Size2D<L> { fn zero() -> Self { Self::new(L::zero(), L::zero()) } fn is_zero(&self) -> bool { self.width.is_zero() && self.height.is_zero() } }
{ let first = parse_one(context, input)?; let second = input .try_parse(|i| parse_one(context, i)) .unwrap_or_else(|_| first.clone());
random_line_split
iced_features.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors /// Gets the available features #[allow(missing_copy_implementations)] #[allow(missing_debug_implementations)] pub struct IcedFeatures; impl IcedFeatures { /// `true` if the gas (AT&amp;T) formatter is available #[must_use] #[inline] pub fn has_gas() -> bool { cfg!(feature = "gas") } /// `true` if the Intel (xed) formatter is available #[must_use] #[inline] pub fn has_intel() -> bool { cfg!(feature = "intel") } /// `true` if the masm formatter is available #[must_use] #[inline] pub fn has_masm() -> bool { cfg!(feature = "masm") } /// `true` if the nasm formatter is available #[must_use] #[inline] pub fn has_nasm() -> bool { cfg!(feature = "nasm") } /// `true` if the fast formatter is available #[must_use] #[inline] pub fn has_fast_fmt() -> bool { cfg!(feature = "fast_fmt") } /// `true` if the decoder is available #[must_use] #[inline] pub fn has_decoder() -> bool { cfg!(feature = "decoder") } /// `true` if the encoder is available #[must_use] #[inline] pub fn has_encoder() -> bool { cfg!(feature = "encoder") } /// `true` if the block encoder is available #[must_use] #[inline] pub fn has_block_encoder() -> bool { cfg!(all(feature = "encoder", feature = "block_encoder")) } /// `true` if the opcode info is available #[must_use] #[inline] pub fn has_op_code_info() -> bool
/// `true` if the instruction info code is available #[must_use] #[inline] pub fn has_instruction_info() -> bool { cfg!(feature = "instr_info") } }
{ cfg!(all(feature = "encoder", feature = "op_code_info")) }
identifier_body
iced_features.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors /// Gets the available features #[allow(missing_copy_implementations)] #[allow(missing_debug_implementations)] pub struct IcedFeatures; impl IcedFeatures { /// `true` if the gas (AT&amp;T) formatter is available #[must_use] #[inline] pub fn has_gas() -> bool { cfg!(feature = "gas") } /// `true` if the Intel (xed) formatter is available #[must_use] #[inline] pub fn has_intel() -> bool { cfg!(feature = "intel") } /// `true` if the masm formatter is available #[must_use] #[inline] pub fn has_masm() -> bool { cfg!(feature = "masm") } /// `true` if the nasm formatter is available #[must_use]
pub fn has_nasm() -> bool { cfg!(feature = "nasm") } /// `true` if the fast formatter is available #[must_use] #[inline] pub fn has_fast_fmt() -> bool { cfg!(feature = "fast_fmt") } /// `true` if the decoder is available #[must_use] #[inline] pub fn has_decoder() -> bool { cfg!(feature = "decoder") } /// `true` if the encoder is available #[must_use] #[inline] pub fn has_encoder() -> bool { cfg!(feature = "encoder") } /// `true` if the block encoder is available #[must_use] #[inline] pub fn has_block_encoder() -> bool { cfg!(all(feature = "encoder", feature = "block_encoder")) } /// `true` if the opcode info is available #[must_use] #[inline] pub fn has_op_code_info() -> bool { cfg!(all(feature = "encoder", feature = "op_code_info")) } /// `true` if the instruction info code is available #[must_use] #[inline] pub fn has_instruction_info() -> bool { cfg!(feature = "instr_info") } }
#[inline]
random_line_split
iced_features.rs
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors /// Gets the available features #[allow(missing_copy_implementations)] #[allow(missing_debug_implementations)] pub struct IcedFeatures; impl IcedFeatures { /// `true` if the gas (AT&amp;T) formatter is available #[must_use] #[inline] pub fn has_gas() -> bool { cfg!(feature = "gas") } /// `true` if the Intel (xed) formatter is available #[must_use] #[inline] pub fn has_intel() -> bool { cfg!(feature = "intel") } /// `true` if the masm formatter is available #[must_use] #[inline] pub fn has_masm() -> bool { cfg!(feature = "masm") } /// `true` if the nasm formatter is available #[must_use] #[inline] pub fn has_nasm() -> bool { cfg!(feature = "nasm") } /// `true` if the fast formatter is available #[must_use] #[inline] pub fn has_fast_fmt() -> bool { cfg!(feature = "fast_fmt") } /// `true` if the decoder is available #[must_use] #[inline] pub fn has_decoder() -> bool { cfg!(feature = "decoder") } /// `true` if the encoder is available #[must_use] #[inline] pub fn has_encoder() -> bool { cfg!(feature = "encoder") } /// `true` if the block encoder is available #[must_use] #[inline] pub fn has_block_encoder() -> bool { cfg!(all(feature = "encoder", feature = "block_encoder")) } /// `true` if the opcode info is available #[must_use] #[inline] pub fn
() -> bool { cfg!(all(feature = "encoder", feature = "op_code_info")) } /// `true` if the instruction info code is available #[must_use] #[inline] pub fn has_instruction_info() -> bool { cfg!(feature = "instr_info") } }
has_op_code_info
identifier_name
roman_numerals.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. // force-host #![crate_type="dylib"] #![feature(plugin_registrar)] extern crate syntax; extern crate rustc; use syntax::codemap::Span; use syntax::parse::token; use syntax::ast::{TokenTree, TtToken}; use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacExpr}; use syntax::ext::build::AstBuilder; // trait for expr_usize use rustc::plugin::Registry; // WARNING WARNING WARNING WARNING WARNING // ======================================= // // This code also appears in src/doc/guide-plugin.md. Please keep // the two copies in sync! FIXME: have rustdoc read this file fn
(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult +'static> { static NUMERALS: &'static [(&'static str, uint)] = &[ ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)]; let text = match args { [TtToken(_, token::Ident(s, _))] => token::get_ident(s).to_string(), _ => { cx.span_err(sp, "argument should be a single identifier"); return DummyResult::any(sp); } }; let mut text = text.as_slice(); let mut total = 0u; while!text.is_empty() { match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) { Some(&(rn, val)) => { total += val; text = text.slice_from(rn.len()); } None => { cx.span_err(sp, "invalid Roman numeral"); return DummyResult::any(sp); } } } MacExpr::new(cx.expr_usize(sp, total)) } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("rn", expand_rn); }
expand_rn
identifier_name
roman_numerals.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. // force-host #![crate_type="dylib"] #![feature(plugin_registrar)] extern crate syntax; extern crate rustc; use syntax::codemap::Span; use syntax::parse::token; use syntax::ast::{TokenTree, TtToken}; use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacExpr}; use syntax::ext::build::AstBuilder; // trait for expr_usize use rustc::plugin::Registry; // WARNING WARNING WARNING WARNING WARNING // ======================================= // // This code also appears in src/doc/guide-plugin.md. Please keep // the two copies in sync! FIXME: have rustdoc read this file fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult +'static> { static NUMERALS: &'static [(&'static str, uint)] = &[ ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)]; let text = match args { [TtToken(_, token::Ident(s, _))] => token::get_ident(s).to_string(), _ => { cx.span_err(sp, "argument should be a single identifier"); return DummyResult::any(sp); } }; let mut text = text.as_slice(); let mut total = 0u; while!text.is_empty() { match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) { Some(&(rn, val)) => { total += val; text = text.slice_from(rn.len()); } None => { cx.span_err(sp, "invalid Roman numeral"); return DummyResult::any(sp); } } } MacExpr::new(cx.expr_usize(sp, total)) } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry)
{ reg.register_macro("rn", expand_rn); }
identifier_body
roman_numerals.rs
// 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. // force-host #![crate_type="dylib"] #![feature(plugin_registrar)] extern crate syntax; extern crate rustc; use syntax::codemap::Span; use syntax::parse::token; use syntax::ast::{TokenTree, TtToken}; use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacExpr}; use syntax::ext::build::AstBuilder; // trait for expr_usize use rustc::plugin::Registry; // WARNING WARNING WARNING WARNING WARNING // ======================================= // // This code also appears in src/doc/guide-plugin.md. Please keep // the two copies in sync! FIXME: have rustdoc read this file fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult +'static> { static NUMERALS: &'static [(&'static str, uint)] = &[ ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)]; let text = match args { [TtToken(_, token::Ident(s, _))] => token::get_ident(s).to_string(), _ => { cx.span_err(sp, "argument should be a single identifier"); return DummyResult::any(sp); } }; let mut text = text.as_slice(); let mut total = 0u; while!text.is_empty() { match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) { Some(&(rn, val)) => { total += val; text = text.slice_from(rn.len()); } None => { cx.span_err(sp, "invalid Roman numeral"); return DummyResult::any(sp); } } } MacExpr::new(cx.expr_usize(sp, total)) } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("rn", expand_rn); }
// 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
random_line_split
main.rs
use slog::{crit, o, Drain}; static POSSIBLE_BACKENDS: &[&str] = &[ #[cfg(feature = "winit")] "--winit : Run anvil as a X11 or Wayland client using winit.", #[cfg(feature = "udev")] "--tty-udev : Run anvil as a tty udev client (requires root if without logind).", #[cfg(feature = "x11")] "--x11 : Run anvil as an X11 client.", ]; fn
() { // A logger facility, here we use the terminal here let log = if std::env::var("ANVIL_MUTEX_LOG").is_ok() { slog::Logger::root(std::sync::Mutex::new(slog_term::term_full().fuse()).fuse(), o!()) } else { slog::Logger::root( slog_async::Async::default(slog_term::term_full().fuse()).fuse(), o!(), ) }; let _guard = slog_scope::set_global_logger(log.clone()); slog_stdlog::init().expect("Could not setup log backend"); let arg = ::std::env::args().nth(1); match arg.as_ref().map(|s| &s[..]) { #[cfg(feature = "winit")] Some("--winit") => { slog::info!(log, "Starting anvil with winit backend"); anvil::winit::run_winit(log); } #[cfg(feature = "udev")] Some("--tty-udev") => { slog::info!(log, "Starting anvil on a tty using udev"); anvil::udev::run_udev(log); } #[cfg(feature = "x11")] Some("--x11") => { slog::info!(log, "Starting anvil with x11 backend"); anvil::x11::run_x11(log); } Some(other) => { crit!(log, "Unknown backend: {}", other); } None => { println!("USAGE: anvil --backend"); println!(); println!("Possible backends are:"); for b in POSSIBLE_BACKENDS { println!("\t{}", b); } } } }
main
identifier_name
main.rs
use slog::{crit, o, Drain}; static POSSIBLE_BACKENDS: &[&str] = &[ #[cfg(feature = "winit")] "--winit : Run anvil as a X11 or Wayland client using winit.", #[cfg(feature = "udev")] "--tty-udev : Run anvil as a tty udev client (requires root if without logind).", #[cfg(feature = "x11")] "--x11 : Run anvil as an X11 client.", ]; fn main() { // A logger facility, here we use the terminal here let log = if std::env::var("ANVIL_MUTEX_LOG").is_ok() { slog::Logger::root(std::sync::Mutex::new(slog_term::term_full().fuse()).fuse(), o!()) } else { slog::Logger::root( slog_async::Async::default(slog_term::term_full().fuse()).fuse(), o!(), ) }; let _guard = slog_scope::set_global_logger(log.clone()); slog_stdlog::init().expect("Could not setup log backend"); let arg = ::std::env::args().nth(1); match arg.as_ref().map(|s| &s[..]) { #[cfg(feature = "winit")] Some("--winit") => { slog::info!(log, "Starting anvil with winit backend"); anvil::winit::run_winit(log); } #[cfg(feature = "udev")] Some("--tty-udev") => { slog::info!(log, "Starting anvil on a tty using udev"); anvil::udev::run_udev(log); } #[cfg(feature = "x11")] Some("--x11") => { slog::info!(log, "Starting anvil with x11 backend"); anvil::x11::run_x11(log); } Some(other) => { crit!(log, "Unknown backend: {}", other); }
println!("\t{}", b); } } } }
None => { println!("USAGE: anvil --backend"); println!(); println!("Possible backends are:"); for b in POSSIBLE_BACKENDS {
random_line_split
main.rs
use slog::{crit, o, Drain}; static POSSIBLE_BACKENDS: &[&str] = &[ #[cfg(feature = "winit")] "--winit : Run anvil as a X11 or Wayland client using winit.", #[cfg(feature = "udev")] "--tty-udev : Run anvil as a tty udev client (requires root if without logind).", #[cfg(feature = "x11")] "--x11 : Run anvil as an X11 client.", ]; fn main() { // A logger facility, here we use the terminal here let log = if std::env::var("ANVIL_MUTEX_LOG").is_ok() { slog::Logger::root(std::sync::Mutex::new(slog_term::term_full().fuse()).fuse(), o!()) } else { slog::Logger::root( slog_async::Async::default(slog_term::term_full().fuse()).fuse(), o!(), ) }; let _guard = slog_scope::set_global_logger(log.clone()); slog_stdlog::init().expect("Could not setup log backend"); let arg = ::std::env::args().nth(1); match arg.as_ref().map(|s| &s[..]) { #[cfg(feature = "winit")] Some("--winit") => { slog::info!(log, "Starting anvil with winit backend"); anvil::winit::run_winit(log); } #[cfg(feature = "udev")] Some("--tty-udev") => { slog::info!(log, "Starting anvil on a tty using udev"); anvil::udev::run_udev(log); } #[cfg(feature = "x11")] Some("--x11") => { slog::info!(log, "Starting anvil with x11 backend"); anvil::x11::run_x11(log); } Some(other) =>
None => { println!("USAGE: anvil --backend"); println!(); println!("Possible backends are:"); for b in POSSIBLE_BACKENDS { println!("\t{}", b); } } } }
{ crit!(log, "Unknown backend: {}", other); }
conditional_block
main.rs
use slog::{crit, o, Drain}; static POSSIBLE_BACKENDS: &[&str] = &[ #[cfg(feature = "winit")] "--winit : Run anvil as a X11 or Wayland client using winit.", #[cfg(feature = "udev")] "--tty-udev : Run anvil as a tty udev client (requires root if without logind).", #[cfg(feature = "x11")] "--x11 : Run anvil as an X11 client.", ]; fn main()
} #[cfg(feature = "udev")] Some("--tty-udev") => { slog::info!(log, "Starting anvil on a tty using udev"); anvil::udev::run_udev(log); } #[cfg(feature = "x11")] Some("--x11") => { slog::info!(log, "Starting anvil with x11 backend"); anvil::x11::run_x11(log); } Some(other) => { crit!(log, "Unknown backend: {}", other); } None => { println!("USAGE: anvil --backend"); println!(); println!("Possible backends are:"); for b in POSSIBLE_BACKENDS { println!("\t{}", b); } } } }
{ // A logger facility, here we use the terminal here let log = if std::env::var("ANVIL_MUTEX_LOG").is_ok() { slog::Logger::root(std::sync::Mutex::new(slog_term::term_full().fuse()).fuse(), o!()) } else { slog::Logger::root( slog_async::Async::default(slog_term::term_full().fuse()).fuse(), o!(), ) }; let _guard = slog_scope::set_global_logger(log.clone()); slog_stdlog::init().expect("Could not setup log backend"); let arg = ::std::env::args().nth(1); match arg.as_ref().map(|s| &s[..]) { #[cfg(feature = "winit")] Some("--winit") => { slog::info!(log, "Starting anvil with winit backend"); anvil::winit::run_winit(log);
identifier_body
ulps_eq.rs
#[cfg(feature = "num-complex")] use num_complex::Complex; #[cfg(not(feature = "std"))] use num_traits::float::FloatCore; use std::{cell, mem}; use AbsDiffEq; /// Equality comparisons between two numbers using both the absolute difference and ULPs /// (Units in Last Place) based comparisons. pub trait UlpsEq<Rhs = Self>: AbsDiffEq<Rhs> where Rhs:?Sized, { /// The default ULPs to tolerate when testing values that are far-apart. /// /// This is used when no `max_ulps` value is supplied to the [`ulps_eq`] macro. fn default_max_ulps() -> u32; /// A test for equality that uses units in the last place (ULP) if the values are far apart. fn ulps_eq(&self, other: &Rhs, epsilon: Self::Epsilon, max_ulps: u32) -> bool; /// The inverse of [`UlpsEq::ulps_eq`]. fn ulps_ne(&self, other: &Rhs, epsilon: Self::Epsilon, max_ulps: u32) -> bool { !Self::ulps_eq(self, other, epsilon, max_ulps) } } /////////////////////////////////////////////////////////////////////////////////////////////////// // Base implementations /////////////////////////////////////////////////////////////////////////////////////////////////// // Implementation based on: [Comparing Floating Point Numbers, 2012 Edition] // (https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/) macro_rules! impl_ulps_eq { ($T:ident, $U:ident) => { impl UlpsEq for $T { #[inline] fn default_max_ulps() -> u32 { 4 } #[inline] fn ulps_eq(&self, other: &$T, epsilon: $T, max_ulps: u32) -> bool { // For when the numbers are really close together if $T::abs_diff_eq(self, other, epsilon) { return true; } // Trivial negative sign check if self.signum()!= other.signum() { return false; } // ULPS difference comparison let int_self: $U = unsafe { mem::transmute(*self) }; let int_other: $U = unsafe { mem::transmute(*other) }; $U::abs(int_self - int_other) <= max_ulps as $U } } }; } impl_ulps_eq!(f32, i32); impl_ulps_eq!(f64, i64); /////////////////////////////////////////////////////////////////////////////////////////////////// // Derived implementations /////////////////////////////////////////////////////////////////////////////////////////////////// impl<'a, T: UlpsEq +?Sized> UlpsEq for &'a T { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &&'a T, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(*self, *other, epsilon, max_ulps) } } impl<'a, T: UlpsEq +?Sized> UlpsEq for &'a mut T { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &&'a mut T, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(*self, *other, epsilon, max_ulps) } } impl<T: UlpsEq + Copy> UlpsEq for cell::Cell<T> { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &cell::Cell<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.get(), &other.get(), epsilon, max_ulps) } } impl<T: UlpsEq +?Sized> UlpsEq for cell::RefCell<T> { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &cell::RefCell<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.borrow(), &other.borrow(), epsilon, max_ulps) } } impl<A, B> UlpsEq<[B]> for [A] where A: UlpsEq<B>, A::Epsilon: Clone, { #[inline] fn default_max_ulps() -> u32 { A::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &[B], epsilon: A::Epsilon, max_ulps: u32) -> bool { self.len() == other.len() && Iterator::zip(self.iter(), other) .all(|(x, y)| A::ulps_eq(x, y, epsilon.clone(), max_ulps.clone())) } } #[cfg(feature = "num-complex")] impl<T: UlpsEq> UlpsEq for Complex<T> where T::Epsilon: Clone, { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn
(&self, other: &Complex<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.re, &other.re, epsilon.clone(), max_ulps) && T::ulps_eq(&self.im, &other.im, epsilon.clone(), max_ulps) } }
ulps_eq
identifier_name
ulps_eq.rs
#[cfg(feature = "num-complex")] use num_complex::Complex; #[cfg(not(feature = "std"))] use num_traits::float::FloatCore; use std::{cell, mem}; use AbsDiffEq; /// Equality comparisons between two numbers using both the absolute difference and ULPs /// (Units in Last Place) based comparisons. pub trait UlpsEq<Rhs = Self>: AbsDiffEq<Rhs> where Rhs:?Sized, { /// The default ULPs to tolerate when testing values that are far-apart. /// /// This is used when no `max_ulps` value is supplied to the [`ulps_eq`] macro. fn default_max_ulps() -> u32; /// A test for equality that uses units in the last place (ULP) if the values are far apart. fn ulps_eq(&self, other: &Rhs, epsilon: Self::Epsilon, max_ulps: u32) -> bool; /// The inverse of [`UlpsEq::ulps_eq`]. fn ulps_ne(&self, other: &Rhs, epsilon: Self::Epsilon, max_ulps: u32) -> bool { !Self::ulps_eq(self, other, epsilon, max_ulps) } } /////////////////////////////////////////////////////////////////////////////////////////////////// // Base implementations /////////////////////////////////////////////////////////////////////////////////////////////////// // Implementation based on: [Comparing Floating Point Numbers, 2012 Edition] // (https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/) macro_rules! impl_ulps_eq { ($T:ident, $U:ident) => { impl UlpsEq for $T { #[inline] fn default_max_ulps() -> u32 { 4 } #[inline] fn ulps_eq(&self, other: &$T, epsilon: $T, max_ulps: u32) -> bool { // For when the numbers are really close together if $T::abs_diff_eq(self, other, epsilon) { return true; } // Trivial negative sign check if self.signum()!= other.signum() { return false; } // ULPS difference comparison let int_self: $U = unsafe { mem::transmute(*self) }; let int_other: $U = unsafe { mem::transmute(*other) }; $U::abs(int_self - int_other) <= max_ulps as $U } } }; } impl_ulps_eq!(f32, i32); impl_ulps_eq!(f64, i64); /////////////////////////////////////////////////////////////////////////////////////////////////// // Derived implementations /////////////////////////////////////////////////////////////////////////////////////////////////// impl<'a, T: UlpsEq +?Sized> UlpsEq for &'a T { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &&'a T, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(*self, *other, epsilon, max_ulps) } } impl<'a, T: UlpsEq +?Sized> UlpsEq for &'a mut T { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &&'a mut T, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(*self, *other, epsilon, max_ulps) } } impl<T: UlpsEq + Copy> UlpsEq for cell::Cell<T> { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &cell::Cell<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.get(), &other.get(), epsilon, max_ulps) } } impl<T: UlpsEq +?Sized> UlpsEq for cell::RefCell<T> { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &cell::RefCell<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.borrow(), &other.borrow(), epsilon, max_ulps) } } impl<A, B> UlpsEq<[B]> for [A] where A: UlpsEq<B>, A::Epsilon: Clone, { #[inline] fn default_max_ulps() -> u32 { A::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &[B], epsilon: A::Epsilon, max_ulps: u32) -> bool { self.len() == other.len() && Iterator::zip(self.iter(), other) .all(|(x, y)| A::ulps_eq(x, y, epsilon.clone(), max_ulps.clone())) } } #[cfg(feature = "num-complex")] impl<T: UlpsEq> UlpsEq for Complex<T> where T::Epsilon: Clone, { #[inline] fn default_max_ulps() -> u32 {
} #[inline] fn ulps_eq(&self, other: &Complex<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.re, &other.re, epsilon.clone(), max_ulps) && T::ulps_eq(&self.im, &other.im, epsilon.clone(), max_ulps) } }
T::default_max_ulps()
random_line_split
ulps_eq.rs
#[cfg(feature = "num-complex")] use num_complex::Complex; #[cfg(not(feature = "std"))] use num_traits::float::FloatCore; use std::{cell, mem}; use AbsDiffEq; /// Equality comparisons between two numbers using both the absolute difference and ULPs /// (Units in Last Place) based comparisons. pub trait UlpsEq<Rhs = Self>: AbsDiffEq<Rhs> where Rhs:?Sized, { /// The default ULPs to tolerate when testing values that are far-apart. /// /// This is used when no `max_ulps` value is supplied to the [`ulps_eq`] macro. fn default_max_ulps() -> u32; /// A test for equality that uses units in the last place (ULP) if the values are far apart. fn ulps_eq(&self, other: &Rhs, epsilon: Self::Epsilon, max_ulps: u32) -> bool; /// The inverse of [`UlpsEq::ulps_eq`]. fn ulps_ne(&self, other: &Rhs, epsilon: Self::Epsilon, max_ulps: u32) -> bool { !Self::ulps_eq(self, other, epsilon, max_ulps) } } /////////////////////////////////////////////////////////////////////////////////////////////////// // Base implementations /////////////////////////////////////////////////////////////////////////////////////////////////// // Implementation based on: [Comparing Floating Point Numbers, 2012 Edition] // (https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/) macro_rules! impl_ulps_eq { ($T:ident, $U:ident) => { impl UlpsEq for $T { #[inline] fn default_max_ulps() -> u32 { 4 } #[inline] fn ulps_eq(&self, other: &$T, epsilon: $T, max_ulps: u32) -> bool { // For when the numbers are really close together if $T::abs_diff_eq(self, other, epsilon) { return true; } // Trivial negative sign check if self.signum()!= other.signum() { return false; } // ULPS difference comparison let int_self: $U = unsafe { mem::transmute(*self) }; let int_other: $U = unsafe { mem::transmute(*other) }; $U::abs(int_self - int_other) <= max_ulps as $U } } }; } impl_ulps_eq!(f32, i32); impl_ulps_eq!(f64, i64); /////////////////////////////////////////////////////////////////////////////////////////////////// // Derived implementations /////////////////////////////////////////////////////////////////////////////////////////////////// impl<'a, T: UlpsEq +?Sized> UlpsEq for &'a T { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &&'a T, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(*self, *other, epsilon, max_ulps) } } impl<'a, T: UlpsEq +?Sized> UlpsEq for &'a mut T { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &&'a mut T, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(*self, *other, epsilon, max_ulps) } } impl<T: UlpsEq + Copy> UlpsEq for cell::Cell<T> { #[inline] fn default_max_ulps() -> u32
#[inline] fn ulps_eq(&self, other: &cell::Cell<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.get(), &other.get(), epsilon, max_ulps) } } impl<T: UlpsEq +?Sized> UlpsEq for cell::RefCell<T> { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &cell::RefCell<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.borrow(), &other.borrow(), epsilon, max_ulps) } } impl<A, B> UlpsEq<[B]> for [A] where A: UlpsEq<B>, A::Epsilon: Clone, { #[inline] fn default_max_ulps() -> u32 { A::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &[B], epsilon: A::Epsilon, max_ulps: u32) -> bool { self.len() == other.len() && Iterator::zip(self.iter(), other) .all(|(x, y)| A::ulps_eq(x, y, epsilon.clone(), max_ulps.clone())) } } #[cfg(feature = "num-complex")] impl<T: UlpsEq> UlpsEq for Complex<T> where T::Epsilon: Clone, { #[inline] fn default_max_ulps() -> u32 { T::default_max_ulps() } #[inline] fn ulps_eq(&self, other: &Complex<T>, epsilon: T::Epsilon, max_ulps: u32) -> bool { T::ulps_eq(&self.re, &other.re, epsilon.clone(), max_ulps) && T::ulps_eq(&self.im, &other.im, epsilon.clone(), max_ulps) } }
{ T::default_max_ulps() }
identifier_body
basic_shape.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/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that are generic over their `ToCss` implementations. use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::animated::{Animate, Procedure, ToAnimatedZero}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; use values::generics::border::BorderRadius; use values::generics::position::Position; use values::generics::rect::Rect; /// A clipping shape, for `clip-path`. pub type ClippingShape<BasicShape, Url> = ShapeSource<BasicShape, GeometryBox, Url>; /// <https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box> #[allow(missing_docs)] #[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum GeometryBox { FillBox, StrokeBox, ViewBox, ShapeBox(ShapeBox), } /// A float area shape, for `shape-outside`. pub type FloatAreaShape<BasicShape, Image> = ShapeSource<BasicShape, ShapeBox, Image>; /// https://drafts.csswg.org/css-shapes-1/#typedef-shape-box #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)] pub enum ShapeBox { MarginBox, BorderBox, PaddingBox, ContentBox, } /// A shape source, for some reference box. #[allow(missing_docs)] #[animation(no_bound(ImageOrUrl))] #[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum ShapeSource<BasicShape, ReferenceBox, ImageOrUrl> { #[animation(error)] ImageOrUrl(ImageOrUrl), Shape(BasicShape, Option<ReferenceBox>), #[animation(error)] Box(ReferenceBox), #[animation(error)] None, } #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum BasicShape<H, V, LengthOrPercentage> { Inset(#[css(field_bound)] InsetRect<LengthOrPercentage>), Circle(#[css(field_bound)] Circle<H, V, LengthOrPercentage>), Ellipse(#[css(field_bound)] Ellipse<H, V, LengthOrPercentage>), Polygon(Polygon<LengthOrPercentage>), } /// <https://drafts.csswg.org/css-shapes/#funcdef-inset> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct InsetRect<LengthOrPercentage> { pub rect: Rect<LengthOrPercentage>, pub round: Option<BorderRadius<LengthOrPercentage>>, } /// <https://drafts.csswg.org/css-shapes/#funcdef-circle> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Circle<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub radius: ShapeRadius<LengthOrPercentage>, } /// <https://drafts.csswg.org/css-shapes/#funcdef-ellipse> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Ellipse<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub semiaxis_x: ShapeRadius<LengthOrPercentage>, pub semiaxis_y: ShapeRadius<LengthOrPercentage>, } /// <https://drafts.csswg.org/css-shapes/#typedef-shape-radius> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum ShapeRadius<LengthOrPercentage> { Length(LengthOrPercentage), #[animation(error)] ClosestSide, #[animation(error)] FarthestSide, } /// A generic type for representing the `polygon()` function /// /// <https://drafts.csswg.org/css-shapes/#funcdef-polygon> #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Polygon<LengthOrPercentage> { /// The filling rule for a polygon. pub fill: FillRule, /// A collection of (x, y) coordinates to draw the polygon. pub coordinates: Vec<(LengthOrPercentage, LengthOrPercentage)>, } // https://drafts.csswg.org/css-shapes/#typedef-fill-rule // NOTE: Basic shapes spec says that these are the only two values, however // https://www.w3.org/TR/SVG/painting.html#FillRuleProperty // says that it can also be `inherit` #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)] pub enum FillRule { Nonzero, Evenodd, } // FIXME(nox): Implement ComputeSquaredDistance for T types and stop // using PartialEq here, this will let us derive this impl. impl<B, T, U> ComputeSquaredDistance for ShapeSource<B, T, U> where B: ComputeSquaredDistance, T: PartialEq, { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { match (self, other) { ( &ShapeSource::Shape(ref this, ref this_box), &ShapeSource::Shape(ref other, ref other_box), ) if this_box == other_box => { this.compute_squared_distance(other) }, _ => Err(()), } } } impl<B, T, U> ToAnimatedZero for ShapeSource<B, T, U> { fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) } } impl<L> ToCss for InsetRect<L> where L: ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("inset(")?; self.rect.to_css(dest)?; if let Some(ref radius) = self.round { dest.write_str(" round ")?; radius.to_css(dest)?; } dest.write_str(")") } } impl<L> Default for ShapeRadius<L> { #[inline] fn default() -> Self { ShapeRadius::ClosestSide } } impl<L> Animate for Polygon<L> where L: Animate, { fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { if self.fill!= other.fill { return Err(()); } if self.coordinates.len()!= other.coordinates.len() { return Err(()); } let coordinates = self.coordinates .iter() .zip(other.coordinates.iter()) .map(|(this, other)| { Ok(( this.0.animate(&other.0, procedure)?, this.1.animate(&other.1, procedure)?, )) }) .collect::<Result<Vec<_>, _>>()?; Ok(Polygon { fill: self.fill, coordinates, }) } } impl<L> ComputeSquaredDistance for Polygon<L> where L: ComputeSquaredDistance, { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.fill!= other.fill { return Err(()); } if self.coordinates.len()!= other.coordinates.len()
self.coordinates .iter() .zip(other.coordinates.iter()) .map(|(this, other)| { let d1 = this.0.compute_squared_distance(&other.0)?; let d2 = this.1.compute_squared_distance(&other.1)?; Ok(d1 + d2) }) .sum() } } impl<L: ToCss> ToCss for Polygon<L> { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("polygon(")?; if self.fill!= FillRule::default() { self.fill.to_css(dest)?; dest.write_str(", ")?; } for (i, coord) in self.coordinates.iter().enumerate() { if i > 0 { dest.write_str(", ")?; } coord.0.to_css(dest)?; dest.write_str(" ")?; coord.1.to_css(dest)?; } dest.write_str(")") } } impl Default for FillRule { #[inline] fn default() -> Self { FillRule::Nonzero } }
{ return Err(()); }
conditional_block
basic_shape.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/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that are generic over their `ToCss` implementations. use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::animated::{Animate, Procedure, ToAnimatedZero}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; use values::generics::border::BorderRadius; use values::generics::position::Position; use values::generics::rect::Rect; /// A clipping shape, for `clip-path`. pub type ClippingShape<BasicShape, Url> = ShapeSource<BasicShape, GeometryBox, Url>; /// <https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box> #[allow(missing_docs)] #[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum GeometryBox { FillBox, StrokeBox, ViewBox, ShapeBox(ShapeBox), } /// A float area shape, for `shape-outside`. pub type FloatAreaShape<BasicShape, Image> = ShapeSource<BasicShape, ShapeBox, Image>; /// https://drafts.csswg.org/css-shapes-1/#typedef-shape-box #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)] pub enum ShapeBox { MarginBox, BorderBox, PaddingBox, ContentBox, } /// A shape source, for some reference box. #[allow(missing_docs)] #[animation(no_bound(ImageOrUrl))] #[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum ShapeSource<BasicShape, ReferenceBox, ImageOrUrl> { #[animation(error)] ImageOrUrl(ImageOrUrl), Shape(BasicShape, Option<ReferenceBox>), #[animation(error)] Box(ReferenceBox), #[animation(error)] None, } #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum BasicShape<H, V, LengthOrPercentage> { Inset(#[css(field_bound)] InsetRect<LengthOrPercentage>), Circle(#[css(field_bound)] Circle<H, V, LengthOrPercentage>), Ellipse(#[css(field_bound)] Ellipse<H, V, LengthOrPercentage>), Polygon(Polygon<LengthOrPercentage>), } /// <https://drafts.csswg.org/css-shapes/#funcdef-inset> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct InsetRect<LengthOrPercentage> { pub rect: Rect<LengthOrPercentage>, pub round: Option<BorderRadius<LengthOrPercentage>>, } /// <https://drafts.csswg.org/css-shapes/#funcdef-circle> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Circle<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub radius: ShapeRadius<LengthOrPercentage>, } /// <https://drafts.csswg.org/css-shapes/#funcdef-ellipse> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Ellipse<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub semiaxis_x: ShapeRadius<LengthOrPercentage>, pub semiaxis_y: ShapeRadius<LengthOrPercentage>, } /// <https://drafts.csswg.org/css-shapes/#typedef-shape-radius> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum ShapeRadius<LengthOrPercentage> { Length(LengthOrPercentage), #[animation(error)] ClosestSide, #[animation(error)] FarthestSide, } /// A generic type for representing the `polygon()` function /// /// <https://drafts.csswg.org/css-shapes/#funcdef-polygon> #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Polygon<LengthOrPercentage> { /// The filling rule for a polygon. pub fill: FillRule, /// A collection of (x, y) coordinates to draw the polygon. pub coordinates: Vec<(LengthOrPercentage, LengthOrPercentage)>, } // https://drafts.csswg.org/css-shapes/#typedef-fill-rule // NOTE: Basic shapes spec says that these are the only two values, however // https://www.w3.org/TR/SVG/painting.html#FillRuleProperty // says that it can also be `inherit` #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)] pub enum FillRule { Nonzero, Evenodd, } // FIXME(nox): Implement ComputeSquaredDistance for T types and stop // using PartialEq here, this will let us derive this impl. impl<B, T, U> ComputeSquaredDistance for ShapeSource<B, T, U> where B: ComputeSquaredDistance, T: PartialEq, { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { match (self, other) { ( &ShapeSource::Shape(ref this, ref this_box), &ShapeSource::Shape(ref other, ref other_box), ) if this_box == other_box => { this.compute_squared_distance(other) }, _ => Err(()), } } } impl<B, T, U> ToAnimatedZero for ShapeSource<B, T, U> { fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) } } impl<L> ToCss for InsetRect<L> where L: ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("inset(")?; self.rect.to_css(dest)?; if let Some(ref radius) = self.round { dest.write_str(" round ")?;
} impl<L> Default for ShapeRadius<L> { #[inline] fn default() -> Self { ShapeRadius::ClosestSide } } impl<L> Animate for Polygon<L> where L: Animate, { fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { if self.fill!= other.fill { return Err(()); } if self.coordinates.len()!= other.coordinates.len() { return Err(()); } let coordinates = self.coordinates .iter() .zip(other.coordinates.iter()) .map(|(this, other)| { Ok(( this.0.animate(&other.0, procedure)?, this.1.animate(&other.1, procedure)?, )) }) .collect::<Result<Vec<_>, _>>()?; Ok(Polygon { fill: self.fill, coordinates, }) } } impl<L> ComputeSquaredDistance for Polygon<L> where L: ComputeSquaredDistance, { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.fill!= other.fill { return Err(()); } if self.coordinates.len()!= other.coordinates.len() { return Err(()); } self.coordinates .iter() .zip(other.coordinates.iter()) .map(|(this, other)| { let d1 = this.0.compute_squared_distance(&other.0)?; let d2 = this.1.compute_squared_distance(&other.1)?; Ok(d1 + d2) }) .sum() } } impl<L: ToCss> ToCss for Polygon<L> { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("polygon(")?; if self.fill!= FillRule::default() { self.fill.to_css(dest)?; dest.write_str(", ")?; } for (i, coord) in self.coordinates.iter().enumerate() { if i > 0 { dest.write_str(", ")?; } coord.0.to_css(dest)?; dest.write_str(" ")?; coord.1.to_css(dest)?; } dest.write_str(")") } } impl Default for FillRule { #[inline] fn default() -> Self { FillRule::Nonzero } }
radius.to_css(dest)?; } dest.write_str(")") }
random_line_split
basic_shape.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/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that are generic over their `ToCss` implementations. use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::animated::{Animate, Procedure, ToAnimatedZero}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; use values::generics::border::BorderRadius; use values::generics::position::Position; use values::generics::rect::Rect; /// A clipping shape, for `clip-path`. pub type ClippingShape<BasicShape, Url> = ShapeSource<BasicShape, GeometryBox, Url>; /// <https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box> #[allow(missing_docs)] #[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum GeometryBox { FillBox, StrokeBox, ViewBox, ShapeBox(ShapeBox), } /// A float area shape, for `shape-outside`. pub type FloatAreaShape<BasicShape, Image> = ShapeSource<BasicShape, ShapeBox, Image>; /// https://drafts.csswg.org/css-shapes-1/#typedef-shape-box #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)] pub enum ShapeBox { MarginBox, BorderBox, PaddingBox, ContentBox, } /// A shape source, for some reference box. #[allow(missing_docs)] #[animation(no_bound(ImageOrUrl))] #[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum ShapeSource<BasicShape, ReferenceBox, ImageOrUrl> { #[animation(error)] ImageOrUrl(ImageOrUrl), Shape(BasicShape, Option<ReferenceBox>), #[animation(error)] Box(ReferenceBox), #[animation(error)] None, } #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum BasicShape<H, V, LengthOrPercentage> { Inset(#[css(field_bound)] InsetRect<LengthOrPercentage>), Circle(#[css(field_bound)] Circle<H, V, LengthOrPercentage>), Ellipse(#[css(field_bound)] Ellipse<H, V, LengthOrPercentage>), Polygon(Polygon<LengthOrPercentage>), } /// <https://drafts.csswg.org/css-shapes/#funcdef-inset> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct InsetRect<LengthOrPercentage> { pub rect: Rect<LengthOrPercentage>, pub round: Option<BorderRadius<LengthOrPercentage>>, } /// <https://drafts.csswg.org/css-shapes/#funcdef-circle> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Circle<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub radius: ShapeRadius<LengthOrPercentage>, } /// <https://drafts.csswg.org/css-shapes/#funcdef-ellipse> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Ellipse<H, V, LengthOrPercentage> { pub position: Position<H, V>, pub semiaxis_x: ShapeRadius<LengthOrPercentage>, pub semiaxis_y: ShapeRadius<LengthOrPercentage>, } /// <https://drafts.csswg.org/css-shapes/#typedef-shape-radius> #[allow(missing_docs)] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum ShapeRadius<LengthOrPercentage> { Length(LengthOrPercentage), #[animation(error)] ClosestSide, #[animation(error)] FarthestSide, } /// A generic type for representing the `polygon()` function /// /// <https://drafts.csswg.org/css-shapes/#funcdef-polygon> #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Polygon<LengthOrPercentage> { /// The filling rule for a polygon. pub fill: FillRule, /// A collection of (x, y) coordinates to draw the polygon. pub coordinates: Vec<(LengthOrPercentage, LengthOrPercentage)>, } // https://drafts.csswg.org/css-shapes/#typedef-fill-rule // NOTE: Basic shapes spec says that these are the only two values, however // https://www.w3.org/TR/SVG/painting.html#FillRuleProperty // says that it can also be `inherit` #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss)] pub enum FillRule { Nonzero, Evenodd, } // FIXME(nox): Implement ComputeSquaredDistance for T types and stop // using PartialEq here, this will let us derive this impl. impl<B, T, U> ComputeSquaredDistance for ShapeSource<B, T, U> where B: ComputeSquaredDistance, T: PartialEq, { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { match (self, other) { ( &ShapeSource::Shape(ref this, ref this_box), &ShapeSource::Shape(ref other, ref other_box), ) if this_box == other_box => { this.compute_squared_distance(other) }, _ => Err(()), } } } impl<B, T, U> ToAnimatedZero for ShapeSource<B, T, U> { fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) } } impl<L> ToCss for InsetRect<L> where L: ToCss + PartialEq, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("inset(")?; self.rect.to_css(dest)?; if let Some(ref radius) = self.round { dest.write_str(" round ")?; radius.to_css(dest)?; } dest.write_str(")") } } impl<L> Default for ShapeRadius<L> { #[inline] fn default() -> Self { ShapeRadius::ClosestSide } } impl<L> Animate for Polygon<L> where L: Animate, { fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { if self.fill!= other.fill { return Err(()); } if self.coordinates.len()!= other.coordinates.len() { return Err(()); } let coordinates = self.coordinates .iter() .zip(other.coordinates.iter()) .map(|(this, other)| { Ok(( this.0.animate(&other.0, procedure)?, this.1.animate(&other.1, procedure)?, )) }) .collect::<Result<Vec<_>, _>>()?; Ok(Polygon { fill: self.fill, coordinates, }) } } impl<L> ComputeSquaredDistance for Polygon<L> where L: ComputeSquaredDistance, { fn
(&self, other: &Self) -> Result<SquaredDistance, ()> { if self.fill!= other.fill { return Err(()); } if self.coordinates.len()!= other.coordinates.len() { return Err(()); } self.coordinates .iter() .zip(other.coordinates.iter()) .map(|(this, other)| { let d1 = this.0.compute_squared_distance(&other.0)?; let d2 = this.1.compute_squared_distance(&other.1)?; Ok(d1 + d2) }) .sum() } } impl<L: ToCss> ToCss for Polygon<L> { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("polygon(")?; if self.fill!= FillRule::default() { self.fill.to_css(dest)?; dest.write_str(", ")?; } for (i, coord) in self.coordinates.iter().enumerate() { if i > 0 { dest.write_str(", ")?; } coord.0.to_css(dest)?; dest.write_str(" ")?; coord.1.to_css(dest)?; } dest.write_str(")") } } impl Default for FillRule { #[inline] fn default() -> Self { FillRule::Nonzero } }
compute_squared_distance
identifier_name
dna.rs
// Copyright 2014-2015 Johannes Köster, Peer Aramillo Irizar. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Implementation of the DNA alphabet. //! //! # Example //! //! ``` //! use bio::alphabets; //! let alphabet = alphabets::dna::alphabet(); //! assert!(alphabet.is_word(b"GATTACA")); //! assert!(alphabet.is_word(b"gattaca"));
use alphabets::Alphabet; use utils::IntoTextIterator; /// The DNA alphabet (uppercase and lowercase). pub fn alphabet() -> Alphabet { Alphabet::new(b"ACGTacgt") } /// The DNA alphabet including N (uppercase and lowercase). pub fn n_alphabet() -> Alphabet { Alphabet::new(b"ACGTNacgtn") } /// The IUPAC DNA alphabet (uppercase and lowercase). pub fn iupac_alphabet() -> Alphabet { Alphabet::new(b"ACGTURYSWKMBDHVNacgturyswkmbdhvn") } lazy_static! { static ref COMPLEMENT: Vec<u8> = { let mut comp = Vec::new(); comp.resize(256, 0); for (v, mut a) in comp.iter_mut().enumerate() { *a = v as u8; } for (&a, &b) in b"AGCTYRWSKMDVHBN".iter().zip(b"TCGARYWSMKHBDVN".iter()) { comp[a as usize] = b; comp[a as usize + 32] = b + 32; // lowercase variants } comp }; } /// Return complement of given DNA alphabet character (IUPAC alphabet supported). pub fn complement(a: u8) -> u8 { COMPLEMENT[a as usize] } /// Calculate reverse complement of given text (IUPAC alphabet supported). pub fn revcomp<'a, T: IntoTextIterator<'a>>(text: T) -> Vec<u8> where T::IntoIter: DoubleEndedIterator { text.into_iter().rev().map(|&a| complement(a)).collect() }
//! assert!(!alphabet.is_word(b"ACGU")); //! ```
random_line_split
dna.rs
// Copyright 2014-2015 Johannes Köster, Peer Aramillo Irizar. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Implementation of the DNA alphabet. //! //! # Example //! //! ``` //! use bio::alphabets; //! let alphabet = alphabets::dna::alphabet(); //! assert!(alphabet.is_word(b"GATTACA")); //! assert!(alphabet.is_word(b"gattaca")); //! assert!(!alphabet.is_word(b"ACGU")); //! ``` use alphabets::Alphabet; use utils::IntoTextIterator; /// The DNA alphabet (uppercase and lowercase). pub fn alphabet() -> Alphabet { Alphabet::new(b"ACGTacgt") } /// The DNA alphabet including N (uppercase and lowercase). pub fn n_alphabet() -> Alphabet { Alphabet::new(b"ACGTNacgtn") } /// The IUPAC DNA alphabet (uppercase and lowercase). pub fn iupac_alphabet() -> Alphabet { Alphabet::new(b"ACGTURYSWKMBDHVNacgturyswkmbdhvn") } lazy_static! { static ref COMPLEMENT: Vec<u8> = { let mut comp = Vec::new(); comp.resize(256, 0); for (v, mut a) in comp.iter_mut().enumerate() { *a = v as u8; } for (&a, &b) in b"AGCTYRWSKMDVHBN".iter().zip(b"TCGARYWSMKHBDVN".iter()) { comp[a as usize] = b; comp[a as usize + 32] = b + 32; // lowercase variants } comp }; } /// Return complement of given DNA alphabet character (IUPAC alphabet supported). pub fn complement(a: u8) -> u8 { COMPLEMENT[a as usize] } /// Calculate reverse complement of given text (IUPAC alphabet supported). pub fn r
'a, T: IntoTextIterator<'a>>(text: T) -> Vec<u8> where T::IntoIter: DoubleEndedIterator { text.into_iter().rev().map(|&a| complement(a)).collect() }
evcomp<
identifier_name
dna.rs
// Copyright 2014-2015 Johannes Köster, Peer Aramillo Irizar. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Implementation of the DNA alphabet. //! //! # Example //! //! ``` //! use bio::alphabets; //! let alphabet = alphabets::dna::alphabet(); //! assert!(alphabet.is_word(b"GATTACA")); //! assert!(alphabet.is_word(b"gattaca")); //! assert!(!alphabet.is_word(b"ACGU")); //! ``` use alphabets::Alphabet; use utils::IntoTextIterator; /// The DNA alphabet (uppercase and lowercase). pub fn alphabet() -> Alphabet { Alphabet::new(b"ACGTacgt") } /// The DNA alphabet including N (uppercase and lowercase). pub fn n_alphabet() -> Alphabet {
/// The IUPAC DNA alphabet (uppercase and lowercase). pub fn iupac_alphabet() -> Alphabet { Alphabet::new(b"ACGTURYSWKMBDHVNacgturyswkmbdhvn") } lazy_static! { static ref COMPLEMENT: Vec<u8> = { let mut comp = Vec::new(); comp.resize(256, 0); for (v, mut a) in comp.iter_mut().enumerate() { *a = v as u8; } for (&a, &b) in b"AGCTYRWSKMDVHBN".iter().zip(b"TCGARYWSMKHBDVN".iter()) { comp[a as usize] = b; comp[a as usize + 32] = b + 32; // lowercase variants } comp }; } /// Return complement of given DNA alphabet character (IUPAC alphabet supported). pub fn complement(a: u8) -> u8 { COMPLEMENT[a as usize] } /// Calculate reverse complement of given text (IUPAC alphabet supported). pub fn revcomp<'a, T: IntoTextIterator<'a>>(text: T) -> Vec<u8> where T::IntoIter: DoubleEndedIterator { text.into_iter().rev().map(|&a| complement(a)).collect() }
Alphabet::new(b"ACGTNacgtn") }
identifier_body
regions-mock-trans.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
extern crate libc; use std::mem; struct arena(()); struct Bcx<'a> { fcx: &'a Fcx<'a> } struct Fcx<'a> { arena: &'a arena, ccx: &'a Ccx } struct Ccx { x: int } fn alloc<'a>(_bcx : &'a arena) -> &'a Bcx<'a> { unsafe { mem::transmute(libc::malloc(mem::size_of::<Bcx<'a>>() as libc::size_t)) } } fn h<'a>(bcx : &'a Bcx<'a>) -> &'a Bcx<'a> { return alloc(bcx.fcx.arena); } fn g(fcx : &Fcx) { let bcx = Bcx { fcx: fcx }; let bcx2 = h(&bcx); unsafe { libc::free(mem::transmute(bcx2)); } } fn f(ccx : &Ccx) { let a = arena(()); let fcx = Fcx { arena: &a, ccx: ccx }; return g(&fcx); } pub fn main() { let ccx = Ccx { x: 0 }; f(&ccx); }
// except according to those terms.
random_line_split
regions-mock-trans.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 crate libc; use std::mem; struct arena(()); struct Bcx<'a> { fcx: &'a Fcx<'a> } struct Fcx<'a> { arena: &'a arena, ccx: &'a Ccx } struct Ccx { x: int } fn alloc<'a>(_bcx : &'a arena) -> &'a Bcx<'a> { unsafe { mem::transmute(libc::malloc(mem::size_of::<Bcx<'a>>() as libc::size_t)) } } fn h<'a>(bcx : &'a Bcx<'a>) -> &'a Bcx<'a> { return alloc(bcx.fcx.arena); } fn g(fcx : &Fcx) { let bcx = Bcx { fcx: fcx }; let bcx2 = h(&bcx); unsafe { libc::free(mem::transmute(bcx2)); } } fn f(ccx : &Ccx) { let a = arena(()); let fcx = Fcx { arena: &a, ccx: ccx }; return g(&fcx); } pub fn
() { let ccx = Ccx { x: 0 }; f(&ccx); }
main
identifier_name
nqueens.rs
// Copyright 2016 Pierre Talbot (IRCAM) // 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. // This example models the n-queens problem using interval domain (with `i32` bounds). use pcp::kernel::*; use pcp::propagators::*; use pcp::variable::ops::*; use pcp::term::*; use pcp::search::search_tree_visitor::Status::*; use pcp::search::*; use pcp::concept::*; use interval::ops::Range; use interval::interval_set::*; use gcollections::ops::*; pub fn
(n: usize) { let mut space = FDSpace::empty(); let mut queens = vec![]; // 2 queens can't share the same line. for _ in 0..n { queens.push(Box::new(space.vstore.alloc(IntervalSet::new(1, n as i32))) as Var<VStore>); } for i in 0..n-1 { for j in i + 1..n { // 2 queens can't share the same diagonal. let q1 = (i + 1) as i32; let q2 = (j + 1) as i32; // Xi + i!= Xj + j reformulated as: Xi!= Xj + j - i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), q2 - q1)) as Var<VStore>))); // Xi - i!= Xj - j reformulated as: Xi!= Xj - j + i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), -q2 + q1)) as Var<VStore>))); } } // 2 queens can't share the same column. join_distinct(&mut space.vstore, &mut space.cstore, queens); // space.cstore.alloc(Box::new(Distinct::new(queens))); // Search step. let mut search = one_solution_engine(); search.start(&space); let (frozen_space, status) = search.enter(space); let space = frozen_space.unfreeze(); // Print result. match status { Satisfiable => { print!("{}-queens problem is satisfiable. The first solution is:\n[", n); for dom in space.vstore.iter() { // At this stage, dom.lower() == dom.upper(). print!("{}, ", dom.lower()); } println!("]"); } Unsatisfiable => println!("{}-queens problem is unsatisfiable.", n), EndOfSearch => println!("Search terminated or was interrupted."), Unknown(_) => unreachable!( "After the search step, the problem instance should be either satisfiable or unsatisfiable.") } }
nqueens
identifier_name
nqueens.rs
// Copyright 2016 Pierre Talbot (IRCAM) // 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. // This example models the n-queens problem using interval domain (with `i32` bounds). use pcp::kernel::*; use pcp::propagators::*; use pcp::variable::ops::*; use pcp::term::*; use pcp::search::search_tree_visitor::Status::*; use pcp::search::*; use pcp::concept::*; use interval::ops::Range; use interval::interval_set::*; use gcollections::ops::*; pub fn nqueens(n: usize) { let mut space = FDSpace::empty(); let mut queens = vec![]; // 2 queens can't share the same line. for _ in 0..n { queens.push(Box::new(space.vstore.alloc(IntervalSet::new(1, n as i32))) as Var<VStore>); } for i in 0..n-1 { for j in i + 1..n { // 2 queens can't share the same diagonal. let q1 = (i + 1) as i32; let q2 = (j + 1) as i32; // Xi + i!= Xj + j reformulated as: Xi!= Xj + j - i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), q2 - q1)) as Var<VStore>))); // Xi - i!= Xj - j reformulated as: Xi!= Xj - j + i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), -q2 + q1)) as Var<VStore>))); } } // 2 queens can't share the same column. join_distinct(&mut space.vstore, &mut space.cstore, queens); // space.cstore.alloc(Box::new(Distinct::new(queens)));
// Search step. let mut search = one_solution_engine(); search.start(&space); let (frozen_space, status) = search.enter(space); let space = frozen_space.unfreeze(); // Print result. match status { Satisfiable => { print!("{}-queens problem is satisfiable. The first solution is:\n[", n); for dom in space.vstore.iter() { // At this stage, dom.lower() == dom.upper(). print!("{}, ", dom.lower()); } println!("]"); } Unsatisfiable => println!("{}-queens problem is unsatisfiable.", n), EndOfSearch => println!("Search terminated or was interrupted."), Unknown(_) => unreachable!( "After the search step, the problem instance should be either satisfiable or unsatisfiable.") } }
random_line_split
nqueens.rs
// Copyright 2016 Pierre Talbot (IRCAM) // 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. // This example models the n-queens problem using interval domain (with `i32` bounds). use pcp::kernel::*; use pcp::propagators::*; use pcp::variable::ops::*; use pcp::term::*; use pcp::search::search_tree_visitor::Status::*; use pcp::search::*; use pcp::concept::*; use interval::ops::Range; use interval::interval_set::*; use gcollections::ops::*; pub fn nqueens(n: usize)
} // 2 queens can't share the same column. join_distinct(&mut space.vstore, &mut space.cstore, queens); // space.cstore.alloc(Box::new(Distinct::new(queens))); // Search step. let mut search = one_solution_engine(); search.start(&space); let (frozen_space, status) = search.enter(space); let space = frozen_space.unfreeze(); // Print result. match status { Satisfiable => { print!("{}-queens problem is satisfiable. The first solution is:\n[", n); for dom in space.vstore.iter() { // At this stage, dom.lower() == dom.upper(). print!("{}, ", dom.lower()); } println!("]"); } Unsatisfiable => println!("{}-queens problem is unsatisfiable.", n), EndOfSearch => println!("Search terminated or was interrupted."), Unknown(_) => unreachable!( "After the search step, the problem instance should be either satisfiable or unsatisfiable.") } }
{ let mut space = FDSpace::empty(); let mut queens = vec![]; // 2 queens can't share the same line. for _ in 0..n { queens.push(Box::new(space.vstore.alloc(IntervalSet::new(1, n as i32))) as Var<VStore>); } for i in 0..n-1 { for j in i + 1..n { // 2 queens can't share the same diagonal. let q1 = (i + 1) as i32; let q2 = (j + 1) as i32; // Xi + i != Xj + j reformulated as: Xi != Xj + j - i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), q2 - q1)) as Var<VStore>))); // Xi - i != Xj - j reformulated as: Xi != Xj - j + i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), -q2 + q1)) as Var<VStore>))); }
identifier_body
nqueens.rs
// Copyright 2016 Pierre Talbot (IRCAM) // 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. // This example models the n-queens problem using interval domain (with `i32` bounds). use pcp::kernel::*; use pcp::propagators::*; use pcp::variable::ops::*; use pcp::term::*; use pcp::search::search_tree_visitor::Status::*; use pcp::search::*; use pcp::concept::*; use interval::ops::Range; use interval::interval_set::*; use gcollections::ops::*; pub fn nqueens(n: usize) { let mut space = FDSpace::empty(); let mut queens = vec![]; // 2 queens can't share the same line. for _ in 0..n { queens.push(Box::new(space.vstore.alloc(IntervalSet::new(1, n as i32))) as Var<VStore>); } for i in 0..n-1 { for j in i + 1..n { // 2 queens can't share the same diagonal. let q1 = (i + 1) as i32; let q2 = (j + 1) as i32; // Xi + i!= Xj + j reformulated as: Xi!= Xj + j - i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), q2 - q1)) as Var<VStore>))); // Xi - i!= Xj - j reformulated as: Xi!= Xj - j + i space.cstore.alloc(Box::new(XNeqY::new( queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), -q2 + q1)) as Var<VStore>))); } } // 2 queens can't share the same column. join_distinct(&mut space.vstore, &mut space.cstore, queens); // space.cstore.alloc(Box::new(Distinct::new(queens))); // Search step. let mut search = one_solution_engine(); search.start(&space); let (frozen_space, status) = search.enter(space); let space = frozen_space.unfreeze(); // Print result. match status { Satisfiable =>
Unsatisfiable => println!("{}-queens problem is unsatisfiable.", n), EndOfSearch => println!("Search terminated or was interrupted."), Unknown(_) => unreachable!( "After the search step, the problem instance should be either satisfiable or unsatisfiable.") } }
{ print!("{}-queens problem is satisfiable. The first solution is:\n[", n); for dom in space.vstore.iter() { // At this stage, dom.lower() == dom.upper(). print!("{}, ", dom.lower()); } println!("]"); }
conditional_block
structural_match.rs
use crate::infer::{InferCtxt, TyCtxtInferExt}; use crate::traits::ObligationCause; use crate::traits::{self, TraitEngine}; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt, TypeFoldable, TypeVisitor}; use rustc_span::Span; use std::ops::ControlFlow; #[derive(Debug)] pub enum NonStructuralMatchTy<'tcx> { Adt(&'tcx AdtDef), Param, Dynamic, Foreign, Opaque, Closure, Generator, Projection, } /// This method traverses the structure of `ty`, trying to find an /// instance of an ADT (i.e. struct or enum) that doesn't implement /// the structural-match traits, or a generic type parameter /// (which cannot be determined to be structural-match). /// /// The "structure of a type" includes all components that would be /// considered when doing a pattern match on a constant of that /// type. /// /// * This means this method descends into fields of structs/enums, /// and also descends into the inner type `T` of `&T` and `&mut T` /// /// * The traversal doesn't dereference unsafe pointers (`*const T`, /// `*mut T`), and it does not visit the type arguments of an /// instantiated generic like `PhantomData<T>`. /// /// The reason we do this search is Rust currently require all ADTs /// reachable from a constant's type to implement the /// structural-match traits, which essentially say that /// the implementation of `PartialEq::eq` behaves *equivalently* to a /// comparison against the unfolded structure. /// /// For more background on why Rust has this requirement, and issues /// that arose when the requirement was not enforced completely, see /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307. pub fn search_for_structural_match_violation<'tcx>( _id: hir::HirId, span: Span, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, ) -> Option<NonStructuralMatchTy<'tcx>> { // FIXME: we should instead pass in an `infcx` from the outside. tcx.infer_ctxt().enter(|infcx| { ty.visit_with(&mut Search { infcx, span, seen: FxHashSet::default() }).break_value() }) } /// This method returns true if and only if `adt_ty` itself has been marked as /// eligible for structural-match: namely, if it implements both /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by /// `#[derive(PartialEq)]` and `#[derive(Eq)]`). /// /// Note that this does *not* recursively check if the substructure of `adt_ty` /// implements the traits. fn type_marked_structural( infcx: &InferCtxt<'_, 'tcx>, adt_ty: Ty<'tcx>, cause: ObligationCause<'tcx>, ) -> bool { let mut fulfillment_cx = traits::FulfillmentContext::new(); // require `#[derive(PartialEq)]` let structural_peq_def_id = infcx.tcx.require_lang_item(LangItem::StructuralPeq, Some(cause.span)); fulfillment_cx.register_bound( infcx, ty::ParamEnv::empty(), adt_ty, structural_peq_def_id, cause.clone(), ); // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.) let structural_teq_def_id = infcx.tcx.require_lang_item(LangItem::StructuralTeq, Some(cause.span)); fulfillment_cx.register_bound( infcx, ty::ParamEnv::empty(), adt_ty, structural_teq_def_id, cause, ); // We deliberately skip *reporting* fulfillment errors (via // `report_fulfillment_errors`), for two reasons: // // 1. The error messages would mention `std::marker::StructuralPartialEq` // (a trait which is solely meant as an implementation detail // for now), and // // 2. We are sometimes doing future-incompatibility lints for // now, so we do not want unconditional errors here. fulfillment_cx.select_all_or_error(infcx).is_empty() } /// This implements the traversal over the structure of a given type to try to /// find instances of ADTs (specifically structs or enums) that do not implement /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`). struct Search<'a, 'tcx> { span: Span, infcx: InferCtxt<'a, 'tcx>, /// Tracks ADTs previously encountered during search, so that /// we will not recur on them again. seen: FxHashSet<hir::def_id::DefId>, } impl Search<'a, 'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.infcx.tcx } fn type_marked_structural(&self, adt_ty: Ty<'tcx>) -> bool { adt_ty.is_structural_eq_shallow(self.tcx()) } } impl<'a, 'tcx> TypeVisitor<'tcx> for Search<'a, 'tcx> { type BreakTy = NonStructuralMatchTy<'tcx>; fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { Some(self.tcx()) } fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { debug!("Search visiting ty: {:?}", ty); let (adt_def, substs) = match *ty.kind() { ty::Adt(adt_def, substs) => (adt_def, substs), ty::Param(_) => { return ControlFlow::Break(NonStructuralMatchTy::Param); } ty::Dynamic(..) => { return ControlFlow::Break(NonStructuralMatchTy::Dynamic); } ty::Foreign(_) => { return ControlFlow::Break(NonStructuralMatchTy::Foreign); } ty::Opaque(..) => { return ControlFlow::Break(NonStructuralMatchTy::Opaque); } ty::Projection(..) => { return ControlFlow::Break(NonStructuralMatchTy::Projection); } ty::Closure(..) => { return ControlFlow::Break(NonStructuralMatchTy::Closure); } ty::Generator(..) | ty::GeneratorWitness(..) => { return ControlFlow::Break(NonStructuralMatchTy::Generator); } ty::RawPtr(..) => { // structural-match ignores substructure of // `*const _`/`*mut _`, so skip `super_visit_with`. // // For example, if you have: // ``` // struct NonStructural; // #[derive(PartialEq, Eq)] // struct T(*const NonStructural); // const C: T = T(std::ptr::null()); // ``` // // Even though `NonStructural` does not implement `PartialEq`, // structural equality on `T` does not recur into the raw // pointer. Therefore, one can still use `C` in a pattern. return ControlFlow::CONTINUE; } ty::FnDef(..) | ty::FnPtr(..) => { // Types of formals and return in `fn(_) -> _` are also irrelevant; // so we do not recur into them via `super_visit_with` return ControlFlow::CONTINUE; } ty::Array(_, n) if { n.try_eval_usize(self.tcx(), ty::ParamEnv::reveal_all()) == Some(0) } => { // rust-lang/rust#62336: ignore type of contents // for empty array. return ControlFlow::CONTINUE; } ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never =>
ty::Array(..) | ty::Slice(_) | ty::Ref(..) | ty::Tuple(..) => { // First check all contained types and then tell the caller to continue searching. return ty.super_visit_with(self); } ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => { bug!("unexpected type during structural-match checking: {:?}", ty); } ty::Error(_) => { self.tcx().sess.delay_span_bug(self.span, "ty::Error in structural-match check"); // We still want to check other types after encountering an error, // as this may still emit relevant errors. return ControlFlow::CONTINUE; } }; if!self.seen.insert(adt_def.did) { debug!("Search already seen adt_def: {:?}", adt_def); return ControlFlow::CONTINUE; } if!self.type_marked_structural(ty) { debug!("Search found ty: {:?}", ty); return ControlFlow::Break(NonStructuralMatchTy::Adt(&adt_def)); } // structural-match does not care about the // instantiation of the generics in an ADT (it // instead looks directly at its fields outside // this match), so we skip super_visit_with. // // (Must not recur on substs for `PhantomData<T>` cf // rust-lang/rust#55028 and rust-lang/rust#55837; but also // want to skip substs when only uses of generic are // behind unsafe pointers `*const T`/`*mut T`.) // even though we skip super_visit_with, we must recur on // fields of ADT. let tcx = self.tcx(); adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| { let ty = self.tcx().normalize_erasing_regions(ty::ParamEnv::empty(), field_ty); debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty); ty.visit_with(self) }) } } pub fn provide(providers: &mut Providers) { providers.has_structural_eq_impls = |tcx, ty| { tcx.infer_ctxt().enter(|infcx| { let cause = ObligationCause::dummy(); type_marked_structural(&infcx, ty, cause) }) }; }
{ // These primitive types are always structural match. // // `Never` is kind of special here, but as it is not inhabitable, this should be fine. return ControlFlow::CONTINUE; }
conditional_block
structural_match.rs
use crate::infer::{InferCtxt, TyCtxtInferExt}; use crate::traits::ObligationCause; use crate::traits::{self, TraitEngine}; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt, TypeFoldable, TypeVisitor}; use rustc_span::Span; use std::ops::ControlFlow; #[derive(Debug)] pub enum NonStructuralMatchTy<'tcx> { Adt(&'tcx AdtDef), Param, Dynamic, Foreign, Opaque, Closure, Generator, Projection, } /// This method traverses the structure of `ty`, trying to find an /// instance of an ADT (i.e. struct or enum) that doesn't implement /// the structural-match traits, or a generic type parameter /// (which cannot be determined to be structural-match). /// /// The "structure of a type" includes all components that would be /// considered when doing a pattern match on a constant of that /// type. /// /// * This means this method descends into fields of structs/enums, /// and also descends into the inner type `T` of `&T` and `&mut T` /// /// * The traversal doesn't dereference unsafe pointers (`*const T`, /// `*mut T`), and it does not visit the type arguments of an /// instantiated generic like `PhantomData<T>`. /// /// The reason we do this search is Rust currently require all ADTs /// reachable from a constant's type to implement the /// structural-match traits, which essentially say that /// the implementation of `PartialEq::eq` behaves *equivalently* to a /// comparison against the unfolded structure. /// /// For more background on why Rust has this requirement, and issues /// that arose when the requirement was not enforced completely, see /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307. pub fn search_for_structural_match_violation<'tcx>( _id: hir::HirId, span: Span, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, ) -> Option<NonStructuralMatchTy<'tcx>> { // FIXME: we should instead pass in an `infcx` from the outside. tcx.infer_ctxt().enter(|infcx| { ty.visit_with(&mut Search { infcx, span, seen: FxHashSet::default() }).break_value() }) } /// This method returns true if and only if `adt_ty` itself has been marked as /// eligible for structural-match: namely, if it implements both /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by
/// Note that this does *not* recursively check if the substructure of `adt_ty` /// implements the traits. fn type_marked_structural( infcx: &InferCtxt<'_, 'tcx>, adt_ty: Ty<'tcx>, cause: ObligationCause<'tcx>, ) -> bool { let mut fulfillment_cx = traits::FulfillmentContext::new(); // require `#[derive(PartialEq)]` let structural_peq_def_id = infcx.tcx.require_lang_item(LangItem::StructuralPeq, Some(cause.span)); fulfillment_cx.register_bound( infcx, ty::ParamEnv::empty(), adt_ty, structural_peq_def_id, cause.clone(), ); // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.) let structural_teq_def_id = infcx.tcx.require_lang_item(LangItem::StructuralTeq, Some(cause.span)); fulfillment_cx.register_bound( infcx, ty::ParamEnv::empty(), adt_ty, structural_teq_def_id, cause, ); // We deliberately skip *reporting* fulfillment errors (via // `report_fulfillment_errors`), for two reasons: // // 1. The error messages would mention `std::marker::StructuralPartialEq` // (a trait which is solely meant as an implementation detail // for now), and // // 2. We are sometimes doing future-incompatibility lints for // now, so we do not want unconditional errors here. fulfillment_cx.select_all_or_error(infcx).is_empty() } /// This implements the traversal over the structure of a given type to try to /// find instances of ADTs (specifically structs or enums) that do not implement /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`). struct Search<'a, 'tcx> { span: Span, infcx: InferCtxt<'a, 'tcx>, /// Tracks ADTs previously encountered during search, so that /// we will not recur on them again. seen: FxHashSet<hir::def_id::DefId>, } impl Search<'a, 'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.infcx.tcx } fn type_marked_structural(&self, adt_ty: Ty<'tcx>) -> bool { adt_ty.is_structural_eq_shallow(self.tcx()) } } impl<'a, 'tcx> TypeVisitor<'tcx> for Search<'a, 'tcx> { type BreakTy = NonStructuralMatchTy<'tcx>; fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { Some(self.tcx()) } fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { debug!("Search visiting ty: {:?}", ty); let (adt_def, substs) = match *ty.kind() { ty::Adt(adt_def, substs) => (adt_def, substs), ty::Param(_) => { return ControlFlow::Break(NonStructuralMatchTy::Param); } ty::Dynamic(..) => { return ControlFlow::Break(NonStructuralMatchTy::Dynamic); } ty::Foreign(_) => { return ControlFlow::Break(NonStructuralMatchTy::Foreign); } ty::Opaque(..) => { return ControlFlow::Break(NonStructuralMatchTy::Opaque); } ty::Projection(..) => { return ControlFlow::Break(NonStructuralMatchTy::Projection); } ty::Closure(..) => { return ControlFlow::Break(NonStructuralMatchTy::Closure); } ty::Generator(..) | ty::GeneratorWitness(..) => { return ControlFlow::Break(NonStructuralMatchTy::Generator); } ty::RawPtr(..) => { // structural-match ignores substructure of // `*const _`/`*mut _`, so skip `super_visit_with`. // // For example, if you have: // ``` // struct NonStructural; // #[derive(PartialEq, Eq)] // struct T(*const NonStructural); // const C: T = T(std::ptr::null()); // ``` // // Even though `NonStructural` does not implement `PartialEq`, // structural equality on `T` does not recur into the raw // pointer. Therefore, one can still use `C` in a pattern. return ControlFlow::CONTINUE; } ty::FnDef(..) | ty::FnPtr(..) => { // Types of formals and return in `fn(_) -> _` are also irrelevant; // so we do not recur into them via `super_visit_with` return ControlFlow::CONTINUE; } ty::Array(_, n) if { n.try_eval_usize(self.tcx(), ty::ParamEnv::reveal_all()) == Some(0) } => { // rust-lang/rust#62336: ignore type of contents // for empty array. return ControlFlow::CONTINUE; } ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => { // These primitive types are always structural match. // // `Never` is kind of special here, but as it is not inhabitable, this should be fine. return ControlFlow::CONTINUE; } ty::Array(..) | ty::Slice(_) | ty::Ref(..) | ty::Tuple(..) => { // First check all contained types and then tell the caller to continue searching. return ty.super_visit_with(self); } ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => { bug!("unexpected type during structural-match checking: {:?}", ty); } ty::Error(_) => { self.tcx().sess.delay_span_bug(self.span, "ty::Error in structural-match check"); // We still want to check other types after encountering an error, // as this may still emit relevant errors. return ControlFlow::CONTINUE; } }; if!self.seen.insert(adt_def.did) { debug!("Search already seen adt_def: {:?}", adt_def); return ControlFlow::CONTINUE; } if!self.type_marked_structural(ty) { debug!("Search found ty: {:?}", ty); return ControlFlow::Break(NonStructuralMatchTy::Adt(&adt_def)); } // structural-match does not care about the // instantiation of the generics in an ADT (it // instead looks directly at its fields outside // this match), so we skip super_visit_with. // // (Must not recur on substs for `PhantomData<T>` cf // rust-lang/rust#55028 and rust-lang/rust#55837; but also // want to skip substs when only uses of generic are // behind unsafe pointers `*const T`/`*mut T`.) // even though we skip super_visit_with, we must recur on // fields of ADT. let tcx = self.tcx(); adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| { let ty = self.tcx().normalize_erasing_regions(ty::ParamEnv::empty(), field_ty); debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty); ty.visit_with(self) }) } } pub fn provide(providers: &mut Providers) { providers.has_structural_eq_impls = |tcx, ty| { tcx.infer_ctxt().enter(|infcx| { let cause = ObligationCause::dummy(); type_marked_structural(&infcx, ty, cause) }) }; }
/// `#[derive(PartialEq)]` and `#[derive(Eq)]`). ///
random_line_split
structural_match.rs
use crate::infer::{InferCtxt, TyCtxtInferExt}; use crate::traits::ObligationCause; use crate::traits::{self, TraitEngine}; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt, TypeFoldable, TypeVisitor}; use rustc_span::Span; use std::ops::ControlFlow; #[derive(Debug)] pub enum NonStructuralMatchTy<'tcx> { Adt(&'tcx AdtDef), Param, Dynamic, Foreign, Opaque, Closure, Generator, Projection, } /// This method traverses the structure of `ty`, trying to find an /// instance of an ADT (i.e. struct or enum) that doesn't implement /// the structural-match traits, or a generic type parameter /// (which cannot be determined to be structural-match). /// /// The "structure of a type" includes all components that would be /// considered when doing a pattern match on a constant of that /// type. /// /// * This means this method descends into fields of structs/enums, /// and also descends into the inner type `T` of `&T` and `&mut T` /// /// * The traversal doesn't dereference unsafe pointers (`*const T`, /// `*mut T`), and it does not visit the type arguments of an /// instantiated generic like `PhantomData<T>`. /// /// The reason we do this search is Rust currently require all ADTs /// reachable from a constant's type to implement the /// structural-match traits, which essentially say that /// the implementation of `PartialEq::eq` behaves *equivalently* to a /// comparison against the unfolded structure. /// /// For more background on why Rust has this requirement, and issues /// that arose when the requirement was not enforced completely, see /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307. pub fn search_for_structural_match_violation<'tcx>( _id: hir::HirId, span: Span, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, ) -> Option<NonStructuralMatchTy<'tcx>> { // FIXME: we should instead pass in an `infcx` from the outside. tcx.infer_ctxt().enter(|infcx| { ty.visit_with(&mut Search { infcx, span, seen: FxHashSet::default() }).break_value() }) } /// This method returns true if and only if `adt_ty` itself has been marked as /// eligible for structural-match: namely, if it implements both /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by /// `#[derive(PartialEq)]` and `#[derive(Eq)]`). /// /// Note that this does *not* recursively check if the substructure of `adt_ty` /// implements the traits. fn type_marked_structural( infcx: &InferCtxt<'_, 'tcx>, adt_ty: Ty<'tcx>, cause: ObligationCause<'tcx>, ) -> bool { let mut fulfillment_cx = traits::FulfillmentContext::new(); // require `#[derive(PartialEq)]` let structural_peq_def_id = infcx.tcx.require_lang_item(LangItem::StructuralPeq, Some(cause.span)); fulfillment_cx.register_bound( infcx, ty::ParamEnv::empty(), adt_ty, structural_peq_def_id, cause.clone(), ); // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.) let structural_teq_def_id = infcx.tcx.require_lang_item(LangItem::StructuralTeq, Some(cause.span)); fulfillment_cx.register_bound( infcx, ty::ParamEnv::empty(), adt_ty, structural_teq_def_id, cause, ); // We deliberately skip *reporting* fulfillment errors (via // `report_fulfillment_errors`), for two reasons: // // 1. The error messages would mention `std::marker::StructuralPartialEq` // (a trait which is solely meant as an implementation detail // for now), and // // 2. We are sometimes doing future-incompatibility lints for // now, so we do not want unconditional errors here. fulfillment_cx.select_all_or_error(infcx).is_empty() } /// This implements the traversal over the structure of a given type to try to /// find instances of ADTs (specifically structs or enums) that do not implement /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`). struct Search<'a, 'tcx> { span: Span, infcx: InferCtxt<'a, 'tcx>, /// Tracks ADTs previously encountered during search, so that /// we will not recur on them again. seen: FxHashSet<hir::def_id::DefId>, } impl Search<'a, 'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.infcx.tcx } fn
(&self, adt_ty: Ty<'tcx>) -> bool { adt_ty.is_structural_eq_shallow(self.tcx()) } } impl<'a, 'tcx> TypeVisitor<'tcx> for Search<'a, 'tcx> { type BreakTy = NonStructuralMatchTy<'tcx>; fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { Some(self.tcx()) } fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { debug!("Search visiting ty: {:?}", ty); let (adt_def, substs) = match *ty.kind() { ty::Adt(adt_def, substs) => (adt_def, substs), ty::Param(_) => { return ControlFlow::Break(NonStructuralMatchTy::Param); } ty::Dynamic(..) => { return ControlFlow::Break(NonStructuralMatchTy::Dynamic); } ty::Foreign(_) => { return ControlFlow::Break(NonStructuralMatchTy::Foreign); } ty::Opaque(..) => { return ControlFlow::Break(NonStructuralMatchTy::Opaque); } ty::Projection(..) => { return ControlFlow::Break(NonStructuralMatchTy::Projection); } ty::Closure(..) => { return ControlFlow::Break(NonStructuralMatchTy::Closure); } ty::Generator(..) | ty::GeneratorWitness(..) => { return ControlFlow::Break(NonStructuralMatchTy::Generator); } ty::RawPtr(..) => { // structural-match ignores substructure of // `*const _`/`*mut _`, so skip `super_visit_with`. // // For example, if you have: // ``` // struct NonStructural; // #[derive(PartialEq, Eq)] // struct T(*const NonStructural); // const C: T = T(std::ptr::null()); // ``` // // Even though `NonStructural` does not implement `PartialEq`, // structural equality on `T` does not recur into the raw // pointer. Therefore, one can still use `C` in a pattern. return ControlFlow::CONTINUE; } ty::FnDef(..) | ty::FnPtr(..) => { // Types of formals and return in `fn(_) -> _` are also irrelevant; // so we do not recur into them via `super_visit_with` return ControlFlow::CONTINUE; } ty::Array(_, n) if { n.try_eval_usize(self.tcx(), ty::ParamEnv::reveal_all()) == Some(0) } => { // rust-lang/rust#62336: ignore type of contents // for empty array. return ControlFlow::CONTINUE; } ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => { // These primitive types are always structural match. // // `Never` is kind of special here, but as it is not inhabitable, this should be fine. return ControlFlow::CONTINUE; } ty::Array(..) | ty::Slice(_) | ty::Ref(..) | ty::Tuple(..) => { // First check all contained types and then tell the caller to continue searching. return ty.super_visit_with(self); } ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => { bug!("unexpected type during structural-match checking: {:?}", ty); } ty::Error(_) => { self.tcx().sess.delay_span_bug(self.span, "ty::Error in structural-match check"); // We still want to check other types after encountering an error, // as this may still emit relevant errors. return ControlFlow::CONTINUE; } }; if!self.seen.insert(adt_def.did) { debug!("Search already seen adt_def: {:?}", adt_def); return ControlFlow::CONTINUE; } if!self.type_marked_structural(ty) { debug!("Search found ty: {:?}", ty); return ControlFlow::Break(NonStructuralMatchTy::Adt(&adt_def)); } // structural-match does not care about the // instantiation of the generics in an ADT (it // instead looks directly at its fields outside // this match), so we skip super_visit_with. // // (Must not recur on substs for `PhantomData<T>` cf // rust-lang/rust#55028 and rust-lang/rust#55837; but also // want to skip substs when only uses of generic are // behind unsafe pointers `*const T`/`*mut T`.) // even though we skip super_visit_with, we must recur on // fields of ADT. let tcx = self.tcx(); adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| { let ty = self.tcx().normalize_erasing_regions(ty::ParamEnv::empty(), field_ty); debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty); ty.visit_with(self) }) } } pub fn provide(providers: &mut Providers) { providers.has_structural_eq_impls = |tcx, ty| { tcx.infer_ctxt().enter(|infcx| { let cause = ObligationCause::dummy(); type_marked_structural(&infcx, ty, cause) }) }; }
type_marked_structural
identifier_name
test_client_full.rs
use std::mem; use bip_util::bt::{self}; use bip_utracker::{TrackerClient, ClientRequest}; use bip_utracker::announce::{ClientState, AnnounceEvent}; use futures::stream::Stream; use futures::{Future}; use {handshaker}; #[test] #[allow(unused)] fn
() { let (sink, mut stream) = handshaker(); let server_addr = "127.0.0.1:3504".parse().unwrap(); let request_capacity = 10; let mut client = TrackerClient::with_capacity("127.0.0.1:4504".parse().unwrap(), sink, request_capacity).unwrap(); for _ in 0..request_capacity { client.request(server_addr, ClientRequest::Announce( [0u8; bt::INFO_HASH_LEN].into(), ClientState::new(0, 0, 0, AnnounceEvent::Started) )).unwrap(); } assert!(client.request(server_addr, ClientRequest::Announce( [0u8; bt::INFO_HASH_LEN].into(), ClientState::new(0, 0, 0, AnnounceEvent::Started) )).is_none()); mem::drop(client); let buffer = stream.collect().wait().unwrap(); assert_eq!(request_capacity, buffer.len()); }
positive_client_request_dropped
identifier_name
test_client_full.rs
use std::mem; use bip_util::bt::{self}; use bip_utracker::{TrackerClient, ClientRequest}; use bip_utracker::announce::{ClientState, AnnounceEvent}; use futures::stream::Stream; use futures::{Future}; use {handshaker}; #[test] #[allow(unused)] fn positive_client_request_dropped()
mem::drop(client); let buffer = stream.collect().wait().unwrap(); assert_eq!(request_capacity, buffer.len()); }
{ let (sink, mut stream) = handshaker(); let server_addr = "127.0.0.1:3504".parse().unwrap(); let request_capacity = 10; let mut client = TrackerClient::with_capacity("127.0.0.1:4504".parse().unwrap(), sink, request_capacity).unwrap(); for _ in 0..request_capacity { client.request(server_addr, ClientRequest::Announce( [0u8; bt::INFO_HASH_LEN].into(), ClientState::new(0, 0, 0, AnnounceEvent::Started) )).unwrap(); } assert!(client.request(server_addr, ClientRequest::Announce( [0u8; bt::INFO_HASH_LEN].into(), ClientState::new(0, 0, 0, AnnounceEvent::Started) )).is_none());
identifier_body
test_client_full.rs
use std::mem; use bip_util::bt::{self}; use bip_utracker::{TrackerClient, ClientRequest}; use bip_utracker::announce::{ClientState, AnnounceEvent}; use futures::stream::Stream;
#[allow(unused)] fn positive_client_request_dropped() { let (sink, mut stream) = handshaker(); let server_addr = "127.0.0.1:3504".parse().unwrap(); let request_capacity = 10; let mut client = TrackerClient::with_capacity("127.0.0.1:4504".parse().unwrap(), sink, request_capacity).unwrap(); for _ in 0..request_capacity { client.request(server_addr, ClientRequest::Announce( [0u8; bt::INFO_HASH_LEN].into(), ClientState::new(0, 0, 0, AnnounceEvent::Started) )).unwrap(); } assert!(client.request(server_addr, ClientRequest::Announce( [0u8; bt::INFO_HASH_LEN].into(), ClientState::new(0, 0, 0, AnnounceEvent::Started) )).is_none()); mem::drop(client); let buffer = stream.collect().wait().unwrap(); assert_eq!(request_capacity, buffer.len()); }
use futures::{Future}; use {handshaker}; #[test]
random_line_split
mod.rs
mod batch; mod interactive; mod text; use crate::command::JudgingCommand; use crate::config::Config; use crate::errors::{JudgeErrorKind, JudgeResult, TestSuiteResult}; use crate::terminal::{TermOut, WriteAnsi, WriteSpaces}; use crate::testsuite::{BatchCase, TestCase, TestCases}; use crate::util::std_unstable::AsMillis_; use futures::{Future, Sink, Stream}; use itertools::Itertools; use tokio::runtime::Runtime; use std::io::{self, BufRead}; use std::num::NonZeroUsize; use std::sync::Arc; use std::time::Duration; use std::{cmp, fmt}; pub(crate) fn num_cases(config: &Config, problem: &str) -> TestSuiteResult<usize> { let (cases, _) = config.testcase_loader().load_merging(problem)?; Ok(match cases { TestCases::Batch(cases) => cases.len(), TestCases::Interactive(cases) => cases.len(), }) } pub(crate) fn timelimit_millis(config: &Config, problem: &str, nth: usize) -> JudgeResult<u128> { fn get_timelimit_millis<C>( cases: &[C], nth: usize, f: fn(&C) -> Option<Duration>, ) -> JudgeResult<u128> { cases .get(nth) .and_then(f) .map(AsMillis_::as_millis_) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), TestCases::Interactive(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), } } pub(crate) fn input(config: &Config, problem: &str, nth: usize) -> JudgeResult<Arc<String>>
pub(crate) fn accepts( config: &Config, problem: &str, nth: usize, mut stdin: impl BufRead, mut stderr: impl TermOut, ) -> JudgeResult<()> { let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => { let case = cases .get(nth) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth))?; let mut output = "".to_owned(); stdin.read_to_string(&mut output)?; let outcome = batch::accepts(&case, &output); if outcome.failure() { outcome.print_details(config.judge_display_limit(), &mut stderr)?; stderr.flush()?; Err(JudgeErrorKind::TestFailed(1, 1).into()) } else { Ok(()) } } TestCases::Interactive(_) => Err(JudgeErrorKind::ExpectedBatch.into()), } } pub(crate) fn only_transpile( stdout: impl TermOut, stderr: impl TermOut, config: &Config, problem: &str, force: bool, ) -> JudgeResult<bool> { match config.solver_transpilation()? { None => Ok(false), Some(transpilation) => { let transpilation = transpilation.expand(problem)?; transpilation.run(stdout, stderr, force)?; Ok(true) } } } /// Executes the tests. /// /// # Errors /// /// Returns `Err` if compilation or execution command fails, or any test fails. pub(crate) fn judge(params: JudgeParams<impl TermOut, impl TermOut>) -> JudgeResult<()> { fn judge_all< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut stdout: impl TermOut, mut stderr: impl TermOut, jobs: NonZeroUsize, display_limit: Option<usize>, cases: Vec<C>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { let num_cases = cases.len(); let names = cases.iter().map(|c| c.name()).collect::<Vec<_>>(); let name_max_width = names.iter().map(|s| stdout.str_width(s)).max().unwrap_or(0); let mut cases = names .into_iter() .zip_eq(cases) .enumerate() .map(|(i, (name, case))| (i, name, case)); let (tx, rx) = futures::sync::mpsc::channel(num_cases); let mut runtime = Runtime::new()?; { let tx = tx.clone(); runtime.spawn(crate::signal::ctrl_c().then(move |r| { let (dummy_i, dummy_name) = (num_cases, Arc::new("".to_owned())); let _ = tx.send((dummy_i, dummy_name, r)).wait(); Ok(()) })); } for _ in 0..jobs.get() { spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; } write!(stderr, "0/{} test finished (0 failure)", num_cases)?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; let (mut num_finished, mut num_failures) = (0, 0); let mut outcomes = rx .take(num_cases as u64) .then::<_, JudgeResult<_>>(|r| { let (i, name, r) = r.unwrap(); let outcome = r?; num_finished += 1; if outcome.failure() { num_failures += 1; } if stderr.supports_color() { stderr.write_str("\x1b[0G\x1b[2K")?; } let color = match num_failures { 0 => 10, _ => 9, }; stderr.with_reset(|o| { write!( o.fg(color)?, "{}/{} {} finished ({})", num_finished, num_cases, if num_finished > 1 { "tests" } else { "test" }, plural!(num_failures, "failure", "failures"), ) })?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; Ok((i, name, outcome)) }) .collect() .wait()?; if stderr.supports_color() { writeln!(stderr)?; stderr.flush()?; } outcomes.sort_by_key(|(i, _, _)| *i); let _ = runtime.shutdown_now().wait(); if num_failures == 0 { for (i, name, outcome) in outcomes { outcome.print_title(&mut stdout, i + 1, num_cases, &name, Some(name_max_width))?; } writeln!( stdout, "All of the {} passed.", plural!(num_cases, "test", "tests") )?; stdout.flush()?; Ok(()) } else { for (i, name, outcome) in outcomes { writeln!(stdout)?; outcome.print_title(&mut stdout, i + 1, num_cases, &name, None)?; outcome.print_details(display_limit, &mut stdout)?; } stdout.flush()?; Err(JudgeErrorKind::TestFailed(num_failures, num_cases).into()) } } fn spawn_head< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut cases: impl Iterator<Item = (usize, Arc<String>, C)>, runtime: &mut Runtime, tx: futures::sync::mpsc::Sender<(usize, Arc<String>, JudgeResult<O>)>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { if let Some((i, name, case)) = cases.next() { runtime.spawn(judge(&case, solver)?.then(move |r| { let _ = tx.send((i, name, r.map_err(Into::into))).wait(); // `rx` may be dropped Ok(()) })); } Ok(()) } let JudgeParams { mut stdout, mut stderr, config, problem, force_compile, jobs, } = params; let (cases, paths_formatted) = config.testcase_loader().load_merging(problem)?; let jobs = jobs .or_else(|| config.judge_jobs()) .unwrap_or_else(|| NonZeroUsize::new(1).unwrap()); let display_limit = config.judge_display_limit(); let tester_transpilations = cases.interactive_tester_transpilations(); let tester_compilations = cases.interactive_tester_compilations(); let solver = config.solver()?.expand(&problem)?; let solver_transpilation = match config.solver_transpilation()? { Some(transpilation) => Some(transpilation.expand(&problem)?), None => None, }; let solver_compilation = match config.solver_compilation()? { Some(compilation) => Some(compilation.expand(&problem)?), None => None, }; for tester_transpilation in tester_transpilations { tester_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } for tester_compilation in tester_compilations { tester_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_transpilation) = solver_transpilation { solver_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_compilation) = solver_compilation { solver_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } solver.write_info(&mut stdout, &paths_formatted)?; stdout.flush()?; let solver = Arc::new(solver); match cases { TestCases::Batch(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver, batch::judge, ), TestCases::Interactive(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver, interactive::judge, ), } } pub(crate) struct JudgeParams<'a, O: TermOut, E: TermOut> { pub stdout: O, pub stderr: E, pub config: &'a Config, pub problem: &'a str, pub force_compile: bool, pub jobs: Option<NonZeroUsize>, } pub(self) trait Outcome: fmt::Display { fn failure(&self) -> bool; fn color(&self) -> u8; fn print_details(&self, display_limit: Option<usize>, out: impl TermOut) -> io::Result<()>; fn print_title( &self, mut out: impl TermOut, i: impl DisplayableNum, n: impl DisplayableNum, name: &str, name_width: Option<usize>, ) -> io::Result<()> { if name_width.is_some() { out.write_spaces(n.num_digits() - i.num_digits())?; } out.with_reset(|o| write!(o.bold()?, "{}/{} ({})", i, n, name))?; let l = out.str_width(name); let name_width = name_width.unwrap_or(0); out.write_spaces(cmp::max(name_width, l) - l + 1)?; out.with_reset(|o| writeln!(o.fg(self.color())?, "{}", self)) } } trait DisplayableNum: fmt::Display + Copy { fn num_digits(self) -> usize; } impl DisplayableNum for usize { fn num_digits(mut self) -> usize { let mut r = 1; while self > 9 { self /= 10; r += 1; } r } } pub(self) fn writeln_size(mut out: impl WriteAnsi, size: usize) -> io::Result<()> { let gib = size / 2usize.pow(30); let mib = (size / 2usize.pow(20)) & 0x3ff; let kib = (size / 2usize.pow(10)) & 0x3ff; let b = size & 0x3ff; out.with_reset(|out| { out.fg(11)?.bold()?; match (gib, mib, kib, b) { (0, 0, 0, b) => writeln!(out, "{}B", b), (0, 0, k, b) => writeln!(out, "{}.{}KiB", k, b / 0x67), (0, m, k, _) => writeln!(out, "{}.{}MiB", m, k / 0x67), (g, m, _, _) => writeln!(out, "{}.{}GiB", g, m / 0x67), } }) }
{ let (cases, _) = config.testcase_loader().load_merging(problem)?; match &cases { TestCases::Batch(cases) => cases .get(nth) .map(BatchCase::input) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()), TestCases::Interactive(cases) if nth < cases.len() => Ok(Arc::new("".to_owned())), TestCases::Interactive(cases) => { Err(JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } } }
identifier_body
mod.rs
mod batch; mod interactive; mod text; use crate::command::JudgingCommand; use crate::config::Config; use crate::errors::{JudgeErrorKind, JudgeResult, TestSuiteResult}; use crate::terminal::{TermOut, WriteAnsi, WriteSpaces}; use crate::testsuite::{BatchCase, TestCase, TestCases}; use crate::util::std_unstable::AsMillis_; use futures::{Future, Sink, Stream}; use itertools::Itertools; use tokio::runtime::Runtime; use std::io::{self, BufRead}; use std::num::NonZeroUsize; use std::sync::Arc; use std::time::Duration; use std::{cmp, fmt}; pub(crate) fn num_cases(config: &Config, problem: &str) -> TestSuiteResult<usize> { let (cases, _) = config.testcase_loader().load_merging(problem)?; Ok(match cases { TestCases::Batch(cases) => cases.len(), TestCases::Interactive(cases) => cases.len(), }) } pub(crate) fn timelimit_millis(config: &Config, problem: &str, nth: usize) -> JudgeResult<u128> { fn get_timelimit_millis<C>( cases: &[C], nth: usize, f: fn(&C) -> Option<Duration>, ) -> JudgeResult<u128> { cases .get(nth) .and_then(f) .map(AsMillis_::as_millis_) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), TestCases::Interactive(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), } } pub(crate) fn input(config: &Config, problem: &str, nth: usize) -> JudgeResult<Arc<String>> { let (cases, _) = config.testcase_loader().load_merging(problem)?; match &cases { TestCases::Batch(cases) => cases .get(nth) .map(BatchCase::input) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()), TestCases::Interactive(cases) if nth < cases.len() => Ok(Arc::new("".to_owned())), TestCases::Interactive(cases) => { Err(JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } } } pub(crate) fn accepts( config: &Config, problem: &str, nth: usize, mut stdin: impl BufRead, mut stderr: impl TermOut, ) -> JudgeResult<()> { let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => { let case = cases .get(nth) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth))?; let mut output = "".to_owned(); stdin.read_to_string(&mut output)?; let outcome = batch::accepts(&case, &output); if outcome.failure() { outcome.print_details(config.judge_display_limit(), &mut stderr)?; stderr.flush()?; Err(JudgeErrorKind::TestFailed(1, 1).into()) } else { Ok(()) } } TestCases::Interactive(_) => Err(JudgeErrorKind::ExpectedBatch.into()), } } pub(crate) fn only_transpile( stdout: impl TermOut, stderr: impl TermOut, config: &Config, problem: &str, force: bool, ) -> JudgeResult<bool> { match config.solver_transpilation()? { None => Ok(false), Some(transpilation) => { let transpilation = transpilation.expand(problem)?; transpilation.run(stdout, stderr, force)?; Ok(true) } } } /// Executes the tests. /// /// # Errors /// /// Returns `Err` if compilation or execution command fails, or any test fails. pub(crate) fn judge(params: JudgeParams<impl TermOut, impl TermOut>) -> JudgeResult<()> { fn judge_all< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut stdout: impl TermOut, mut stderr: impl TermOut, jobs: NonZeroUsize, display_limit: Option<usize>, cases: Vec<C>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { let num_cases = cases.len(); let names = cases.iter().map(|c| c.name()).collect::<Vec<_>>(); let name_max_width = names.iter().map(|s| stdout.str_width(s)).max().unwrap_or(0); let mut cases = names .into_iter() .zip_eq(cases) .enumerate() .map(|(i, (name, case))| (i, name, case)); let (tx, rx) = futures::sync::mpsc::channel(num_cases); let mut runtime = Runtime::new()?; { let tx = tx.clone(); runtime.spawn(crate::signal::ctrl_c().then(move |r| { let (dummy_i, dummy_name) = (num_cases, Arc::new("".to_owned())); let _ = tx.send((dummy_i, dummy_name, r)).wait(); Ok(()) })); } for _ in 0..jobs.get() { spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; } write!(stderr, "0/{} test finished (0 failure)", num_cases)?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; let (mut num_finished, mut num_failures) = (0, 0); let mut outcomes = rx .take(num_cases as u64) .then::<_, JudgeResult<_>>(|r| { let (i, name, r) = r.unwrap(); let outcome = r?; num_finished += 1; if outcome.failure() { num_failures += 1; } if stderr.supports_color() { stderr.write_str("\x1b[0G\x1b[2K")?; } let color = match num_failures { 0 => 10, _ => 9, }; stderr.with_reset(|o| { write!( o.fg(color)?, "{}/{} {} finished ({})", num_finished, num_cases, if num_finished > 1 { "tests" } else { "test" }, plural!(num_failures, "failure", "failures"), ) })?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; Ok((i, name, outcome)) }) .collect() .wait()?; if stderr.supports_color() { writeln!(stderr)?; stderr.flush()?; } outcomes.sort_by_key(|(i, _, _)| *i); let _ = runtime.shutdown_now().wait(); if num_failures == 0 { for (i, name, outcome) in outcomes { outcome.print_title(&mut stdout, i + 1, num_cases, &name, Some(name_max_width))?; } writeln!( stdout, "All of the {} passed.", plural!(num_cases, "test", "tests") )?; stdout.flush()?; Ok(()) } else { for (i, name, outcome) in outcomes { writeln!(stdout)?; outcome.print_title(&mut stdout, i + 1, num_cases, &name, None)?; outcome.print_details(display_limit, &mut stdout)?; } stdout.flush()?; Err(JudgeErrorKind::TestFailed(num_failures, num_cases).into()) } } fn spawn_head< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut cases: impl Iterator<Item = (usize, Arc<String>, C)>, runtime: &mut Runtime, tx: futures::sync::mpsc::Sender<(usize, Arc<String>, JudgeResult<O>)>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { if let Some((i, name, case)) = cases.next() { runtime.spawn(judge(&case, solver)?.then(move |r| { let _ = tx.send((i, name, r.map_err(Into::into))).wait(); // `rx` may be dropped Ok(()) })); } Ok(()) } let JudgeParams { mut stdout, mut stderr, config, problem, force_compile, jobs, } = params; let (cases, paths_formatted) = config.testcase_loader().load_merging(problem)?; let jobs = jobs .or_else(|| config.judge_jobs()) .unwrap_or_else(|| NonZeroUsize::new(1).unwrap()); let display_limit = config.judge_display_limit(); let tester_transpilations = cases.interactive_tester_transpilations(); let tester_compilations = cases.interactive_tester_compilations(); let solver = config.solver()?.expand(&problem)?; let solver_transpilation = match config.solver_transpilation()? { Some(transpilation) => Some(transpilation.expand(&problem)?), None => None, }; let solver_compilation = match config.solver_compilation()? { Some(compilation) => Some(compilation.expand(&problem)?), None => None, }; for tester_transpilation in tester_transpilations { tester_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } for tester_compilation in tester_compilations { tester_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_transpilation) = solver_transpilation { solver_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_compilation) = solver_compilation { solver_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } solver.write_info(&mut stdout, &paths_formatted)?; stdout.flush()?; let solver = Arc::new(solver); match cases { TestCases::Batch(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver,
), TestCases::Interactive(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver, interactive::judge, ), } } pub(crate) struct JudgeParams<'a, O: TermOut, E: TermOut> { pub stdout: O, pub stderr: E, pub config: &'a Config, pub problem: &'a str, pub force_compile: bool, pub jobs: Option<NonZeroUsize>, } pub(self) trait Outcome: fmt::Display { fn failure(&self) -> bool; fn color(&self) -> u8; fn print_details(&self, display_limit: Option<usize>, out: impl TermOut) -> io::Result<()>; fn print_title( &self, mut out: impl TermOut, i: impl DisplayableNum, n: impl DisplayableNum, name: &str, name_width: Option<usize>, ) -> io::Result<()> { if name_width.is_some() { out.write_spaces(n.num_digits() - i.num_digits())?; } out.with_reset(|o| write!(o.bold()?, "{}/{} ({})", i, n, name))?; let l = out.str_width(name); let name_width = name_width.unwrap_or(0); out.write_spaces(cmp::max(name_width, l) - l + 1)?; out.with_reset(|o| writeln!(o.fg(self.color())?, "{}", self)) } } trait DisplayableNum: fmt::Display + Copy { fn num_digits(self) -> usize; } impl DisplayableNum for usize { fn num_digits(mut self) -> usize { let mut r = 1; while self > 9 { self /= 10; r += 1; } r } } pub(self) fn writeln_size(mut out: impl WriteAnsi, size: usize) -> io::Result<()> { let gib = size / 2usize.pow(30); let mib = (size / 2usize.pow(20)) & 0x3ff; let kib = (size / 2usize.pow(10)) & 0x3ff; let b = size & 0x3ff; out.with_reset(|out| { out.fg(11)?.bold()?; match (gib, mib, kib, b) { (0, 0, 0, b) => writeln!(out, "{}B", b), (0, 0, k, b) => writeln!(out, "{}.{}KiB", k, b / 0x67), (0, m, k, _) => writeln!(out, "{}.{}MiB", m, k / 0x67), (g, m, _, _) => writeln!(out, "{}.{}GiB", g, m / 0x67), } }) }
batch::judge,
random_line_split
mod.rs
mod batch; mod interactive; mod text; use crate::command::JudgingCommand; use crate::config::Config; use crate::errors::{JudgeErrorKind, JudgeResult, TestSuiteResult}; use crate::terminal::{TermOut, WriteAnsi, WriteSpaces}; use crate::testsuite::{BatchCase, TestCase, TestCases}; use crate::util::std_unstable::AsMillis_; use futures::{Future, Sink, Stream}; use itertools::Itertools; use tokio::runtime::Runtime; use std::io::{self, BufRead}; use std::num::NonZeroUsize; use std::sync::Arc; use std::time::Duration; use std::{cmp, fmt}; pub(crate) fn num_cases(config: &Config, problem: &str) -> TestSuiteResult<usize> { let (cases, _) = config.testcase_loader().load_merging(problem)?; Ok(match cases { TestCases::Batch(cases) => cases.len(), TestCases::Interactive(cases) => cases.len(), }) } pub(crate) fn timelimit_millis(config: &Config, problem: &str, nth: usize) -> JudgeResult<u128> { fn get_timelimit_millis<C>( cases: &[C], nth: usize, f: fn(&C) -> Option<Duration>, ) -> JudgeResult<u128> { cases .get(nth) .and_then(f) .map(AsMillis_::as_millis_) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), TestCases::Interactive(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), } } pub(crate) fn input(config: &Config, problem: &str, nth: usize) -> JudgeResult<Arc<String>> { let (cases, _) = config.testcase_loader().load_merging(problem)?; match &cases { TestCases::Batch(cases) => cases .get(nth) .map(BatchCase::input) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()), TestCases::Interactive(cases) if nth < cases.len() => Ok(Arc::new("".to_owned())), TestCases::Interactive(cases) => { Err(JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } } } pub(crate) fn accepts( config: &Config, problem: &str, nth: usize, mut stdin: impl BufRead, mut stderr: impl TermOut, ) -> JudgeResult<()> { let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => { let case = cases .get(nth) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth))?; let mut output = "".to_owned(); stdin.read_to_string(&mut output)?; let outcome = batch::accepts(&case, &output); if outcome.failure() { outcome.print_details(config.judge_display_limit(), &mut stderr)?; stderr.flush()?; Err(JudgeErrorKind::TestFailed(1, 1).into()) } else { Ok(()) } } TestCases::Interactive(_) => Err(JudgeErrorKind::ExpectedBatch.into()), } } pub(crate) fn only_transpile( stdout: impl TermOut, stderr: impl TermOut, config: &Config, problem: &str, force: bool, ) -> JudgeResult<bool> { match config.solver_transpilation()? { None => Ok(false), Some(transpilation) => { let transpilation = transpilation.expand(problem)?; transpilation.run(stdout, stderr, force)?; Ok(true) } } } /// Executes the tests. /// /// # Errors /// /// Returns `Err` if compilation or execution command fails, or any test fails. pub(crate) fn judge(params: JudgeParams<impl TermOut, impl TermOut>) -> JudgeResult<()> { fn judge_all< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut stdout: impl TermOut, mut stderr: impl TermOut, jobs: NonZeroUsize, display_limit: Option<usize>, cases: Vec<C>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { let num_cases = cases.len(); let names = cases.iter().map(|c| c.name()).collect::<Vec<_>>(); let name_max_width = names.iter().map(|s| stdout.str_width(s)).max().unwrap_or(0); let mut cases = names .into_iter() .zip_eq(cases) .enumerate() .map(|(i, (name, case))| (i, name, case)); let (tx, rx) = futures::sync::mpsc::channel(num_cases); let mut runtime = Runtime::new()?; { let tx = tx.clone(); runtime.spawn(crate::signal::ctrl_c().then(move |r| { let (dummy_i, dummy_name) = (num_cases, Arc::new("".to_owned())); let _ = tx.send((dummy_i, dummy_name, r)).wait(); Ok(()) })); } for _ in 0..jobs.get() { spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; } write!(stderr, "0/{} test finished (0 failure)", num_cases)?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; let (mut num_finished, mut num_failures) = (0, 0); let mut outcomes = rx .take(num_cases as u64) .then::<_, JudgeResult<_>>(|r| { let (i, name, r) = r.unwrap(); let outcome = r?; num_finished += 1; if outcome.failure() { num_failures += 1; } if stderr.supports_color() { stderr.write_str("\x1b[0G\x1b[2K")?; } let color = match num_failures { 0 => 10, _ => 9, }; stderr.with_reset(|o| { write!( o.fg(color)?, "{}/{} {} finished ({})", num_finished, num_cases, if num_finished > 1 { "tests" } else { "test" }, plural!(num_failures, "failure", "failures"), ) })?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; Ok((i, name, outcome)) }) .collect() .wait()?; if stderr.supports_color() { writeln!(stderr)?; stderr.flush()?; } outcomes.sort_by_key(|(i, _, _)| *i); let _ = runtime.shutdown_now().wait(); if num_failures == 0
else { for (i, name, outcome) in outcomes { writeln!(stdout)?; outcome.print_title(&mut stdout, i + 1, num_cases, &name, None)?; outcome.print_details(display_limit, &mut stdout)?; } stdout.flush()?; Err(JudgeErrorKind::TestFailed(num_failures, num_cases).into()) } } fn spawn_head< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut cases: impl Iterator<Item = (usize, Arc<String>, C)>, runtime: &mut Runtime, tx: futures::sync::mpsc::Sender<(usize, Arc<String>, JudgeResult<O>)>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { if let Some((i, name, case)) = cases.next() { runtime.spawn(judge(&case, solver)?.then(move |r| { let _ = tx.send((i, name, r.map_err(Into::into))).wait(); // `rx` may be dropped Ok(()) })); } Ok(()) } let JudgeParams { mut stdout, mut stderr, config, problem, force_compile, jobs, } = params; let (cases, paths_formatted) = config.testcase_loader().load_merging(problem)?; let jobs = jobs .or_else(|| config.judge_jobs()) .unwrap_or_else(|| NonZeroUsize::new(1).unwrap()); let display_limit = config.judge_display_limit(); let tester_transpilations = cases.interactive_tester_transpilations(); let tester_compilations = cases.interactive_tester_compilations(); let solver = config.solver()?.expand(&problem)?; let solver_transpilation = match config.solver_transpilation()? { Some(transpilation) => Some(transpilation.expand(&problem)?), None => None, }; let solver_compilation = match config.solver_compilation()? { Some(compilation) => Some(compilation.expand(&problem)?), None => None, }; for tester_transpilation in tester_transpilations { tester_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } for tester_compilation in tester_compilations { tester_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_transpilation) = solver_transpilation { solver_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_compilation) = solver_compilation { solver_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } solver.write_info(&mut stdout, &paths_formatted)?; stdout.flush()?; let solver = Arc::new(solver); match cases { TestCases::Batch(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver, batch::judge, ), TestCases::Interactive(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver, interactive::judge, ), } } pub(crate) struct JudgeParams<'a, O: TermOut, E: TermOut> { pub stdout: O, pub stderr: E, pub config: &'a Config, pub problem: &'a str, pub force_compile: bool, pub jobs: Option<NonZeroUsize>, } pub(self) trait Outcome: fmt::Display { fn failure(&self) -> bool; fn color(&self) -> u8; fn print_details(&self, display_limit: Option<usize>, out: impl TermOut) -> io::Result<()>; fn print_title( &self, mut out: impl TermOut, i: impl DisplayableNum, n: impl DisplayableNum, name: &str, name_width: Option<usize>, ) -> io::Result<()> { if name_width.is_some() { out.write_spaces(n.num_digits() - i.num_digits())?; } out.with_reset(|o| write!(o.bold()?, "{}/{} ({})", i, n, name))?; let l = out.str_width(name); let name_width = name_width.unwrap_or(0); out.write_spaces(cmp::max(name_width, l) - l + 1)?; out.with_reset(|o| writeln!(o.fg(self.color())?, "{}", self)) } } trait DisplayableNum: fmt::Display + Copy { fn num_digits(self) -> usize; } impl DisplayableNum for usize { fn num_digits(mut self) -> usize { let mut r = 1; while self > 9 { self /= 10; r += 1; } r } } pub(self) fn writeln_size(mut out: impl WriteAnsi, size: usize) -> io::Result<()> { let gib = size / 2usize.pow(30); let mib = (size / 2usize.pow(20)) & 0x3ff; let kib = (size / 2usize.pow(10)) & 0x3ff; let b = size & 0x3ff; out.with_reset(|out| { out.fg(11)?.bold()?; match (gib, mib, kib, b) { (0, 0, 0, b) => writeln!(out, "{}B", b), (0, 0, k, b) => writeln!(out, "{}.{}KiB", k, b / 0x67), (0, m, k, _) => writeln!(out, "{}.{}MiB", m, k / 0x67), (g, m, _, _) => writeln!(out, "{}.{}GiB", g, m / 0x67), } }) }
{ for (i, name, outcome) in outcomes { outcome.print_title(&mut stdout, i + 1, num_cases, &name, Some(name_max_width))?; } writeln!( stdout, "All of the {} passed.", plural!(num_cases, "test", "tests") )?; stdout.flush()?; Ok(()) }
conditional_block
mod.rs
mod batch; mod interactive; mod text; use crate::command::JudgingCommand; use crate::config::Config; use crate::errors::{JudgeErrorKind, JudgeResult, TestSuiteResult}; use crate::terminal::{TermOut, WriteAnsi, WriteSpaces}; use crate::testsuite::{BatchCase, TestCase, TestCases}; use crate::util::std_unstable::AsMillis_; use futures::{Future, Sink, Stream}; use itertools::Itertools; use tokio::runtime::Runtime; use std::io::{self, BufRead}; use std::num::NonZeroUsize; use std::sync::Arc; use std::time::Duration; use std::{cmp, fmt}; pub(crate) fn num_cases(config: &Config, problem: &str) -> TestSuiteResult<usize> { let (cases, _) = config.testcase_loader().load_merging(problem)?; Ok(match cases { TestCases::Batch(cases) => cases.len(), TestCases::Interactive(cases) => cases.len(), }) } pub(crate) fn timelimit_millis(config: &Config, problem: &str, nth: usize) -> JudgeResult<u128> { fn get_timelimit_millis<C>( cases: &[C], nth: usize, f: fn(&C) -> Option<Duration>, ) -> JudgeResult<u128> { cases .get(nth) .and_then(f) .map(AsMillis_::as_millis_) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), TestCases::Interactive(cases) => get_timelimit_millis(&cases, nth, |t| t.timelimit()), } } pub(crate) fn input(config: &Config, problem: &str, nth: usize) -> JudgeResult<Arc<String>> { let (cases, _) = config.testcase_loader().load_merging(problem)?; match &cases { TestCases::Batch(cases) => cases .get(nth) .map(BatchCase::input) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()), TestCases::Interactive(cases) if nth < cases.len() => Ok(Arc::new("".to_owned())), TestCases::Interactive(cases) => { Err(JudgeErrorKind::IndexOutOfBounds(cases.len(), nth).into()) } } } pub(crate) fn accepts( config: &Config, problem: &str, nth: usize, mut stdin: impl BufRead, mut stderr: impl TermOut, ) -> JudgeResult<()> { let (cases, _) = config.testcase_loader().load_merging(problem)?; match cases { TestCases::Batch(cases) => { let case = cases .get(nth) .ok_or_else(|| JudgeErrorKind::IndexOutOfBounds(cases.len(), nth))?; let mut output = "".to_owned(); stdin.read_to_string(&mut output)?; let outcome = batch::accepts(&case, &output); if outcome.failure() { outcome.print_details(config.judge_display_limit(), &mut stderr)?; stderr.flush()?; Err(JudgeErrorKind::TestFailed(1, 1).into()) } else { Ok(()) } } TestCases::Interactive(_) => Err(JudgeErrorKind::ExpectedBatch.into()), } } pub(crate) fn only_transpile( stdout: impl TermOut, stderr: impl TermOut, config: &Config, problem: &str, force: bool, ) -> JudgeResult<bool> { match config.solver_transpilation()? { None => Ok(false), Some(transpilation) => { let transpilation = transpilation.expand(problem)?; transpilation.run(stdout, stderr, force)?; Ok(true) } } } /// Executes the tests. /// /// # Errors /// /// Returns `Err` if compilation or execution command fails, or any test fails. pub(crate) fn
(params: JudgeParams<impl TermOut, impl TermOut>) -> JudgeResult<()> { fn judge_all< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut stdout: impl TermOut, mut stderr: impl TermOut, jobs: NonZeroUsize, display_limit: Option<usize>, cases: Vec<C>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { let num_cases = cases.len(); let names = cases.iter().map(|c| c.name()).collect::<Vec<_>>(); let name_max_width = names.iter().map(|s| stdout.str_width(s)).max().unwrap_or(0); let mut cases = names .into_iter() .zip_eq(cases) .enumerate() .map(|(i, (name, case))| (i, name, case)); let (tx, rx) = futures::sync::mpsc::channel(num_cases); let mut runtime = Runtime::new()?; { let tx = tx.clone(); runtime.spawn(crate::signal::ctrl_c().then(move |r| { let (dummy_i, dummy_name) = (num_cases, Arc::new("".to_owned())); let _ = tx.send((dummy_i, dummy_name, r)).wait(); Ok(()) })); } for _ in 0..jobs.get() { spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; } write!(stderr, "0/{} test finished (0 failure)", num_cases)?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; let (mut num_finished, mut num_failures) = (0, 0); let mut outcomes = rx .take(num_cases as u64) .then::<_, JudgeResult<_>>(|r| { let (i, name, r) = r.unwrap(); let outcome = r?; num_finished += 1; if outcome.failure() { num_failures += 1; } if stderr.supports_color() { stderr.write_str("\x1b[0G\x1b[2K")?; } let color = match num_failures { 0 => 10, _ => 9, }; stderr.with_reset(|o| { write!( o.fg(color)?, "{}/{} {} finished ({})", num_finished, num_cases, if num_finished > 1 { "tests" } else { "test" }, plural!(num_failures, "failure", "failures"), ) })?; if!stderr.supports_color() { writeln!(stderr)?; } stderr.flush()?; spawn_head(&mut cases, &mut runtime, tx.clone(), solver, judge)?; Ok((i, name, outcome)) }) .collect() .wait()?; if stderr.supports_color() { writeln!(stderr)?; stderr.flush()?; } outcomes.sort_by_key(|(i, _, _)| *i); let _ = runtime.shutdown_now().wait(); if num_failures == 0 { for (i, name, outcome) in outcomes { outcome.print_title(&mut stdout, i + 1, num_cases, &name, Some(name_max_width))?; } writeln!( stdout, "All of the {} passed.", plural!(num_cases, "test", "tests") )?; stdout.flush()?; Ok(()) } else { for (i, name, outcome) in outcomes { writeln!(stdout)?; outcome.print_title(&mut stdout, i + 1, num_cases, &name, None)?; outcome.print_details(display_limit, &mut stdout)?; } stdout.flush()?; Err(JudgeErrorKind::TestFailed(num_failures, num_cases).into()) } } fn spawn_head< C: TestCase, O: Outcome + Send +'static, F: Future<Item = O, Error = io::Error> + Send +'static, >( mut cases: impl Iterator<Item = (usize, Arc<String>, C)>, runtime: &mut Runtime, tx: futures::sync::mpsc::Sender<(usize, Arc<String>, JudgeResult<O>)>, solver: &Arc<JudgingCommand>, judge: fn(&C, &Arc<JudgingCommand>) -> JudgeResult<F>, ) -> JudgeResult<()> { if let Some((i, name, case)) = cases.next() { runtime.spawn(judge(&case, solver)?.then(move |r| { let _ = tx.send((i, name, r.map_err(Into::into))).wait(); // `rx` may be dropped Ok(()) })); } Ok(()) } let JudgeParams { mut stdout, mut stderr, config, problem, force_compile, jobs, } = params; let (cases, paths_formatted) = config.testcase_loader().load_merging(problem)?; let jobs = jobs .or_else(|| config.judge_jobs()) .unwrap_or_else(|| NonZeroUsize::new(1).unwrap()); let display_limit = config.judge_display_limit(); let tester_transpilations = cases.interactive_tester_transpilations(); let tester_compilations = cases.interactive_tester_compilations(); let solver = config.solver()?.expand(&problem)?; let solver_transpilation = match config.solver_transpilation()? { Some(transpilation) => Some(transpilation.expand(&problem)?), None => None, }; let solver_compilation = match config.solver_compilation()? { Some(compilation) => Some(compilation.expand(&problem)?), None => None, }; for tester_transpilation in tester_transpilations { tester_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } for tester_compilation in tester_compilations { tester_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_transpilation) = solver_transpilation { solver_transpilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } if let Some(solver_compilation) = solver_compilation { solver_compilation.run(&mut stdout, &mut stderr, force_compile)?; writeln!(stdout)?; } solver.write_info(&mut stdout, &paths_formatted)?; stdout.flush()?; let solver = Arc::new(solver); match cases { TestCases::Batch(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver, batch::judge, ), TestCases::Interactive(cases) => judge_all( stdout, stderr, jobs, display_limit, cases, &solver, interactive::judge, ), } } pub(crate) struct JudgeParams<'a, O: TermOut, E: TermOut> { pub stdout: O, pub stderr: E, pub config: &'a Config, pub problem: &'a str, pub force_compile: bool, pub jobs: Option<NonZeroUsize>, } pub(self) trait Outcome: fmt::Display { fn failure(&self) -> bool; fn color(&self) -> u8; fn print_details(&self, display_limit: Option<usize>, out: impl TermOut) -> io::Result<()>; fn print_title( &self, mut out: impl TermOut, i: impl DisplayableNum, n: impl DisplayableNum, name: &str, name_width: Option<usize>, ) -> io::Result<()> { if name_width.is_some() { out.write_spaces(n.num_digits() - i.num_digits())?; } out.with_reset(|o| write!(o.bold()?, "{}/{} ({})", i, n, name))?; let l = out.str_width(name); let name_width = name_width.unwrap_or(0); out.write_spaces(cmp::max(name_width, l) - l + 1)?; out.with_reset(|o| writeln!(o.fg(self.color())?, "{}", self)) } } trait DisplayableNum: fmt::Display + Copy { fn num_digits(self) -> usize; } impl DisplayableNum for usize { fn num_digits(mut self) -> usize { let mut r = 1; while self > 9 { self /= 10; r += 1; } r } } pub(self) fn writeln_size(mut out: impl WriteAnsi, size: usize) -> io::Result<()> { let gib = size / 2usize.pow(30); let mib = (size / 2usize.pow(20)) & 0x3ff; let kib = (size / 2usize.pow(10)) & 0x3ff; let b = size & 0x3ff; out.with_reset(|out| { out.fg(11)?.bold()?; match (gib, mib, kib, b) { (0, 0, 0, b) => writeln!(out, "{}B", b), (0, 0, k, b) => writeln!(out, "{}.{}KiB", k, b / 0x67), (0, m, k, _) => writeln!(out, "{}.{}MiB", m, k / 0x67), (g, m, _, _) => writeln!(out, "{}.{}GiB", g, m / 0x67), } }) }
judge
identifier_name
string_slice_runtime.rs
#[derive( Debug, PartialEq )] pub struct Struct1< 'a > { pub string_slice_1 : &'a str, } impl< 'a > Struct1< 'a > { #[inline] pub fn former() -> Struct1Former< 'a > {
Struct1Former { string_slice_1 : ::core::option::Option::None, } } } pub struct Struct1Former< 'a > { string_slice_1 : ::core::option::Option< &'a str >, } impl< 'a > Struct1Former< 'a > { #[inline] pub fn form( mut self ) -> Struct1< 'a > { let string_slice_1 = if self.string_slice_1.is_some() { self.string_slice_1.take().unwrap() } else { let val : &'a str = ::core::default::Default::default(); val }; Struct1 { string_slice_1 } } #[inline] pub fn string_slice_1< Src >( mut self, src : Src ) -> Self where Src : ::core::convert::Into< &'a str >, { debug_assert!( self.string_slice_1.is_none() ); self.string_slice_1 = ::core::option::Option::Some( src.into() ); self } } // include!( "./string_slice_only_test.rs" );
random_line_split
string_slice_runtime.rs
#[derive( Debug, PartialEq )] pub struct Struct1< 'a > { pub string_slice_1 : &'a str, } impl< 'a > Struct1< 'a > { #[inline] pub fn former() -> Struct1Former< 'a > { Struct1Former { string_slice_1 : ::core::option::Option::None, } } } pub struct Struct1Former< 'a > { string_slice_1 : ::core::option::Option< &'a str >, } impl< 'a > Struct1Former< 'a > { #[inline] pub fn form( mut self ) -> Struct1< 'a > { let string_slice_1 = if self.string_slice_1.is_some() { self.string_slice_1.take().unwrap() } else
; Struct1 { string_slice_1 } } #[inline] pub fn string_slice_1< Src >( mut self, src : Src ) -> Self where Src : ::core::convert::Into< &'a str >, { debug_assert!( self.string_slice_1.is_none() ); self.string_slice_1 = ::core::option::Option::Some( src.into() ); self } } // include!( "./string_slice_only_test.rs" );
{ let val : &'a str = ::core::default::Default::default(); val }
conditional_block
string_slice_runtime.rs
#[derive( Debug, PartialEq )] pub struct Struct1< 'a > { pub string_slice_1 : &'a str, } impl< 'a > Struct1< 'a > { #[inline] pub fn former() -> Struct1Former< 'a > { Struct1Former { string_slice_1 : ::core::option::Option::None, } } } pub struct Struct1Former< 'a > { string_slice_1 : ::core::option::Option< &'a str >, } impl< 'a > Struct1Former< 'a > { #[inline] pub fn form( mut self ) -> Struct1< 'a > { let string_slice_1 = if self.string_slice_1.is_some() { self.string_slice_1.take().unwrap() } else { let val : &'a str = ::core::default::Default::default(); val }; Struct1 { string_slice_1 } } #[inline] pub fn string_slice_1< Src >( mut self, src : Src ) -> Self where Src : ::core::convert::Into< &'a str >,
} // include!( "./string_slice_only_test.rs" );
{ debug_assert!( self.string_slice_1.is_none() ); self.string_slice_1 = ::core::option::Option::Some( src.into() ); self }
identifier_body
string_slice_runtime.rs
#[derive( Debug, PartialEq )] pub struct Struct1< 'a > { pub string_slice_1 : &'a str, } impl< 'a > Struct1< 'a > { #[inline] pub fn former() -> Struct1Former< 'a > { Struct1Former { string_slice_1 : ::core::option::Option::None, } } } pub struct
< 'a > { string_slice_1 : ::core::option::Option< &'a str >, } impl< 'a > Struct1Former< 'a > { #[inline] pub fn form( mut self ) -> Struct1< 'a > { let string_slice_1 = if self.string_slice_1.is_some() { self.string_slice_1.take().unwrap() } else { let val : &'a str = ::core::default::Default::default(); val }; Struct1 { string_slice_1 } } #[inline] pub fn string_slice_1< Src >( mut self, src : Src ) -> Self where Src : ::core::convert::Into< &'a str >, { debug_assert!( self.string_slice_1.is_none() ); self.string_slice_1 = ::core::option::Option::Some( src.into() ); self } } // include!( "./string_slice_only_test.rs" );
Struct1Former
identifier_name
strukt.rs
use {value,types,Value,Expression,ExpressionTrait,Type}; use std; #[derive(Clone,Debug,PartialEq,Eq)] pub struct Struct { fields: Vec<Value>, } impl Struct { pub fn new(fields: Vec<Value>) -> Self { Struct { fields: fields, } } pub fn fields(&self) -> std::slice::Iter<Value> { self.fields.iter() } pub fn ty(&self) -> Type { // Create the struct type from the types of the values. types::Struct::new( self.fields.iter().map(|ref f| f.node.ty()) ).into() } } impl value::LiteralTrait for Struct { } impl ExpressionTrait for Struct { } impl Into<Expression> for Struct { fn
(self) -> Expression { Expression::Literal(self.into()) } } impl Into<value::Literal> for Struct { fn into(self) -> value::Literal { value::Literal::Struct(self) } }
into
identifier_name
strukt.rs
use {value,types,Value,Expression,ExpressionTrait,Type}; use std; #[derive(Clone,Debug,PartialEq,Eq)] pub struct Struct { fields: Vec<Value>, } impl Struct { pub fn new(fields: Vec<Value>) -> Self { Struct { fields: fields, } } pub fn fields(&self) -> std::slice::Iter<Value> { self.fields.iter() } pub fn ty(&self) -> Type { // Create the struct type from the types of the values. types::Struct::new( self.fields.iter().map(|ref f| f.node.ty()) ).into() } } impl value::LiteralTrait for Struct { } impl ExpressionTrait for Struct { } impl Into<Expression> for Struct { fn into(self) -> Expression { Expression::Literal(self.into()) } } impl Into<value::Literal> for Struct { fn into(self) -> value::Literal
}
{ value::Literal::Struct(self) }
identifier_body
strukt.rs
use {value,types,Value,Expression,ExpressionTrait,Type}; use std; #[derive(Clone,Debug,PartialEq,Eq)] pub struct Struct { fields: Vec<Value>, } impl Struct { pub fn new(fields: Vec<Value>) -> Self { Struct { fields: fields, } } pub fn fields(&self) -> std::slice::Iter<Value> { self.fields.iter() } pub fn ty(&self) -> Type { // Create the struct type from the types of the values. types::Struct::new( self.fields.iter().map(|ref f| f.node.ty()) ).into() } } impl value::LiteralTrait for Struct { } impl ExpressionTrait for Struct { }
{ fn into(self) -> Expression { Expression::Literal(self.into()) } } impl Into<value::Literal> for Struct { fn into(self) -> value::Literal { value::Literal::Struct(self) } }
impl Into<Expression> for Struct
random_line_split
main.rs
fn main() { let mut sequence = String::from("1113122113"); for _ in 0..40 { sequence = look_and_say(sequence); } println!("The length is {} :D", sequence.len()); } fn
(s: String) -> String { let mut ret = String::new(); let chars = s.chars().collect::<Vec<_>>(); let mut index = 0; let mut current_run = None; while index < s.len() { let next_char = chars[index]; current_run = match current_run { Some((c, length)) => { if next_char == c { index += 1; Some((next_char, length + 1)) } else { ret = format!("{}{}{}", ret, length, c); None } }, None => { index += 1; Some((next_char, 1)) } }; } if let Some((c, length)) = current_run { ret = format!("{}{}{}", ret, length, c); } ret } #[test] fn a() { assert_eq!(look_and_say(String::from("1")), "11"); } #[test] fn b() { assert_eq!(look_and_say(String::from("11")), "21"); } #[test] fn c() { assert_eq!(look_and_say(String::from("21")), "1211"); } #[test] fn d() { assert_eq!(look_and_say(String::from("1211")), "111221"); } #[test] fn e() { assert_eq!(look_and_say(String::from("111221")), "312211"); }
look_and_say
identifier_name
main.rs
fn main() { let mut sequence = String::from("1113122113"); for _ in 0..40 { sequence = look_and_say(sequence); } println!("The length is {} :D", sequence.len()); } fn look_and_say(s: String) -> String { let mut ret = String::new(); let chars = s.chars().collect::<Vec<_>>(); let mut index = 0; let mut current_run = None; while index < s.len() { let next_char = chars[index]; current_run = match current_run { Some((c, length)) => { if next_char == c { index += 1; Some((next_char, length + 1)) } else { ret = format!("{}{}{}", ret, length, c); None } }, None => { index += 1; Some((next_char, 1)) } }; } if let Some((c, length)) = current_run { ret = format!("{}{}{}", ret, length, c); } ret } #[test] fn a()
#[test] fn b() { assert_eq!(look_and_say(String::from("11")), "21"); } #[test] fn c() { assert_eq!(look_and_say(String::from("21")), "1211"); } #[test] fn d() { assert_eq!(look_and_say(String::from("1211")), "111221"); } #[test] fn e() { assert_eq!(look_and_say(String::from("111221")), "312211"); }
{ assert_eq!(look_and_say(String::from("1")), "11"); }
identifier_body
main.rs
fn main() { let mut sequence = String::from("1113122113"); for _ in 0..40 { sequence = look_and_say(sequence); } println!("The length is {} :D", sequence.len()); } fn look_and_say(s: String) -> String { let mut ret = String::new(); let chars = s.chars().collect::<Vec<_>>(); let mut index = 0; let mut current_run = None; while index < s.len() { let next_char = chars[index]; current_run = match current_run { Some((c, length)) => { if next_char == c { index += 1; Some((next_char, length + 1)) } else { ret = format!("{}{}{}", ret, length, c); None } }, None =>
}; } if let Some((c, length)) = current_run { ret = format!("{}{}{}", ret, length, c); } ret } #[test] fn a() { assert_eq!(look_and_say(String::from("1")), "11"); } #[test] fn b() { assert_eq!(look_and_say(String::from("11")), "21"); } #[test] fn c() { assert_eq!(look_and_say(String::from("21")), "1211"); } #[test] fn d() { assert_eq!(look_and_say(String::from("1211")), "111221"); } #[test] fn e() { assert_eq!(look_and_say(String::from("111221")), "312211"); }
{ index += 1; Some((next_char, 1)) }
conditional_block
main.rs
fn main() { let mut sequence = String::from("1113122113"); for _ in 0..40 { sequence = look_and_say(sequence); } println!("The length is {} :D", sequence.len()); } fn look_and_say(s: String) -> String { let mut ret = String::new(); let chars = s.chars().collect::<Vec<_>>(); let mut index = 0; let mut current_run = None; while index < s.len() { let next_char = chars[index]; current_run = match current_run { Some((c, length)) => { if next_char == c { index += 1; Some((next_char, length + 1)) } else { ret = format!("{}{}{}", ret, length, c); None } }, None => { index += 1; Some((next_char, 1)) } }; } if let Some((c, length)) = current_run { ret = format!("{}{}{}", ret, length, c); } ret } #[test] fn a() { assert_eq!(look_and_say(String::from("1")), "11"); } #[test]
fn b() { assert_eq!(look_and_say(String::from("11")), "21"); } #[test] fn c() { assert_eq!(look_and_say(String::from("21")), "1211"); } #[test] fn d() { assert_eq!(look_and_say(String::from("1211")), "111221"); } #[test] fn e() { assert_eq!(look_and_say(String::from("111221")), "312211"); }
random_line_split
location.rs
header! { /// `Location` header, defined in /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.2) /// /// The `Location` header field is used in some responses to refer to a /// specific resource in relation to the response. The type of /// relationship is defined by the combination of request method and /// status code semantics. /// /// # ABNF /// ```plain /// Location = URI-reference /// ``` /// /// # Example values /// * `/People.html#tim` /// * `http://www.example.net/index.html` /// /// # Examples /// ``` /// use hyper::header::{Headers, Location}; /// /// let mut headers = Headers::new(); /// headers.set(Location("/People.html#tim".to_owned())); /// ``` /// ``` /// use hyper::header::{Headers, Location}; /// /// let mut headers = Headers::new(); /// headers.set(Location("http://www.example.com/index.html".to_owned())); /// ```
// Testcase from RFC test_header!(test1, vec![b"/People.html#tim"]); test_header!(test2, vec![b"http://www.example.net/index.html"]); } } bench_header!(bench, Location, { vec![b"http://foo.com/hello:3000".to_vec()] });
// TODO: Use URL (Location, "Location") => [String] test_location {
random_line_split
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { Node::reflect_node(box HTMLSelectElement::new_inherited(local_name, prefix, document), document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None; let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false); last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) } // Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed =>
} } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } } impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
{ el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); }
conditional_block
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { Node::reflect_node(box HTMLSelectElement::new_inherited(local_name, prefix, document), document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None; let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false); last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn
(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) } // Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed => { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); } } } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } } impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
Validity
identifier_name
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { Node::reflect_node(box HTMLSelectElement::new_inherited(local_name, prefix, document), document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None; let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false); last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) } // Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed => { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); } } } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue
} impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
{ match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } }
identifier_body
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { Node::reflect_node(box HTMLSelectElement::new_inherited(local_name, prefix, document), document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None;
last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) } // Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed => { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); } } } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } } impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false);
random_line_split
regions-implied-bounds-projection-gap-3.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. // Along with the other tests in this series, illustrates the // "projection gap": in this test, we know that `T::Foo: 'x`, and that // is (naturally) enough to conclude that `T::Foo: 'x`. // compile-pass #![allow(dead_code)] #![allow(unused_variables)] trait Trait1<'x> { type Foo; } // calling this fn should trigger a check that the type argument // supplied is well-formed. fn wf<T>() { } fn func<'x, T:Trait1<'x>>(t: &'x T::Foo) { wf::<&'x T::Foo>(); } fn
() { }
main
identifier_name
regions-implied-bounds-projection-gap-3.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. // Along with the other tests in this series, illustrates the // "projection gap": in this test, we know that `T::Foo: 'x`, and that // is (naturally) enough to conclude that `T::Foo: 'x`. // compile-pass #![allow(dead_code)] #![allow(unused_variables)] trait Trait1<'x> { type Foo; } // calling this fn should trigger a check that the type argument // supplied is well-formed. fn wf<T>() { } fn func<'x, T:Trait1<'x>>(t: &'x T::Foo) { wf::<&'x T::Foo>(); } fn main()
{ }
identifier_body
regions-implied-bounds-projection-gap-3.rs
// 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. // Along with the other tests in this series, illustrates the // "projection gap": in this test, we know that `T::Foo: 'x`, and that // is (naturally) enough to conclude that `T::Foo: 'x`. // compile-pass #![allow(dead_code)] #![allow(unused_variables)] trait Trait1<'x> { type Foo; } // calling this fn should trigger a check that the type argument // supplied is well-formed. fn wf<T>() { } fn func<'x, T:Trait1<'x>>(t: &'x T::Foo) { wf::<&'x T::Foo>(); } fn main() { }
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
random_line_split
mod.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). // File-specific allowances to silence internal warnings of `py_class!`. #![allow( clippy::used_underscore_binding, clippy::transmute_ptr_to_ptr, clippy::zero_ptr )] pub mod engine_aware; pub mod fs; mod interface; #[cfg(test)] mod interface_tests; mod stdio; use std::collections::BTreeMap; use std::convert::AsRef; use std::convert::TryInto; use std::fmt; use crate::core::{Failure, Key, TypeId, Value}; use crate::interning::Interns; use cpython::{ py_class, CompareOp, FromPyObject, ObjectProtocol, PyBool, PyBytes, PyClone, PyDict, PyErr, PyObject, PyResult as CPyResult, PyTuple, PyType, Python, PythonObject, ToPyObject, }; use lazy_static::lazy_static; use logging::PythonLogLevel; /// Return the Python value None. pub fn none() -> PyObject { let gil = Python::acquire_gil(); gil.python().None() } pub fn get_type_for(val: &PyObject) -> TypeId { let gil = Python::acquire_gil(); let py = gil.python(); (&val.get_type(py)).into() } pub fn is_union(ty: TypeId) -> bool { let gil = Python::acquire_gil(); let py = gil.python(); let py_type = (&ty).as_py_type(py); let unions = py.import("pants.engine.unions").unwrap(); unions .call(py, "is_union", (py_type,), None) .unwrap() .extract(py) .unwrap() } pub fn equals(h1: &PyObject, h2: &PyObject) -> bool { let gil = Python::acquire_gil(); let py = gil.python(); // NB: Although it does not precisely align with Python's definition of equality, we ban matches // between non-equal types to avoid legacy behavior like `assert True == 1`, which is very // surprising in interning, and would likely be surprising anywhere else in the engine where we // compare things. if h1.get_type(py)!= h2.get_type(py) { return false; } h1.rich_compare(gil.python(), h2, CompareOp::Eq) .unwrap() .cast_as::<PyBool>(gil.python()) .unwrap() .is_true() } pub fn type_for_type_id(ty: TypeId) -> PyType { let gil = Python::acquire_gil(); (&ty).as_py_type(gil.python()) } pub fn type_for(py_type: PyType) -> TypeId { (&py_type).into() } pub fn key_for(val: Value) -> Result<Key, PyErr> { let gil = Python::acquire_gil(); INTERNS.key_insert(gil.python(), val) } pub fn val_for(key: &Key) -> Value { INTERNS.key_get(key) } pub fn store_tuple(values: Vec<Value>) -> Value { let gil = Python::acquire_gil(); let arg_handles: Vec<_> = values .into_iter() .map(|v| v.consume_into_py_object(gil.python())) .collect(); Value::from(PyTuple::new(gil.python(), &arg_handles).into_object()) } /// Store a slice containing 2-tuples of (key, value) as a Python dictionary. pub fn store_dict(keys_and_values: Vec<(Value, Value)>) -> Result<Value, PyErr> { let gil = Python::acquire_gil(); let py = gil.python(); let dict = PyDict::new(py); for (k, v) in keys_and_values { dict.set_item( gil.python(), k.consume_into_py_object(py), v.consume_into_py_object(py), )?; } Ok(Value::from(dict.into_object())) } /// /// Store an opaque buffer of bytes to pass to Python. This will end up as a Python `bytes`. /// pub fn store_bytes(bytes: &[u8]) -> Value { let gil = Python::acquire_gil(); Value::from(PyBytes::new(gil.python(), bytes).into_object()) } /// /// Store an buffer of utf8 bytes to pass to Python. This will end up as a Python `unicode`. /// pub fn store_utf8(utf8: &str) -> Value { let gil = Python::acquire_gil(); Value::from(utf8.to_py_object(gil.python()).into_object()) } pub fn store_u64(val: u64) -> Value { let gil = Python::acquire_gil(); Value::from(val.to_py_object(gil.python()).into_object()) } pub fn store_i64(val: i64) -> Value { let gil = Python::acquire_gil(); Value::from(val.to_py_object(gil.python()).into_object()) } pub fn store_bool(val: bool) -> Value { let gil = Python::acquire_gil(); Value::from(val.to_py_object(gil.python()).into_object()) } /// /// Check if a Python object has the specified field. /// pub fn hasattr(value: &PyObject, field: &str) -> bool { let gil = Python::acquire_gil(); let py = gil.python(); value.hasattr(py, field).unwrap() } /// /// Gets an attribute of the given value as the given type. /// pub fn getattr<T>(value: &PyObject, field: &str) -> Result<T, String> where for<'a> T: FromPyObject<'a>, { let gil = Python::acquire_gil(); let py = gil.python(); value .getattr(py, field) .map_err(|e| format!("Could not get field `{}`: {:?}", field, e))? .extract::<T>(py) .map_err(|e| { format!( "Field `{}` was not convertible to type {}: {:?}", field, core::any::type_name::<T>(), e ) }) } /// /// Collect the Values contained within an outer Python Iterable PyObject. /// pub fn collect_iterable(value: &PyObject) -> Result<Vec<PyObject>, String> { let gil = Python::acquire_gil(); let py = gil.python(); match value.iter(py) { Ok(py_iter) => py_iter .enumerate() .map(|(i, py_res)| { py_res.map_err(|py_err| { format!( "Could not iterate {}, failed to extract {}th item: {:?}", val_to_str(value), i, py_err ) }) }) .collect(), Err(py_err) => Err(format!( "Could not iterate {}: {:?}", val_to_str(value), py_err )), } } pub fn getattr_from_frozendict(value: &PyObject, field: &str) -> BTreeMap<String, String> { let frozendict = getattr(value, field).unwrap(); let pydict: PyDict = getattr(&frozendict, "_data").unwrap(); let gil = Python::acquire_gil(); let py = gil.python(); pydict .items(py) .into_iter() .map(|(k, v)| (val_to_str(&Value::new(k)), val_to_str(&Value::new(v)))) .collect() } pub fn getattr_as_string(value: &PyObject, field: &str) -> String { // TODO: It's possible to view a python string as a `Cow<str>`, so we could avoid actually // cloning in some cases. // TODO: We can't directly extract as a string here, because val_to_str defaults to empty string // for None. val_to_str(&getattr(value, field).unwrap()) } pub fn key_to_str(key: &Key) -> String { val_to_str(&val_for(key).as_ref()) } pub fn type_to_str(type_id: TypeId) -> String { getattr_as_string(&type_for_type_id(type_id).into_object(), "__name__") } pub fn val_to_str(obj: &PyObject) -> String { let gil = Python::acquire_gil(); let py = gil.python(); if *obj == py.None() { return "".to_string(); } let pystring = obj.str(py).unwrap(); pystring.to_string(py).unwrap().into_owned() } pub fn val_to_log_level(obj: &PyObject) -> Result<log::Level, String> { let res: Result<PythonLogLevel, String> = getattr(obj, "_level").and_then(|n: u64| { n.try_into() .map_err(|e: num_enum::TryFromPrimitiveError<_>| { format!("Could not parse {:?} as a LogLevel: {}", val_to_str(obj), e) }) }); res.map(|py_level| py_level.into()) } pub fn create_exception(msg: &str) -> Value { let gil = Python::acquire_gil(); let py = gil.python(); Value::from(PyErr::new::<cpython::exc::Exception, _>(py, msg).instance(py)) } pub fn check_for_python_none(value: PyObject) -> Option<PyObject> { let gil = Python::acquire_gil(); let py = gil.python(); if value == py.None() { return None; } Some(value) } pub fn call_method(value: &PyObject, method: &str, args: &[Value]) -> Result<PyObject, PyErr> { let arg_handles: Vec<PyObject> = args.iter().map(|v| v.clone().into()).collect(); let gil = Python::acquire_gil(); let args_tuple = PyTuple::new(gil.python(), &arg_handles); value.call_method(gil.python(), method, args_tuple, None) } pub fn call_function<T: AsRef<PyObject>>(func: T, args: &[Value]) -> Result<PyObject, PyErr> { let func: &PyObject = func.as_ref(); let arg_handles: Vec<PyObject> = args.iter().map(|v| v.clone().into()).collect(); let gil = Python::acquire_gil(); let args_tuple = PyTuple::new(gil.python(), &arg_handles); func.call(gil.python(), args_tuple, None) } pub fn generator_send(generator: &Value, arg: &Value) -> Result<GeneratorResponse, Failure> { let gil = Python::acquire_gil(); let py = gil.python(); let selectors = py.import("pants.engine.internals.selectors").unwrap(); let response = selectors .call( py, "native_engine_generator_send", (generator as &PyObject, arg as &PyObject), None, ) .map_err(|py_err| Failure::from_py_err_with_gil(py, py_err))?; if let Ok(b) = response.cast_as::<PyGeneratorResponseBreak>(py) { Ok(GeneratorResponse::Break(Value::new( b.val(py).clone_ref(py), ))) } else if let Ok(get) = response.cast_as::<PyGeneratorResponseGet>(py) { Ok(GeneratorResponse::Get(Get::new(py, get)?)) } else if let Ok(get_multi) = response.cast_as::<PyGeneratorResponseGetMulti>(py) { let gets = get_multi .gets(py) .iter(py) .map(|g| { let get = g .cast_as::<PyGeneratorResponseGet>(py) .map_err(|e| Failure::from_py_err_with_gil(py, e.into()))?; Ok(Get::new(py, get)?) }) .collect::<Result<Vec<_>, _>>()?; Ok(GeneratorResponse::GetMulti(gets)) } else { panic!( "native_engine_generator_send returned unrecognized type: {:?}", response ); } } /// /// NB: Panics on failure. Only recommended for use with built-in types, such as /// those configured in types::Types. /// pub fn unsafe_call(type_id: TypeId, args: &[Value]) -> Value { let py_type = type_for_type_id(type_id); let arg_handles: Vec<PyObject> = args.iter().map(|v| v.clone().into()).collect(); let gil = Python::acquire_gil(); let args_tuple = PyTuple::new(gil.python(), &arg_handles); py_type .call(gil.python(), args_tuple, None) .map(Value::from) .unwrap_or_else(|e| { let gil = Python::acquire_gil(); panic!( "Core type constructor `{}` failed: {:?}", py_type.name(gil.python()), e ); }) } lazy_static! { static ref INTERNS: Interns = Interns::new(); } py_class!(pub class PyGeneratorResponseBreak |py| { data val: PyObject; def __new__(_cls, val: PyObject) -> CPyResult<Self> { Self::create_instance(py, val) } }); py_class!(pub class PyGeneratorResponseGet |py| {
data subject: PyObject; def __new__(_cls, product: PyType, declared_subject: PyType, subject: PyObject) -> CPyResult<Self> { Self::create_instance(py, product, declared_subject, subject) } }); py_class!(pub class PyGeneratorResponseGetMulti |py| { data gets: PyTuple; def __new__(_cls, gets: PyTuple) -> CPyResult<Self> { Self::create_instance(py, gets) } }); #[derive(Debug)] pub struct Get { pub output: TypeId, pub input: Key, pub input_type: TypeId, } impl Get { fn new(py: Python, get: &PyGeneratorResponseGet) -> Result<Get, Failure> { Ok(Get { output: get.product(py).into(), input: INTERNS .key_insert(py, get.subject(py).clone_ref(py).into()) .map_err(|e| Failure::from_py_err_with_gil(py, e))?, input_type: get.declared_subject(py).into(), }) } } impl fmt::Display for Get { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { write!( f, "Get({}, {})", type_to_str(self.output), key_to_str(&self.input) ) } } pub enum GeneratorResponse { Break(Value), Get(Get), GetMulti(Vec<Get>), }
data product: PyType; data declared_subject: PyType;
random_line_split
mod.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). // File-specific allowances to silence internal warnings of `py_class!`. #![allow( clippy::used_underscore_binding, clippy::transmute_ptr_to_ptr, clippy::zero_ptr )] pub mod engine_aware; pub mod fs; mod interface; #[cfg(test)] mod interface_tests; mod stdio; use std::collections::BTreeMap; use std::convert::AsRef; use std::convert::TryInto; use std::fmt; use crate::core::{Failure, Key, TypeId, Value}; use crate::interning::Interns; use cpython::{ py_class, CompareOp, FromPyObject, ObjectProtocol, PyBool, PyBytes, PyClone, PyDict, PyErr, PyObject, PyResult as CPyResult, PyTuple, PyType, Python, PythonObject, ToPyObject, }; use lazy_static::lazy_static; use logging::PythonLogLevel; /// Return the Python value None. pub fn none() -> PyObject { let gil = Python::acquire_gil(); gil.python().None() } pub fn get_type_for(val: &PyObject) -> TypeId { let gil = Python::acquire_gil(); let py = gil.python(); (&val.get_type(py)).into() } pub fn is_union(ty: TypeId) -> bool { let gil = Python::acquire_gil(); let py = gil.python(); let py_type = (&ty).as_py_type(py); let unions = py.import("pants.engine.unions").unwrap(); unions .call(py, "is_union", (py_type,), None) .unwrap() .extract(py) .unwrap() } pub fn equals(h1: &PyObject, h2: &PyObject) -> bool { let gil = Python::acquire_gil(); let py = gil.python(); // NB: Although it does not precisely align with Python's definition of equality, we ban matches // between non-equal types to avoid legacy behavior like `assert True == 1`, which is very // surprising in interning, and would likely be surprising anywhere else in the engine where we // compare things. if h1.get_type(py)!= h2.get_type(py) { return false; } h1.rich_compare(gil.python(), h2, CompareOp::Eq) .unwrap() .cast_as::<PyBool>(gil.python()) .unwrap() .is_true() } pub fn type_for_type_id(ty: TypeId) -> PyType { let gil = Python::acquire_gil(); (&ty).as_py_type(gil.python()) } pub fn type_for(py_type: PyType) -> TypeId { (&py_type).into() } pub fn key_for(val: Value) -> Result<Key, PyErr> { let gil = Python::acquire_gil(); INTERNS.key_insert(gil.python(), val) } pub fn val_for(key: &Key) -> Value { INTERNS.key_get(key) } pub fn store_tuple(values: Vec<Value>) -> Value { let gil = Python::acquire_gil(); let arg_handles: Vec<_> = values .into_iter() .map(|v| v.consume_into_py_object(gil.python())) .collect(); Value::from(PyTuple::new(gil.python(), &arg_handles).into_object()) } /// Store a slice containing 2-tuples of (key, value) as a Python dictionary. pub fn store_dict(keys_and_values: Vec<(Value, Value)>) -> Result<Value, PyErr> { let gil = Python::acquire_gil(); let py = gil.python(); let dict = PyDict::new(py); for (k, v) in keys_and_values { dict.set_item( gil.python(), k.consume_into_py_object(py), v.consume_into_py_object(py), )?; } Ok(Value::from(dict.into_object())) } /// /// Store an opaque buffer of bytes to pass to Python. This will end up as a Python `bytes`. /// pub fn store_bytes(bytes: &[u8]) -> Value { let gil = Python::acquire_gil(); Value::from(PyBytes::new(gil.python(), bytes).into_object()) } /// /// Store an buffer of utf8 bytes to pass to Python. This will end up as a Python `unicode`. /// pub fn store_utf8(utf8: &str) -> Value { let gil = Python::acquire_gil(); Value::from(utf8.to_py_object(gil.python()).into_object()) } pub fn store_u64(val: u64) -> Value { let gil = Python::acquire_gil(); Value::from(val.to_py_object(gil.python()).into_object()) } pub fn store_i64(val: i64) -> Value { let gil = Python::acquire_gil(); Value::from(val.to_py_object(gil.python()).into_object()) } pub fn store_bool(val: bool) -> Value { let gil = Python::acquire_gil(); Value::from(val.to_py_object(gil.python()).into_object()) } /// /// Check if a Python object has the specified field. /// pub fn hasattr(value: &PyObject, field: &str) -> bool { let gil = Python::acquire_gil(); let py = gil.python(); value.hasattr(py, field).unwrap() } /// /// Gets an attribute of the given value as the given type. /// pub fn
<T>(value: &PyObject, field: &str) -> Result<T, String> where for<'a> T: FromPyObject<'a>, { let gil = Python::acquire_gil(); let py = gil.python(); value .getattr(py, field) .map_err(|e| format!("Could not get field `{}`: {:?}", field, e))? .extract::<T>(py) .map_err(|e| { format!( "Field `{}` was not convertible to type {}: {:?}", field, core::any::type_name::<T>(), e ) }) } /// /// Collect the Values contained within an outer Python Iterable PyObject. /// pub fn collect_iterable(value: &PyObject) -> Result<Vec<PyObject>, String> { let gil = Python::acquire_gil(); let py = gil.python(); match value.iter(py) { Ok(py_iter) => py_iter .enumerate() .map(|(i, py_res)| { py_res.map_err(|py_err| { format!( "Could not iterate {}, failed to extract {}th item: {:?}", val_to_str(value), i, py_err ) }) }) .collect(), Err(py_err) => Err(format!( "Could not iterate {}: {:?}", val_to_str(value), py_err )), } } pub fn getattr_from_frozendict(value: &PyObject, field: &str) -> BTreeMap<String, String> { let frozendict = getattr(value, field).unwrap(); let pydict: PyDict = getattr(&frozendict, "_data").unwrap(); let gil = Python::acquire_gil(); let py = gil.python(); pydict .items(py) .into_iter() .map(|(k, v)| (val_to_str(&Value::new(k)), val_to_str(&Value::new(v)))) .collect() } pub fn getattr_as_string(value: &PyObject, field: &str) -> String { // TODO: It's possible to view a python string as a `Cow<str>`, so we could avoid actually // cloning in some cases. // TODO: We can't directly extract as a string here, because val_to_str defaults to empty string // for None. val_to_str(&getattr(value, field).unwrap()) } pub fn key_to_str(key: &Key) -> String { val_to_str(&val_for(key).as_ref()) } pub fn type_to_str(type_id: TypeId) -> String { getattr_as_string(&type_for_type_id(type_id).into_object(), "__name__") } pub fn val_to_str(obj: &PyObject) -> String { let gil = Python::acquire_gil(); let py = gil.python(); if *obj == py.None() { return "".to_string(); } let pystring = obj.str(py).unwrap(); pystring.to_string(py).unwrap().into_owned() } pub fn val_to_log_level(obj: &PyObject) -> Result<log::Level, String> { let res: Result<PythonLogLevel, String> = getattr(obj, "_level").and_then(|n: u64| { n.try_into() .map_err(|e: num_enum::TryFromPrimitiveError<_>| { format!("Could not parse {:?} as a LogLevel: {}", val_to_str(obj), e) }) }); res.map(|py_level| py_level.into()) } pub fn create_exception(msg: &str) -> Value { let gil = Python::acquire_gil(); let py = gil.python(); Value::from(PyErr::new::<cpython::exc::Exception, _>(py, msg).instance(py)) } pub fn check_for_python_none(value: PyObject) -> Option<PyObject> { let gil = Python::acquire_gil(); let py = gil.python(); if value == py.None() { return None; } Some(value) } pub fn call_method(value: &PyObject, method: &str, args: &[Value]) -> Result<PyObject, PyErr> { let arg_handles: Vec<PyObject> = args.iter().map(|v| v.clone().into()).collect(); let gil = Python::acquire_gil(); let args_tuple = PyTuple::new(gil.python(), &arg_handles); value.call_method(gil.python(), method, args_tuple, None) } pub fn call_function<T: AsRef<PyObject>>(func: T, args: &[Value]) -> Result<PyObject, PyErr> { let func: &PyObject = func.as_ref(); let arg_handles: Vec<PyObject> = args.iter().map(|v| v.clone().into()).collect(); let gil = Python::acquire_gil(); let args_tuple = PyTuple::new(gil.python(), &arg_handles); func.call(gil.python(), args_tuple, None) } pub fn generator_send(generator: &Value, arg: &Value) -> Result<GeneratorResponse, Failure> { let gil = Python::acquire_gil(); let py = gil.python(); let selectors = py.import("pants.engine.internals.selectors").unwrap(); let response = selectors .call( py, "native_engine_generator_send", (generator as &PyObject, arg as &PyObject), None, ) .map_err(|py_err| Failure::from_py_err_with_gil(py, py_err))?; if let Ok(b) = response.cast_as::<PyGeneratorResponseBreak>(py) { Ok(GeneratorResponse::Break(Value::new( b.val(py).clone_ref(py), ))) } else if let Ok(get) = response.cast_as::<PyGeneratorResponseGet>(py) { Ok(GeneratorResponse::Get(Get::new(py, get)?)) } else if let Ok(get_multi) = response.cast_as::<PyGeneratorResponseGetMulti>(py) { let gets = get_multi .gets(py) .iter(py) .map(|g| { let get = g .cast_as::<PyGeneratorResponseGet>(py) .map_err(|e| Failure::from_py_err_with_gil(py, e.into()))?; Ok(Get::new(py, get)?) }) .collect::<Result<Vec<_>, _>>()?; Ok(GeneratorResponse::GetMulti(gets)) } else { panic!( "native_engine_generator_send returned unrecognized type: {:?}", response ); } } /// /// NB: Panics on failure. Only recommended for use with built-in types, such as /// those configured in types::Types. /// pub fn unsafe_call(type_id: TypeId, args: &[Value]) -> Value { let py_type = type_for_type_id(type_id); let arg_handles: Vec<PyObject> = args.iter().map(|v| v.clone().into()).collect(); let gil = Python::acquire_gil(); let args_tuple = PyTuple::new(gil.python(), &arg_handles); py_type .call(gil.python(), args_tuple, None) .map(Value::from) .unwrap_or_else(|e| { let gil = Python::acquire_gil(); panic!( "Core type constructor `{}` failed: {:?}", py_type.name(gil.python()), e ); }) } lazy_static! { static ref INTERNS: Interns = Interns::new(); } py_class!(pub class PyGeneratorResponseBreak |py| { data val: PyObject; def __new__(_cls, val: PyObject) -> CPyResult<Self> { Self::create_instance(py, val) } }); py_class!(pub class PyGeneratorResponseGet |py| { data product: PyType; data declared_subject: PyType; data subject: PyObject; def __new__(_cls, product: PyType, declared_subject: PyType, subject: PyObject) -> CPyResult<Self> { Self::create_instance(py, product, declared_subject, subject) } }); py_class!(pub class PyGeneratorResponseGetMulti |py| { data gets: PyTuple; def __new__(_cls, gets: PyTuple) -> CPyResult<Self> { Self::create_instance(py, gets) } }); #[derive(Debug)] pub struct Get { pub output: TypeId, pub input: Key, pub input_type: TypeId, } impl Get { fn new(py: Python, get: &PyGeneratorResponseGet) -> Result<Get, Failure> { Ok(Get { output: get.product(py).into(), input: INTERNS .key_insert(py, get.subject(py).clone_ref(py).into()) .map_err(|e| Failure::from_py_err_with_gil(py, e))?, input_type: get.declared_subject(py).into(), }) } } impl fmt::Display for Get { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { write!( f, "Get({}, {})", type_to_str(self.output), key_to_str(&self.input) ) } } pub enum GeneratorResponse { Break(Value), Get(Get), GetMulti(Vec<Get>), }
getattr
identifier_name