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
csssupportsrule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::parser::ParserContext; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::{CssRuleType, SupportsRule}; use style::stylesheets::supports_rule::SupportsCondition; use style_traits::{ParsingMode, ToCss}; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_malloc_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited( parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>, ) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new( window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>, ) -> DomRoot<CSSSupportsRule> { reflect_dom_object( Box::new(CSSSupportsRule::new_inherited( parent_stylesheet, supportsrule, )), window, CSSSupportsRuleBinding::Wrap, ) } /// <https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface> pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// <https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface> pub fn set_condition_text(&self, text: DOMString) { let mut input = ParserInput::new(&text); let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom( &url, Some(CssRuleType::Supports), ParsingMode::DEFAULT, quirks_mode, None, None, ); let enabled = { let namespaces = self .cssconditionrule .parent_stylesheet() .style_stylesheet() .contents .namespaces .read(); cond.eval(&context, &namespaces) }; let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } } } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString
}
{ let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule .read_with(&guard) .to_css_string(&guard) .into() }
identifier_body
borrowck-borrow-overloaded-auto-deref.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. // Test how overloaded deref interacts with borrows when only // Deref and not DerefMut is implemented. use std::ops::Deref; struct Rc<T> { value: *const T } impl<T> Deref for Rc<T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.value } } } struct Point { x: isize, y: isize } impl Point { fn get(&self) -> (isize, isize) { (self.x, self.y) } fn set(&mut self, x: isize, y: isize) { self.x = x; self.y = y; } fn x_ref(&self) -> &isize { &self.x } fn y_mut(&mut self) -> &mut isize { &mut self.y } } fn deref_imm_field(x: Rc<Point>) { let __isize = &x.y; } fn deref_mut_field1(x: Rc<Point>) { let __isize = &mut x.y; //~ ERROR cannot borrow } fn deref_mut_field2(mut x: Rc<Point>) { let __isize = &mut x.y; //~ ERROR cannot borrow } fn deref_extend_field(x: &Rc<Point>) -> &isize { &x.y } fn deref_extend_mut_field1(x: &Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } fn deref_extend_mut_field2(x: &mut Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } fn assign_field1<'a>(x: Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field2<'a>(x: &'a Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field3<'a>(x: &'a mut Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn deref_imm_method(x: Rc<Point>) { let __isize = x.get(); } fn
(x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_mut_method2(mut x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_extend_method(x: &Rc<Point>) -> &isize { x.x_ref() } fn deref_extend_mut_method1(x: &Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn deref_extend_mut_method2(x: &mut Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn assign_method1<'a>(x: Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method2<'a>(x: &'a Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method3<'a>(x: &'a mut Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } pub fn main() {}
deref_mut_method1
identifier_name
borrowck-borrow-overloaded-auto-deref.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. // Test how overloaded deref interacts with borrows when only // Deref and not DerefMut is implemented. use std::ops::Deref; struct Rc<T> { value: *const T }
fn deref(&self) -> &T { unsafe { &*self.value } } } struct Point { x: isize, y: isize } impl Point { fn get(&self) -> (isize, isize) { (self.x, self.y) } fn set(&mut self, x: isize, y: isize) { self.x = x; self.y = y; } fn x_ref(&self) -> &isize { &self.x } fn y_mut(&mut self) -> &mut isize { &mut self.y } } fn deref_imm_field(x: Rc<Point>) { let __isize = &x.y; } fn deref_mut_field1(x: Rc<Point>) { let __isize = &mut x.y; //~ ERROR cannot borrow } fn deref_mut_field2(mut x: Rc<Point>) { let __isize = &mut x.y; //~ ERROR cannot borrow } fn deref_extend_field(x: &Rc<Point>) -> &isize { &x.y } fn deref_extend_mut_field1(x: &Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } fn deref_extend_mut_field2(x: &mut Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } fn assign_field1<'a>(x: Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field2<'a>(x: &'a Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field3<'a>(x: &'a mut Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn deref_imm_method(x: Rc<Point>) { let __isize = x.get(); } fn deref_mut_method1(x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_mut_method2(mut x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_extend_method(x: &Rc<Point>) -> &isize { x.x_ref() } fn deref_extend_mut_method1(x: &Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn deref_extend_mut_method2(x: &mut Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn assign_method1<'a>(x: Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method2<'a>(x: &'a Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method3<'a>(x: &'a mut Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } pub fn main() {}
impl<T> Deref for Rc<T> { type Target = T;
random_line_split
borrowck-borrow-overloaded-auto-deref.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. // Test how overloaded deref interacts with borrows when only // Deref and not DerefMut is implemented. use std::ops::Deref; struct Rc<T> { value: *const T } impl<T> Deref for Rc<T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.value } } } struct Point { x: isize, y: isize } impl Point { fn get(&self) -> (isize, isize) { (self.x, self.y) } fn set(&mut self, x: isize, y: isize) { self.x = x; self.y = y; } fn x_ref(&self) -> &isize { &self.x } fn y_mut(&mut self) -> &mut isize { &mut self.y } } fn deref_imm_field(x: Rc<Point>) { let __isize = &x.y; } fn deref_mut_field1(x: Rc<Point>) { let __isize = &mut x.y; //~ ERROR cannot borrow } fn deref_mut_field2(mut x: Rc<Point>) { let __isize = &mut x.y; //~ ERROR cannot borrow } fn deref_extend_field(x: &Rc<Point>) -> &isize { &x.y } fn deref_extend_mut_field1(x: &Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } fn deref_extend_mut_field2(x: &mut Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } fn assign_field1<'a>(x: Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field2<'a>(x: &'a Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field3<'a>(x: &'a mut Rc<Point>) { x.y = 3; //~ ERROR cannot assign } fn deref_imm_method(x: Rc<Point>) { let __isize = x.get(); } fn deref_mut_method1(x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_mut_method2(mut x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_extend_method(x: &Rc<Point>) -> &isize
fn deref_extend_mut_method1(x: &Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn deref_extend_mut_method2(x: &mut Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn assign_method1<'a>(x: Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method2<'a>(x: &'a Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method3<'a>(x: &'a mut Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } pub fn main() {}
{ x.x_ref() }
identifier_body
bytes.rs
// These are tests specifically crafted for regexes that can match arbitrary // bytes. // A silly wrapper to make it possible to write and match raw bytes. struct R<'a>(&'a [u8]); impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } mat!(word_boundary, r"(?-u) \b", " δ", None); #[cfg(feature = "unicode-perl")] mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(word_not_boundary_unicode, r" \B", " δ", None); mat!(perl_w_ascii, r"(?-u)\w+", "aδ", Some((0, 1))); #[cfg(feature = "unicode-perl")]
mat!(perl_d_unicode, r"\d+", "1२३9", Some((0, 8))); mat!(perl_s_ascii, r"(?-u)\s+", " \u{1680}", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_s_unicode, r"\s+", " \u{1680}", Some((0, 4))); // The first `(.+)` matches two Unicode codepoints, but can't match the 5th // byte, which isn't valid UTF-8. The second (byte based) `(.+)` takes over and // matches. mat!( mixed1, r"(.+)(?-u)(.+)", R(b"\xCE\x93\xCE\x94\xFF"), Some((0, 5)), Some((0, 4)), Some((4, 5)) ); mat!(case_ascii_one, r"(?i-u)a", "A", Some((0, 1))); mat!(case_ascii_class, r"(?i-u)[a-z]+", "AaAaA", Some((0, 5))); #[cfg(feature = "unicode-case")] mat!(case_unicode, r"(?i)[a-z]+", "aA\u{212A}aA", Some((0, 7))); mat!(case_not_unicode, r"(?i-u)[a-z]+", "aA\u{212A}aA", Some((0, 2))); mat!(negate_unicode, r"[^a]", "δ", Some((0, 2))); mat!(negate_not_unicode, r"(?-u)[^a]", "δ", Some((0, 1))); // This doesn't match in a normal Unicode regex because the implicit preceding // `.*?` is Unicode aware. mat!(dotstar_prefix_not_unicode1, r"(?-u)a", R(b"\xFFa"), Some((1, 2))); mat!(dotstar_prefix_not_unicode2, r"a", R(b"\xFFa"), Some((1, 2))); // Have fun with null bytes. mat!( null_bytes, r"(?-u)(?P<cstr>[^\x00]+)\x00", R(b"foo\x00"), Some((0, 4)), Some((0, 3)) ); // Test that lookahead operators work properly in the face of invalid UTF-8. // See: https://github.com/rust-lang/regex/issues/277 matiter!( invalidutf8_anchor1, r"(?-u)\xcc?^", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (0, 0) ); matiter!( invalidutf8_anchor2, r"(?-u)^\xf7|4\xff\d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########[] d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########\[] #####\x80\S7|$", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (22, 22) ); matiter!( invalidutf8_anchor3, r"(?-u)^|ddp\xff\xffdddddlQd@\x80", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (0, 0) ); // See https://github.com/rust-lang/regex/issues/303 #[test] fn negated_full_byte_range() { assert!(::regex::bytes::Regex::new(r#"(?-u)[^\x00-\xff]"#).is_err()); } matiter!(word_boundary_ascii1, r"(?-u:\B)x(?-u:\B)", "áxβ"); matiter!( word_boundary_ascii2, r"(?-u:\B)", "0\u{7EF5E}", (2, 2), (3, 3), (4, 4), (5, 5) ); // See: https://github.com/rust-lang/regex/issues/264 mat!(ascii_boundary_no_capture, r"(?-u)\B", "\u{28f3e}", Some((0, 0))); mat!(ascii_boundary_capture, r"(?-u)(\B)", "\u{28f3e}", Some((0, 0))); // See: https://github.com/rust-lang/regex/issues/271 mat!(end_not_wb, r"$(?-u:\B)", "\u{5c124}\u{b576c}", Some((8, 8)));
mat!(perl_w_unicode, r"\w+", "aδ", Some((0, 3))); mat!(perl_d_ascii, r"(?-u)\d+", "1२३9", Some((0, 1))); #[cfg(feature = "unicode-perl")]
random_line_split
bytes.rs
// These are tests specifically crafted for regexes that can match arbitrary // bytes. // A silly wrapper to make it possible to write and match raw bytes. struct R<'a>(&'a [u8]); impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8]
} mat!(word_boundary, r"(?-u) \b", " δ", None); #[cfg(feature = "unicode-perl")] mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(word_not_boundary_unicode, r" \B", " δ", None); mat!(perl_w_ascii, r"(?-u)\w+", "aδ", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_w_unicode, r"\w+", "aδ", Some((0, 3))); mat!(perl_d_ascii, r"(?-u)\d+", "1२३9", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_d_unicode, r"\d+", "1२३9", Some((0, 8))); mat!(perl_s_ascii, r"(?-u)\s+", " \u{1680}", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_s_unicode, r"\s+", " \u{1680}", Some((0, 4))); // The first `(.+)` matches two Unicode codepoints, but can't match the 5th // byte, which isn't valid UTF-8. The second (byte based) `(.+)` takes over and // matches. mat!( mixed1, r"(.+)(?-u)(.+)", R(b"\xCE\x93\xCE\x94\xFF"), Some((0, 5)), Some((0, 4)), Some((4, 5)) ); mat!(case_ascii_one, r"(?i-u)a", "A", Some((0, 1))); mat!(case_ascii_class, r"(?i-u)[a-z]+", "AaAaA", Some((0, 5))); #[cfg(feature = "unicode-case")] mat!(case_unicode, r"(?i)[a-z]+", "aA\u{212A}aA", Some((0, 7))); mat!(case_not_unicode, r"(?i-u)[a-z]+", "aA\u{212A}aA", Some((0, 2))); mat!(negate_unicode, r"[^a]", "δ", Some((0, 2))); mat!(negate_not_unicode, r"(?-u)[^a]", "δ", Some((0, 1))); // This doesn't match in a normal Unicode regex because the implicit preceding // `.*?` is Unicode aware. mat!(dotstar_prefix_not_unicode1, r"(?-u)a", R(b"\xFFa"), Some((1, 2))); mat!(dotstar_prefix_not_unicode2, r"a", R(b"\xFFa"), Some((1, 2))); // Have fun with null bytes. mat!( null_bytes, r"(?-u)(?P<cstr>[^\x00]+)\x00", R(b"foo\x00"), Some((0, 4)), Some((0, 3)) ); // Test that lookahead operators work properly in the face of invalid UTF-8. // See: https://github.com/rust-lang/regex/issues/277 matiter!( invalidutf8_anchor1, r"(?-u)\xcc?^", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (0, 0) ); matiter!( invalidutf8_anchor2, r"(?-u)^\xf7|4\xff\d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########[] d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########\[] #####\x80\S7|$", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (22, 22) ); matiter!( invalidutf8_anchor3, r"(?-u)^|ddp\xff\xffdddddlQd@\x80", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (0, 0) ); // See https://github.com/rust-lang/regex/issues/303 #[test] fn negated_full_byte_range() { assert!(::regex::bytes::Regex::new(r#"(?-u)[^\x00-\xff]"#).is_err()); } matiter!(word_boundary_ascii1, r"(?-u:\B)x(?-u:\B)", "áxβ"); matiter!( word_boundary_ascii2, r"(?-u:\B)", "0\u{7EF5E}", (2, 2), (3, 3), (4, 4), (5, 5) ); // See: https://github.com/rust-lang/regex/issues/264 mat!(ascii_boundary_no_capture, r"(?-u)\B", "\u{28f3e}", Some((0, 0))); mat!(ascii_boundary_capture, r"(?-u)(\B)", "\u{28f3e}", Some((0, 0))); // See: https://github.com/rust-lang/regex/issues/271 mat!(end_not_wb, r"$(?-u:\B)", "\u{5c124}\u{b576c}", Some((8, 8)));
{ self.0 }
identifier_body
bytes.rs
// These are tests specifically crafted for regexes that can match arbitrary // bytes. // A silly wrapper to make it possible to write and match raw bytes. struct
<'a>(&'a [u8]); impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } mat!(word_boundary, r"(?-u) \b", " δ", None); #[cfg(feature = "unicode-perl")] mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(word_not_boundary_unicode, r" \B", " δ", None); mat!(perl_w_ascii, r"(?-u)\w+", "aδ", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_w_unicode, r"\w+", "aδ", Some((0, 3))); mat!(perl_d_ascii, r"(?-u)\d+", "1२३9", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_d_unicode, r"\d+", "1२३9", Some((0, 8))); mat!(perl_s_ascii, r"(?-u)\s+", " \u{1680}", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_s_unicode, r"\s+", " \u{1680}", Some((0, 4))); // The first `(.+)` matches two Unicode codepoints, but can't match the 5th // byte, which isn't valid UTF-8. The second (byte based) `(.+)` takes over and // matches. mat!( mixed1, r"(.+)(?-u)(.+)", R(b"\xCE\x93\xCE\x94\xFF"), Some((0, 5)), Some((0, 4)), Some((4, 5)) ); mat!(case_ascii_one, r"(?i-u)a", "A", Some((0, 1))); mat!(case_ascii_class, r"(?i-u)[a-z]+", "AaAaA", Some((0, 5))); #[cfg(feature = "unicode-case")] mat!(case_unicode, r"(?i)[a-z]+", "aA\u{212A}aA", Some((0, 7))); mat!(case_not_unicode, r"(?i-u)[a-z]+", "aA\u{212A}aA", Some((0, 2))); mat!(negate_unicode, r"[^a]", "δ", Some((0, 2))); mat!(negate_not_unicode, r"(?-u)[^a]", "δ", Some((0, 1))); // This doesn't match in a normal Unicode regex because the implicit preceding // `.*?` is Unicode aware. mat!(dotstar_prefix_not_unicode1, r"(?-u)a", R(b"\xFFa"), Some((1, 2))); mat!(dotstar_prefix_not_unicode2, r"a", R(b"\xFFa"), Some((1, 2))); // Have fun with null bytes. mat!( null_bytes, r"(?-u)(?P<cstr>[^\x00]+)\x00", R(b"foo\x00"), Some((0, 4)), Some((0, 3)) ); // Test that lookahead operators work properly in the face of invalid UTF-8. // See: https://github.com/rust-lang/regex/issues/277 matiter!( invalidutf8_anchor1, r"(?-u)\xcc?^", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (0, 0) ); matiter!( invalidutf8_anchor2, r"(?-u)^\xf7|4\xff\d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########[] d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########\[] #####\x80\S7|$", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (22, 22) ); matiter!( invalidutf8_anchor3, r"(?-u)^|ddp\xff\xffdddddlQd@\x80", R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), (0, 0) ); // See https://github.com/rust-lang/regex/issues/303 #[test] fn negated_full_byte_range() { assert!(::regex::bytes::Regex::new(r#"(?-u)[^\x00-\xff]"#).is_err()); } matiter!(word_boundary_ascii1, r"(?-u:\B)x(?-u:\B)", "áxβ"); matiter!( word_boundary_ascii2, r"(?-u:\B)", "0\u{7EF5E}", (2, 2), (3, 3), (4, 4), (5, 5) ); // See: https://github.com/rust-lang/regex/issues/264 mat!(ascii_boundary_no_capture, r"(?-u)\B", "\u{28f3e}", Some((0, 0))); mat!(ascii_boundary_capture, r"(?-u)(\B)", "\u{28f3e}", Some((0, 0))); // See: https://github.com/rust-lang/regex/issues/271 mat!(end_not_wb, r"$(?-u:\B)", "\u{5c124}\u{b576c}", Some((8, 8)));
R
identifier_name
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { result: RequestResult } struct RequestResult { body: Option<Vec<u8>>, response: Option<ClientResponse> } impl RequestResult { fn new() -> RequestResult { RequestResult { body: None, response: None } } } impl Client { pub fn new() -> Client { Client { result: RequestResult::new() } } pub fn request(&mut self, url: &str) -> Vec<u8> { let client = HttpClient::new().unwrap(); let _ = client.request(url.parse().unwrap(), ClientHandler::new(&mut self.result)); // wait for request to complete thread::park(); // close client and returns request body client.close(); if let Some(buffer) = self.result.body.take() { buffer } else
} pub fn status(&self) -> ::hyper::status::StatusCode { *self.result.response.as_ref().unwrap().status() } } struct ClientHandler { thread: Thread, buffer: Buffer, result: *mut RequestResult } unsafe impl Send for ClientHandler {} impl ClientHandler { fn new(result: &mut RequestResult) -> ClientHandler { ClientHandler { thread: thread::current(), buffer: Buffer::new(), result: result as *mut RequestResult } } } impl Drop for ClientHandler { fn drop(&mut self) { unsafe { (*self.result).body = Some(self.buffer.take()); } // unlocks waiting thread self.thread.unpark(); } } impl Handler<HttpStream> for ClientHandler { fn on_request(&mut self, _req: &mut ClientRequest) -> Next { Next::read() } fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { Next::read() } fn on_response(&mut self, res: ClientResponse) -> Next { use hyper::header::ContentLength; if let Some(&ContentLength(len)) = res.headers().get::<ContentLength>() { self.buffer.set_capacity(len as usize); } unsafe { (*self.result).response = Some(res); } Next::read() } fn on_response_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { if let Ok(keep_reading) = self.buffer.read_from(decoder) { if keep_reading { return Next::read(); } } Next::end() } fn on_error(&mut self, err: ::hyper::Error) -> Next { println!("ERROR: {}", err); Next::remove() } }
{ Vec::new() }
conditional_block
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { result: RequestResult } struct RequestResult { body: Option<Vec<u8>>, response: Option<ClientResponse> } impl RequestResult { fn new() -> RequestResult { RequestResult { body: None, response: None } } } impl Client { pub fn new() -> Client { Client { result: RequestResult::new() } } pub fn request(&mut self, url: &str) -> Vec<u8> { let client = HttpClient::new().unwrap(); let _ = client.request(url.parse().unwrap(), ClientHandler::new(&mut self.result)); // wait for request to complete thread::park(); // close client and returns request body client.close(); if let Some(buffer) = self.result.body.take() { buffer } else { Vec::new() } } pub fn status(&self) -> ::hyper::status::StatusCode { *self.result.response.as_ref().unwrap().status() } } struct ClientHandler { thread: Thread, buffer: Buffer, result: *mut RequestResult } unsafe impl Send for ClientHandler {} impl ClientHandler { fn new(result: &mut RequestResult) -> ClientHandler { ClientHandler { thread: thread::current(), buffer: Buffer::new(), result: result as *mut RequestResult } } } impl Drop for ClientHandler { fn drop(&mut self) { unsafe { (*self.result).body = Some(self.buffer.take()); } // unlocks waiting thread self.thread.unpark();
fn on_request(&mut self, _req: &mut ClientRequest) -> Next { Next::read() } fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { Next::read() } fn on_response(&mut self, res: ClientResponse) -> Next { use hyper::header::ContentLength; if let Some(&ContentLength(len)) = res.headers().get::<ContentLength>() { self.buffer.set_capacity(len as usize); } unsafe { (*self.result).response = Some(res); } Next::read() } fn on_response_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { if let Ok(keep_reading) = self.buffer.read_from(decoder) { if keep_reading { return Next::read(); } } Next::end() } fn on_error(&mut self, err: ::hyper::Error) -> Next { println!("ERROR: {}", err); Next::remove() } }
} } impl Handler<HttpStream> for ClientHandler {
random_line_split
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { result: RequestResult } struct RequestResult { body: Option<Vec<u8>>, response: Option<ClientResponse> } impl RequestResult { fn new() -> RequestResult { RequestResult { body: None, response: None } } } impl Client { pub fn new() -> Client { Client { result: RequestResult::new() } } pub fn request(&mut self, url: &str) -> Vec<u8> { let client = HttpClient::new().unwrap(); let _ = client.request(url.parse().unwrap(), ClientHandler::new(&mut self.result)); // wait for request to complete thread::park(); // close client and returns request body client.close(); if let Some(buffer) = self.result.body.take() { buffer } else { Vec::new() } } pub fn status(&self) -> ::hyper::status::StatusCode { *self.result.response.as_ref().unwrap().status() } } struct ClientHandler { thread: Thread, buffer: Buffer, result: *mut RequestResult } unsafe impl Send for ClientHandler {} impl ClientHandler { fn new(result: &mut RequestResult) -> ClientHandler { ClientHandler { thread: thread::current(), buffer: Buffer::new(), result: result as *mut RequestResult } } } impl Drop for ClientHandler { fn drop(&mut self)
} impl Handler<HttpStream> for ClientHandler { fn on_request(&mut self, _req: &mut ClientRequest) -> Next { Next::read() } fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { Next::read() } fn on_response(&mut self, res: ClientResponse) -> Next { use hyper::header::ContentLength; if let Some(&ContentLength(len)) = res.headers().get::<ContentLength>() { self.buffer.set_capacity(len as usize); } unsafe { (*self.result).response = Some(res); } Next::read() } fn on_response_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { if let Ok(keep_reading) = self.buffer.read_from(decoder) { if keep_reading { return Next::read(); } } Next::end() } fn on_error(&mut self, err: ::hyper::Error) -> Next { println!("ERROR: {}", err); Next::remove() } }
{ unsafe { (*self.result).body = Some(self.buffer.take()); } // unlocks waiting thread self.thread.unpark(); }
identifier_body
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { result: RequestResult } struct RequestResult { body: Option<Vec<u8>>, response: Option<ClientResponse> } impl RequestResult { fn new() -> RequestResult { RequestResult { body: None, response: None } } } impl Client { pub fn new() -> Client { Client { result: RequestResult::new() } } pub fn request(&mut self, url: &str) -> Vec<u8> { let client = HttpClient::new().unwrap(); let _ = client.request(url.parse().unwrap(), ClientHandler::new(&mut self.result)); // wait for request to complete thread::park(); // close client and returns request body client.close(); if let Some(buffer) = self.result.body.take() { buffer } else { Vec::new() } } pub fn status(&self) -> ::hyper::status::StatusCode { *self.result.response.as_ref().unwrap().status() } } struct ClientHandler { thread: Thread, buffer: Buffer, result: *mut RequestResult } unsafe impl Send for ClientHandler {} impl ClientHandler { fn new(result: &mut RequestResult) -> ClientHandler { ClientHandler { thread: thread::current(), buffer: Buffer::new(), result: result as *mut RequestResult } } } impl Drop for ClientHandler { fn drop(&mut self) { unsafe { (*self.result).body = Some(self.buffer.take()); } // unlocks waiting thread self.thread.unpark(); } } impl Handler<HttpStream> for ClientHandler { fn on_request(&mut self, _req: &mut ClientRequest) -> Next { Next::read() } fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { Next::read() } fn on_response(&mut self, res: ClientResponse) -> Next { use hyper::header::ContentLength; if let Some(&ContentLength(len)) = res.headers().get::<ContentLength>() { self.buffer.set_capacity(len as usize); } unsafe { (*self.result).response = Some(res); } Next::read() } fn on_response_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { if let Ok(keep_reading) = self.buffer.read_from(decoder) { if keep_reading { return Next::read(); } } Next::end() } fn
(&mut self, err: ::hyper::Error) -> Next { println!("ERROR: {}", err); Next::remove() } }
on_error
identifier_name
lib.rs
#![allow(dead_code)] extern crate oscillator; extern crate stopwatch; use oscillator::Oscillator; use stopwatch::Stopwatch; fn assert_near(a : f32, b : f32)
#[test] fn test_new() { let mut osc = Oscillator::new(); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_null_freq() { let mut osc = Oscillator::start_new(); osc.set_frequency(0.0); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_cycle() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 500 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 1.0); } #[test] fn test_freq() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); osc.set_frequency(0.5); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 2000 { } assert_near(osc.get_value(), 1.0); }
{ assert!((a-b).abs() < 0.05) }
identifier_body
lib.rs
#![allow(dead_code)] extern crate oscillator; extern crate stopwatch; use oscillator::Oscillator; use stopwatch::Stopwatch; fn assert_near(a : f32, b : f32) { assert!((a-b).abs() < 0.05) } #[test] fn test_new() { let mut osc = Oscillator::new(); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_null_freq() { let mut osc = Oscillator::start_new(); osc.set_frequency(0.0); assert_eq!(osc.get_value(), 1.0); }
#[test] fn test_cycle() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 500 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 1.0); } #[test] fn test_freq() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); osc.set_frequency(0.5); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 2000 { } assert_near(osc.get_value(), 1.0); }
random_line_split
lib.rs
#![allow(dead_code)] extern crate oscillator; extern crate stopwatch; use oscillator::Oscillator; use stopwatch::Stopwatch; fn assert_near(a : f32, b : f32) { assert!((a-b).abs() < 0.05) } #[test] fn test_new() { let mut osc = Oscillator::new(); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_null_freq() { let mut osc = Oscillator::start_new(); osc.set_frequency(0.0); assert_eq!(osc.get_value(), 1.0); } #[test] fn
() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 500 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 1.0); } #[test] fn test_freq() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); osc.set_frequency(0.5); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 2000 { } assert_near(osc.get_value(), 1.0); }
test_cycle
identifier_name
build.rs
use std::env; fn main() { println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set");
if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.contains("linux") || target.contains("netbsd") || target.contains("dragonfly") || target.contains("openbsd") || target.contains("solaris") || target.contains("illumos") || target.contains("apple-darwin") || target.contains("apple-ios") || target.contains("uwp") || target.contains("windows") || target.contains("fuchsia") || (target.contains("sgx") && target.contains("fortanix")) || target.contains("hermit") || target.contains("l4re") || target.contains("redox") || target.contains("haiku") || target.contains("vxworks") || target.contains("wasm32") || target.contains("wasm64") || target.contains("asmjs") || target.contains("espidf") || target.contains("solid") { // These platforms don't have any special requirements. } else { // This is for Cargo's build-std support, to mark std as unstable for // typically no_std platforms. // This covers: // - os=none ("bare metal" targets) // - mipsel-sony-psp // - nvptx64-nvidia-cuda // - arch=avr // - tvos (aarch64-apple-tvos, x86_64-apple-tvos) // - uefi (x86_64-unknown-uefi, i686-unknown-uefi) // - JSON targets // - Any new targets that have not been explicitly added above. println!("cargo:rustc-cfg=feature=\"restricted-std\""); } println!("cargo:rustc-env=STD_ENV_ARCH={}", env::var("CARGO_CFG_TARGET_ARCH").unwrap()); println!("cargo:rustc-cfg=backtrace_in_libstd"); }
if target.contains("freebsd") {
random_line_split
build.rs
use std::env; fn main() { println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set"); if target.contains("freebsd") { if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.contains("linux") || target.contains("netbsd") || target.contains("dragonfly") || target.contains("openbsd") || target.contains("solaris") || target.contains("illumos") || target.contains("apple-darwin") || target.contains("apple-ios") || target.contains("uwp") || target.contains("windows") || target.contains("fuchsia") || (target.contains("sgx") && target.contains("fortanix")) || target.contains("hermit") || target.contains("l4re") || target.contains("redox") || target.contains("haiku") || target.contains("vxworks") || target.contains("wasm32") || target.contains("wasm64") || target.contains("asmjs") || target.contains("espidf") || target.contains("solid")
else { // This is for Cargo's build-std support, to mark std as unstable for // typically no_std platforms. // This covers: // - os=none ("bare metal" targets) // - mipsel-sony-psp // - nvptx64-nvidia-cuda // - arch=avr // - tvos (aarch64-apple-tvos, x86_64-apple-tvos) // - uefi (x86_64-unknown-uefi, i686-unknown-uefi) // - JSON targets // - Any new targets that have not been explicitly added above. println!("cargo:rustc-cfg=feature=\"restricted-std\""); } println!("cargo:rustc-env=STD_ENV_ARCH={}", env::var("CARGO_CFG_TARGET_ARCH").unwrap()); println!("cargo:rustc-cfg=backtrace_in_libstd"); }
{ // These platforms don't have any special requirements. }
conditional_block
build.rs
use std::env; fn
() { println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set"); if target.contains("freebsd") { if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.contains("linux") || target.contains("netbsd") || target.contains("dragonfly") || target.contains("openbsd") || target.contains("solaris") || target.contains("illumos") || target.contains("apple-darwin") || target.contains("apple-ios") || target.contains("uwp") || target.contains("windows") || target.contains("fuchsia") || (target.contains("sgx") && target.contains("fortanix")) || target.contains("hermit") || target.contains("l4re") || target.contains("redox") || target.contains("haiku") || target.contains("vxworks") || target.contains("wasm32") || target.contains("wasm64") || target.contains("asmjs") || target.contains("espidf") || target.contains("solid") { // These platforms don't have any special requirements. } else { // This is for Cargo's build-std support, to mark std as unstable for // typically no_std platforms. // This covers: // - os=none ("bare metal" targets) // - mipsel-sony-psp // - nvptx64-nvidia-cuda // - arch=avr // - tvos (aarch64-apple-tvos, x86_64-apple-tvos) // - uefi (x86_64-unknown-uefi, i686-unknown-uefi) // - JSON targets // - Any new targets that have not been explicitly added above. println!("cargo:rustc-cfg=feature=\"restricted-std\""); } println!("cargo:rustc-env=STD_ENV_ARCH={}", env::var("CARGO_CFG_TARGET_ARCH").unwrap()); println!("cargo:rustc-cfg=backtrace_in_libstd"); }
main
identifier_name
build.rs
use std::env; fn main()
|| target.contains("l4re") || target.contains("redox") || target.contains("haiku") || target.contains("vxworks") || target.contains("wasm32") || target.contains("wasm64") || target.contains("asmjs") || target.contains("espidf") || target.contains("solid") { // These platforms don't have any special requirements. } else { // This is for Cargo's build-std support, to mark std as unstable for // typically no_std platforms. // This covers: // - os=none ("bare metal" targets) // - mipsel-sony-psp // - nvptx64-nvidia-cuda // - arch=avr // - tvos (aarch64-apple-tvos, x86_64-apple-tvos) // - uefi (x86_64-unknown-uefi, i686-unknown-uefi) // - JSON targets // - Any new targets that have not been explicitly added above. println!("cargo:rustc-cfg=feature=\"restricted-std\""); } println!("cargo:rustc-env=STD_ENV_ARCH={}", env::var("CARGO_CFG_TARGET_ARCH").unwrap()); println!("cargo:rustc-cfg=backtrace_in_libstd"); }
{ println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set"); if target.contains("freebsd") { if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.contains("linux") || target.contains("netbsd") || target.contains("dragonfly") || target.contains("openbsd") || target.contains("solaris") || target.contains("illumos") || target.contains("apple-darwin") || target.contains("apple-ios") || target.contains("uwp") || target.contains("windows") || target.contains("fuchsia") || (target.contains("sgx") && target.contains("fortanix")) || target.contains("hermit")
identifier_body
issue-9906.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast windows doesn't like extern mod // aux-build:issue-9906.rs pub use other::FooBar; pub use other::foo; mod other { pub struct FooBar{value: int} impl FooBar{ pub fn new(val: int) -> FooBar { FooBar{value: val} } } pub fn
(){ 1+1; } }
foo
identifier_name
issue-9906.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// except according to those terms. // xfail-fast windows doesn't like extern mod // aux-build:issue-9906.rs pub use other::FooBar; pub use other::foo; mod other { pub struct FooBar{value: int} impl FooBar{ pub fn new(val: int) -> FooBar { FooBar{value: val} } } pub fn foo(){ 1+1; } }
// 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
random_line_split
result.rs
use std::error::Error; use std::fmt; use std::fmt::Display; use std::ptr; use env::NapiEnv; use sys::{napi_create_error, napi_create_range_error, napi_create_type_error, napi_status, napi_value}; use value::{NapiString, NapiValue}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum
{ InvalidArg, ObjectExpected, StringExpected, NameExpected, FunctionExpected, NumberExpected, BooleanExpected, ArrayExpected, GenericFailure, PendingException, Cancelled, EscapeCalledTwice, ApplicationError, } #[derive(Clone, Debug)] pub struct NapiError { pub kind: NapiErrorKind, pub message: Option<String>, pub exception: Option<napi_value>, } pub type NapiResult<T> = Result<T, NapiError>; impl NapiErrorKind { pub fn from_napi_status(status: napi_status) -> Self { match status { napi_status::napi_invalid_arg => NapiErrorKind::InvalidArg, napi_status::napi_object_expected => NapiErrorKind::ObjectExpected, napi_status::napi_string_expected => NapiErrorKind::StringExpected, napi_status::napi_name_expected => NapiErrorKind::NameExpected, napi_status::napi_function_expected => { NapiErrorKind::FunctionExpected } napi_status::napi_number_expected => NapiErrorKind::NumberExpected, napi_status::napi_boolean_expected => { NapiErrorKind::BooleanExpected } napi_status::napi_array_expected => NapiErrorKind::ArrayExpected, napi_status::napi_generic_failure => NapiErrorKind::GenericFailure, napi_status::napi_pending_exception => { NapiErrorKind::PendingException } napi_status::napi_cancelled => NapiErrorKind::Cancelled, napi_status::napi_escape_called_twice => { NapiErrorKind::EscapeCalledTwice } _ => { // Both situations should never happen, so just panic. panic!( "Either the JavaScript VM returned an unknown status code, \ or NapiErrorKind::from_napi_status was called with \ napi_status::napi_ok" ); } } } } impl Error for NapiError { fn description(&self) -> &str { match self.kind { NapiErrorKind::InvalidArg => "NapiError: invalid argument", NapiErrorKind::ObjectExpected => "NapiError: object expected", NapiErrorKind::StringExpected => "NapiError: string expected", NapiErrorKind::NameExpected => "NapiError: name expected", NapiErrorKind::FunctionExpected => "NapiError: function expected", NapiErrorKind::NumberExpected => "NapiError: number expected", NapiErrorKind::BooleanExpected => "NapiError: boolean argument", NapiErrorKind::ArrayExpected => "NapiError: array expected", NapiErrorKind::GenericFailure => "NapiError: generic failure", NapiErrorKind::PendingException => "NapiError: pending exception", NapiErrorKind::Cancelled => "NapiError: cancelled", NapiErrorKind::EscapeCalledTwice => { "NapiError: escape called twice" } NapiErrorKind::ApplicationError => "NapiError: application error", } } } impl Display for NapiError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "{}", self.description()) .and_then(|result| { if let Some(ref message) = self.message { write!(formatter, " ({})", message) } else { Ok(result) } }) .and_then(|result| { if self.exception.is_some() { write!(formatter, ", JavaScript exception attached") } else { Ok(result) } }) } } macro_rules! error_constructor { ($name:ident => $napi_fn_name:ident) => { pub fn $name(env: &NapiEnv, message: &NapiString) -> NapiError { let mut exception = ptr::null_mut(); let status = unsafe { $napi_fn_name( env.as_sys_env(), ptr::null_mut(), message.as_sys_value(), &mut exception, ) }; if let Err(error) = env.handle_status(status) { return error; } NapiError { kind: NapiErrorKind::ApplicationError, message: None, exception: Some(exception), } } } } impl NapiError { error_constructor!(error => napi_create_error); error_constructor!(type_error => napi_create_type_error); error_constructor!(range_error => napi_create_range_error); }
NapiErrorKind
identifier_name
result.rs
use std::error::Error; use std::fmt; use std::fmt::Display; use std::ptr; use env::NapiEnv; use sys::{napi_create_error, napi_create_range_error, napi_create_type_error, napi_status, napi_value}; use value::{NapiString, NapiValue}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NapiErrorKind { InvalidArg, ObjectExpected, StringExpected, NameExpected, FunctionExpected, NumberExpected, BooleanExpected, ArrayExpected, GenericFailure, PendingException, Cancelled, EscapeCalledTwice, ApplicationError, } #[derive(Clone, Debug)] pub struct NapiError { pub kind: NapiErrorKind, pub message: Option<String>, pub exception: Option<napi_value>, } pub type NapiResult<T> = Result<T, NapiError>; impl NapiErrorKind { pub fn from_napi_status(status: napi_status) -> Self { match status { napi_status::napi_invalid_arg => NapiErrorKind::InvalidArg, napi_status::napi_object_expected => NapiErrorKind::ObjectExpected, napi_status::napi_string_expected => NapiErrorKind::StringExpected, napi_status::napi_name_expected => NapiErrorKind::NameExpected, napi_status::napi_function_expected => { NapiErrorKind::FunctionExpected } napi_status::napi_number_expected => NapiErrorKind::NumberExpected, napi_status::napi_boolean_expected => { NapiErrorKind::BooleanExpected } napi_status::napi_array_expected => NapiErrorKind::ArrayExpected, napi_status::napi_generic_failure => NapiErrorKind::GenericFailure, napi_status::napi_pending_exception => { NapiErrorKind::PendingException } napi_status::napi_cancelled => NapiErrorKind::Cancelled, napi_status::napi_escape_called_twice => { NapiErrorKind::EscapeCalledTwice } _ => { // Both situations should never happen, so just panic. panic!( "Either the JavaScript VM returned an unknown status code, \ or NapiErrorKind::from_napi_status was called with \ napi_status::napi_ok" ); } } } } impl Error for NapiError { fn description(&self) -> &str { match self.kind { NapiErrorKind::InvalidArg => "NapiError: invalid argument", NapiErrorKind::ObjectExpected => "NapiError: object expected", NapiErrorKind::StringExpected => "NapiError: string expected", NapiErrorKind::NameExpected => "NapiError: name expected", NapiErrorKind::FunctionExpected => "NapiError: function expected", NapiErrorKind::NumberExpected => "NapiError: number expected", NapiErrorKind::BooleanExpected => "NapiError: boolean argument", NapiErrorKind::ArrayExpected => "NapiError: array expected", NapiErrorKind::GenericFailure => "NapiError: generic failure",
NapiErrorKind::EscapeCalledTwice => { "NapiError: escape called twice" } NapiErrorKind::ApplicationError => "NapiError: application error", } } } impl Display for NapiError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "{}", self.description()) .and_then(|result| { if let Some(ref message) = self.message { write!(formatter, " ({})", message) } else { Ok(result) } }) .and_then(|result| { if self.exception.is_some() { write!(formatter, ", JavaScript exception attached") } else { Ok(result) } }) } } macro_rules! error_constructor { ($name:ident => $napi_fn_name:ident) => { pub fn $name(env: &NapiEnv, message: &NapiString) -> NapiError { let mut exception = ptr::null_mut(); let status = unsafe { $napi_fn_name( env.as_sys_env(), ptr::null_mut(), message.as_sys_value(), &mut exception, ) }; if let Err(error) = env.handle_status(status) { return error; } NapiError { kind: NapiErrorKind::ApplicationError, message: None, exception: Some(exception), } } } } impl NapiError { error_constructor!(error => napi_create_error); error_constructor!(type_error => napi_create_type_error); error_constructor!(range_error => napi_create_range_error); }
NapiErrorKind::PendingException => "NapiError: pending exception", NapiErrorKind::Cancelled => "NapiError: cancelled",
random_line_split
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mpsc::Receiver<Message>, num_chairs: usize, waiting_customers: VecDeque<Customer>, free_barbers: VecDeque<Barber>, } enum Message { BarberFree(Barber), CustomerArrives(Customer), } impl Barber { fn new(id: i32, shop: &Barbershop) -> Barber { Barber{ id: id, to_shop: shop.tx.clone(), } } fn
(self, c: Customer) { println!("Barber {:?} is cutting hair of customer {:?}.", self.id, c.id); thread::sleep_ms(c.hair_length); self.to_shop.clone().send(Message::BarberFree(self)).unwrap(); } } impl Barbershop { fn new(num_chairs: usize) -> Barbershop { let (tx, rx) = mpsc::channel::<Message>(); Barbershop{ tx: tx, rx: rx, num_chairs: num_chairs, waiting_customers: VecDeque::<Customer>::new(), free_barbers: VecDeque::<Barber>::new(), } } fn hire_barber(&mut self, id: i32) { let b = Barber::new(id, self); self.barber_free(b); } fn serve_customer(&mut self) { if self.free_barbers.len() == 0 { return; } if self.waiting_customers.len() == 0 { return; } let b = self.free_barbers.pop_front().unwrap(); let c = self.waiting_customers.pop_front().unwrap(); thread::spawn(move || b.cut_hair(c)); } fn barber_free(&mut self, b: Barber) { self.free_barbers.push_back(b); self.serve_customer(); } fn new_customer(&mut self, c: Customer) { if self.waiting_customers.len() < self.num_chairs { self.waiting_customers.push_back(c); self.serve_customer(); } else { println!("Turned away customer {:?}.", c.id); } } fn operate(&mut self) { loop { let m = self.rx.recv().unwrap(); match m { Message::BarberFree(b) => self.barber_free(b), Message::CustomerArrives(c) => self.new_customer(c), }; } } } pub fn sleeping_barbers() { let mut shop = Barbershop::new(5); let to_shop = shop.tx.clone(); let hair_lengths = Range::new(50, 1000); let customer_interval = Range::new(50, 500); let mut rng = rand::thread_rng(); shop.hire_barber(1); shop.hire_barber(2); thread::spawn(move || shop.operate()); for i in 1..20 { let c = Customer{ id: i, hair_length: hair_lengths.ind_sample(&mut rng), }; println!("Customer {:?} arrives at shop.", i); to_shop.send(Message::CustomerArrives(c)).unwrap(); thread::sleep_ms(customer_interval.ind_sample(&mut rng)); } thread::sleep_ms(10000); }
cut_hair
identifier_name
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mpsc::Receiver<Message>, num_chairs: usize, waiting_customers: VecDeque<Customer>, free_barbers: VecDeque<Barber>, } enum Message { BarberFree(Barber), CustomerArrives(Customer), } impl Barber { fn new(id: i32, shop: &Barbershop) -> Barber { Barber{ id: id, to_shop: shop.tx.clone(), } } fn cut_hair(self, c: Customer) { println!("Barber {:?} is cutting hair of customer {:?}.", self.id, c.id); thread::sleep_ms(c.hair_length); self.to_shop.clone().send(Message::BarberFree(self)).unwrap(); } } impl Barbershop { fn new(num_chairs: usize) -> Barbershop
fn hire_barber(&mut self, id: i32) { let b = Barber::new(id, self); self.barber_free(b); } fn serve_customer(&mut self) { if self.free_barbers.len() == 0 { return; } if self.waiting_customers.len() == 0 { return; } let b = self.free_barbers.pop_front().unwrap(); let c = self.waiting_customers.pop_front().unwrap(); thread::spawn(move || b.cut_hair(c)); } fn barber_free(&mut self, b: Barber) { self.free_barbers.push_back(b); self.serve_customer(); } fn new_customer(&mut self, c: Customer) { if self.waiting_customers.len() < self.num_chairs { self.waiting_customers.push_back(c); self.serve_customer(); } else { println!("Turned away customer {:?}.", c.id); } } fn operate(&mut self) { loop { let m = self.rx.recv().unwrap(); match m { Message::BarberFree(b) => self.barber_free(b), Message::CustomerArrives(c) => self.new_customer(c), }; } } } pub fn sleeping_barbers() { let mut shop = Barbershop::new(5); let to_shop = shop.tx.clone(); let hair_lengths = Range::new(50, 1000); let customer_interval = Range::new(50, 500); let mut rng = rand::thread_rng(); shop.hire_barber(1); shop.hire_barber(2); thread::spawn(move || shop.operate()); for i in 1..20 { let c = Customer{ id: i, hair_length: hair_lengths.ind_sample(&mut rng), }; println!("Customer {:?} arrives at shop.", i); to_shop.send(Message::CustomerArrives(c)).unwrap(); thread::sleep_ms(customer_interval.ind_sample(&mut rng)); } thread::sleep_ms(10000); }
{ let (tx, rx) = mpsc::channel::<Message>(); Barbershop{ tx: tx, rx: rx, num_chairs: num_chairs, waiting_customers: VecDeque::<Customer>::new(), free_barbers: VecDeque::<Barber>::new(), } }
identifier_body
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mpsc::Receiver<Message>, num_chairs: usize, waiting_customers: VecDeque<Customer>, free_barbers: VecDeque<Barber>, } enum Message { BarberFree(Barber), CustomerArrives(Customer), } impl Barber { fn new(id: i32, shop: &Barbershop) -> Barber { Barber{ id: id, to_shop: shop.tx.clone(), } } fn cut_hair(self, c: Customer) { println!("Barber {:?} is cutting hair of customer {:?}.", self.id, c.id); thread::sleep_ms(c.hair_length); self.to_shop.clone().send(Message::BarberFree(self)).unwrap(); } } impl Barbershop { fn new(num_chairs: usize) -> Barbershop { let (tx, rx) = mpsc::channel::<Message>(); Barbershop{ tx: tx, rx: rx, num_chairs: num_chairs, waiting_customers: VecDeque::<Customer>::new(), free_barbers: VecDeque::<Barber>::new(), } } fn hire_barber(&mut self, id: i32) { let b = Barber::new(id, self); self.barber_free(b); } fn serve_customer(&mut self) { if self.free_barbers.len() == 0 { return; } if self.waiting_customers.len() == 0
let b = self.free_barbers.pop_front().unwrap(); let c = self.waiting_customers.pop_front().unwrap(); thread::spawn(move || b.cut_hair(c)); } fn barber_free(&mut self, b: Barber) { self.free_barbers.push_back(b); self.serve_customer(); } fn new_customer(&mut self, c: Customer) { if self.waiting_customers.len() < self.num_chairs { self.waiting_customers.push_back(c); self.serve_customer(); } else { println!("Turned away customer {:?}.", c.id); } } fn operate(&mut self) { loop { let m = self.rx.recv().unwrap(); match m { Message::BarberFree(b) => self.barber_free(b), Message::CustomerArrives(c) => self.new_customer(c), }; } } } pub fn sleeping_barbers() { let mut shop = Barbershop::new(5); let to_shop = shop.tx.clone(); let hair_lengths = Range::new(50, 1000); let customer_interval = Range::new(50, 500); let mut rng = rand::thread_rng(); shop.hire_barber(1); shop.hire_barber(2); thread::spawn(move || shop.operate()); for i in 1..20 { let c = Customer{ id: i, hair_length: hair_lengths.ind_sample(&mut rng), }; println!("Customer {:?} arrives at shop.", i); to_shop.send(Message::CustomerArrives(c)).unwrap(); thread::sleep_ms(customer_interval.ind_sample(&mut rng)); } thread::sleep_ms(10000); }
{ return; }
conditional_block
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mpsc::Receiver<Message>, num_chairs: usize, waiting_customers: VecDeque<Customer>, free_barbers: VecDeque<Barber>, } enum Message { BarberFree(Barber), CustomerArrives(Customer), } impl Barber { fn new(id: i32, shop: &Barbershop) -> Barber { Barber{ id: id, to_shop: shop.tx.clone(), } } fn cut_hair(self, c: Customer) { println!("Barber {:?} is cutting hair of customer {:?}.", self.id, c.id); thread::sleep_ms(c.hair_length); self.to_shop.clone().send(Message::BarberFree(self)).unwrap(); } } impl Barbershop { fn new(num_chairs: usize) -> Barbershop { let (tx, rx) = mpsc::channel::<Message>(); Barbershop{ tx: tx, rx: rx, num_chairs: num_chairs, waiting_customers: VecDeque::<Customer>::new(), free_barbers: VecDeque::<Barber>::new(), } } fn hire_barber(&mut self, id: i32) { let b = Barber::new(id, self); self.barber_free(b); } fn serve_customer(&mut self) { if self.free_barbers.len() == 0 { return; } if self.waiting_customers.len() == 0 { return; } let b = self.free_barbers.pop_front().unwrap(); let c = self.waiting_customers.pop_front().unwrap(); thread::spawn(move || b.cut_hair(c)); } fn barber_free(&mut self, b: Barber) { self.free_barbers.push_back(b); self.serve_customer(); } fn new_customer(&mut self, c: Customer) { if self.waiting_customers.len() < self.num_chairs { self.waiting_customers.push_back(c); self.serve_customer(); } else { println!("Turned away customer {:?}.", c.id); } } fn operate(&mut self) { loop { let m = self.rx.recv().unwrap(); match m { Message::BarberFree(b) => self.barber_free(b), Message::CustomerArrives(c) => self.new_customer(c), }; } } } pub fn sleeping_barbers() { let mut shop = Barbershop::new(5); let to_shop = shop.tx.clone(); let hair_lengths = Range::new(50, 1000); let customer_interval = Range::new(50, 500); let mut rng = rand::thread_rng(); shop.hire_barber(1); shop.hire_barber(2); thread::spawn(move || shop.operate()); for i in 1..20 { let c = Customer{ id: i,
} thread::sleep_ms(10000); }
hair_length: hair_lengths.ind_sample(&mut rng), }; println!("Customer {:?} arrives at shop.", i); to_shop.send(Message::CustomerArrives(c)).unwrap(); thread::sleep_ms(customer_interval.ind_sample(&mut rng));
random_line_split
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_,..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } macro_rules! my_recursive_macro { () => { my_recursive_macro!(); //~ ERROR recursion limit }; } macro_rules! my_macro { () => {}; } fn main() { my_faulty_macro!(); my_recursive_macro!(); test!(); non_exisiting!(); derive!(Debug); let a = pat_macro!(); } #[my_macro] fn
() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
use_bang_macro_as_attr
identifier_name
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_,..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } macro_rules! my_recursive_macro { () => { my_recursive_macro!(); //~ ERROR recursion limit }; } macro_rules! my_macro { () => {}; } fn main() { my_faulty_macro!(); my_recursive_macro!(); test!(); non_exisiting!(); derive!(Debug); let a = pat_macro!(); }
#[my_macro] fn use_bang_macro_as_attr() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
random_line_split
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_,..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } macro_rules! my_recursive_macro { () => { my_recursive_macro!(); //~ ERROR recursion limit }; } macro_rules! my_macro { () => {}; } fn main()
#[my_macro] fn use_bang_macro_as_attr() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
{ my_faulty_macro!(); my_recursive_macro!(); test!(); non_exisiting!(); derive!(Debug); let a = pat_macro!(); }
identifier_body
nested-matchs.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 baz() ->! { fail!(); } fn foo()
} pub fn main() { foo(); }
{ match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{:?}", bar); } None::<int> => { println!("hello"); } }
identifier_body
nested-matchs.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 baz() ->! { fail!(); } fn foo() { match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{:?}", bar);
} None::<int> => { println!("hello"); } } } pub fn main() { foo(); }
random_line_split
nested-matchs.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
() ->! { fail!(); } fn foo() { match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{:?}", bar); } None::<int> => { println!("hello"); } } } pub fn main() { foo(); }
baz
identifier_name
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; #[derive(Debug, Hash)] pub struct Semaphore(pub vk::Semaphore); #[derive(Debug, Hash, PartialEq, Eq)] pub struct Fence(pub vk::Fence); #[derive(Debug, Hash)] pub struct Event(pub vk::Event); #[derive(Debug, Hash)] pub struct GraphicsPipeline(pub vk::Pipeline); #[derive(Debug, Hash)] pub struct ComputePipeline(pub vk::Pipeline); #[derive(Debug, Hash)] pub struct Memory { pub(crate) raw: vk::DeviceMemory, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct Buffer { pub(crate) raw: vk::Buffer, } unsafe impl Sync for Buffer {} unsafe impl Send for Buffer {} #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct BufferView { pub(crate) raw: vk::BufferView, } #[derive(Debug, Hash, PartialEq, Eq)] pub struct Image { pub(crate) raw: vk::Image,
#[derive(Debug, Hash, PartialEq, Eq)] pub struct ImageView { pub(crate) image: vk::Image, pub(crate) raw: vk::ImageView, pub(crate) range: SubresourceRange, } #[derive(Debug, Hash)] pub struct Sampler(pub vk::Sampler); #[derive(Debug, Hash)] pub struct RenderPass { pub raw: vk::RenderPass, pub attachment_count: usize, } pub type FramebufferKey = SmallVec<[vk::ImageView; ROUGH_MAX_ATTACHMENT_COUNT]>; #[derive(Debug)] pub enum Framebuffer { ImageLess(vk::Framebuffer), Legacy { name: String, map: Mutex<HashMap<FramebufferKey, vk::Framebuffer>>, extent: Extent, }, } pub(crate) type SortedBindings = Arc<Vec<pso::DescriptorSetLayoutBinding>>; #[derive(Debug)] pub struct DescriptorSetLayout { pub(crate) raw: vk::DescriptorSetLayout, pub(crate) bindings: SortedBindings, } #[derive(Debug)] pub struct DescriptorSet { pub(crate) raw: vk::DescriptorSet, pub(crate) bindings: SortedBindings, } #[derive(Debug, Hash)] pub struct PipelineLayout { pub(crate) raw: vk::PipelineLayout, } #[derive(Debug)] pub struct PipelineCache { pub(crate) raw: vk::PipelineCache, } #[derive(Debug, Eq, Hash, PartialEq)] pub struct ShaderModule { pub(crate) raw: vk::ShaderModule, } #[derive(Debug)] pub struct DescriptorPool { raw: vk::DescriptorPool, device: Arc<RawDevice>, /// This vec only exists to re-use allocations when `DescriptorSet`s are freed. temp_raw_sets: Vec<vk::DescriptorSet>, /// This vec only exists for collecting the layouts when allocating new sets. temp_raw_layouts: Vec<vk::DescriptorSetLayout>, /// This vec only exists for collecting the bindings when allocating new sets. temp_layout_bindings: Vec<SortedBindings>, } impl DescriptorPool { pub(crate) fn new(raw: vk::DescriptorPool, device: &Arc<RawDevice>) -> Self { DescriptorPool { raw, device: Arc::clone(device), temp_raw_sets: Vec::new(), temp_raw_layouts: Vec::new(), temp_layout_bindings: Vec::new(), } } pub(crate) fn finish(self) -> vk::DescriptorPool { self.raw } } impl pso::DescriptorPool<Backend> for DescriptorPool { unsafe fn allocate_one( &mut self, layout: &DescriptorSetLayout, ) -> Result<DescriptorSet, pso::AllocationError> { let raw_layouts = [layout.raw]; let info = vk::DescriptorSetAllocateInfo::builder() .descriptor_pool(self.raw) .set_layouts(&raw_layouts); self.device .raw .allocate_descriptor_sets(&info) //Note: https://github.com/MaikKlein/ash/issues/358 .map(|mut sets| DescriptorSet { raw: sets.pop().unwrap(), bindings: Arc::clone(&layout.bindings), }) .map_err(|err| match err { vk::Result::ERROR_OUT_OF_HOST_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Host) } vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Device) } vk::Result::ERROR_OUT_OF_POOL_MEMORY => pso::AllocationError::OutOfPoolMemory, _ => pso::AllocationError::FragmentedPool, }) } unsafe fn allocate<'a, I, E>( &mut self, layouts: I, list: &mut E, ) -> Result<(), pso::AllocationError> where I: Iterator<Item = &'a DescriptorSetLayout>, E: Extend<DescriptorSet>, { self.temp_raw_layouts.clear(); self.temp_layout_bindings.clear(); for layout in layouts { self.temp_raw_layouts.push(layout.raw); self.temp_layout_bindings.push(Arc::clone(&layout.bindings)); } let info = vk::DescriptorSetAllocateInfo::builder() .descriptor_pool(self.raw) .set_layouts(&self.temp_raw_layouts); self.device .raw .allocate_descriptor_sets(&info) .map(|sets| { list.extend( sets.into_iter() .zip(self.temp_layout_bindings.drain(..)) .map(|(raw, bindings)| DescriptorSet { raw, bindings }), ) }) .map_err(|err| match err { vk::Result::ERROR_OUT_OF_HOST_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Host) } vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Device) } vk::Result::ERROR_OUT_OF_POOL_MEMORY => pso::AllocationError::OutOfPoolMemory, _ => pso::AllocationError::FragmentedPool, }) } unsafe fn free<I>(&mut self, descriptor_sets: I) where I: Iterator<Item = DescriptorSet>, { let sets_iter = descriptor_sets.map(|d| d.raw); inplace_or_alloc_from_iter(sets_iter, |sets| { if!sets.is_empty() { if let Err(e) = self.device.raw.free_descriptor_sets(self.raw, sets) { error!("free_descriptor_sets error {}", e); } } }) } unsafe fn reset(&mut self) { assert_eq!( Ok(()), self.device .raw .reset_descriptor_pool(self.raw, vk::DescriptorPoolResetFlags::empty()) ); } } #[derive(Debug, Hash)] pub struct QueryPool(pub vk::QueryPool);
pub(crate) ty: vk::ImageType, pub(crate) flags: vk::ImageCreateFlags, pub(crate) extent: vk::Extent3D, }
random_line_split
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; #[derive(Debug, Hash)] pub struct Semaphore(pub vk::Semaphore); #[derive(Debug, Hash, PartialEq, Eq)] pub struct Fence(pub vk::Fence); #[derive(Debug, Hash)] pub struct Event(pub vk::Event); #[derive(Debug, Hash)] pub struct GraphicsPipeline(pub vk::Pipeline); #[derive(Debug, Hash)] pub struct ComputePipeline(pub vk::Pipeline); #[derive(Debug, Hash)] pub struct Memory { pub(crate) raw: vk::DeviceMemory, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct Buffer { pub(crate) raw: vk::Buffer, } unsafe impl Sync for Buffer {} unsafe impl Send for Buffer {} #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct BufferView { pub(crate) raw: vk::BufferView, } #[derive(Debug, Hash, PartialEq, Eq)] pub struct Image { pub(crate) raw: vk::Image, pub(crate) ty: vk::ImageType, pub(crate) flags: vk::ImageCreateFlags, pub(crate) extent: vk::Extent3D, } #[derive(Debug, Hash, PartialEq, Eq)] pub struct ImageView { pub(crate) image: vk::Image, pub(crate) raw: vk::ImageView, pub(crate) range: SubresourceRange, } #[derive(Debug, Hash)] pub struct Sampler(pub vk::Sampler); #[derive(Debug, Hash)] pub struct RenderPass { pub raw: vk::RenderPass, pub attachment_count: usize, } pub type FramebufferKey = SmallVec<[vk::ImageView; ROUGH_MAX_ATTACHMENT_COUNT]>; #[derive(Debug)] pub enum Framebuffer { ImageLess(vk::Framebuffer), Legacy { name: String, map: Mutex<HashMap<FramebufferKey, vk::Framebuffer>>, extent: Extent, }, } pub(crate) type SortedBindings = Arc<Vec<pso::DescriptorSetLayoutBinding>>; #[derive(Debug)] pub struct DescriptorSetLayout { pub(crate) raw: vk::DescriptorSetLayout, pub(crate) bindings: SortedBindings, } #[derive(Debug)] pub struct DescriptorSet { pub(crate) raw: vk::DescriptorSet, pub(crate) bindings: SortedBindings, } #[derive(Debug, Hash)] pub struct PipelineLayout { pub(crate) raw: vk::PipelineLayout, } #[derive(Debug)] pub struct PipelineCache { pub(crate) raw: vk::PipelineCache, } #[derive(Debug, Eq, Hash, PartialEq)] pub struct ShaderModule { pub(crate) raw: vk::ShaderModule, } #[derive(Debug)] pub struct DescriptorPool { raw: vk::DescriptorPool, device: Arc<RawDevice>, /// This vec only exists to re-use allocations when `DescriptorSet`s are freed. temp_raw_sets: Vec<vk::DescriptorSet>, /// This vec only exists for collecting the layouts when allocating new sets. temp_raw_layouts: Vec<vk::DescriptorSetLayout>, /// This vec only exists for collecting the bindings when allocating new sets. temp_layout_bindings: Vec<SortedBindings>, } impl DescriptorPool { pub(crate) fn
(raw: vk::DescriptorPool, device: &Arc<RawDevice>) -> Self { DescriptorPool { raw, device: Arc::clone(device), temp_raw_sets: Vec::new(), temp_raw_layouts: Vec::new(), temp_layout_bindings: Vec::new(), } } pub(crate) fn finish(self) -> vk::DescriptorPool { self.raw } } impl pso::DescriptorPool<Backend> for DescriptorPool { unsafe fn allocate_one( &mut self, layout: &DescriptorSetLayout, ) -> Result<DescriptorSet, pso::AllocationError> { let raw_layouts = [layout.raw]; let info = vk::DescriptorSetAllocateInfo::builder() .descriptor_pool(self.raw) .set_layouts(&raw_layouts); self.device .raw .allocate_descriptor_sets(&info) //Note: https://github.com/MaikKlein/ash/issues/358 .map(|mut sets| DescriptorSet { raw: sets.pop().unwrap(), bindings: Arc::clone(&layout.bindings), }) .map_err(|err| match err { vk::Result::ERROR_OUT_OF_HOST_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Host) } vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Device) } vk::Result::ERROR_OUT_OF_POOL_MEMORY => pso::AllocationError::OutOfPoolMemory, _ => pso::AllocationError::FragmentedPool, }) } unsafe fn allocate<'a, I, E>( &mut self, layouts: I, list: &mut E, ) -> Result<(), pso::AllocationError> where I: Iterator<Item = &'a DescriptorSetLayout>, E: Extend<DescriptorSet>, { self.temp_raw_layouts.clear(); self.temp_layout_bindings.clear(); for layout in layouts { self.temp_raw_layouts.push(layout.raw); self.temp_layout_bindings.push(Arc::clone(&layout.bindings)); } let info = vk::DescriptorSetAllocateInfo::builder() .descriptor_pool(self.raw) .set_layouts(&self.temp_raw_layouts); self.device .raw .allocate_descriptor_sets(&info) .map(|sets| { list.extend( sets.into_iter() .zip(self.temp_layout_bindings.drain(..)) .map(|(raw, bindings)| DescriptorSet { raw, bindings }), ) }) .map_err(|err| match err { vk::Result::ERROR_OUT_OF_HOST_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Host) } vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Device) } vk::Result::ERROR_OUT_OF_POOL_MEMORY => pso::AllocationError::OutOfPoolMemory, _ => pso::AllocationError::FragmentedPool, }) } unsafe fn free<I>(&mut self, descriptor_sets: I) where I: Iterator<Item = DescriptorSet>, { let sets_iter = descriptor_sets.map(|d| d.raw); inplace_or_alloc_from_iter(sets_iter, |sets| { if!sets.is_empty() { if let Err(e) = self.device.raw.free_descriptor_sets(self.raw, sets) { error!("free_descriptor_sets error {}", e); } } }) } unsafe fn reset(&mut self) { assert_eq!( Ok(()), self.device .raw .reset_descriptor_pool(self.raw, vk::DescriptorPoolResetFlags::empty()) ); } } #[derive(Debug, Hash)] pub struct QueryPool(pub vk::QueryPool);
new
identifier_name
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; #[derive(Debug, Hash)] pub struct Semaphore(pub vk::Semaphore); #[derive(Debug, Hash, PartialEq, Eq)] pub struct Fence(pub vk::Fence); #[derive(Debug, Hash)] pub struct Event(pub vk::Event); #[derive(Debug, Hash)] pub struct GraphicsPipeline(pub vk::Pipeline); #[derive(Debug, Hash)] pub struct ComputePipeline(pub vk::Pipeline); #[derive(Debug, Hash)] pub struct Memory { pub(crate) raw: vk::DeviceMemory, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct Buffer { pub(crate) raw: vk::Buffer, } unsafe impl Sync for Buffer {} unsafe impl Send for Buffer {} #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct BufferView { pub(crate) raw: vk::BufferView, } #[derive(Debug, Hash, PartialEq, Eq)] pub struct Image { pub(crate) raw: vk::Image, pub(crate) ty: vk::ImageType, pub(crate) flags: vk::ImageCreateFlags, pub(crate) extent: vk::Extent3D, } #[derive(Debug, Hash, PartialEq, Eq)] pub struct ImageView { pub(crate) image: vk::Image, pub(crate) raw: vk::ImageView, pub(crate) range: SubresourceRange, } #[derive(Debug, Hash)] pub struct Sampler(pub vk::Sampler); #[derive(Debug, Hash)] pub struct RenderPass { pub raw: vk::RenderPass, pub attachment_count: usize, } pub type FramebufferKey = SmallVec<[vk::ImageView; ROUGH_MAX_ATTACHMENT_COUNT]>; #[derive(Debug)] pub enum Framebuffer { ImageLess(vk::Framebuffer), Legacy { name: String, map: Mutex<HashMap<FramebufferKey, vk::Framebuffer>>, extent: Extent, }, } pub(crate) type SortedBindings = Arc<Vec<pso::DescriptorSetLayoutBinding>>; #[derive(Debug)] pub struct DescriptorSetLayout { pub(crate) raw: vk::DescriptorSetLayout, pub(crate) bindings: SortedBindings, } #[derive(Debug)] pub struct DescriptorSet { pub(crate) raw: vk::DescriptorSet, pub(crate) bindings: SortedBindings, } #[derive(Debug, Hash)] pub struct PipelineLayout { pub(crate) raw: vk::PipelineLayout, } #[derive(Debug)] pub struct PipelineCache { pub(crate) raw: vk::PipelineCache, } #[derive(Debug, Eq, Hash, PartialEq)] pub struct ShaderModule { pub(crate) raw: vk::ShaderModule, } #[derive(Debug)] pub struct DescriptorPool { raw: vk::DescriptorPool, device: Arc<RawDevice>, /// This vec only exists to re-use allocations when `DescriptorSet`s are freed. temp_raw_sets: Vec<vk::DescriptorSet>, /// This vec only exists for collecting the layouts when allocating new sets. temp_raw_layouts: Vec<vk::DescriptorSetLayout>, /// This vec only exists for collecting the bindings when allocating new sets. temp_layout_bindings: Vec<SortedBindings>, } impl DescriptorPool { pub(crate) fn new(raw: vk::DescriptorPool, device: &Arc<RawDevice>) -> Self { DescriptorPool { raw, device: Arc::clone(device), temp_raw_sets: Vec::new(), temp_raw_layouts: Vec::new(), temp_layout_bindings: Vec::new(), } } pub(crate) fn finish(self) -> vk::DescriptorPool { self.raw } } impl pso::DescriptorPool<Backend> for DescriptorPool { unsafe fn allocate_one( &mut self, layout: &DescriptorSetLayout, ) -> Result<DescriptorSet, pso::AllocationError> { let raw_layouts = [layout.raw]; let info = vk::DescriptorSetAllocateInfo::builder() .descriptor_pool(self.raw) .set_layouts(&raw_layouts); self.device .raw .allocate_descriptor_sets(&info) //Note: https://github.com/MaikKlein/ash/issues/358 .map(|mut sets| DescriptorSet { raw: sets.pop().unwrap(), bindings: Arc::clone(&layout.bindings), }) .map_err(|err| match err { vk::Result::ERROR_OUT_OF_HOST_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Host) } vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Device) } vk::Result::ERROR_OUT_OF_POOL_MEMORY => pso::AllocationError::OutOfPoolMemory, _ => pso::AllocationError::FragmentedPool, }) } unsafe fn allocate<'a, I, E>( &mut self, layouts: I, list: &mut E, ) -> Result<(), pso::AllocationError> where I: Iterator<Item = &'a DescriptorSetLayout>, E: Extend<DescriptorSet>, { self.temp_raw_layouts.clear(); self.temp_layout_bindings.clear(); for layout in layouts { self.temp_raw_layouts.push(layout.raw); self.temp_layout_bindings.push(Arc::clone(&layout.bindings)); } let info = vk::DescriptorSetAllocateInfo::builder() .descriptor_pool(self.raw) .set_layouts(&self.temp_raw_layouts); self.device .raw .allocate_descriptor_sets(&info) .map(|sets| { list.extend( sets.into_iter() .zip(self.temp_layout_bindings.drain(..)) .map(|(raw, bindings)| DescriptorSet { raw, bindings }), ) }) .map_err(|err| match err { vk::Result::ERROR_OUT_OF_HOST_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Host) } vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { pso::AllocationError::OutOfMemory(OutOfMemory::Device) } vk::Result::ERROR_OUT_OF_POOL_MEMORY => pso::AllocationError::OutOfPoolMemory, _ => pso::AllocationError::FragmentedPool, }) } unsafe fn free<I>(&mut self, descriptor_sets: I) where I: Iterator<Item = DescriptorSet>, { let sets_iter = descriptor_sets.map(|d| d.raw); inplace_or_alloc_from_iter(sets_iter, |sets| { if!sets.is_empty()
}) } unsafe fn reset(&mut self) { assert_eq!( Ok(()), self.device .raw .reset_descriptor_pool(self.raw, vk::DescriptorPoolResetFlags::empty()) ); } } #[derive(Debug, Hash)] pub struct QueryPool(pub vk::QueryPool);
{ if let Err(e) = self.device.raw.free_descriptor_sets(self.raw, sets) { error!("free_descriptor_sets error {}", e); } }
conditional_block
audio.rs
().unwrap(); //! //! let desired_spec = AudioSpecDesired { //! freq: Some(44100), //! channels: Some(1), // mono //! samples: None // default sample size //! }; //! //! let device = audio_subsystem.open_playback(None, &desired_spec, |spec| { //! // initialize the audio callback //! SquareWave { //! phase_inc: 440.0 / spec.freq as f32, //! phase: 0.0, //! volume: 0.25 //! } //! }).unwrap(); //! //! // Start playback //! device.resume(); //! //! // Play for 2 seconds //! std::thread::sleep(Duration::from_millis(2000)); //! ``` use std::ffi::{CStr, CString}; use num::FromPrimitive; use libc::{c_int, c_void, uint8_t, c_char}; use std::ops::{Deref, DerefMut}; use std::path::Path; use std::marker::PhantomData; use std::mem; use std::ptr; use AudioSubsystem; use get_error; use rwops::RWops; use sys::audio as ll; impl AudioSubsystem { /// Opens a new audio device given the desired parameters and callback. #[inline] pub fn open_playback<CB, F>(&self, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String> where CB: AudioCallback, F: FnOnce(AudioSpec) -> CB { AudioDevice::open_playback(self, device, spec, get_callback) } pub fn current_audio_driver(&self) -> &'static str { unsafe { let buf = ll::SDL_GetCurrentAudioDriver(); assert!(!buf.is_null()); CStr::from_ptr(buf as *const _).to_str().unwrap() } } pub fn num_audio_playback_devices(&self) -> Option<u32> { let result = unsafe { ll::SDL_GetNumAudioDevices(0) }; if result < 0 { // SDL cannot retreive a list of audio devices. This is not necessarily an error (see the SDL2 docs). None } else { Some(result as u32) } } pub fn audio_playback_device_name(&self, index: u32) -> Result<String, String> { unsafe { let dev_name = ll::SDL_GetAudioDeviceName(index as c_int, 0); if dev_name.is_null() { Err(get_error()) } else { let cstr = CStr::from_ptr(dev_name as *const _); Ok(cstr.to_str().unwrap().to_owned()) } } } } #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum AudioFormat { /// Unsigned 8-bit samples U8 = ll::AUDIO_U8 as isize, /// Signed 8-bit samples S8 = ll::AUDIO_S8 as isize, /// Unsigned 16-bit samples, little-endian U16LSB = ll::AUDIO_U16LSB as isize, /// Unsigned 16-bit samples, big-endian U16MSB = ll::AUDIO_U16MSB as isize, /// Signed 16-bit samples, little-endian S16LSB = ll::AUDIO_S16LSB as isize, /// Signed 16-bit samples, big-endian S16MSB = ll::AUDIO_S16MSB as isize, /// Signed 32-bit samples, little-endian S32LSB = ll::AUDIO_S32LSB as isize, /// Signed 32-bit samples, big-endian S32MSB = ll::AUDIO_S32MSB as isize, /// 32-bit floating point samples, little-endian F32LSB = ll::AUDIO_F32LSB as isize, /// 32-bit floating point samples, big-endian F32MSB = ll::AUDIO_F32MSB as isize } impl AudioFormat { fn from_ll(raw: ll::SDL_AudioFormat) -> Option<AudioFormat> { use self::AudioFormat::*; match raw { ll::AUDIO_U8 => Some(U8), ll::AUDIO_S8 => Some(S8), ll::AUDIO_U16LSB => Some(U16LSB), ll::AUDIO_U16MSB => Some(U16MSB), ll::AUDIO_S16LSB => Some(S16LSB), ll::AUDIO_S16MSB => Some(S16MSB), ll::AUDIO_S32LSB => Some(S32LSB), ll::AUDIO_S32MSB => Some(S32MSB), ll::AUDIO_F32LSB => Some(F32LSB), ll::AUDIO_F32MSB => Some(F32MSB), _ => None } } fn to_ll(self) -> ll::SDL_AudioFormat { self as ll::SDL_AudioFormat } } #[cfg(target_endian = "little")] impl AudioFormat { /// Unsigned 16-bit samples, native endian #[inline] pub fn u16_sys() -> AudioFormat { AudioFormat::U16LSB } /// Signed 16-bit samples, native endian #[inline] pub fn s16_sys() -> AudioFormat { AudioFormat::S16LSB } /// Signed 32-bit samples, native endian #[inline] pub fn s32_sys() -> AudioFormat { AudioFormat::S32LSB } /// 32-bit floating point samples, native endian #[inline] pub fn f32_sys() -> AudioFormat { AudioFormat::F32LSB } } #[cfg(target_endian = "big")] impl AudioFormat { /// Unsigned 16-bit samples, native endian #[inline] pub fn u16_sys() -> AudioFormat { AudioFormat::U16MSB } /// Signed 16-bit samples, native endian #[inline] pub fn s16_sys() -> AudioFormat { AudioFormat::S16MSB } /// Signed 32-bit samples, native endian #[inline] pub fn s32_sys() -> AudioFormat { AudioFormat::S32MSB } /// 32-bit floating point samples, native endian #[inline] pub fn f32_sys() -> AudioFormat { AudioFormat::F32MSB } } #[repr(C)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum AudioStatus { Stopped = ll::SDL_AUDIO_STOPPED as isize, Playing = ll::SDL_AUDIO_PLAYING as isize, Paused = ll::SDL_AUDIO_PAUSED as isize, } impl FromPrimitive for AudioStatus { fn from_i64(n: i64) -> Option<AudioStatus> { use self::AudioStatus::*; Some( match n as ll::SDL_AudioStatus { ll::SDL_AUDIO_STOPPED => Stopped, ll::SDL_AUDIO_PLAYING => Playing, ll::SDL_AUDIO_PAUSED => Paused, _ => return None, }) } fn
(n: u64) -> Option<AudioStatus> { FromPrimitive::from_i64(n as i64) } } #[derive(Copy, Clone)] pub struct DriverIterator { length: i32, index: i32 } impl Iterator for DriverIterator { type Item = &'static str; #[inline] fn next(&mut self) -> Option<&'static str> { if self.index >= self.length { None } else { unsafe { let buf = ll::SDL_GetAudioDriver(self.index); assert!(!buf.is_null()); self.index += 1; Some(CStr::from_ptr(buf as *const _).to_str().unwrap()) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let l = self.length as usize; (l, Some(l)) } } impl ExactSizeIterator for DriverIterator { } /// Gets an iterator of all audio drivers compiled into the SDL2 library. #[inline] pub fn drivers() -> DriverIterator { // This function is thread-safe and doesn't require the audio subsystem to be initialized. // The list of drivers are read-only and statically compiled into SDL2, varying by platform. // SDL_GetNumAudioDrivers can never return a negative value. DriverIterator { length: unsafe { ll::SDL_GetNumAudioDrivers() }, index: 0 } } pub struct AudioSpecWAV { pub freq: i32, pub format: AudioFormat, pub channels: u8, audio_buf: *mut u8, audio_len: u32 } impl AudioSpecWAV { /// Loads a WAVE from the file path. pub fn load_wav<P: AsRef<Path>>(path: P) -> Result<AudioSpecWAV, String> { let mut file = try!(RWops::from_file(path, "rb")); AudioSpecWAV::load_wav_rw(&mut file) } /// Loads a WAVE from the data source. pub fn load_wav_rw(src: &mut RWops) -> Result<AudioSpecWAV, String> { use std::mem::uninitialized; use std::ptr::null_mut; let mut desired = unsafe { uninitialized::<ll::SDL_AudioSpec>() }; let mut audio_buf: *mut u8 = null_mut(); let mut audio_len: u32 = 0; unsafe { let ret = ll::SDL_LoadWAV_RW(src.raw(), 0, &mut desired, &mut audio_buf, &mut audio_len); if ret.is_null() { Err(get_error()) } else { Ok(AudioSpecWAV { freq: desired.freq, format: AudioFormat::from_ll(desired.format).unwrap(), channels: desired.channels, audio_buf: audio_buf, audio_len: audio_len }) } } } pub fn buffer(&self) -> &[u8] { use std::slice::from_raw_parts; unsafe { let ptr = self.audio_buf as *const u8; let len = self.audio_len as usize; from_raw_parts(ptr, len) } } } impl Drop for AudioSpecWAV { fn drop(&mut self) { unsafe { ll::SDL_FreeWAV(self.audio_buf); } } } pub trait AudioCallback: Send where Self::Channel: AudioFormatNum +'static { type Channel; fn callback(&mut self, &mut [Self::Channel]); } /// A phantom type for retreiving the SDL_AudioFormat of a given generic type. /// All format types are returned as native-endian. pub trait AudioFormatNum { fn audio_format() -> AudioFormat; fn zero() -> Self; } /// AUDIO_S8 impl AudioFormatNum for i8 { fn audio_format() -> AudioFormat { AudioFormat::S8 } fn zero() -> i8 { 0 } } /// AUDIO_U8 impl AudioFormatNum for u8 { fn audio_format() -> AudioFormat { AudioFormat::U8 } fn zero() -> u8 { 0 } } /// AUDIO_S16 impl AudioFormatNum for i16 { fn audio_format() -> AudioFormat { AudioFormat::s16_sys() } fn zero() -> i16 { 0 } } /// AUDIO_U16 impl AudioFormatNum for u16 { fn audio_format() -> AudioFormat { AudioFormat::u16_sys() } fn zero() -> u16 { 0 } } /// AUDIO_S32 impl AudioFormatNum for i32 { fn audio_format() -> AudioFormat { AudioFormat::s32_sys() } fn zero() -> i32 { 0 } } /// AUDIO_F32 impl AudioFormatNum for f32 { fn audio_format() -> AudioFormat { AudioFormat::f32_sys() } fn zero() -> f32 { 0.0 } } extern "C" fn audio_callback_marshall<CB: AudioCallback> (userdata: *mut c_void, stream: *mut uint8_t, len: c_int) { use std::slice::from_raw_parts_mut; use std::mem::{size_of, transmute}; unsafe { let mut cb_userdata: &mut CB = transmute(userdata); let buf: &mut [CB::Channel] = from_raw_parts_mut( stream as *mut CB::Channel, len as usize / size_of::<CB::Channel>() ); cb_userdata.callback(buf); } } #[derive(Clone)] pub struct AudioSpecDesired { /// DSP frequency (samples per second). Set to None for the device's fallback frequency. pub freq: Option<i32>, /// Number of separate audio channels. Set to None for the device's fallback number of channels. pub channels: Option<u8>, /// Audio buffer size in samples (power of 2). Set to None for the device's fallback sample size. pub samples: Option<u16>, } impl AudioSpecDesired { fn convert_to_ll<CB: AudioCallback>(freq: Option<i32>, channels: Option<u8>, samples: Option<u16>, userdata: *mut CB) -> ll::SDL_AudioSpec { use std::mem::transmute; if let Some(freq) = freq { assert!(freq > 0); } if let Some(channels) = channels { assert!(channels > 0); } if let Some(samples) = samples { assert!(samples > 0); } // A value of 0 means "fallback" or "default". unsafe { ll::SDL_AudioSpec { freq: freq.unwrap_or(0), format: <CB::Channel as AudioFormatNum>::audio_format().to_ll(), channels: channels.unwrap_or(0), silence: 0, samples: samples.unwrap_or(0), padding: 0, size: 0, callback: Some(audio_callback_marshall::<CB> as extern "C" fn (arg1: *mut c_void, arg2: *mut uint8_t, arg3: c_int)), userdata: transmute(userdata) } } } } #[allow(missing_copy_implementations)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct AudioSpec { pub freq: i32, pub format: AudioFormat, pub channels: u8, pub silence: u8, pub samples: u16, pub size: u32 } impl AudioSpec { fn convert_from_ll(spec: ll::SDL_AudioSpec) -> AudioSpec { AudioSpec { freq: spec.freq, format: AudioFormat::from_ll(spec.format).unwrap(), channels: spec.channels, silence: spec.silence, samples: spec.samples, size: spec.size } } } enum AudioDeviceID { PlaybackDevice(ll::SDL_AudioDeviceID) } impl AudioDeviceID { fn id(&self) -> ll::SDL_AudioDeviceID { match self { &AudioDeviceID::PlaybackDevice(id) => id } } } impl Drop for AudioDeviceID { fn drop(&mut self) { //! Shut down audio processing and close the audio device. unsafe { ll::SDL_CloseAudioDevice(self.id()) } } } /// Wraps SDL_AudioDeviceID and owns the callback data used by the audio device. pub struct AudioDevice<CB: AudioCallback> { subsystem: AudioSubsystem, device_id: AudioDeviceID, /// Store the callback to keep it alive for the entire duration of `AudioDevice`. userdata: Box<CB> } impl<CB: AudioCallback> AudioDevice<CB> { /// Opens a new audio device given the desired parameters and callback. pub fn open_playback<F>(a: &AudioSubsystem, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String> where F: FnOnce(AudioSpec) -> CB { // SDL_OpenAudioDevice needs a userdata pointer, but we can't initialize the // callback without the obtained AudioSpec. // Create an uninitialized box that will be initialized after SDL_OpenAudioDevice. let userdata: *mut CB = unsafe { let b: Box<CB> = Box::new(mem::uninitialized()); mem::transmute(b) }; let desired = AudioSpecDesired::convert_to_ll(spec.freq, spec.channels, spec.samples, userdata); let mut obtained = unsafe { mem::uninitialized::<ll::SDL_AudioSpec>() }; unsafe { let device = match device { Some(device) => Some(CString::new(device).unwrap()), None => None }; let device_ptr = device.map_or(ptr::null(), |s| s.as_ptr()); let iscapture_flag = 0; let device_id = ll::SDL_OpenAudioDevice( device_ptr as *const c_char, iscapture_flag, &desired, &mut obtained, 0 ); match device_id { 0 => { Err(get_error()) }, id => { let device_id = AudioDeviceID::PlaybackDevice(id); let spec = AudioSpec::convert_from_ll(obtained); let mut userdata: Box<CB> = mem::transmute(userdata); let garbage = mem::replace(&mut userdata as &mut CB, get_callback(spec)); mem::forget(garbage); Ok(AudioDevice { subsystem: a.clone(), device_id: device_id, userdata: userdata }) } } } } #[inline] pub fn subsystem(&self) -> &AudioSubsystem { &self.subsystem } pub fn status(&self) -> AudioStatus { unsafe { let status = ll::SDL_GetAudioDeviceStatus(self.device_id.id()); FromPrimitive::from_i32(status as i32).unwrap() } } /// Pauses playback of the audio device. pub fn pause(&self) { unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 1) } } /// Starts playback of the audio device. pub fn resume(&self) { unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 0) } } /// Locks the audio device using `SDL_LockAudioDevice`. /// /// When the returned lock guard is dropped, `SDL_UnlockAudioDevice` is /// called. /// Use this method to read and mutate callback data. pub fn lock<'a>(&'a mut self) -> AudioDeviceLockGuard<'a, CB> { unsafe { ll::SDL_LockAudioDevice(self.device_id.id()) }; AudioDeviceLockGuard { device: self, _nosend: PhantomData } } /// Closes the audio device and saves the callback data from being dropped. /// /// Note that simply dropping `AudioDevice` will close the audio device, /// but the callback data will be dropped. pub fn close_and_get_callback(self) -> CB { drop(self.device_id); *self.userdata } } /// Similar to `std::sync::MutexGuard`, but for use with `AudioDevice::lock()`. pub struct AudioDeviceLockGuard<'a, CB> where CB: AudioCallback, CB: 'a { device: &'a mut AudioDevice<CB>, _nosend: PhantomData<*mut ()> } impl<'a, CB: AudioCallback> Deref for AudioDeviceLockGuard<'a, CB> { type Target = CB; fn deref(&self) -> &CB { &self.device.userdata } } impl<'a, CB: AudioCallback> DerefMut for AudioDeviceLockGuard<'a, CB> { fn deref_mut(&mut self) -> &mut CB { &mut self.device.userdata } } impl<'a, CB: AudioCallback> Drop for AudioDeviceLockGuard<'a, CB> { fn drop(&mut self) { unsafe { ll::SDL_UnlockAudioDevice(self.device.device_id.id()) } } } #[derive(Copy, Clone)] pub struct AudioCVT { raw: ll::SDL_AudioCVT } impl AudioCVT { pub fn new(src_format: AudioFormat, src_channels: u8, src_rate: i32, dst_format: AudioFormat, dst_channels: u8, dst_rate: i32) -> Result<AudioCVT, String> { use std::mem; unsafe { let mut raw: ll::SDL_AudioCVT = mem::uninitialized(); let ret = ll::SDL_BuildAudioCVT(&mut raw, src_format.to_ll(), src_channels, src_rate as c_int, dst_format.to_ll(), dst_channels, dst_rate as c_int); if ret == 1 || ret == 0 { Ok(AudioCVT { raw: raw }) } else { Err(get_error()) } } } pub fn convert(&self, mut src: Vec<u8>) -> Vec<u8> { //! Convert audio data to a desired audio format. //! //! The `src` vector is adjusted to the capacity necessary to perform //! the conversion in place; then it is passed to the SDL library. //! //! Certain conversions may cause buffer overflows. See AngryLawyer/rust-sdl2 issue #270. use num::traits as num; unsafe { if self.raw.needed!= 0 { let mut raw = self.raw; // calculate the size of the dst buffer raw.len = num::cast(src.len()).expect("Buffer length overflow"); let dst_size = self.capacity(src.len()); let needed = dst_size - src.len(); src.reserve_exact(needed); // perform the conversion in place raw.buf = src.as_mut_ptr(); let ret = ll::SDL_ConvertAudio(&mut raw);
from_u64
identifier_name
audio.rs
audio().unwrap(); //! //! let desired_spec = AudioSpecDesired { //! freq: Some(44100), //! channels: Some(1), // mono //! samples: None // default sample size //! }; //! //! let device = audio_subsystem.open_playback(None, &desired_spec, |spec| { //! // initialize the audio callback //! SquareWave { //! phase_inc: 440.0 / spec.freq as f32, //! phase: 0.0, //! volume: 0.25 //! } //! }).unwrap(); //! //! // Start playback //! device.resume(); //! //! // Play for 2 seconds //! std::thread::sleep(Duration::from_millis(2000)); //! ``` use std::ffi::{CStr, CString}; use num::FromPrimitive; use libc::{c_int, c_void, uint8_t, c_char}; use std::ops::{Deref, DerefMut}; use std::path::Path; use std::marker::PhantomData; use std::mem; use std::ptr; use AudioSubsystem; use get_error; use rwops::RWops; use sys::audio as ll; impl AudioSubsystem { /// Opens a new audio device given the desired parameters and callback. #[inline] pub fn open_playback<CB, F>(&self, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String> where CB: AudioCallback, F: FnOnce(AudioSpec) -> CB { AudioDevice::open_playback(self, device, spec, get_callback) } pub fn current_audio_driver(&self) -> &'static str { unsafe { let buf = ll::SDL_GetCurrentAudioDriver(); assert!(!buf.is_null()); CStr::from_ptr(buf as *const _).to_str().unwrap() } } pub fn num_audio_playback_devices(&self) -> Option<u32> { let result = unsafe { ll::SDL_GetNumAudioDevices(0) }; if result < 0 { // SDL cannot retreive a list of audio devices. This is not necessarily an error (see the SDL2 docs). None } else { Some(result as u32) } } pub fn audio_playback_device_name(&self, index: u32) -> Result<String, String> { unsafe { let dev_name = ll::SDL_GetAudioDeviceName(index as c_int, 0); if dev_name.is_null() { Err(get_error()) } else { let cstr = CStr::from_ptr(dev_name as *const _); Ok(cstr.to_str().unwrap().to_owned()) } } } } #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum AudioFormat { /// Unsigned 8-bit samples U8 = ll::AUDIO_U8 as isize, /// Signed 8-bit samples S8 = ll::AUDIO_S8 as isize, /// Unsigned 16-bit samples, little-endian U16LSB = ll::AUDIO_U16LSB as isize, /// Unsigned 16-bit samples, big-endian U16MSB = ll::AUDIO_U16MSB as isize, /// Signed 16-bit samples, little-endian S16LSB = ll::AUDIO_S16LSB as isize, /// Signed 16-bit samples, big-endian S16MSB = ll::AUDIO_S16MSB as isize, /// Signed 32-bit samples, little-endian S32LSB = ll::AUDIO_S32LSB as isize, /// Signed 32-bit samples, big-endian S32MSB = ll::AUDIO_S32MSB as isize, /// 32-bit floating point samples, little-endian F32LSB = ll::AUDIO_F32LSB as isize, /// 32-bit floating point samples, big-endian F32MSB = ll::AUDIO_F32MSB as isize } impl AudioFormat { fn from_ll(raw: ll::SDL_AudioFormat) -> Option<AudioFormat> { use self::AudioFormat::*; match raw { ll::AUDIO_U8 => Some(U8), ll::AUDIO_S8 => Some(S8), ll::AUDIO_U16LSB => Some(U16LSB), ll::AUDIO_U16MSB => Some(U16MSB), ll::AUDIO_S16LSB => Some(S16LSB), ll::AUDIO_S16MSB => Some(S16MSB), ll::AUDIO_S32LSB => Some(S32LSB), ll::AUDIO_S32MSB => Some(S32MSB), ll::AUDIO_F32LSB => Some(F32LSB), ll::AUDIO_F32MSB => Some(F32MSB), _ => None } } fn to_ll(self) -> ll::SDL_AudioFormat { self as ll::SDL_AudioFormat } } #[cfg(target_endian = "little")] impl AudioFormat { /// Unsigned 16-bit samples, native endian #[inline] pub fn u16_sys() -> AudioFormat { AudioFormat::U16LSB } /// Signed 16-bit samples, native endian #[inline] pub fn s16_sys() -> AudioFormat { AudioFormat::S16LSB } /// Signed 32-bit samples, native endian #[inline] pub fn s32_sys() -> AudioFormat { AudioFormat::S32LSB } /// 32-bit floating point samples, native endian #[inline] pub fn f32_sys() -> AudioFormat { AudioFormat::F32LSB } } #[cfg(target_endian = "big")] impl AudioFormat { /// Unsigned 16-bit samples, native endian #[inline] pub fn u16_sys() -> AudioFormat { AudioFormat::U16MSB } /// Signed 16-bit samples, native endian #[inline] pub fn s16_sys() -> AudioFormat { AudioFormat::S16MSB } /// Signed 32-bit samples, native endian #[inline] pub fn s32_sys() -> AudioFormat { AudioFormat::S32MSB } /// 32-bit floating point samples, native endian #[inline] pub fn f32_sys() -> AudioFormat { AudioFormat::F32MSB } } #[repr(C)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum AudioStatus { Stopped = ll::SDL_AUDIO_STOPPED as isize, Playing = ll::SDL_AUDIO_PLAYING as isize, Paused = ll::SDL_AUDIO_PAUSED as isize, } impl FromPrimitive for AudioStatus { fn from_i64(n: i64) -> Option<AudioStatus> { use self::AudioStatus::*; Some( match n as ll::SDL_AudioStatus { ll::SDL_AUDIO_STOPPED => Stopped, ll::SDL_AUDIO_PLAYING => Playing, ll::SDL_AUDIO_PAUSED => Paused, _ => return None, }) } fn from_u64(n: u64) -> Option<AudioStatus> { FromPrimitive::from_i64(n as i64) } } #[derive(Copy, Clone)] pub struct DriverIterator { length: i32, index: i32 } impl Iterator for DriverIterator { type Item = &'static str; #[inline] fn next(&mut self) -> Option<&'static str> { if self.index >= self.length { None } else { unsafe { let buf = ll::SDL_GetAudioDriver(self.index); assert!(!buf.is_null()); self.index += 1; Some(CStr::from_ptr(buf as *const _).to_str().unwrap()) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) {
impl ExactSizeIterator for DriverIterator { } /// Gets an iterator of all audio drivers compiled into the SDL2 library. #[inline] pub fn drivers() -> DriverIterator { // This function is thread-safe and doesn't require the audio subsystem to be initialized. // The list of drivers are read-only and statically compiled into SDL2, varying by platform. // SDL_GetNumAudioDrivers can never return a negative value. DriverIterator { length: unsafe { ll::SDL_GetNumAudioDrivers() }, index: 0 } } pub struct AudioSpecWAV { pub freq: i32, pub format: AudioFormat, pub channels: u8, audio_buf: *mut u8, audio_len: u32 } impl AudioSpecWAV { /// Loads a WAVE from the file path. pub fn load_wav<P: AsRef<Path>>(path: P) -> Result<AudioSpecWAV, String> { let mut file = try!(RWops::from_file(path, "rb")); AudioSpecWAV::load_wav_rw(&mut file) } /// Loads a WAVE from the data source. pub fn load_wav_rw(src: &mut RWops) -> Result<AudioSpecWAV, String> { use std::mem::uninitialized; use std::ptr::null_mut; let mut desired = unsafe { uninitialized::<ll::SDL_AudioSpec>() }; let mut audio_buf: *mut u8 = null_mut(); let mut audio_len: u32 = 0; unsafe { let ret = ll::SDL_LoadWAV_RW(src.raw(), 0, &mut desired, &mut audio_buf, &mut audio_len); if ret.is_null() { Err(get_error()) } else { Ok(AudioSpecWAV { freq: desired.freq, format: AudioFormat::from_ll(desired.format).unwrap(), channels: desired.channels, audio_buf: audio_buf, audio_len: audio_len }) } } } pub fn buffer(&self) -> &[u8] { use std::slice::from_raw_parts; unsafe { let ptr = self.audio_buf as *const u8; let len = self.audio_len as usize; from_raw_parts(ptr, len) } } } impl Drop for AudioSpecWAV { fn drop(&mut self) { unsafe { ll::SDL_FreeWAV(self.audio_buf); } } } pub trait AudioCallback: Send where Self::Channel: AudioFormatNum +'static { type Channel; fn callback(&mut self, &mut [Self::Channel]); } /// A phantom type for retreiving the SDL_AudioFormat of a given generic type. /// All format types are returned as native-endian. pub trait AudioFormatNum { fn audio_format() -> AudioFormat; fn zero() -> Self; } /// AUDIO_S8 impl AudioFormatNum for i8 { fn audio_format() -> AudioFormat { AudioFormat::S8 } fn zero() -> i8 { 0 } } /// AUDIO_U8 impl AudioFormatNum for u8 { fn audio_format() -> AudioFormat { AudioFormat::U8 } fn zero() -> u8 { 0 } } /// AUDIO_S16 impl AudioFormatNum for i16 { fn audio_format() -> AudioFormat { AudioFormat::s16_sys() } fn zero() -> i16 { 0 } } /// AUDIO_U16 impl AudioFormatNum for u16 { fn audio_format() -> AudioFormat { AudioFormat::u16_sys() } fn zero() -> u16 { 0 } } /// AUDIO_S32 impl AudioFormatNum for i32 { fn audio_format() -> AudioFormat { AudioFormat::s32_sys() } fn zero() -> i32 { 0 } } /// AUDIO_F32 impl AudioFormatNum for f32 { fn audio_format() -> AudioFormat { AudioFormat::f32_sys() } fn zero() -> f32 { 0.0 } } extern "C" fn audio_callback_marshall<CB: AudioCallback> (userdata: *mut c_void, stream: *mut uint8_t, len: c_int) { use std::slice::from_raw_parts_mut; use std::mem::{size_of, transmute}; unsafe { let mut cb_userdata: &mut CB = transmute(userdata); let buf: &mut [CB::Channel] = from_raw_parts_mut( stream as *mut CB::Channel, len as usize / size_of::<CB::Channel>() ); cb_userdata.callback(buf); } } #[derive(Clone)] pub struct AudioSpecDesired { /// DSP frequency (samples per second). Set to None for the device's fallback frequency. pub freq: Option<i32>, /// Number of separate audio channels. Set to None for the device's fallback number of channels. pub channels: Option<u8>, /// Audio buffer size in samples (power of 2). Set to None for the device's fallback sample size. pub samples: Option<u16>, } impl AudioSpecDesired { fn convert_to_ll<CB: AudioCallback>(freq: Option<i32>, channels: Option<u8>, samples: Option<u16>, userdata: *mut CB) -> ll::SDL_AudioSpec { use std::mem::transmute; if let Some(freq) = freq { assert!(freq > 0); } if let Some(channels) = channels { assert!(channels > 0); } if let Some(samples) = samples { assert!(samples > 0); } // A value of 0 means "fallback" or "default". unsafe { ll::SDL_AudioSpec { freq: freq.unwrap_or(0), format: <CB::Channel as AudioFormatNum>::audio_format().to_ll(), channels: channels.unwrap_or(0), silence: 0, samples: samples.unwrap_or(0), padding: 0, size: 0, callback: Some(audio_callback_marshall::<CB> as extern "C" fn (arg1: *mut c_void, arg2: *mut uint8_t, arg3: c_int)), userdata: transmute(userdata) } } } } #[allow(missing_copy_implementations)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct AudioSpec { pub freq: i32, pub format: AudioFormat, pub channels: u8, pub silence: u8, pub samples: u16, pub size: u32 } impl AudioSpec { fn convert_from_ll(spec: ll::SDL_AudioSpec) -> AudioSpec { AudioSpec { freq: spec.freq, format: AudioFormat::from_ll(spec.format).unwrap(), channels: spec.channels, silence: spec.silence, samples: spec.samples, size: spec.size } } } enum AudioDeviceID { PlaybackDevice(ll::SDL_AudioDeviceID) } impl AudioDeviceID { fn id(&self) -> ll::SDL_AudioDeviceID { match self { &AudioDeviceID::PlaybackDevice(id) => id } } } impl Drop for AudioDeviceID { fn drop(&mut self) { //! Shut down audio processing and close the audio device. unsafe { ll::SDL_CloseAudioDevice(self.id()) } } } /// Wraps SDL_AudioDeviceID and owns the callback data used by the audio device. pub struct AudioDevice<CB: AudioCallback> { subsystem: AudioSubsystem, device_id: AudioDeviceID, /// Store the callback to keep it alive for the entire duration of `AudioDevice`. userdata: Box<CB> } impl<CB: AudioCallback> AudioDevice<CB> { /// Opens a new audio device given the desired parameters and callback. pub fn open_playback<F>(a: &AudioSubsystem, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String> where F: FnOnce(AudioSpec) -> CB { // SDL_OpenAudioDevice needs a userdata pointer, but we can't initialize the // callback without the obtained AudioSpec. // Create an uninitialized box that will be initialized after SDL_OpenAudioDevice. let userdata: *mut CB = unsafe { let b: Box<CB> = Box::new(mem::uninitialized()); mem::transmute(b) }; let desired = AudioSpecDesired::convert_to_ll(spec.freq, spec.channels, spec.samples, userdata); let mut obtained = unsafe { mem::uninitialized::<ll::SDL_AudioSpec>() }; unsafe { let device = match device { Some(device) => Some(CString::new(device).unwrap()), None => None }; let device_ptr = device.map_or(ptr::null(), |s| s.as_ptr()); let iscapture_flag = 0; let device_id = ll::SDL_OpenAudioDevice( device_ptr as *const c_char, iscapture_flag, &desired, &mut obtained, 0 ); match device_id { 0 => { Err(get_error()) }, id => { let device_id = AudioDeviceID::PlaybackDevice(id); let spec = AudioSpec::convert_from_ll(obtained); let mut userdata: Box<CB> = mem::transmute(userdata); let garbage = mem::replace(&mut userdata as &mut CB, get_callback(spec)); mem::forget(garbage); Ok(AudioDevice { subsystem: a.clone(), device_id: device_id, userdata: userdata }) } } } } #[inline] pub fn subsystem(&self) -> &AudioSubsystem { &self.subsystem } pub fn status(&self) -> AudioStatus { unsafe { let status = ll::SDL_GetAudioDeviceStatus(self.device_id.id()); FromPrimitive::from_i32(status as i32).unwrap() } } /// Pauses playback of the audio device. pub fn pause(&self) { unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 1) } } /// Starts playback of the audio device. pub fn resume(&self) { unsafe { ll::SDL_PauseAudioDevice(self.device_id.id(), 0) } } /// Locks the audio device using `SDL_LockAudioDevice`. /// /// When the returned lock guard is dropped, `SDL_UnlockAudioDevice` is /// called. /// Use this method to read and mutate callback data. pub fn lock<'a>(&'a mut self) -> AudioDeviceLockGuard<'a, CB> { unsafe { ll::SDL_LockAudioDevice(self.device_id.id()) }; AudioDeviceLockGuard { device: self, _nosend: PhantomData } } /// Closes the audio device and saves the callback data from being dropped. /// /// Note that simply dropping `AudioDevice` will close the audio device, /// but the callback data will be dropped. pub fn close_and_get_callback(self) -> CB { drop(self.device_id); *self.userdata } } /// Similar to `std::sync::MutexGuard`, but for use with `AudioDevice::lock()`. pub struct AudioDeviceLockGuard<'a, CB> where CB: AudioCallback, CB: 'a { device: &'a mut AudioDevice<CB>, _nosend: PhantomData<*mut ()> } impl<'a, CB: AudioCallback> Deref for AudioDeviceLockGuard<'a, CB> { type Target = CB; fn deref(&self) -> &CB { &self.device.userdata } } impl<'a, CB: AudioCallback> DerefMut for AudioDeviceLockGuard<'a, CB> { fn deref_mut(&mut self) -> &mut CB { &mut self.device.userdata } } impl<'a, CB: AudioCallback> Drop for AudioDeviceLockGuard<'a, CB> { fn drop(&mut self) { unsafe { ll::SDL_UnlockAudioDevice(self.device.device_id.id()) } } } #[derive(Copy, Clone)] pub struct AudioCVT { raw: ll::SDL_AudioCVT } impl AudioCVT { pub fn new(src_format: AudioFormat, src_channels: u8, src_rate: i32, dst_format: AudioFormat, dst_channels: u8, dst_rate: i32) -> Result<AudioCVT, String> { use std::mem; unsafe { let mut raw: ll::SDL_AudioCVT = mem::uninitialized(); let ret = ll::SDL_BuildAudioCVT(&mut raw, src_format.to_ll(), src_channels, src_rate as c_int, dst_format.to_ll(), dst_channels, dst_rate as c_int); if ret == 1 || ret == 0 { Ok(AudioCVT { raw: raw }) } else { Err(get_error()) } } } pub fn convert(&self, mut src: Vec<u8>) -> Vec<u8> { //! Convert audio data to a desired audio format. //! //! The `src` vector is adjusted to the capacity necessary to perform //! the conversion in place; then it is passed to the SDL library. //! //! Certain conversions may cause buffer overflows. See AngryLawyer/rust-sdl2 issue #270. use num::traits as num; unsafe { if self.raw.needed!= 0 { let mut raw = self.raw; // calculate the size of the dst buffer raw.len = num::cast(src.len()).expect("Buffer length overflow"); let dst_size = self.capacity(src.len()); let needed = dst_size - src.len(); src.reserve_exact(needed); // perform the conversion in place raw.buf = src.as_mut_ptr(); let ret = ll::SDL_ConvertAudio(&mut raw); // There
let l = self.length as usize; (l, Some(l)) } }
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. /*! `Worker` provides a mechanism to run tasks asynchronously (i.e. in the background) with some additional features, for example, ticks. A worker contains: - A runner (which should implement the `Runnable` trait): to run tasks one by one or in batch. - A scheduler: to send tasks to the runner, returns immediately. Briefly speaking, this is a mpsc (multiple-producer-single-consumer) model. */ mod future; mod metrics; mod pool; pub use self::future::dummy_scheduler as dummy_future_scheduler; pub use self::future::Runnable as FutureRunnable; pub use self::future::Scheduler as FutureScheduler; pub use self::future::{Stopped, Worker as FutureWorker}; pub use pool::{ dummy_scheduler, Builder, LazyWorker, ReceiverWrapper, Runnable, RunnableWithTimer, ScheduleError, Scheduler, Worker, }; #[cfg(test)] mod tests { use std::sync::mpsc; use std::thread; use std::time::Duration; use super::*; struct StepRunner { ch: mpsc::Sender<u64>, } impl Runnable for StepRunner { type Task = u64; fn run(&mut self, step: u64) { self.ch.send(step).unwrap(); thread::sleep(Duration::from_millis(step)); } fn shutdown(&mut self) { self.ch.send(0).unwrap(); } } struct BatchRunner { ch: mpsc::Sender<Vec<u64>>, } impl Runnable for BatchRunner { type Task = u64; fn run(&mut self, ms: u64) { self.ch.send(vec![ms]).unwrap(); } fn shutdown(&mut self) { let _ = self.ch.send(vec![]); } } struct TickRunner { ch: mpsc::Sender<&'static str>, } impl Runnable for TickRunner { type Task = &'static str; fn run(&mut self, msg: &'static str) { self.ch.send(msg).unwrap(); } fn shutdown(&mut self) { self.ch.send("").unwrap(); } } #[test] fn test_worker() { let worker = Worker::new("test-worker"); let (tx, rx) = mpsc::channel(); let scheduler = worker.start("test-worker", StepRunner { ch: tx }); assert!(!worker.is_busy()); scheduler.schedule(60).unwrap(); scheduler.schedule(40).unwrap(); scheduler.schedule(50).unwrap(); assert!(worker.is_busy()); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 60); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 40); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 50); // task is handled before we update the busy status, so that we need some sleep. thread::sleep(Duration::from_millis(100)); assert!(!worker.is_busy()); drop(scheduler); worker.stop(); // now worker can't handle any task assert!(worker.is_busy()); drop(worker); // when shutdown, StepRunner should send back a 0. assert_eq!(0, rx.recv().unwrap()); } #[test] fn test_threaded() { let worker = Worker::new("test-worker-threaded"); let (tx, rx) = mpsc::channel(); let scheduler = worker.start("test-worker", StepRunner { ch: tx }); thread::spawn(move || { scheduler.schedule(90).unwrap(); scheduler.schedule(110).unwrap(); }); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 90); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 110); worker.stop(); assert_eq!(0, rx.recv().unwrap()); } #[test] fn test_pending_capacity() { let worker = Builder::new("test-worker-busy") .pending_capacity(3) .create(); let mut lazy_worker = worker.lazy_build("test-busy"); let scheduler = lazy_worker.scheduler(); for i in 0..3 { scheduler.schedule(i).unwrap(); } assert_eq!(scheduler.schedule(3).unwrap_err(), ScheduleError::Full(3));
worker.stop(); drop(rx); } }
let (tx, rx) = mpsc::channel(); lazy_worker.start(BatchRunner { ch: tx }); assert!(rx.recv_timeout(Duration::from_secs(3)).is_ok());
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. /*! `Worker` provides a mechanism to run tasks asynchronously (i.e. in the background) with some additional features, for example, ticks. A worker contains: - A runner (which should implement the `Runnable` trait): to run tasks one by one or in batch. - A scheduler: to send tasks to the runner, returns immediately. Briefly speaking, this is a mpsc (multiple-producer-single-consumer) model. */ mod future; mod metrics; mod pool; pub use self::future::dummy_scheduler as dummy_future_scheduler; pub use self::future::Runnable as FutureRunnable; pub use self::future::Scheduler as FutureScheduler; pub use self::future::{Stopped, Worker as FutureWorker}; pub use pool::{ dummy_scheduler, Builder, LazyWorker, ReceiverWrapper, Runnable, RunnableWithTimer, ScheduleError, Scheduler, Worker, }; #[cfg(test)] mod tests { use std::sync::mpsc; use std::thread; use std::time::Duration; use super::*; struct StepRunner { ch: mpsc::Sender<u64>, } impl Runnable for StepRunner { type Task = u64; fn run(&mut self, step: u64) { self.ch.send(step).unwrap(); thread::sleep(Duration::from_millis(step)); } fn shutdown(&mut self) { self.ch.send(0).unwrap(); } } struct BatchRunner { ch: mpsc::Sender<Vec<u64>>, } impl Runnable for BatchRunner { type Task = u64; fn run(&mut self, ms: u64) { self.ch.send(vec![ms]).unwrap(); } fn shutdown(&mut self) { let _ = self.ch.send(vec![]); } } struct TickRunner { ch: mpsc::Sender<&'static str>, } impl Runnable for TickRunner { type Task = &'static str; fn run(&mut self, msg: &'static str) { self.ch.send(msg).unwrap(); } fn shutdown(&mut self) { self.ch.send("").unwrap(); } } #[test] fn test_worker() { let worker = Worker::new("test-worker"); let (tx, rx) = mpsc::channel(); let scheduler = worker.start("test-worker", StepRunner { ch: tx }); assert!(!worker.is_busy()); scheduler.schedule(60).unwrap(); scheduler.schedule(40).unwrap(); scheduler.schedule(50).unwrap(); assert!(worker.is_busy()); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 60); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 40); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 50); // task is handled before we update the busy status, so that we need some sleep. thread::sleep(Duration::from_millis(100)); assert!(!worker.is_busy()); drop(scheduler); worker.stop(); // now worker can't handle any task assert!(worker.is_busy()); drop(worker); // when shutdown, StepRunner should send back a 0. assert_eq!(0, rx.recv().unwrap()); } #[test] fn test_threaded() { let worker = Worker::new("test-worker-threaded"); let (tx, rx) = mpsc::channel(); let scheduler = worker.start("test-worker", StepRunner { ch: tx }); thread::spawn(move || { scheduler.schedule(90).unwrap(); scheduler.schedule(110).unwrap(); }); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 90); assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 110); worker.stop(); assert_eq!(0, rx.recv().unwrap()); } #[test] fn
() { let worker = Builder::new("test-worker-busy") .pending_capacity(3) .create(); let mut lazy_worker = worker.lazy_build("test-busy"); let scheduler = lazy_worker.scheduler(); for i in 0..3 { scheduler.schedule(i).unwrap(); } assert_eq!(scheduler.schedule(3).unwrap_err(), ScheduleError::Full(3)); let (tx, rx) = mpsc::channel(); lazy_worker.start(BatchRunner { ch: tx }); assert!(rx.recv_timeout(Duration::from_secs(3)).is_ok()); worker.stop(); drop(rx); } }
test_pending_capacity
identifier_name
health.rs
use futures::future::ok; use http::FutureHandled; use http::ServerResponse; use hyper; use hyper::Request; use hyper::Response; use hyper::server::NewService; use hyper::server::Service; use std::io; /// `/health` service returning OK status if microservice is running (obviously) #[derive(Debug, Copy, Clone)] pub struct Health; impl NewService for Health { type Request = Request; type Response = Response; type Error = hyper::Error; type Instance = Health; fn new_service(&self) -> io::Result<Self::Instance> { Ok(Health) } } impl Service for Health { type Request = Request;
type Response = Response; type Error = hyper::Error; type Future = FutureHandled; fn call(&self, _req: Request) -> Self::Future { box ok(ServerResponse::Data(HealthStatus::ok()).into()) } } #[derive(Debug, Copy, Clone, Serialize)] struct HealthStatus { status: &'static str, } impl HealthStatus { fn ok() -> Self { HealthStatus { status: "OK" } } }
random_line_split
health.rs
use futures::future::ok; use http::FutureHandled; use http::ServerResponse; use hyper; use hyper::Request; use hyper::Response; use hyper::server::NewService; use hyper::server::Service; use std::io; /// `/health` service returning OK status if microservice is running (obviously) #[derive(Debug, Copy, Clone)] pub struct Health; impl NewService for Health { type Request = Request; type Response = Response; type Error = hyper::Error; type Instance = Health; fn new_service(&self) -> io::Result<Self::Instance> { Ok(Health) } } impl Service for Health { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = FutureHandled; fn call(&self, _req: Request) -> Self::Future { box ok(ServerResponse::Data(HealthStatus::ok()).into()) } } #[derive(Debug, Copy, Clone, Serialize)] struct HealthStatus { status: &'static str, } impl HealthStatus { fn ok() -> Self
}
{ HealthStatus { status: "OK" } }
identifier_body
health.rs
use futures::future::ok; use http::FutureHandled; use http::ServerResponse; use hyper; use hyper::Request; use hyper::Response; use hyper::server::NewService; use hyper::server::Service; use std::io; /// `/health` service returning OK status if microservice is running (obviously) #[derive(Debug, Copy, Clone)] pub struct Health; impl NewService for Health { type Request = Request; type Response = Response; type Error = hyper::Error; type Instance = Health; fn new_service(&self) -> io::Result<Self::Instance> { Ok(Health) } } impl Service for Health { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = FutureHandled; fn call(&self, _req: Request) -> Self::Future { box ok(ServerResponse::Data(HealthStatus::ok()).into()) } } #[derive(Debug, Copy, Clone, Serialize)] struct
{ status: &'static str, } impl HealthStatus { fn ok() -> Self { HealthStatus { status: "OK" } } }
HealthStatus
identifier_name
borrowck-uniq-via-lend.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 borrow(_v: &int) {} fn local() { let mut v = ~3; borrow(v); } fn local_rec() { struct F { f: ~int } let mut v = F {f: ~3}; borrow(v.f); } fn
() { struct F { f: G } struct G { g: H } struct H { h: ~int } let mut v = F {f: G {g: H {h: ~3}}}; borrow(v.f.g.h); } fn aliased_imm() { let mut v = ~3; let _w = &v; borrow(v); } fn aliased_const() { let mut v = ~3; let _w = &const v; borrow(v); } fn aliased_mut() { let mut v = ~3; let _w = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn aliased_other() { let mut v = ~3, w = ~4; let _x = &mut w; borrow(v); } fn aliased_other_reassign() { let mut v = ~3, w = ~4; let mut _x = &mut w; _x = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn main() { }
local_recs
identifier_name
borrowck-uniq-via-lend.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 borrow(_v: &int) {} fn local() { let mut v = ~3; borrow(v); }
fn local_rec() { struct F { f: ~int } let mut v = F {f: ~3}; borrow(v.f); } fn local_recs() { struct F { f: G } struct G { g: H } struct H { h: ~int } let mut v = F {f: G {g: H {h: ~3}}}; borrow(v.f.g.h); } fn aliased_imm() { let mut v = ~3; let _w = &v; borrow(v); } fn aliased_const() { let mut v = ~3; let _w = &const v; borrow(v); } fn aliased_mut() { let mut v = ~3; let _w = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn aliased_other() { let mut v = ~3, w = ~4; let _x = &mut w; borrow(v); } fn aliased_other_reassign() { let mut v = ~3, w = ~4; let mut _x = &mut w; _x = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn main() { }
random_line_split
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive(Debug)] enum SysInfoError { Io(io::Error), ParseFloat(ParseFloatError), Format(String), } impl From<io::Error> for SysInfoError { fn from(e: io::Error) -> SysInfoError { SysInfoError::Io(e) } } impl From<ParseFloatError> for SysInfoError { fn from(e: ParseFloatError) -> SysInfoError { SysInfoError::ParseFloat(e) } } #[derive(Debug)] struct Uptime { uptime: f64, idle: f64, } const WINDOW: usize = 10; struct CpuMeasureState { cpus: usize, uptimes: VecDeque<Uptime>, } fn uptime() -> Result<Uptime, SysInfoError> { let mut f = File::open("/proc/uptime")?; let mut content = String::new(); f.read_to_string(&mut content)?; let mut iter = content.split_whitespace(); let uptime_str = iter.next().ok_or(SysInfoError::Format("Missing uptime".to_string()))?; let idle_str = iter.next().ok_or(SysInfoError::Format("Missing idle time".to_string()))?; Ok(Uptime { uptime: f64::from_str(uptime_str)?, idle: f64::from_str(idle_str)?, }) } fn init_cpu_measurement() -> Result<CpuMeasureState, SysInfoError> { let mut v = VecDeque::new(); v.push_back(uptime()?); Ok(CpuMeasureState { cpus: num_cpus::get(), uptimes: v, }) } fn cpu_usage(s: &mut CpuMeasureState) -> Result<f64, SysInfoError> { let last_uptime = uptime()?; if s.uptimes.len() > WINDOW { s.uptimes.pop_front(); } s.uptimes.push_back(last_uptime); let du = s.uptimes.back().unwrap().uptime - s.uptimes.front().unwrap().uptime; if du < 0.001
let cpus = s.cpus as f64; let di = (s.uptimes.back().unwrap().idle - s.uptimes.front().unwrap().idle) / cpus; return Ok(1.0 - (di / du)); } fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 { let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min; f = f.min(new_max).max(new_min); f as u8 } fn send_info(port: &mut serial::SystemPort, cpu_used: f64, mem_used: f64) -> serial::Result<()> { let cpu_used_scaled = scale(cpu_used, 0.0, 1.0, 0.0, 235.0); let mem_used_scaled = scale(mem_used, 0.0, 1.0, 0.0, 235.0); port.write_all(&[33, mem_used_scaled, cpu_used_scaled])?; port.flush()?; Ok(()) } fn open_serial_port() -> serial::Result<serial::SystemPort> { let mut port = serial::open("/dev/ttyUSB0")?; let mut settings = port.read_settings()?; settings.set_baud_rate(serial::Baud9600)?; settings.set_parity(serial::ParityNone); settings.set_stop_bits(serial::Stop1); port.write_settings(&settings)?; Ok(port) } fn two_words(s: String) -> Option<(String, String)> { let mut iter = s.split_whitespace(); if let Some(first) = iter.next() { if let Some(second) = iter.next() { return Some((first.to_string(), second.to_string())); } } None } fn get_mem_usage() -> io::Result<f64> { let f = BufReader::new(File::open("/proc/meminfo")?); let (total, avail) = f.lines() .map(|l| l.unwrap()) .map(two_words) .filter_map(|x| x) .scan((None, None), |state, item| { let (key, val) = item; if key == "MemTotal:" { state.0 = Some(val.parse::<f64>().unwrap_or(1.0)); return Some(*state); } if key == "MemAvailable:" { state.1 = Some(val.parse::<f64>().unwrap_or(0.0)); return Some(*state); } Some(*state) }) .filter_map(|state| { let (total_option, avail_option) = state; if let Some(total) = total_option { if let Some(avail) = avail_option { return Some((total, avail)); } } None }) .next() .unwrap(); Ok(1.0 - avail / total) } fn main() { let mut port = open_serial_port().unwrap(); let mut cm = init_cpu_measurement().unwrap(); let delay = Duration::from_millis(100); loop { sleep(delay); let cpu_usage = cpu_usage(&mut cm).unwrap(); let mem_usage = get_mem_usage().unwrap(); send_info(&mut port, cpu_usage, mem_usage).unwrap(); } }
{ return Ok(0.0); }
conditional_block
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive(Debug)] enum SysInfoError { Io(io::Error), ParseFloat(ParseFloatError), Format(String), } impl From<io::Error> for SysInfoError { fn from(e: io::Error) -> SysInfoError { SysInfoError::Io(e) } } impl From<ParseFloatError> for SysInfoError { fn from(e: ParseFloatError) -> SysInfoError { SysInfoError::ParseFloat(e) } } #[derive(Debug)] struct Uptime { uptime: f64, idle: f64, } const WINDOW: usize = 10; struct CpuMeasureState { cpus: usize, uptimes: VecDeque<Uptime>, } fn uptime() -> Result<Uptime, SysInfoError> { let mut f = File::open("/proc/uptime")?; let mut content = String::new(); f.read_to_string(&mut content)?; let mut iter = content.split_whitespace(); let uptime_str = iter.next().ok_or(SysInfoError::Format("Missing uptime".to_string()))?; let idle_str = iter.next().ok_or(SysInfoError::Format("Missing idle time".to_string()))?; Ok(Uptime { uptime: f64::from_str(uptime_str)?, idle: f64::from_str(idle_str)?, }) } fn init_cpu_measurement() -> Result<CpuMeasureState, SysInfoError> { let mut v = VecDeque::new(); v.push_back(uptime()?); Ok(CpuMeasureState { cpus: num_cpus::get(), uptimes: v, }) } fn cpu_usage(s: &mut CpuMeasureState) -> Result<f64, SysInfoError> { let last_uptime = uptime()?; if s.uptimes.len() > WINDOW { s.uptimes.pop_front(); } s.uptimes.push_back(last_uptime); let du = s.uptimes.back().unwrap().uptime - s.uptimes.front().unwrap().uptime; if du < 0.001 { return Ok(0.0); } let cpus = s.cpus as f64; let di = (s.uptimes.back().unwrap().idle - s.uptimes.front().unwrap().idle) / cpus; return Ok(1.0 - (di / du)); } fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 { let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min; f = f.min(new_max).max(new_min); f as u8 } fn send_info(port: &mut serial::SystemPort, cpu_used: f64, mem_used: f64) -> serial::Result<()> { let cpu_used_scaled = scale(cpu_used, 0.0, 1.0, 0.0, 235.0); let mem_used_scaled = scale(mem_used, 0.0, 1.0, 0.0, 235.0); port.write_all(&[33, mem_used_scaled, cpu_used_scaled])?; port.flush()?; Ok(()) } fn open_serial_port() -> serial::Result<serial::SystemPort> { let mut port = serial::open("/dev/ttyUSB0")?; let mut settings = port.read_settings()?; settings.set_baud_rate(serial::Baud9600)?; settings.set_parity(serial::ParityNone); settings.set_stop_bits(serial::Stop1); port.write_settings(&settings)?; Ok(port) } fn two_words(s: String) -> Option<(String, String)> { let mut iter = s.split_whitespace(); if let Some(first) = iter.next() { if let Some(second) = iter.next() { return Some((first.to_string(), second.to_string())); } } None } fn get_mem_usage() -> io::Result<f64> { let f = BufReader::new(File::open("/proc/meminfo")?); let (total, avail) = f.lines() .map(|l| l.unwrap()) .map(two_words) .filter_map(|x| x) .scan((None, None), |state, item| { let (key, val) = item; if key == "MemTotal:" { state.0 = Some(val.parse::<f64>().unwrap_or(1.0)); return Some(*state); } if key == "MemAvailable:" {
return Some(*state); } Some(*state) }) .filter_map(|state| { let (total_option, avail_option) = state; if let Some(total) = total_option { if let Some(avail) = avail_option { return Some((total, avail)); } } None }) .next() .unwrap(); Ok(1.0 - avail / total) } fn main() { let mut port = open_serial_port().unwrap(); let mut cm = init_cpu_measurement().unwrap(); let delay = Duration::from_millis(100); loop { sleep(delay); let cpu_usage = cpu_usage(&mut cm).unwrap(); let mem_usage = get_mem_usage().unwrap(); send_info(&mut port, cpu_usage, mem_usage).unwrap(); } }
state.1 = Some(val.parse::<f64>().unwrap_or(0.0));
random_line_split
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive(Debug)] enum SysInfoError { Io(io::Error), ParseFloat(ParseFloatError), Format(String), } impl From<io::Error> for SysInfoError { fn from(e: io::Error) -> SysInfoError { SysInfoError::Io(e) } } impl From<ParseFloatError> for SysInfoError { fn from(e: ParseFloatError) -> SysInfoError { SysInfoError::ParseFloat(e) } } #[derive(Debug)] struct Uptime { uptime: f64, idle: f64, } const WINDOW: usize = 10; struct CpuMeasureState { cpus: usize, uptimes: VecDeque<Uptime>, } fn uptime() -> Result<Uptime, SysInfoError> { let mut f = File::open("/proc/uptime")?; let mut content = String::new(); f.read_to_string(&mut content)?; let mut iter = content.split_whitespace(); let uptime_str = iter.next().ok_or(SysInfoError::Format("Missing uptime".to_string()))?; let idle_str = iter.next().ok_or(SysInfoError::Format("Missing idle time".to_string()))?; Ok(Uptime { uptime: f64::from_str(uptime_str)?, idle: f64::from_str(idle_str)?, }) } fn init_cpu_measurement() -> Result<CpuMeasureState, SysInfoError> { let mut v = VecDeque::new(); v.push_back(uptime()?); Ok(CpuMeasureState { cpus: num_cpus::get(), uptimes: v, }) } fn cpu_usage(s: &mut CpuMeasureState) -> Result<f64, SysInfoError>
fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 { let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min; f = f.min(new_max).max(new_min); f as u8 } fn send_info(port: &mut serial::SystemPort, cpu_used: f64, mem_used: f64) -> serial::Result<()> { let cpu_used_scaled = scale(cpu_used, 0.0, 1.0, 0.0, 235.0); let mem_used_scaled = scale(mem_used, 0.0, 1.0, 0.0, 235.0); port.write_all(&[33, mem_used_scaled, cpu_used_scaled])?; port.flush()?; Ok(()) } fn open_serial_port() -> serial::Result<serial::SystemPort> { let mut port = serial::open("/dev/ttyUSB0")?; let mut settings = port.read_settings()?; settings.set_baud_rate(serial::Baud9600)?; settings.set_parity(serial::ParityNone); settings.set_stop_bits(serial::Stop1); port.write_settings(&settings)?; Ok(port) } fn two_words(s: String) -> Option<(String, String)> { let mut iter = s.split_whitespace(); if let Some(first) = iter.next() { if let Some(second) = iter.next() { return Some((first.to_string(), second.to_string())); } } None } fn get_mem_usage() -> io::Result<f64> { let f = BufReader::new(File::open("/proc/meminfo")?); let (total, avail) = f.lines() .map(|l| l.unwrap()) .map(two_words) .filter_map(|x| x) .scan((None, None), |state, item| { let (key, val) = item; if key == "MemTotal:" { state.0 = Some(val.parse::<f64>().unwrap_or(1.0)); return Some(*state); } if key == "MemAvailable:" { state.1 = Some(val.parse::<f64>().unwrap_or(0.0)); return Some(*state); } Some(*state) }) .filter_map(|state| { let (total_option, avail_option) = state; if let Some(total) = total_option { if let Some(avail) = avail_option { return Some((total, avail)); } } None }) .next() .unwrap(); Ok(1.0 - avail / total) } fn main() { let mut port = open_serial_port().unwrap(); let mut cm = init_cpu_measurement().unwrap(); let delay = Duration::from_millis(100); loop { sleep(delay); let cpu_usage = cpu_usage(&mut cm).unwrap(); let mem_usage = get_mem_usage().unwrap(); send_info(&mut port, cpu_usage, mem_usage).unwrap(); } }
{ let last_uptime = uptime()?; if s.uptimes.len() > WINDOW { s.uptimes.pop_front(); } s.uptimes.push_back(last_uptime); let du = s.uptimes.back().unwrap().uptime - s.uptimes.front().unwrap().uptime; if du < 0.001 { return Ok(0.0); } let cpus = s.cpus as f64; let di = (s.uptimes.back().unwrap().idle - s.uptimes.front().unwrap().idle) / cpus; return Ok(1.0 - (di / du)); }
identifier_body
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive(Debug)] enum SysInfoError { Io(io::Error), ParseFloat(ParseFloatError), Format(String), } impl From<io::Error> for SysInfoError { fn from(e: io::Error) -> SysInfoError { SysInfoError::Io(e) } } impl From<ParseFloatError> for SysInfoError { fn from(e: ParseFloatError) -> SysInfoError { SysInfoError::ParseFloat(e) } } #[derive(Debug)] struct Uptime { uptime: f64, idle: f64, } const WINDOW: usize = 10; struct CpuMeasureState { cpus: usize, uptimes: VecDeque<Uptime>, } fn uptime() -> Result<Uptime, SysInfoError> { let mut f = File::open("/proc/uptime")?; let mut content = String::new(); f.read_to_string(&mut content)?; let mut iter = content.split_whitespace(); let uptime_str = iter.next().ok_or(SysInfoError::Format("Missing uptime".to_string()))?; let idle_str = iter.next().ok_or(SysInfoError::Format("Missing idle time".to_string()))?; Ok(Uptime { uptime: f64::from_str(uptime_str)?, idle: f64::from_str(idle_str)?, }) } fn init_cpu_measurement() -> Result<CpuMeasureState, SysInfoError> { let mut v = VecDeque::new(); v.push_back(uptime()?); Ok(CpuMeasureState { cpus: num_cpus::get(), uptimes: v, }) } fn cpu_usage(s: &mut CpuMeasureState) -> Result<f64, SysInfoError> { let last_uptime = uptime()?; if s.uptimes.len() > WINDOW { s.uptimes.pop_front(); } s.uptimes.push_back(last_uptime); let du = s.uptimes.back().unwrap().uptime - s.uptimes.front().unwrap().uptime; if du < 0.001 { return Ok(0.0); } let cpus = s.cpus as f64; let di = (s.uptimes.back().unwrap().idle - s.uptimes.front().unwrap().idle) / cpus; return Ok(1.0 - (di / du)); } fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 { let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min; f = f.min(new_max).max(new_min); f as u8 } fn send_info(port: &mut serial::SystemPort, cpu_used: f64, mem_used: f64) -> serial::Result<()> { let cpu_used_scaled = scale(cpu_used, 0.0, 1.0, 0.0, 235.0); let mem_used_scaled = scale(mem_used, 0.0, 1.0, 0.0, 235.0); port.write_all(&[33, mem_used_scaled, cpu_used_scaled])?; port.flush()?; Ok(()) } fn open_serial_port() -> serial::Result<serial::SystemPort> { let mut port = serial::open("/dev/ttyUSB0")?; let mut settings = port.read_settings()?; settings.set_baud_rate(serial::Baud9600)?; settings.set_parity(serial::ParityNone); settings.set_stop_bits(serial::Stop1); port.write_settings(&settings)?; Ok(port) } fn two_words(s: String) -> Option<(String, String)> { let mut iter = s.split_whitespace(); if let Some(first) = iter.next() { if let Some(second) = iter.next() { return Some((first.to_string(), second.to_string())); } } None } fn get_mem_usage() -> io::Result<f64> { let f = BufReader::new(File::open("/proc/meminfo")?); let (total, avail) = f.lines() .map(|l| l.unwrap()) .map(two_words) .filter_map(|x| x) .scan((None, None), |state, item| { let (key, val) = item; if key == "MemTotal:" { state.0 = Some(val.parse::<f64>().unwrap_or(1.0)); return Some(*state); } if key == "MemAvailable:" { state.1 = Some(val.parse::<f64>().unwrap_or(0.0)); return Some(*state); } Some(*state) }) .filter_map(|state| { let (total_option, avail_option) = state; if let Some(total) = total_option { if let Some(avail) = avail_option { return Some((total, avail)); } } None }) .next() .unwrap(); Ok(1.0 - avail / total) } fn
() { let mut port = open_serial_port().unwrap(); let mut cm = init_cpu_measurement().unwrap(); let delay = Duration::from_millis(100); loop { sleep(delay); let cpu_usage = cpu_usage(&mut cm).unwrap(); let mem_usage = get_mem_usage().unwrap(); send_info(&mut port, cpu_usage, mem_usage).unwrap(); } }
main
identifier_name
quality.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/. */ //TODO(eijebong): Remove this once typed headers figure out quality // This is copy pasted from the old hyper headers to avoid hardcoding everything // (I would probably also make some silly mistakes while migrating...) use http::header::HeaderValue; use mime::Mime; use std::{fmt, str}; /// A quality value, as specified in [RFC7231]. /// /// Quality values are decimal numbers between 0 and 1 (inclusive) with up to 3 fractional digits of precision. /// /// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3.1 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Quality(u16); impl Quality { /// Creates a quality value from a value between 0 and 1000 inclusive. /// /// This is semantically divided by 1000 to produce a value between 0 and 1. /// /// # Panics /// /// Panics if the value is greater than 1000. pub fn from_u16(quality: u16) -> Quality { assert!(quality <= 1000); Quality(quality) } } /// A value paired with its "quality" as defined in [RFC7231]. /// /// Quality items are used in content negotiation headers such as `Accept` and `Accept-Encoding`. /// /// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3 #[derive(Clone, Debug, PartialEq)] pub struct QualityItem<T> { pub item: T, pub quality: Quality, } impl<T> QualityItem<T> { /// Creates a new quality item. pub fn new(item: T, quality: Quality) -> QualityItem<T> { QualityItem { item, quality } } } impl<T> fmt::Display for QualityItem<T> where T: fmt::Display, { fn
(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.item, fmt)?; match self.quality.0 { 1000 => Ok(()), 0 => fmt.write_str("; q=0"), mut x => { fmt.write_str("; q=0.")?; let mut digits = *b"000"; digits[2] = (x % 10) as u8 + b'0'; x /= 10; digits[1] = (x % 10) as u8 + b'0'; x /= 10; digits[0] = (x % 10) as u8 + b'0'; let s = str::from_utf8(&digits[..]).unwrap(); fmt.write_str(s.trim_right_matches('0')) }, } } } pub fn quality_to_value(q: Vec<QualityItem<Mime>>) -> HeaderValue { HeaderValue::from_str( &q.iter() .map(|q| q.to_string()) .collect::<Vec<String>>() .join(", "), ) .unwrap() }
fmt
identifier_name
quality.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/. */ //TODO(eijebong): Remove this once typed headers figure out quality // This is copy pasted from the old hyper headers to avoid hardcoding everything // (I would probably also make some silly mistakes while migrating...) use http::header::HeaderValue; use mime::Mime; use std::{fmt, str}; /// A quality value, as specified in [RFC7231]. /// /// Quality values are decimal numbers between 0 and 1 (inclusive) with up to 3 fractional digits of precision. /// /// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3.1 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Quality(u16); impl Quality { /// Creates a quality value from a value between 0 and 1000 inclusive. /// /// This is semantically divided by 1000 to produce a value between 0 and 1. /// /// # Panics /// /// Panics if the value is greater than 1000. pub fn from_u16(quality: u16) -> Quality { assert!(quality <= 1000); Quality(quality) } } /// A value paired with its "quality" as defined in [RFC7231]. /// /// Quality items are used in content negotiation headers such as `Accept` and `Accept-Encoding`. /// /// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3 #[derive(Clone, Debug, PartialEq)] pub struct QualityItem<T> { pub item: T, pub quality: Quality, } impl<T> QualityItem<T> { /// Creates a new quality item. pub fn new(item: T, quality: Quality) -> QualityItem<T> { QualityItem { item, quality } } } impl<T> fmt::Display for QualityItem<T> where T: fmt::Display, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.item, fmt)?; match self.quality.0 { 1000 => Ok(()), 0 => fmt.write_str("; q=0"), mut x => { fmt.write_str("; q=0.")?; let mut digits = *b"000"; digits[2] = (x % 10) as u8 + b'0'; x /= 10; digits[1] = (x % 10) as u8 + b'0'; x /= 10; digits[0] = (x % 10) as u8 + b'0'; let s = str::from_utf8(&digits[..]).unwrap(); fmt.write_str(s.trim_right_matches('0')) }, } } } pub fn quality_to_value(q: Vec<QualityItem<Mime>>) -> HeaderValue
{ HeaderValue::from_str( &q.iter() .map(|q| q.to_string()) .collect::<Vec<String>>() .join(", "), ) .unwrap() }
identifier_body
quality.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/. */ //TODO(eijebong): Remove this once typed headers figure out quality // This is copy pasted from the old hyper headers to avoid hardcoding everything // (I would probably also make some silly mistakes while migrating...) use http::header::HeaderValue; use mime::Mime; use std::{fmt, str}; /// A quality value, as specified in [RFC7231]. /// /// Quality values are decimal numbers between 0 and 1 (inclusive) with up to 3 fractional digits of precision. /// /// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3.1 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Quality(u16); impl Quality { /// Creates a quality value from a value between 0 and 1000 inclusive. /// /// This is semantically divided by 1000 to produce a value between 0 and 1. /// /// # Panics /// /// Panics if the value is greater than 1000. pub fn from_u16(quality: u16) -> Quality { assert!(quality <= 1000); Quality(quality) } } /// A value paired with its "quality" as defined in [RFC7231]. /// /// Quality items are used in content negotiation headers such as `Accept` and `Accept-Encoding`. /// /// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3 #[derive(Clone, Debug, PartialEq)] pub struct QualityItem<T> { pub item: T, pub quality: Quality, } impl<T> QualityItem<T> { /// Creates a new quality item. pub fn new(item: T, quality: Quality) -> QualityItem<T> { QualityItem { item, quality } } } impl<T> fmt::Display for QualityItem<T> where T: fmt::Display, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.item, fmt)?; match self.quality.0 { 1000 => Ok(()), 0 => fmt.write_str("; q=0"), mut x => {
x /= 10; digits[1] = (x % 10) as u8 + b'0'; x /= 10; digits[0] = (x % 10) as u8 + b'0'; let s = str::from_utf8(&digits[..]).unwrap(); fmt.write_str(s.trim_right_matches('0')) }, } } } pub fn quality_to_value(q: Vec<QualityItem<Mime>>) -> HeaderValue { HeaderValue::from_str( &q.iter() .map(|q| q.to_string()) .collect::<Vec<String>>() .join(", "), ) .unwrap() }
fmt.write_str("; q=0.")?; let mut digits = *b"000"; digits[2] = (x % 10) as u8 + b'0';
random_line_split
issue-19367.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. struct S { o: Option<String> } // Make sure we don't reuse the same alloca when matching // on field of struct or tuple which we reassign in the match body. fn
() { let mut a = (0, Some("right".to_string())); let b = match a.1 { Some(v) => { a.1 = Some("wrong".to_string()); v } None => String::new() }; println!("{}", b); assert_eq!(b, "right"); let mut s = S{ o: Some("right".to_string()) }; let b = match s.o { Some(v) => { s.o = Some("wrong".to_string()); v } None => String::new(), }; println!("{}", b); assert_eq!(b, "right"); }
main
identifier_name
issue-19367.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. struct S { o: Option<String> }
fn main() { let mut a = (0, Some("right".to_string())); let b = match a.1 { Some(v) => { a.1 = Some("wrong".to_string()); v } None => String::new() }; println!("{}", b); assert_eq!(b, "right"); let mut s = S{ o: Some("right".to_string()) }; let b = match s.o { Some(v) => { s.o = Some("wrong".to_string()); v } None => String::new(), }; println!("{}", b); assert_eq!(b, "right"); }
// Make sure we don't reuse the same alloca when matching // on field of struct or tuple which we reassign in the match body.
random_line_split
revisions_test.rs
extern crate gitters; use gitters::objects; use gitters::revisions; #[test] fn full_sha1_resolves_to_self() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21")); } #[test] fn partial_sha1_resolves_to_full_sha1_if_unambiguous() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025e")); } #[test] fn multiple_parent_specification_resolves_to_ancestor_sha1() { assert_eq!( Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), revisions::resolve("d7698dd^^^")); } #[test] fn
() { assert_eq!( Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), revisions::resolve("d7698dd~3")); } #[test] fn branch_resolves_to_sha1() { assert_eq!( Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())), revisions::resolve("introduce-tests")); } #[test] fn invalid_revision_does_not_resolve() { assert_eq!( Err(revisions::Error::InvalidRevision), revisions::resolve("invalid")); }
ancestor_specification_resolves_to_ancestor_sha1
identifier_name
revisions_test.rs
extern crate gitters; use gitters::objects; use gitters::revisions; #[test] fn full_sha1_resolves_to_self() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21")); } #[test] fn partial_sha1_resolves_to_full_sha1_if_unambiguous() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025e")); } #[test] fn multiple_parent_specification_resolves_to_ancestor_sha1() { assert_eq!( Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), revisions::resolve("d7698dd^^^")); } #[test] fn ancestor_specification_resolves_to_ancestor_sha1() { assert_eq!( Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), revisions::resolve("d7698dd~3")); } #[test] fn branch_resolves_to_sha1()
#[test] fn invalid_revision_does_not_resolve() { assert_eq!( Err(revisions::Error::InvalidRevision), revisions::resolve("invalid")); }
{ assert_eq!( Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())), revisions::resolve("introduce-tests")); }
identifier_body
revisions_test.rs
extern crate gitters; use gitters::objects; use gitters::revisions; #[test] fn full_sha1_resolves_to_self() {
} #[test] fn partial_sha1_resolves_to_full_sha1_if_unambiguous() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025e")); } #[test] fn multiple_parent_specification_resolves_to_ancestor_sha1() { assert_eq!( Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), revisions::resolve("d7698dd^^^")); } #[test] fn ancestor_specification_resolves_to_ancestor_sha1() { assert_eq!( Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), revisions::resolve("d7698dd~3")); } #[test] fn branch_resolves_to_sha1() { assert_eq!( Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())), revisions::resolve("introduce-tests")); } #[test] fn invalid_revision_does_not_resolve() { assert_eq!( Err(revisions::Error::InvalidRevision), revisions::resolve("invalid")); }
assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21"));
random_line_split
display_controller.rs
use std::thread; use std::sync::{mpsc, Arc, Mutex}; use rustc_serialize::json; use input_parser; use channel::Channel; use current_state::{self, CurrentState}; use rdispatcher::{Subscribe, SubscribeHandle, DispatchMessage, Broadcast, BroadcastHandle}; use dispatch_type::DispatchType; use view::View; use view_data::ViewData; use message::Message; pub struct DisplayController { _view_guard: Option<thread::JoinHandle<()>>, _print_guard: Option<thread::JoinHandle<()>>, current_state: Arc<Mutex<CurrentState>>, subscribe_tx: mpsc::Sender<DispatchMessage<DispatchType>>, subscribe_rx: Arc<Mutex<mpsc::Receiver<DispatchMessage<DispatchType>>>>, broadcast_tx: Option<mpsc::Sender<DispatchMessage<DispatchType>>> } impl DisplayController { pub fn new(initial_state: &str) -> DisplayController { let initial_state = current_state::new_from_str(&initial_state).unwrap(); let (tx, rx) = mpsc::channel::<DispatchMessage<DispatchType>>(); DisplayController { _view_guard: None, _print_guard: None, current_state: Arc::new(Mutex::new(initial_state)), subscribe_rx: Arc::new(Mutex::new(rx)), subscribe_tx: tx, broadcast_tx: None } } pub fn start(&mut self) { // For communicating from and to the view let (view_tx, view_rx) = mpsc::channel::<ViewData>(); self.spawn_view_loop(view_rx); self.spawn_print_loop(view_tx); } fn spawn_view_loop(&mut self, view_rx: mpsc::Receiver<ViewData>) { let broadcast_tx = self.broadcast_tx.clone().expect("Expected broadcaster to be present in display controller"); let guard = thread::spawn(move || { let mut view = View::new(); let on_input = Box::new(move |string: String, channel_id: String| { let (payload, dtype) = input_parser::parse(string, channel_id); let message = DispatchMessage { payload: payload, dispatch_type: dtype }; broadcast_tx.send(message).ok().expect("[on_input] Could not send input"); }); view.init(on_input, view_rx); }); self._view_guard = Some(guard); } fn spawn_print_loop(&mut self, view_tx: mpsc::Sender<ViewData>) { let rx = self.subscribe_rx.clone(); let state = self.current_state.clone(); let default_channel = self.default_channel(); let guard = thread::spawn(move || { let mut all_view_data: Vec<ViewData> = vec![]; let mut current_view_data = ViewData::new(default_channel); loop { let message = rx.lock().unwrap().recv().unwrap(); let locked_state = state.lock().unwrap(); match message.dispatch_type { DispatchType::RawIncomingMessage => handle_raw_incoming(&message.payload, &locked_state, &mut current_view_data, &mut all_view_data), DispatchType::ChangeCurrentChannel => handle_change_current_channel(&message.payload, &locked_state, &mut current_view_data, &mut all_view_data), DispatchType::ListChannels => handle_list_channels(&message.payload, &locked_state, &mut current_view_data, &mut all_view_data), DispatchType::UserInput => handle_user_input(&message.payload, &locked_state, &mut current_view_data) // _ => panic!("Got something I didn't expect: {:?}", message.payload) } current_view_data.update_unread(&all_view_data); view_tx.send(current_view_data.clone()).ok().expect("[print_loop] Could not send view data to view"); } }); self._print_guard = Some(guard); } fn default_channel(&self) -> Channel { self.current_state.lock().unwrap().default_channel() .expect("Could not find default channel") .clone() } } fn handle_raw_incoming(payload: &str, state: &CurrentState, current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) { match state.parse_incoming_message(payload) { Ok(parsed) => { match parsed.channel.as_ref() { Some(channel) if channel == &current_view_data.channel => { current_view_data.add_message(parsed.clone()) }, Some(channel) => { for data in all_view_data.iter_mut() { if &data.channel == channel { data.add_message(parsed.clone()); data.has_unread = true; break; } } }, None => debug!("{}", parsed) } }, Err(err) => debug!("Failed to parse message {} and gave err: {}",payload, err) }; } fn handle_change_current_channel(payload: &str, state: &CurrentState, mut current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) { match state.name_to_channel(payload) { Some(channel) => { all_view_data.push(current_view_data.clone()); match all_view_data.iter().position(|d| &d.channel == channel) { Some(idx) => { *current_view_data = all_view_data.remove(idx); current_view_data.has_unread = false; }, None => { *current_view_data = ViewData::new(channel.clone()); } } current_view_data.add_debug(format!("Changed channel to: {}", channel.name)) }, None => { current_view_data.add_debug(format!("Channel not found: {}", payload)) } } } fn
(payload: &str, state: &CurrentState, current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) { let channel_names = state.channel_names(); current_view_data.add_debug(format!("Channels: {}", channel_names.connect(", "))); } fn handle_user_input(payload: &str, state: &CurrentState, current_view_data: &mut ViewData) { let me = state.me.clone(); // Only interested in message, not channel let (_, payload): (String, String) = json::decode(&payload).ok().expect(&format!("[display_controller] Could not parse payload {}", payload)); let message = Message { ts: None, text: Some(payload), user: Some(me), channel: None, event_type: Some("message".to_string()), user_id: None, channel_id: None }; current_view_data.add_message(message); } impl Subscribe<DispatchType> for DisplayController { fn subscribe_handle(&self) -> SubscribeHandle<DispatchType> { self.subscribe_tx.clone() } } impl Broadcast<DispatchType> for DisplayController { fn broadcast_handle(&mut self) -> BroadcastHandle<DispatchType> { let (tx, rx) = mpsc::channel::<DispatchMessage<DispatchType>>(); self.broadcast_tx = Some(tx); rx } }
handle_list_channels
identifier_name
display_controller.rs
use std::thread; use std::sync::{mpsc, Arc, Mutex}; use rustc_serialize::json; use input_parser; use channel::Channel; use current_state::{self, CurrentState}; use rdispatcher::{Subscribe, SubscribeHandle, DispatchMessage, Broadcast, BroadcastHandle}; use dispatch_type::DispatchType; use view::View; use view_data::ViewData; use message::Message; pub struct DisplayController { _view_guard: Option<thread::JoinHandle<()>>, _print_guard: Option<thread::JoinHandle<()>>, current_state: Arc<Mutex<CurrentState>>, subscribe_tx: mpsc::Sender<DispatchMessage<DispatchType>>, subscribe_rx: Arc<Mutex<mpsc::Receiver<DispatchMessage<DispatchType>>>>, broadcast_tx: Option<mpsc::Sender<DispatchMessage<DispatchType>>> } impl DisplayController { pub fn new(initial_state: &str) -> DisplayController { let initial_state = current_state::new_from_str(&initial_state).unwrap(); let (tx, rx) = mpsc::channel::<DispatchMessage<DispatchType>>(); DisplayController { _view_guard: None, _print_guard: None, current_state: Arc::new(Mutex::new(initial_state)), subscribe_rx: Arc::new(Mutex::new(rx)), subscribe_tx: tx, broadcast_tx: None } } pub fn start(&mut self) { // For communicating from and to the view let (view_tx, view_rx) = mpsc::channel::<ViewData>(); self.spawn_view_loop(view_rx); self.spawn_print_loop(view_tx); } fn spawn_view_loop(&mut self, view_rx: mpsc::Receiver<ViewData>) { let broadcast_tx = self.broadcast_tx.clone().expect("Expected broadcaster to be present in display controller"); let guard = thread::spawn(move || { let mut view = View::new(); let on_input = Box::new(move |string: String, channel_id: String| { let (payload, dtype) = input_parser::parse(string, channel_id); let message = DispatchMessage { payload: payload, dispatch_type: dtype }; broadcast_tx.send(message).ok().expect("[on_input] Could not send input"); }); view.init(on_input, view_rx); }); self._view_guard = Some(guard); } fn spawn_print_loop(&mut self, view_tx: mpsc::Sender<ViewData>) { let rx = self.subscribe_rx.clone(); let state = self.current_state.clone(); let default_channel = self.default_channel(); let guard = thread::spawn(move || { let mut all_view_data: Vec<ViewData> = vec![]; let mut current_view_data = ViewData::new(default_channel); loop { let message = rx.lock().unwrap().recv().unwrap(); let locked_state = state.lock().unwrap(); match message.dispatch_type { DispatchType::RawIncomingMessage => handle_raw_incoming(&message.payload, &locked_state, &mut current_view_data, &mut all_view_data), DispatchType::ChangeCurrentChannel => handle_change_current_channel(&message.payload, &locked_state, &mut current_view_data, &mut all_view_data), DispatchType::ListChannels => handle_list_channels(&message.payload, &locked_state, &mut current_view_data, &mut all_view_data), DispatchType::UserInput => handle_user_input(&message.payload, &locked_state, &mut current_view_data) // _ => panic!("Got something I didn't expect: {:?}", message.payload) } current_view_data.update_unread(&all_view_data); view_tx.send(current_view_data.clone()).ok().expect("[print_loop] Could not send view data to view"); } }); self._print_guard = Some(guard); } fn default_channel(&self) -> Channel { self.current_state.lock().unwrap().default_channel() .expect("Could not find default channel") .clone() } } fn handle_raw_incoming(payload: &str, state: &CurrentState, current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) { match state.parse_incoming_message(payload) { Ok(parsed) => { match parsed.channel.as_ref() { Some(channel) if channel == &current_view_data.channel => { current_view_data.add_message(parsed.clone()) }, Some(channel) => { for data in all_view_data.iter_mut() { if &data.channel == channel { data.add_message(parsed.clone()); data.has_unread = true; break; } } }, None => debug!("{}", parsed) } }, Err(err) => debug!("Failed to parse message {} and gave err: {}",payload, err) }; } fn handle_change_current_channel(payload: &str, state: &CurrentState, mut current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) { match state.name_to_channel(payload) { Some(channel) => { all_view_data.push(current_view_data.clone()); match all_view_data.iter().position(|d| &d.channel == channel) { Some(idx) => { *current_view_data = all_view_data.remove(idx); current_view_data.has_unread = false; }, None => { *current_view_data = ViewData::new(channel.clone()); } } current_view_data.add_debug(format!("Changed channel to: {}", channel.name)) }, None => { current_view_data.add_debug(format!("Channel not found: {}", payload)) } } } fn handle_list_channels(payload: &str, state: &CurrentState, current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) { let channel_names = state.channel_names(); current_view_data.add_debug(format!("Channels: {}", channel_names.connect(", "))); } fn handle_user_input(payload: &str, state: &CurrentState, current_view_data: &mut ViewData) { let me = state.me.clone(); // Only interested in message, not channel let (_, payload): (String, String) = json::decode(&payload).ok().expect(&format!("[display_controller] Could not parse payload {}", payload)); let message = Message { ts: None, text: Some(payload), user: Some(me), channel: None, event_type: Some("message".to_string()), user_id: None, channel_id: None }; current_view_data.add_message(message); } impl Subscribe<DispatchType> for DisplayController { fn subscribe_handle(&self) -> SubscribeHandle<DispatchType> { self.subscribe_tx.clone() }
fn broadcast_handle(&mut self) -> BroadcastHandle<DispatchType> { let (tx, rx) = mpsc::channel::<DispatchMessage<DispatchType>>(); self.broadcast_tx = Some(tx); rx } }
} impl Broadcast<DispatchType> for DisplayController {
random_line_split
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with queues is simply a pair of unsigned integers. It is expected that a //! higher-level API on top of this could allow safe fork-join parallelism. use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; use libc::usleep; use rand::{Rng, XorShiftRng, weak_rng}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; use task::spawn_named; use task_state; /// A unit of work. /// /// # Type parameters /// /// - `QueueData`: global custom data for the entire work queue. /// - `WorkData`: custom data specific to each unit of work. pub struct WorkUnit<QueueData, WorkData> { /// The function to execute. pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData:'static, WorkData:'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData), /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. Stop, /// Tells the worker to measure the heap size of its TLS using the supplied function. HeapSizeOfTLS(fn() -> usize), /// Tells the worker thread to terminate. Exit, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {} /// Messages to the supervisor. enum SupervisorMsg<QueueData:'static, WorkData:'static> { Finished, HeapSizeOfTLS(usize), ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>), } unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {} /// Information that the supervisor thread keeps about the worker threads. struct WorkerInfo<QueueData:'static, WorkData:'static> { /// The communication channel to the workers. chan: Sender<WorkerMsg<QueueData, WorkData>>, /// The worker end of the deque, if we have it. deque: Option<Worker<WorkUnit<QueueData, WorkData>>>, /// The thief end of the work-stealing deque. thief: Stealer<WorkUnit<QueueData, WorkData>>, } /// Information specific to each worker thread that the thread keeps. struct WorkerThread<QueueData:'static, WorkData:'static> { /// The index of this worker. index: usize, /// The communication port from the supervisor. port: Receiver<WorkerMsg<QueueData, WorkData>>, /// The communication channel on which messages are sent to the supervisor. chan: Sender<SupervisorMsg<QueueData, WorkData>>, /// The thief end of the work-stealing deque for all other workers. other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>, /// The random number generator for this worker. rng: XorShiftRng, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {} const SPINS_UNTIL_BACKOFF: u32 = 128; const BACKOFF_INCREMENT_IN_US: u32 = 5; const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6; fn next_power_of_two(mut v: u32) -> u32 { v -= 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v += 1; v } impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> { /// The main logic. This function starts up the worker and listens for /// messages. fn start(&mut self) { let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1; loop { // Wait for a start message. let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() { WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data), WorkerMsg::Stop => panic!("unexpected stop message"), WorkerMsg::Exit => return, WorkerMsg::HeapSizeOfTLS(f) => { self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap(); continue; } }; let mut back_off_sleep = 0 as u32; // We're off! 'outer: loop { let work_unit; match deque.pop() { Some(work) => work_unit = work, None => { // Become a thief. let mut i = 0; loop { // Don't just use `rand % len` because that's slow on ARM. let mut victim; loop { victim = self.rng.next_u32() & deque_index_mask; if (victim as usize) < self.other_deques.len() { break } } match self.other_deques[victim as usize].steal() { Empty | Abort => { // Continue.
} Data(work) => { work_unit = work; back_off_sleep = 0 as u32; break } } if i > SPINS_UNTIL_BACKOFF { if back_off_sleep >= BACKOFF_INCREMENT_IN_US * BACKOFFS_UNTIL_CONTROL_CHECK { match self.port.try_recv() { Ok(WorkerMsg::Stop) => break 'outer, Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"), _ => {} } } unsafe { usleep(back_off_sleep as u32); } back_off_sleep += BACKOFF_INCREMENT_IN_US; i = 0 } else { i += 1 } } } } // At this point, we have some work. Perform it. let mut proxy = WorkerProxy { worker: &mut deque, ref_count: ref_count, // queue_data is kept alive in the stack frame of // WorkQueue::run until we send the // SupervisorMsg::ReturnDeque message below. queue_data: unsafe { &*queue_data }, worker_index: self.index as u8, }; (work_unit.fun)(work_unit.data, &mut proxy); // The work is done. Now decrement the count of outstanding work items. If this was // the last work unit in the queue, then send a message on the channel. unsafe { if (*ref_count).fetch_sub(1, Ordering::Release) == 1 { self.chan.send(SupervisorMsg::Finished).unwrap() } } } // Give the deque back to the supervisor. self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap() } } } /// A handle to the work queue that individual work units have. pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> { worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>, ref_count: *mut AtomicUsize, queue_data: &'a QueueData, worker_index: u8, } impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> { /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { unsafe { drop((*self.ref_count).fetch_add(1, Ordering::Relaxed)); } self.worker.push(work_unit); } /// Retrieves the queue user data. #[inline] pub fn user_data(&self) -> &'a QueueData { self.queue_data } /// Retrieves the index of the worker. #[inline] pub fn worker_index(&self) -> u8 { self.worker_index } } /// A work queue on which units of work can be submitted. pub struct WorkQueue<QueueData:'static, WorkData:'static> { /// Information about each of the workers. workers: Vec<WorkerInfo<QueueData, WorkData>>, /// A port on which deques can be received from the workers. port: Receiver<SupervisorMsg<QueueData, WorkData>>, /// The amount of work that has been enqueued. work_count: usize, } impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> { /// Creates a new work queue and spawns all the threads associated with /// it. pub fn new(task_name: &'static str, state: task_state::TaskState, thread_count: usize) -> WorkQueue<QueueData, WorkData> { // Set up data structures. let (supervisor_chan, supervisor_port) = channel(); let (mut infos, mut threads) = (vec!(), vec!()); for i in 0..thread_count { let (worker_chan, worker_port) = channel(); let pool = BufferPool::new(); let (worker, thief) = pool.deque(); infos.push(WorkerInfo { chan: worker_chan, deque: Some(worker), thief: thief, }); threads.push(WorkerThread { index: i, port: worker_port, chan: supervisor_chan.clone(), other_deques: vec!(), rng: weak_rng(), }); } // Connect workers to one another. for (i, mut thread) in threads.iter_mut().enumerate() { for (j, info) in infos.iter().enumerate() { if i!= j { thread.other_deques.push(info.thief.clone()) } } assert!(thread.other_deques.len() == thread_count - 1) } // Spawn threads. for (i, thread) in threads.into_iter().enumerate() { spawn_named( format!("{} worker {}/{}", task_name, i + 1, thread_count), move || { task_state::initialize(state | task_state::IN_WORKER); let mut thread = thread; thread.start() }) } WorkQueue { workers: infos, port: supervisor_port, work_count: 0, } } /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { let deque = &mut self.workers[0].deque; match *deque { None => { panic!("tried to push a block but we don't have the deque?!") } Some(ref mut deque) => deque.push(work_unit), } self.work_count += 1 } /// Synchronously runs all the enqueued tasks and waits for them to complete. pub fn run(&mut self, data: &QueueData) { // Tell the workers to start. let mut work_count = AtomicUsize::new(self.work_count); for worker in &mut self.workers { worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, data)).unwrap() } // Wait for the work to finish. drop(self.port.recv()); self.work_count = 0; // Tell everyone to stop. for worker in &self.workers { worker.chan.send(WorkerMsg::Stop).unwrap() } // Get our deques back. for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque), SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"), SupervisorMsg::Finished => panic!("unexpected finished message!"), } } } /// Synchronously measure memory usage of any thread-local storage. pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> { // Tell the workers to measure themselves. for worker in &self.workers { worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap() } // Wait for the workers to finish measuring themselves. let mut sizes = vec![]; for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::HeapSizeOfTLS(size) => { sizes.push(size); } _ => panic!("unexpected message!"), } } sizes } pub fn shutdown(&mut self) { for worker in &self.workers { worker.chan.send(WorkerMsg::Exit).unwrap() } } }
random_line_split
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with queues is simply a pair of unsigned integers. It is expected that a //! higher-level API on top of this could allow safe fork-join parallelism. use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; use libc::usleep; use rand::{Rng, XorShiftRng, weak_rng}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; use task::spawn_named; use task_state; /// A unit of work. /// /// # Type parameters /// /// - `QueueData`: global custom data for the entire work queue. /// - `WorkData`: custom data specific to each unit of work. pub struct WorkUnit<QueueData, WorkData> { /// The function to execute. pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData:'static, WorkData:'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData), /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. Stop, /// Tells the worker to measure the heap size of its TLS using the supplied function. HeapSizeOfTLS(fn() -> usize), /// Tells the worker thread to terminate. Exit, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {} /// Messages to the supervisor. enum SupervisorMsg<QueueData:'static, WorkData:'static> { Finished, HeapSizeOfTLS(usize), ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>), } unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {} /// Information that the supervisor thread keeps about the worker threads. struct
<QueueData:'static, WorkData:'static> { /// The communication channel to the workers. chan: Sender<WorkerMsg<QueueData, WorkData>>, /// The worker end of the deque, if we have it. deque: Option<Worker<WorkUnit<QueueData, WorkData>>>, /// The thief end of the work-stealing deque. thief: Stealer<WorkUnit<QueueData, WorkData>>, } /// Information specific to each worker thread that the thread keeps. struct WorkerThread<QueueData:'static, WorkData:'static> { /// The index of this worker. index: usize, /// The communication port from the supervisor. port: Receiver<WorkerMsg<QueueData, WorkData>>, /// The communication channel on which messages are sent to the supervisor. chan: Sender<SupervisorMsg<QueueData, WorkData>>, /// The thief end of the work-stealing deque for all other workers. other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>, /// The random number generator for this worker. rng: XorShiftRng, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {} const SPINS_UNTIL_BACKOFF: u32 = 128; const BACKOFF_INCREMENT_IN_US: u32 = 5; const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6; fn next_power_of_two(mut v: u32) -> u32 { v -= 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v += 1; v } impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> { /// The main logic. This function starts up the worker and listens for /// messages. fn start(&mut self) { let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1; loop { // Wait for a start message. let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() { WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data), WorkerMsg::Stop => panic!("unexpected stop message"), WorkerMsg::Exit => return, WorkerMsg::HeapSizeOfTLS(f) => { self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap(); continue; } }; let mut back_off_sleep = 0 as u32; // We're off! 'outer: loop { let work_unit; match deque.pop() { Some(work) => work_unit = work, None => { // Become a thief. let mut i = 0; loop { // Don't just use `rand % len` because that's slow on ARM. let mut victim; loop { victim = self.rng.next_u32() & deque_index_mask; if (victim as usize) < self.other_deques.len() { break } } match self.other_deques[victim as usize].steal() { Empty | Abort => { // Continue. } Data(work) => { work_unit = work; back_off_sleep = 0 as u32; break } } if i > SPINS_UNTIL_BACKOFF { if back_off_sleep >= BACKOFF_INCREMENT_IN_US * BACKOFFS_UNTIL_CONTROL_CHECK { match self.port.try_recv() { Ok(WorkerMsg::Stop) => break 'outer, Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"), _ => {} } } unsafe { usleep(back_off_sleep as u32); } back_off_sleep += BACKOFF_INCREMENT_IN_US; i = 0 } else { i += 1 } } } } // At this point, we have some work. Perform it. let mut proxy = WorkerProxy { worker: &mut deque, ref_count: ref_count, // queue_data is kept alive in the stack frame of // WorkQueue::run until we send the // SupervisorMsg::ReturnDeque message below. queue_data: unsafe { &*queue_data }, worker_index: self.index as u8, }; (work_unit.fun)(work_unit.data, &mut proxy); // The work is done. Now decrement the count of outstanding work items. If this was // the last work unit in the queue, then send a message on the channel. unsafe { if (*ref_count).fetch_sub(1, Ordering::Release) == 1 { self.chan.send(SupervisorMsg::Finished).unwrap() } } } // Give the deque back to the supervisor. self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap() } } } /// A handle to the work queue that individual work units have. pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> { worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>, ref_count: *mut AtomicUsize, queue_data: &'a QueueData, worker_index: u8, } impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> { /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { unsafe { drop((*self.ref_count).fetch_add(1, Ordering::Relaxed)); } self.worker.push(work_unit); } /// Retrieves the queue user data. #[inline] pub fn user_data(&self) -> &'a QueueData { self.queue_data } /// Retrieves the index of the worker. #[inline] pub fn worker_index(&self) -> u8 { self.worker_index } } /// A work queue on which units of work can be submitted. pub struct WorkQueue<QueueData:'static, WorkData:'static> { /// Information about each of the workers. workers: Vec<WorkerInfo<QueueData, WorkData>>, /// A port on which deques can be received from the workers. port: Receiver<SupervisorMsg<QueueData, WorkData>>, /// The amount of work that has been enqueued. work_count: usize, } impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> { /// Creates a new work queue and spawns all the threads associated with /// it. pub fn new(task_name: &'static str, state: task_state::TaskState, thread_count: usize) -> WorkQueue<QueueData, WorkData> { // Set up data structures. let (supervisor_chan, supervisor_port) = channel(); let (mut infos, mut threads) = (vec!(), vec!()); for i in 0..thread_count { let (worker_chan, worker_port) = channel(); let pool = BufferPool::new(); let (worker, thief) = pool.deque(); infos.push(WorkerInfo { chan: worker_chan, deque: Some(worker), thief: thief, }); threads.push(WorkerThread { index: i, port: worker_port, chan: supervisor_chan.clone(), other_deques: vec!(), rng: weak_rng(), }); } // Connect workers to one another. for (i, mut thread) in threads.iter_mut().enumerate() { for (j, info) in infos.iter().enumerate() { if i!= j { thread.other_deques.push(info.thief.clone()) } } assert!(thread.other_deques.len() == thread_count - 1) } // Spawn threads. for (i, thread) in threads.into_iter().enumerate() { spawn_named( format!("{} worker {}/{}", task_name, i + 1, thread_count), move || { task_state::initialize(state | task_state::IN_WORKER); let mut thread = thread; thread.start() }) } WorkQueue { workers: infos, port: supervisor_port, work_count: 0, } } /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { let deque = &mut self.workers[0].deque; match *deque { None => { panic!("tried to push a block but we don't have the deque?!") } Some(ref mut deque) => deque.push(work_unit), } self.work_count += 1 } /// Synchronously runs all the enqueued tasks and waits for them to complete. pub fn run(&mut self, data: &QueueData) { // Tell the workers to start. let mut work_count = AtomicUsize::new(self.work_count); for worker in &mut self.workers { worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, data)).unwrap() } // Wait for the work to finish. drop(self.port.recv()); self.work_count = 0; // Tell everyone to stop. for worker in &self.workers { worker.chan.send(WorkerMsg::Stop).unwrap() } // Get our deques back. for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque), SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"), SupervisorMsg::Finished => panic!("unexpected finished message!"), } } } /// Synchronously measure memory usage of any thread-local storage. pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> { // Tell the workers to measure themselves. for worker in &self.workers { worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap() } // Wait for the workers to finish measuring themselves. let mut sizes = vec![]; for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::HeapSizeOfTLS(size) => { sizes.push(size); } _ => panic!("unexpected message!"), } } sizes } pub fn shutdown(&mut self) { for worker in &self.workers { worker.chan.send(WorkerMsg::Exit).unwrap() } } }
WorkerInfo
identifier_name
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use blue_pill::stm32f103xx; use blue_pill::time::Hertz; use hal::prelude::*; use rtfm::{Local, P0, P1, T0, T1, TMax}; use stm32f103xx::interrupt::TIM1_UP_TIM10; // CONFIGURATION const FREQUENCY: Hertz = Hertz(1); // RESOURCES peripherals!(stm32f103xx, { GPIOC: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM1: Peripheral { ceiling: C1, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax)
// IDLE LOOP fn idle(_prio: P0, _thr: T0) ->! { // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, { blink: Task { interrupt: TIM1_UP_TIM10, priority: P1, enabled: true, }, }); fn blink(mut task: TIM1_UP_TIM10, ref prio: P1, ref thr: T1) { static STATE: Local<bool, TIM1_UP_TIM10> = Local::new(false); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); // NOTE(wait) timeout should have already occurred timer.wait().unwrap(); let state = STATE.borrow_mut(&mut task); *state =!*state; if *state { Green.on(); } else { Green.off(); } }
{ let gpioc = &GPIOC.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); led::init(gpioc, rcc); timer.init(FREQUENCY.invert(), rcc); timer.resume(); }
identifier_body
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use blue_pill::stm32f103xx; use blue_pill::time::Hertz; use hal::prelude::*; use rtfm::{Local, P0, P1, T0, T1, TMax}; use stm32f103xx::interrupt::TIM1_UP_TIM10; // CONFIGURATION const FREQUENCY: Hertz = Hertz(1); // RESOURCES peripherals!(stm32f103xx, { GPIOC: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM1: Peripheral { ceiling: C1, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax) { let gpioc = &GPIOC.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); led::init(gpioc, rcc); timer.init(FREQUENCY.invert(), rcc); timer.resume(); } // IDLE LOOP fn idle(_prio: P0, _thr: T0) ->! { // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, { blink: Task { interrupt: TIM1_UP_TIM10, priority: P1, enabled: true, }, }); fn blink(mut task: TIM1_UP_TIM10, ref prio: P1, ref thr: T1) { static STATE: Local<bool, TIM1_UP_TIM10> = Local::new(false); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); // NOTE(wait) timeout should have already occurred timer.wait().unwrap(); let state = STATE.borrow_mut(&mut task); *state =!*state; if *state { Green.on();
} else { Green.off(); } }
random_line_split
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use blue_pill::stm32f103xx; use blue_pill::time::Hertz; use hal::prelude::*; use rtfm::{Local, P0, P1, T0, T1, TMax}; use stm32f103xx::interrupt::TIM1_UP_TIM10; // CONFIGURATION const FREQUENCY: Hertz = Hertz(1); // RESOURCES peripherals!(stm32f103xx, { GPIOC: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM1: Peripheral { ceiling: C1, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax) { let gpioc = &GPIOC.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); led::init(gpioc, rcc); timer.init(FREQUENCY.invert(), rcc); timer.resume(); } // IDLE LOOP fn idle(_prio: P0, _thr: T0) ->! { // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, { blink: Task { interrupt: TIM1_UP_TIM10, priority: P1, enabled: true, }, }); fn
(mut task: TIM1_UP_TIM10, ref prio: P1, ref thr: T1) { static STATE: Local<bool, TIM1_UP_TIM10> = Local::new(false); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); // NOTE(wait) timeout should have already occurred timer.wait().unwrap(); let state = STATE.borrow_mut(&mut task); *state =!*state; if *state { Green.on(); } else { Green.off(); } }
blink
identifier_name
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use blue_pill::stm32f103xx; use blue_pill::time::Hertz; use hal::prelude::*; use rtfm::{Local, P0, P1, T0, T1, TMax}; use stm32f103xx::interrupt::TIM1_UP_TIM10; // CONFIGURATION const FREQUENCY: Hertz = Hertz(1); // RESOURCES peripherals!(stm32f103xx, { GPIOC: Peripheral { ceiling: C0, }, RCC: Peripheral { ceiling: C0, }, TIM1: Peripheral { ceiling: C1, }, }); // INITIALIZATION PHASE fn init(ref prio: P0, thr: &TMax) { let gpioc = &GPIOC.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); led::init(gpioc, rcc); timer.init(FREQUENCY.invert(), rcc); timer.resume(); } // IDLE LOOP fn idle(_prio: P0, _thr: T0) ->! { // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, { blink: Task { interrupt: TIM1_UP_TIM10, priority: P1, enabled: true, }, }); fn blink(mut task: TIM1_UP_TIM10, ref prio: P1, ref thr: T1) { static STATE: Local<bool, TIM1_UP_TIM10> = Local::new(false); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); // NOTE(wait) timeout should have already occurred timer.wait().unwrap(); let state = STATE.borrow_mut(&mut task); *state =!*state; if *state
else { Green.off(); } }
{ Green.on(); }
conditional_block
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } fn size_hint(&self) -> (usize, Option<usize>) { debug_assert!(self.begin <= self.end); let exact: usize = (self.end - self.begin) as usize; (exact, Some::<usize>(exact)) } // fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> // where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, // { // FlatMap{iter: self, f: f, frontiter: None, backiter: None } // } } } } type T = u32; Iterator_impl!(T); // impl<I: Iterator> IntoIterator for I { // type Item = I::Item; // type IntoIter = I; // // fn into_iter(self) -> I { // self // } // } // impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F> // where F: FnMut(I::Item) -> U, // { // type Item = U::Item; // // #[inline] // fn next(&mut self) -> Option<U::Item> { // loop { // if let Some(ref mut inner) = self.frontiter { // if let Some(x) = inner.by_ref().next() { // return Some(x) // } // } // match self.iter.next().map(|x| (self.f)(x)) { // None => return self.backiter.as_mut().and_then(|it| it.next()), // next => self.frontiter = next.map(IntoIterator::into_iter), // } // } // } // // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { // let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let lo = flo.saturating_add(blo); // match (self.iter.size_hint(), fhi, bhi) { // ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)), // _ => (lo, None) // } // } // } struct F; type Item = T; type U = A<T>; type Args = (Item,); impl FnOnce<Args> for F { type Output = U; extern "rust-call" fn call_once(self, (item,): Args) -> Self::Output
} impl FnMut<Args> for F { extern "rust-call" fn call_mut(&mut self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } #[test] fn size_hint_test1() { let a: A<T> = A { begin: 0, end: 10 }; let f: F = F; let mut flat_map: FlatMap<A<T>, U, F> = a.flat_map::<U, F>(f); for n in 0.. 10 { for i in 0..n { let x: Option<<U as IntoIterator>::Item> = flat_map.next(); match x { Some(v) => { assert_eq!(v, i); } None => { assert!(false); } } let (lower, _): (usize, Option<usize>) = flat_map.size_hint(); assert_eq!(lower, (n - i - 1) as usize); } } assert_eq!(flat_map.next(), None::<Item>); } }
{ A { begin: 0, end: item } }
identifier_body
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } fn size_hint(&self) -> (usize, Option<usize>) { debug_assert!(self.begin <= self.end); let exact: usize = (self.end - self.begin) as usize; (exact, Some::<usize>(exact)) } // fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> // where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, // { // FlatMap{iter: self, f: f, frontiter: None, backiter: None } // } } } } type T = u32; Iterator_impl!(T); // impl<I: Iterator> IntoIterator for I { // type Item = I::Item; // type IntoIter = I; // // fn into_iter(self) -> I { // self // } // } // impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F> // where F: FnMut(I::Item) -> U, // { // type Item = U::Item; // // #[inline] // fn next(&mut self) -> Option<U::Item> { // loop { // if let Some(ref mut inner) = self.frontiter { // if let Some(x) = inner.by_ref().next() { // return Some(x) // } // } // match self.iter.next().map(|x| (self.f)(x)) { // None => return self.backiter.as_mut().and_then(|it| it.next()), // next => self.frontiter = next.map(IntoIterator::into_iter), // } // } // } // // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { // let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let lo = flo.saturating_add(blo); // match (self.iter.size_hint(), fhi, bhi) { // ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)), // _ => (lo, None) // } // } // } struct F; type Item = T; type U = A<T>; type Args = (Item,); impl FnOnce<Args> for F { type Output = U; extern "rust-call" fn call_once(self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } impl FnMut<Args> for F { extern "rust-call" fn call_mut(&mut self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } #[test] fn size_hint_test1() { let a: A<T> = A { begin: 0, end: 10 }; let f: F = F; let mut flat_map: FlatMap<A<T>, U, F> = a.flat_map::<U, F>(f); for n in 0.. 10 {
for i in 0..n { let x: Option<<U as IntoIterator>::Item> = flat_map.next(); match x { Some(v) => { assert_eq!(v, i); } None => { assert!(false); } } let (lower, _): (usize, Option<usize>) = flat_map.size_hint(); assert_eq!(lower, (n - i - 1) as usize); } } assert_eq!(flat_map.next(), None::<Item>); } }
random_line_split
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct
<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } fn size_hint(&self) -> (usize, Option<usize>) { debug_assert!(self.begin <= self.end); let exact: usize = (self.end - self.begin) as usize; (exact, Some::<usize>(exact)) } // fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> // where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, // { // FlatMap{iter: self, f: f, frontiter: None, backiter: None } // } } } } type T = u32; Iterator_impl!(T); // impl<I: Iterator> IntoIterator for I { // type Item = I::Item; // type IntoIter = I; // // fn into_iter(self) -> I { // self // } // } // impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F> // where F: FnMut(I::Item) -> U, // { // type Item = U::Item; // // #[inline] // fn next(&mut self) -> Option<U::Item> { // loop { // if let Some(ref mut inner) = self.frontiter { // if let Some(x) = inner.by_ref().next() { // return Some(x) // } // } // match self.iter.next().map(|x| (self.f)(x)) { // None => return self.backiter.as_mut().and_then(|it| it.next()), // next => self.frontiter = next.map(IntoIterator::into_iter), // } // } // } // // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { // let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let lo = flo.saturating_add(blo); // match (self.iter.size_hint(), fhi, bhi) { // ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)), // _ => (lo, None) // } // } // } struct F; type Item = T; type U = A<T>; type Args = (Item,); impl FnOnce<Args> for F { type Output = U; extern "rust-call" fn call_once(self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } impl FnMut<Args> for F { extern "rust-call" fn call_mut(&mut self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } #[test] fn size_hint_test1() { let a: A<T> = A { begin: 0, end: 10 }; let f: F = F; let mut flat_map: FlatMap<A<T>, U, F> = a.flat_map::<U, F>(f); for n in 0.. 10 { for i in 0..n { let x: Option<<U as IntoIterator>::Item> = flat_map.next(); match x { Some(v) => { assert_eq!(v, i); } None => { assert!(false); } } let (lower, _): (usize, Option<usize>) = flat_map.size_hint(); assert_eq!(lower, (n - i - 1) as usize); } } assert_eq!(flat_map.next(), None::<Item>); } }
A
identifier_name
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } fn size_hint(&self) -> (usize, Option<usize>) { debug_assert!(self.begin <= self.end); let exact: usize = (self.end - self.begin) as usize; (exact, Some::<usize>(exact)) } // fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> // where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, // { // FlatMap{iter: self, f: f, frontiter: None, backiter: None } // } } } } type T = u32; Iterator_impl!(T); // impl<I: Iterator> IntoIterator for I { // type Item = I::Item; // type IntoIter = I; // // fn into_iter(self) -> I { // self // } // } // impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F> // where F: FnMut(I::Item) -> U, // { // type Item = U::Item; // // #[inline] // fn next(&mut self) -> Option<U::Item> { // loop { // if let Some(ref mut inner) = self.frontiter { // if let Some(x) = inner.by_ref().next() { // return Some(x) // } // } // match self.iter.next().map(|x| (self.f)(x)) { // None => return self.backiter.as_mut().and_then(|it| it.next()), // next => self.frontiter = next.map(IntoIterator::into_iter), // } // } // } // // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { // let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); // let lo = flo.saturating_add(blo); // match (self.iter.size_hint(), fhi, bhi) { // ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)), // _ => (lo, None) // } // } // } struct F; type Item = T; type U = A<T>; type Args = (Item,); impl FnOnce<Args> for F { type Output = U; extern "rust-call" fn call_once(self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } impl FnMut<Args> for F { extern "rust-call" fn call_mut(&mut self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } #[test] fn size_hint_test1() { let a: A<T> = A { begin: 0, end: 10 }; let f: F = F; let mut flat_map: FlatMap<A<T>, U, F> = a.flat_map::<U, F>(f); for n in 0.. 10 { for i in 0..n { let x: Option<<U as IntoIterator>::Item> = flat_map.next(); match x { Some(v) => { assert_eq!(v, i); } None =>
} let (lower, _): (usize, Option<usize>) = flat_map.size_hint(); assert_eq!(lower, (n - i - 1) as usize); } } assert_eq!(flat_map.next(), None::<Item>); } }
{ assert!(false); }
conditional_block
num.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. //! Integer and floating-point number formatting // FIXME: #6220 Implement floating point formatting #![allow(unsigned_negation)] use fmt; use iter::IteratorExt; use num::{Int, cast}; use slice::SliceExt; use str; /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { /// The number of digits. fn base(&self) -> u8; /// A radix-specific prefix string. fn prefix(&self) -> &'static str { "" } /// Converts an integer to corresponding radix digit. fn digit(&self, x: u8) -> u8; /// Format an integer using the radix using a formatter. fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 64 // characters for a base 2 number. let zero = Int::zero(); let is_positive = x >= zero; let mut buf = [0; 64]; let mut curr = buf.len(); let base = cast(self.base()).unwrap(); if is_positive { // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } } else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = zero - (x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } } let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) }; f.pad_integral(is_positive, self.prefix(), buf) } } /// A binary (base 2) radix #[derive(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[derive(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[derive(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[derive(Clone, PartialEq)] struct LowerHex; /// A hexadecimal (base 16) radix, formatted with upper-case characters #[derive(Clone, PartialEq)] struct UpperHex; macro_rules! radix { ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { impl GenericRadix for $T { fn base(&self) -> u8 { $base } fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } } } } } radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x } radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x } radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x } radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'a' + (x - 10) } radix! { UpperHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'A' + (x - 10) } /// A radix with in the range of `2..36`. #[derive(Clone, Copy, PartialEq)] #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub struct Radix { base: u8, } impl Radix { fn new(base: u8) -> Radix { assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base); Radix { base: base } } } impl GenericRadix for Radix { fn base(&self) -> u8 { self.base } fn
(&self, x: u8) -> u8 { match x { x @ 0... 9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } } } /// A helper type for formatting radixes. #[unstable(feature = "core", reason = "may be renamed or move to a different module")] #[derive(Copy)] pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Examples /// /// ``` /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string()); /// ``` #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } } } } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) } } } } macro_rules! debug { ($T:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } } } macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base! { Display for $Int as $Int -> Decimal } int_base! { Binary for $Int as $Uint -> Binary } int_base! { Octal for $Int as $Uint -> Octal } int_base! { LowerHex for $Int as $Uint -> LowerHex } int_base! { UpperHex for $Int as $Uint -> UpperHex } radix_fmt! { $Int as $Int, fmt_int } debug! { $Int } int_base! { Display for $Uint as $Uint -> Decimal } int_base! { Binary for $Uint as $Uint -> Binary } int_base! { Octal for $Uint as $Uint -> Octal } int_base! { LowerHex for $Uint as $Uint -> LowerHex } int_base! { UpperHex for $Uint as $Uint -> UpperHex } radix_fmt! { $Uint as $Uint, fmt_int } debug! { $Uint } } } integer! { isize, usize } integer! { i8, u8 } integer! { i16, u16 } integer! { i32, u32 } integer! { i64, u64 }
digit
identifier_name
num.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. //! Integer and floating-point number formatting // FIXME: #6220 Implement floating point formatting #![allow(unsigned_negation)] use fmt; use iter::IteratorExt; use num::{Int, cast}; use slice::SliceExt; use str; /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { /// The number of digits. fn base(&self) -> u8; /// A radix-specific prefix string. fn prefix(&self) -> &'static str { "" } /// Converts an integer to corresponding radix digit. fn digit(&self, x: u8) -> u8; /// Format an integer using the radix using a formatter. fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 64 // characters for a base 2 number. let zero = Int::zero(); let is_positive = x >= zero; let mut buf = [0; 64]; let mut curr = buf.len(); let base = cast(self.base()).unwrap(); if is_positive { // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } } else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = zero - (x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } } let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) }; f.pad_integral(is_positive, self.prefix(), buf) } } /// A binary (base 2) radix #[derive(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[derive(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[derive(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[derive(Clone, PartialEq)] struct LowerHex; /// A hexadecimal (base 16) radix, formatted with upper-case characters #[derive(Clone, PartialEq)] struct UpperHex; macro_rules! radix { ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { impl GenericRadix for $T { fn base(&self) -> u8 { $base } fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } } } } } radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x } radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x } radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x } radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'a' + (x - 10) } radix! { UpperHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'A' + (x - 10) } /// A radix with in the range of `2..36`. #[derive(Clone, Copy, PartialEq)] #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub struct Radix { base: u8, } impl Radix { fn new(base: u8) -> Radix { assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base); Radix { base: base } } } impl GenericRadix for Radix { fn base(&self) -> u8 { self.base } fn digit(&self, x: u8) -> u8
} /// A helper type for formatting radixes. #[unstable(feature = "core", reason = "may be renamed or move to a different module")] #[derive(Copy)] pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Examples /// /// ``` /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string()); /// ``` #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } } } } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) } } } } macro_rules! debug { ($T:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } } } macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base! { Display for $Int as $Int -> Decimal } int_base! { Binary for $Int as $Uint -> Binary } int_base! { Octal for $Int as $Uint -> Octal } int_base! { LowerHex for $Int as $Uint -> LowerHex } int_base! { UpperHex for $Int as $Uint -> UpperHex } radix_fmt! { $Int as $Int, fmt_int } debug! { $Int } int_base! { Display for $Uint as $Uint -> Decimal } int_base! { Binary for $Uint as $Uint -> Binary } int_base! { Octal for $Uint as $Uint -> Octal } int_base! { LowerHex for $Uint as $Uint -> LowerHex } int_base! { UpperHex for $Uint as $Uint -> UpperHex } radix_fmt! { $Uint as $Uint, fmt_int } debug! { $Uint } } } integer! { isize, usize } integer! { i8, u8 } integer! { i16, u16 } integer! { i32, u32 } integer! { i64, u64 }
{ match x { x @ 0 ... 9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } }
identifier_body
num.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. //! Integer and floating-point number formatting // FIXME: #6220 Implement floating point formatting #![allow(unsigned_negation)] use fmt; use iter::IteratorExt; use num::{Int, cast}; use slice::SliceExt; use str; /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { /// The number of digits. fn base(&self) -> u8; /// A radix-specific prefix string. fn prefix(&self) -> &'static str { "" } /// Converts an integer to corresponding radix digit. fn digit(&self, x: u8) -> u8; /// Format an integer using the radix using a formatter. fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 64 // characters for a base 2 number. let zero = Int::zero(); let is_positive = x >= zero; let mut buf = [0; 64]; let mut curr = buf.len(); let base = cast(self.base()).unwrap(); if is_positive { // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } } else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = zero - (x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } } let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) }; f.pad_integral(is_positive, self.prefix(), buf) } } /// A binary (base 2) radix #[derive(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[derive(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[derive(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[derive(Clone, PartialEq)] struct LowerHex; /// A hexadecimal (base 16) radix, formatted with upper-case characters #[derive(Clone, PartialEq)] struct UpperHex; macro_rules! radix { ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { impl GenericRadix for $T { fn base(&self) -> u8 { $base }
} } } } } radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x } radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x } radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x } radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'a' + (x - 10) } radix! { UpperHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'A' + (x - 10) } /// A radix with in the range of `2..36`. #[derive(Clone, Copy, PartialEq)] #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub struct Radix { base: u8, } impl Radix { fn new(base: u8) -> Radix { assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base); Radix { base: base } } } impl GenericRadix for Radix { fn base(&self) -> u8 { self.base } fn digit(&self, x: u8) -> u8 { match x { x @ 0... 9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } } } /// A helper type for formatting radixes. #[unstable(feature = "core", reason = "may be renamed or move to a different module")] #[derive(Copy)] pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Examples /// /// ``` /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string()); /// ``` #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } } } } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) } } } } macro_rules! debug { ($T:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } } } macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base! { Display for $Int as $Int -> Decimal } int_base! { Binary for $Int as $Uint -> Binary } int_base! { Octal for $Int as $Uint -> Octal } int_base! { LowerHex for $Int as $Uint -> LowerHex } int_base! { UpperHex for $Int as $Uint -> UpperHex } radix_fmt! { $Int as $Int, fmt_int } debug! { $Int } int_base! { Display for $Uint as $Uint -> Decimal } int_base! { Binary for $Uint as $Uint -> Binary } int_base! { Octal for $Uint as $Uint -> Octal } int_base! { LowerHex for $Uint as $Uint -> LowerHex } int_base! { UpperHex for $Uint as $Uint -> UpperHex } radix_fmt! { $Uint as $Uint, fmt_int } debug! { $Uint } } } integer! { isize, usize } integer! { i8, u8 } integer! { i16, u16 } integer! { i32, u32 } integer! { i64, u64 }
fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
random_line_split
num.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. //! Integer and floating-point number formatting // FIXME: #6220 Implement floating point formatting #![allow(unsigned_negation)] use fmt; use iter::IteratorExt; use num::{Int, cast}; use slice::SliceExt; use str; /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { /// The number of digits. fn base(&self) -> u8; /// A radix-specific prefix string. fn prefix(&self) -> &'static str { "" } /// Converts an integer to corresponding radix digit. fn digit(&self, x: u8) -> u8; /// Format an integer using the radix using a formatter. fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 64 // characters for a base 2 number. let zero = Int::zero(); let is_positive = x >= zero; let mut buf = [0; 64]; let mut curr = buf.len(); let base = cast(self.base()).unwrap(); if is_positive
else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = zero - (x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } } let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) }; f.pad_integral(is_positive, self.prefix(), buf) } } /// A binary (base 2) radix #[derive(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[derive(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[derive(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[derive(Clone, PartialEq)] struct LowerHex; /// A hexadecimal (base 16) radix, formatted with upper-case characters #[derive(Clone, PartialEq)] struct UpperHex; macro_rules! radix { ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { impl GenericRadix for $T { fn base(&self) -> u8 { $base } fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } } } } } radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x } radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x } radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x } radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'a' + (x - 10) } radix! { UpperHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b'A' + (x - 10) } /// A radix with in the range of `2..36`. #[derive(Clone, Copy, PartialEq)] #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub struct Radix { base: u8, } impl Radix { fn new(base: u8) -> Radix { assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base); Radix { base: base } } } impl GenericRadix for Radix { fn base(&self) -> u8 { self.base } fn digit(&self, x: u8) -> u8 { match x { x @ 0... 9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } } } /// A helper type for formatting radixes. #[unstable(feature = "core", reason = "may be renamed or move to a different module")] #[derive(Copy)] pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Examples /// /// ``` /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string()); /// ``` #[unstable(feature = "core", reason = "may be renamed or move to a different module")] pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } } } } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) } } } } macro_rules! debug { ($T:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } } } macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base! { Display for $Int as $Int -> Decimal } int_base! { Binary for $Int as $Uint -> Binary } int_base! { Octal for $Int as $Uint -> Octal } int_base! { LowerHex for $Int as $Uint -> LowerHex } int_base! { UpperHex for $Int as $Uint -> UpperHex } radix_fmt! { $Int as $Int, fmt_int } debug! { $Int } int_base! { Display for $Uint as $Uint -> Decimal } int_base! { Binary for $Uint as $Uint -> Binary } int_base! { Octal for $Uint as $Uint -> Octal } int_base! { LowerHex for $Uint as $Uint -> LowerHex } int_base! { UpperHex for $Uint as $Uint -> UpperHex } radix_fmt! { $Uint as $Uint, fmt_int } debug! { $Uint } } } integer! { isize, usize } integer! { i8, u8 } integer! { i16, u16 } integer! { i32, u32 } integer! { i64, u64 }
{ // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; // Deaccumulate the number. *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer. curr -= 1; if x == zero { break }; // No more digits left to accumulate. } }
conditional_block
benchmark.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! This benchmark generates linear stack with specified parameters, and then //! measures how log it takes to convert it from Bonsai to Hg. #![deny(warnings)] use anyhow::{anyhow, Error, Result}; use blobrepo::BlobRepo; use clap::Arg; use cmdlib::args::{self, get_and_parse_opt, ArgType, MononokeMatches}; use context::CoreContext; use derived_data_utils::{derived_data_utils, POSSIBLE_DERIVED_TYPES}; use fbinit::FacebookInit; use futures::future::TryFutureExt; use futures_stats::futures03::TimedFutureExt; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use simulated_repo::{new_benchmark_repo, DelaySettings, GenManifest}; use tokio::runtime::Runtime; const ARG_SEED: &str = "seed"; const ARG_TYPE: &str = "type"; const ARG_STACK_SIZE: &str = "stack-size"; const ARG_BLOBSTORE_PUT_MEAN_SECS: &str = "blobstore-put-mean-secs"; const ARG_BLOBSTORE_PUT_STDDEV_SECS: &str = "blobstore-put-stddev-secs"; const ARG_BLOBSTORE_GET_MEAN_SECS: &str = "blobstore-get-mean-secs"; const ARG_BLOBSTORE_GET_STDDEV_SECS: &str = "blobstore-get-stddev-secs"; const ARG_USE_BACKFILL_MODE: &str = "use-backfill-mode"; pub type Normal = rand_distr::Normal<f64>; async fn run( ctx: CoreContext, repo: BlobRepo, rng_seed: u64, stack_size: usize, derived_data_type: &str, use_backfill_mode: bool, ) -> Result<(), Error> { println!("rng seed: {}", rng_seed); let mut rng = XorShiftRng::seed_from_u64(rng_seed); // reproducable Rng let mut gen = GenManifest::new(); let settings = Default::default(); let (stats, csidq) = gen .gen_stack( ctx.clone(), repo.clone(), &mut rng, &settings, None, std::iter::repeat(16).take(stack_size), ) .timed() .await; println!("stack generated: {:?} {:?}", gen.size(), stats); let csid = csidq?; let derive_utils = derived_data_utils(ctx.fb, &repo, derived_data_type)?; let (stats2, result) = if use_backfill_mode { derive_utils .backfill_batch_dangerous( ctx, repo.clone(), vec![csid], true, /* parallel */ None, /* No gaps */ ) .map_ok(|_| ()) .timed() .await } else { derive_utils .derive(ctx.clone(), repo.clone(), csid) .map_ok(|_| ()) .timed() .await }; println!("bonsai conversion: {:?}", stats2); println!("{:?} -> {:?}", csid.to_string(), result); Ok(()) } fn parse_norm_distribution( matches: &MononokeMatches, mean_key: &str, stddev_key: &str, ) -> Result<Option<Normal>, Error> { let put_mean = get_and_parse_opt(matches, mean_key); let put_stddev = get_and_parse_opt(matches, stddev_key); match (put_mean, put_stddev) { (Some(put_mean), Some(put_stddev)) => { let dist = Normal::new(put_mean, put_stddev) .map_err(|err| anyhow!("can't create normal distribution {:?}", err))?; Ok(Some(dist)) } _ => Ok(None), } } #[fbinit::main] fn main(fb: FacebookInit) -> Result<()>
.long(ARG_STACK_SIZE) .takes_value(true) .value_name(ARG_STACK_SIZE) .help("Size of the generated stack"), ) .arg( Arg::with_name(ARG_BLOBSTORE_PUT_MEAN_SECS) .long(ARG_BLOBSTORE_PUT_MEAN_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_PUT_MEAN_SECS) .help("Mean value of blobstore put calls. Will be used to emulate blobstore delay"), ) .arg( Arg::with_name(ARG_BLOBSTORE_PUT_STDDEV_SECS) .long(ARG_BLOBSTORE_PUT_STDDEV_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_PUT_STDDEV_SECS) .help( "Std deviation of blobstore put calls. Will be used to emulate blobstore delay", ), ) .arg( Arg::with_name(ARG_BLOBSTORE_GET_MEAN_SECS) .long(ARG_BLOBSTORE_GET_MEAN_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_GET_MEAN_SECS) .help("Mean value of blobstore put calls. Will be used to emulate blobstore delay"), ) .arg( Arg::with_name(ARG_BLOBSTORE_GET_STDDEV_SECS) .long(ARG_BLOBSTORE_GET_STDDEV_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_GET_STDDEV_SECS) .help( "Std deviation of blobstore put calls. Will be used to emulate blobstore delay", ), ) .arg( Arg::with_name(ARG_TYPE) .required(true) .index(1) .possible_values(POSSIBLE_DERIVED_TYPES) .help("derived data type"), ) .arg( Arg::with_name(ARG_USE_BACKFILL_MODE) .long(ARG_USE_BACKFILL_MODE) .takes_value(false) .help("Use backfilling mode while deriving"), ) .get_matches(fb)?; let logger = matches.logger(); let ctx = CoreContext::new_with_logger(fb, logger.clone()); let mut delay: DelaySettings = Default::default(); if let Some(dist) = parse_norm_distribution( &matches, ARG_BLOBSTORE_PUT_MEAN_SECS, ARG_BLOBSTORE_PUT_STDDEV_SECS, )? { delay.blobstore_put_dist = dist; } if let Some(dist) = parse_norm_distribution( &matches, ARG_BLOBSTORE_GET_MEAN_SECS, ARG_BLOBSTORE_GET_STDDEV_SECS, )? { delay.blobstore_get_dist = dist; } let repo = new_benchmark_repo(fb, delay)?; let seed = matches .value_of(ARG_SEED) .and_then(|s| s.parse::<u64>().ok()) .unwrap_or_else(rand::random); let stack_size: usize = matches .value_of(ARG_STACK_SIZE) .unwrap_or("50") .parse() .expect("stack size must be a positive integer"); let runtime = Runtime::new()?; let derived_data_type = matches .value_of(ARG_TYPE) .ok_or_else(|| anyhow!("{} not set", ARG_TYPE))?; runtime.block_on(run( ctx, repo, seed, stack_size, derived_data_type, matches.is_present(ARG_USE_BACKFILL_MODE), )) }
{ let matches = args::MononokeAppBuilder::new("mononoke benchmark") .without_arg_types(vec![ ArgType::Config, ArgType::Repo, ArgType::Tunables, ArgType::Runtime, // we construct our own runtime, so these args would do nothing ]) .with_advanced_args_hidden() .build() .arg( Arg::with_name(ARG_SEED) .short("s") .long(ARG_SEED) .takes_value(true) .value_name(ARG_SEED) .help("seed changeset generator for u64 seed"), ) .arg( Arg::with_name(ARG_STACK_SIZE)
identifier_body
benchmark.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! This benchmark generates linear stack with specified parameters, and then //! measures how log it takes to convert it from Bonsai to Hg. #![deny(warnings)] use anyhow::{anyhow, Error, Result}; use blobrepo::BlobRepo; use clap::Arg; use cmdlib::args::{self, get_and_parse_opt, ArgType, MononokeMatches}; use context::CoreContext; use derived_data_utils::{derived_data_utils, POSSIBLE_DERIVED_TYPES}; use fbinit::FacebookInit; use futures::future::TryFutureExt; use futures_stats::futures03::TimedFutureExt; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use simulated_repo::{new_benchmark_repo, DelaySettings, GenManifest}; use tokio::runtime::Runtime; const ARG_SEED: &str = "seed"; const ARG_TYPE: &str = "type"; const ARG_STACK_SIZE: &str = "stack-size"; const ARG_BLOBSTORE_PUT_MEAN_SECS: &str = "blobstore-put-mean-secs"; const ARG_BLOBSTORE_PUT_STDDEV_SECS: &str = "blobstore-put-stddev-secs"; const ARG_BLOBSTORE_GET_MEAN_SECS: &str = "blobstore-get-mean-secs"; const ARG_BLOBSTORE_GET_STDDEV_SECS: &str = "blobstore-get-stddev-secs"; const ARG_USE_BACKFILL_MODE: &str = "use-backfill-mode"; pub type Normal = rand_distr::Normal<f64>; async fn
( ctx: CoreContext, repo: BlobRepo, rng_seed: u64, stack_size: usize, derived_data_type: &str, use_backfill_mode: bool, ) -> Result<(), Error> { println!("rng seed: {}", rng_seed); let mut rng = XorShiftRng::seed_from_u64(rng_seed); // reproducable Rng let mut gen = GenManifest::new(); let settings = Default::default(); let (stats, csidq) = gen .gen_stack( ctx.clone(), repo.clone(), &mut rng, &settings, None, std::iter::repeat(16).take(stack_size), ) .timed() .await; println!("stack generated: {:?} {:?}", gen.size(), stats); let csid = csidq?; let derive_utils = derived_data_utils(ctx.fb, &repo, derived_data_type)?; let (stats2, result) = if use_backfill_mode { derive_utils .backfill_batch_dangerous( ctx, repo.clone(), vec![csid], true, /* parallel */ None, /* No gaps */ ) .map_ok(|_| ()) .timed() .await } else { derive_utils .derive(ctx.clone(), repo.clone(), csid) .map_ok(|_| ()) .timed() .await }; println!("bonsai conversion: {:?}", stats2); println!("{:?} -> {:?}", csid.to_string(), result); Ok(()) } fn parse_norm_distribution( matches: &MononokeMatches, mean_key: &str, stddev_key: &str, ) -> Result<Option<Normal>, Error> { let put_mean = get_and_parse_opt(matches, mean_key); let put_stddev = get_and_parse_opt(matches, stddev_key); match (put_mean, put_stddev) { (Some(put_mean), Some(put_stddev)) => { let dist = Normal::new(put_mean, put_stddev) .map_err(|err| anyhow!("can't create normal distribution {:?}", err))?; Ok(Some(dist)) } _ => Ok(None), } } #[fbinit::main] fn main(fb: FacebookInit) -> Result<()> { let matches = args::MononokeAppBuilder::new("mononoke benchmark") .without_arg_types(vec![ ArgType::Config, ArgType::Repo, ArgType::Tunables, ArgType::Runtime, // we construct our own runtime, so these args would do nothing ]) .with_advanced_args_hidden() .build() .arg( Arg::with_name(ARG_SEED) .short("s") .long(ARG_SEED) .takes_value(true) .value_name(ARG_SEED) .help("seed changeset generator for u64 seed"), ) .arg( Arg::with_name(ARG_STACK_SIZE) .long(ARG_STACK_SIZE) .takes_value(true) .value_name(ARG_STACK_SIZE) .help("Size of the generated stack"), ) .arg( Arg::with_name(ARG_BLOBSTORE_PUT_MEAN_SECS) .long(ARG_BLOBSTORE_PUT_MEAN_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_PUT_MEAN_SECS) .help("Mean value of blobstore put calls. Will be used to emulate blobstore delay"), ) .arg( Arg::with_name(ARG_BLOBSTORE_PUT_STDDEV_SECS) .long(ARG_BLOBSTORE_PUT_STDDEV_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_PUT_STDDEV_SECS) .help( "Std deviation of blobstore put calls. Will be used to emulate blobstore delay", ), ) .arg( Arg::with_name(ARG_BLOBSTORE_GET_MEAN_SECS) .long(ARG_BLOBSTORE_GET_MEAN_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_GET_MEAN_SECS) .help("Mean value of blobstore put calls. Will be used to emulate blobstore delay"), ) .arg( Arg::with_name(ARG_BLOBSTORE_GET_STDDEV_SECS) .long(ARG_BLOBSTORE_GET_STDDEV_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_GET_STDDEV_SECS) .help( "Std deviation of blobstore put calls. Will be used to emulate blobstore delay", ), ) .arg( Arg::with_name(ARG_TYPE) .required(true) .index(1) .possible_values(POSSIBLE_DERIVED_TYPES) .help("derived data type"), ) .arg( Arg::with_name(ARG_USE_BACKFILL_MODE) .long(ARG_USE_BACKFILL_MODE) .takes_value(false) .help("Use backfilling mode while deriving"), ) .get_matches(fb)?; let logger = matches.logger(); let ctx = CoreContext::new_with_logger(fb, logger.clone()); let mut delay: DelaySettings = Default::default(); if let Some(dist) = parse_norm_distribution( &matches, ARG_BLOBSTORE_PUT_MEAN_SECS, ARG_BLOBSTORE_PUT_STDDEV_SECS, )? { delay.blobstore_put_dist = dist; } if let Some(dist) = parse_norm_distribution( &matches, ARG_BLOBSTORE_GET_MEAN_SECS, ARG_BLOBSTORE_GET_STDDEV_SECS, )? { delay.blobstore_get_dist = dist; } let repo = new_benchmark_repo(fb, delay)?; let seed = matches .value_of(ARG_SEED) .and_then(|s| s.parse::<u64>().ok()) .unwrap_or_else(rand::random); let stack_size: usize = matches .value_of(ARG_STACK_SIZE) .unwrap_or("50") .parse() .expect("stack size must be a positive integer"); let runtime = Runtime::new()?; let derived_data_type = matches .value_of(ARG_TYPE) .ok_or_else(|| anyhow!("{} not set", ARG_TYPE))?; runtime.block_on(run( ctx, repo, seed, stack_size, derived_data_type, matches.is_present(ARG_USE_BACKFILL_MODE), )) }
run
identifier_name
benchmark.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! This benchmark generates linear stack with specified parameters, and then //! measures how log it takes to convert it from Bonsai to Hg. #![deny(warnings)] use anyhow::{anyhow, Error, Result}; use blobrepo::BlobRepo; use clap::Arg; use cmdlib::args::{self, get_and_parse_opt, ArgType, MononokeMatches}; use context::CoreContext; use derived_data_utils::{derived_data_utils, POSSIBLE_DERIVED_TYPES}; use fbinit::FacebookInit; use futures::future::TryFutureExt; use futures_stats::futures03::TimedFutureExt; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use simulated_repo::{new_benchmark_repo, DelaySettings, GenManifest}; use tokio::runtime::Runtime; const ARG_SEED: &str = "seed"; const ARG_TYPE: &str = "type"; const ARG_STACK_SIZE: &str = "stack-size"; const ARG_BLOBSTORE_PUT_MEAN_SECS: &str = "blobstore-put-mean-secs"; const ARG_BLOBSTORE_PUT_STDDEV_SECS: &str = "blobstore-put-stddev-secs"; const ARG_BLOBSTORE_GET_MEAN_SECS: &str = "blobstore-get-mean-secs"; const ARG_BLOBSTORE_GET_STDDEV_SECS: &str = "blobstore-get-stddev-secs"; const ARG_USE_BACKFILL_MODE: &str = "use-backfill-mode"; pub type Normal = rand_distr::Normal<f64>; async fn run( ctx: CoreContext, repo: BlobRepo, rng_seed: u64, stack_size: usize, derived_data_type: &str, use_backfill_mode: bool, ) -> Result<(), Error> {
let mut gen = GenManifest::new(); let settings = Default::default(); let (stats, csidq) = gen .gen_stack( ctx.clone(), repo.clone(), &mut rng, &settings, None, std::iter::repeat(16).take(stack_size), ) .timed() .await; println!("stack generated: {:?} {:?}", gen.size(), stats); let csid = csidq?; let derive_utils = derived_data_utils(ctx.fb, &repo, derived_data_type)?; let (stats2, result) = if use_backfill_mode { derive_utils .backfill_batch_dangerous( ctx, repo.clone(), vec![csid], true, /* parallel */ None, /* No gaps */ ) .map_ok(|_| ()) .timed() .await } else { derive_utils .derive(ctx.clone(), repo.clone(), csid) .map_ok(|_| ()) .timed() .await }; println!("bonsai conversion: {:?}", stats2); println!("{:?} -> {:?}", csid.to_string(), result); Ok(()) } fn parse_norm_distribution( matches: &MononokeMatches, mean_key: &str, stddev_key: &str, ) -> Result<Option<Normal>, Error> { let put_mean = get_and_parse_opt(matches, mean_key); let put_stddev = get_and_parse_opt(matches, stddev_key); match (put_mean, put_stddev) { (Some(put_mean), Some(put_stddev)) => { let dist = Normal::new(put_mean, put_stddev) .map_err(|err| anyhow!("can't create normal distribution {:?}", err))?; Ok(Some(dist)) } _ => Ok(None), } } #[fbinit::main] fn main(fb: FacebookInit) -> Result<()> { let matches = args::MononokeAppBuilder::new("mononoke benchmark") .without_arg_types(vec![ ArgType::Config, ArgType::Repo, ArgType::Tunables, ArgType::Runtime, // we construct our own runtime, so these args would do nothing ]) .with_advanced_args_hidden() .build() .arg( Arg::with_name(ARG_SEED) .short("s") .long(ARG_SEED) .takes_value(true) .value_name(ARG_SEED) .help("seed changeset generator for u64 seed"), ) .arg( Arg::with_name(ARG_STACK_SIZE) .long(ARG_STACK_SIZE) .takes_value(true) .value_name(ARG_STACK_SIZE) .help("Size of the generated stack"), ) .arg( Arg::with_name(ARG_BLOBSTORE_PUT_MEAN_SECS) .long(ARG_BLOBSTORE_PUT_MEAN_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_PUT_MEAN_SECS) .help("Mean value of blobstore put calls. Will be used to emulate blobstore delay"), ) .arg( Arg::with_name(ARG_BLOBSTORE_PUT_STDDEV_SECS) .long(ARG_BLOBSTORE_PUT_STDDEV_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_PUT_STDDEV_SECS) .help( "Std deviation of blobstore put calls. Will be used to emulate blobstore delay", ), ) .arg( Arg::with_name(ARG_BLOBSTORE_GET_MEAN_SECS) .long(ARG_BLOBSTORE_GET_MEAN_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_GET_MEAN_SECS) .help("Mean value of blobstore put calls. Will be used to emulate blobstore delay"), ) .arg( Arg::with_name(ARG_BLOBSTORE_GET_STDDEV_SECS) .long(ARG_BLOBSTORE_GET_STDDEV_SECS) .takes_value(true) .value_name(ARG_BLOBSTORE_GET_STDDEV_SECS) .help( "Std deviation of blobstore put calls. Will be used to emulate blobstore delay", ), ) .arg( Arg::with_name(ARG_TYPE) .required(true) .index(1) .possible_values(POSSIBLE_DERIVED_TYPES) .help("derived data type"), ) .arg( Arg::with_name(ARG_USE_BACKFILL_MODE) .long(ARG_USE_BACKFILL_MODE) .takes_value(false) .help("Use backfilling mode while deriving"), ) .get_matches(fb)?; let logger = matches.logger(); let ctx = CoreContext::new_with_logger(fb, logger.clone()); let mut delay: DelaySettings = Default::default(); if let Some(dist) = parse_norm_distribution( &matches, ARG_BLOBSTORE_PUT_MEAN_SECS, ARG_BLOBSTORE_PUT_STDDEV_SECS, )? { delay.blobstore_put_dist = dist; } if let Some(dist) = parse_norm_distribution( &matches, ARG_BLOBSTORE_GET_MEAN_SECS, ARG_BLOBSTORE_GET_STDDEV_SECS, )? { delay.blobstore_get_dist = dist; } let repo = new_benchmark_repo(fb, delay)?; let seed = matches .value_of(ARG_SEED) .and_then(|s| s.parse::<u64>().ok()) .unwrap_or_else(rand::random); let stack_size: usize = matches .value_of(ARG_STACK_SIZE) .unwrap_or("50") .parse() .expect("stack size must be a positive integer"); let runtime = Runtime::new()?; let derived_data_type = matches .value_of(ARG_TYPE) .ok_or_else(|| anyhow!("{} not set", ARG_TYPE))?; runtime.block_on(run( ctx, repo, seed, stack_size, derived_data_type, matches.is_present(ARG_USE_BACKFILL_MODE), )) }
println!("rng seed: {}", rng_seed); let mut rng = XorShiftRng::seed_from_u64(rng_seed); // reproducable Rng
random_line_split
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> MapResult {} "cool"} fn weird_comment(/* /*/ double level */ comment */ x: Hello /*/*/* tripple, even */*/*/, // Does this work? y: World ) { simple(/* does this preserve comments now? */ 42, NoWay) } fn
<T>(arg: T) -> &SomeType where T: Fn(// First arg A, // Second argument B, C, D, /* pre comment */ E /* last comment */) -> &SomeType { arg(a, b, c, d, e) } fn foo() -> ! {} pub fn http_fetch_async(listener:Box< AsyncCORSResponseListener+Send >, script_chan: Box<ScriptChan+Send>) { } fn some_func<T:Box<Trait+Bound>>(val:T){} fn zzzzzzzzzzzzzzzzzzzz<Type, NodeType> (selff: Type, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>) -> SearchStack<'a, K, V, Type, NodeType>{ } unsafe fn generic_call(cx: *mut JSContext, argc: libc::c_uint, vp: *mut JSVal, is_lenient: bool, call: unsafe extern fn(*const JSJitInfo, *mut JSContext, HandleObject, *mut libc::c_void, u32, *mut JSVal) -> u8) { let f: fn ( _, _ ) -> _ = panic!() ; } pub fn start_export_thread<C: CryptoSchemee +'static>(database: &Database, crypto_scheme: &C, block_size: usize, source_path: &Path) -> BonzoResult<mpsc::Consumer<'static, FileInstruction>> {} pub fn waltz(cwd: &Path) -> CliAssert { { { formatted_comment = rewrite_comment(comment, block_style, width, offset, formatting_fig); } } } // #2003 mod foo { fn __bindgen_test_layout_i_open0_c_open1_char_a_open2_char_close2_close1_close0_instantiation() { foo(); } }
generic
identifier_name
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> MapResult {} "cool"} fn weird_comment(/* /*/ double level */ comment */ x: Hello /*/*/* tripple, even */*/*/, // Does this work? y: World ) { simple(/* does this preserve comments now? */ 42, NoWay) } fn generic<T>(arg: T) -> &SomeType where T: Fn(// First arg A, // Second argument B, C, D, /* pre comment */ E /* last comment */) -> &SomeType { arg(a, b, c, d, e) } fn foo() -> ! {} pub fn http_fetch_async(listener:Box< AsyncCORSResponseListener+Send >, script_chan: Box<ScriptChan+Send>) { } fn some_func<T:Box<Trait+Bound>>(val:T){} fn zzzzzzzzzzzzzzzzzzzz<Type, NodeType> (selff: Type, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>) -> SearchStack<'a, K, V, Type, NodeType>{ } unsafe fn generic_call(cx: *mut JSContext, argc: libc::c_uint, vp: *mut JSVal, is_lenient: bool, call: unsafe extern fn(*const JSJitInfo, *mut JSContext, HandleObject, *mut libc::c_void, u32, *mut JSVal) -> u8) { let f: fn ( _, _ ) -> _ = panic!() ; } pub fn start_export_thread<C: CryptoSchemee +'static>(database: &Database, crypto_scheme: &C, block_size: usize, source_path: &Path) -> BonzoResult<mpsc::Consumer<'static, FileInstruction>> {} pub fn waltz(cwd: &Path) -> CliAssert { { {
// #2003 mod foo { fn __bindgen_test_layout_i_open0_c_open1_char_a_open2_char_close2_close1_close0_instantiation() { foo(); } }
formatted_comment = rewrite_comment(comment, block_style, width, offset, formatting_fig); } } }
random_line_split
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> MapResult {} "cool"} fn weird_comment(/* /*/ double level */ comment */ x: Hello /*/*/* tripple, even */*/*/, // Does this work? y: World ) { simple(/* does this preserve comments now? */ 42, NoWay) } fn generic<T>(arg: T) -> &SomeType where T: Fn(// First arg A, // Second argument B, C, D, /* pre comment */ E /* last comment */) -> &SomeType { arg(a, b, c, d, e) } fn foo() -> !
pub fn http_fetch_async(listener:Box< AsyncCORSResponseListener+Send >, script_chan: Box<ScriptChan+Send>) { } fn some_func<T:Box<Trait+Bound>>(val:T){} fn zzzzzzzzzzzzzzzzzzzz<Type, NodeType> (selff: Type, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>) -> SearchStack<'a, K, V, Type, NodeType>{ } unsafe fn generic_call(cx: *mut JSContext, argc: libc::c_uint, vp: *mut JSVal, is_lenient: bool, call: unsafe extern fn(*const JSJitInfo, *mut JSContext, HandleObject, *mut libc::c_void, u32, *mut JSVal) -> u8) { let f: fn ( _, _ ) -> _ = panic!() ; } pub fn start_export_thread<C: CryptoSchemee +'static>(database: &Database, crypto_scheme: &C, block_size: usize, source_path: &Path) -> BonzoResult<mpsc::Consumer<'static, FileInstruction>> {} pub fn waltz(cwd: &Path) -> CliAssert { { { formatted_comment = rewrite_comment(comment, block_style, width, offset, formatting_fig); } } } // #2003 mod foo { fn __bindgen_test_layout_i_open0_c_open1_char_a_open2_char_close2_close1_close0_instantiation() { foo(); } }
{}
identifier_body
lib.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/. */ #[cfg(target_os = "android")] extern crate android_injected_glue; #[cfg(target_os = "android")] extern crate android_logger; #[cfg(target_os = "android")] extern crate jni; #[cfg(any(target_os = "android", target_os = "windows"))] extern crate libc; #[macro_use] extern crate log; extern crate serde_json; extern crate servo; #[cfg(target_os = "windows")] extern crate winapi; mod api;
// If not Android, expose the C-API #[cfg(not(target_os = "android"))] mod capi; #[cfg(not(target_os = "android"))] pub use capi::*; // If Android, expose the JNI-API #[cfg(target_os = "android")] mod jniapi; #[cfg(target_os = "android")] pub use jniapi::*;
mod gl_glue;
random_line_split
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use cssparser::{Parser, RGBA}; use euclid::{TypedScale, Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError}; use style_traits::viewport::ViewportConstraints; use values::{specified, KeyframesName}; use values::computed::{self, ToComputedValue}; use values::computed::font::FontSize; /// A device is a structure that represents the current media a given document /// is displayed in. /// /// This is the struct against which media queries are evaluated. #[derive(MallocSizeOf)] pub struct Device { /// The current media type used by de device. media_type: MediaType, /// The current viewport size, in CSS pixels. viewport_size: TypedSize2D<f32, CSSPixel>, /// The current device pixel ratio, from CSS pixels to device pixels. device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, /// The font size of the root element /// This is set when computing the style of the root /// element, and used for rem units in other elements /// /// When computing the style of the root element, there can't be any /// other style being computed at the same time, given we need the style of /// the parent to compute everything else. So it is correct to just use /// a relaxed atomic here. #[ignore_malloc_size_of = "Pure stack type"] root_font_size: AtomicIsize, /// Whether any styles computed in the document relied on the root font-size /// by using rem units. #[ignore_malloc_size_of = "Pure stack type"] used_root_font_size: AtomicBool, /// Whether any styles computed in the document relied on the viewport size. #[ignore_malloc_size_of = "Pure stack type"] used_viewport_units: AtomicBool, } impl Device { /// Trivially construct a new `Device`. pub fn new( media_type: MediaType, viewport_size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel> ) -> Device { Device { media_type, viewport_size, device_pixel_ratio, // FIXME(bz): Seems dubious? root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize), used_root_font_size: AtomicBool::new(false), used_viewport_units: AtomicBool::new(false), } } /// Return the default computed values for this device. pub fn default_computed_values(&self) -> &ComputedValues { // FIXME(bz): This isn't really right, but it's no more wrong // than what we used to do. See // https://github.com/servo/servo/issues/14773 for fixing it properly. ComputedValues::initial_values() } /// Get the font size of the root element (for rem) pub fn root_font_size(&self) -> Au { self.used_root_font_size.store(true, Ordering::Relaxed); Au::new(self.root_font_size.load(Ordering::Relaxed) as i32) } /// Set the font size of the root element (for rem) pub fn set_root_font_size(&self, size: Au) { self.root_font_size.store(size.0 as isize, Ordering::Relaxed) } /// Sets the body text color for the "inherit color from body" quirk. /// /// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk> pub fn set_body_text_color(&self, _color: RGBA) { // Servo doesn't implement this quirk (yet) } /// Whether a given animation name may be referenced from style. pub fn animation_name_may_be_referenced(&self, _: &KeyframesName) -> bool { // Assume it is, since we don't have any good way to prove it's not. true } /// Returns whether we ever looked up the root font size of the Device. pub fn used_root_font_size(&self) -> bool { self.used_root_font_size.load(Ordering::Relaxed) } /// Returns the viewport size of the current device in app units, needed, /// among other things, to resolve viewport units. #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new(Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height)) } /// Like the above, but records that we've used viewport units. pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.used_viewport_units.store(true, Ordering::Relaxed); self.au_viewport_size() } /// Whether viewport units were used since the last device change. pub fn used_viewport_units(&self) -> bool { self.used_viewport_units.load(Ordering::Relaxed) } /// Returns the device pixel ratio. pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { self.device_pixel_ratio } /// Take into account a viewport rule taken from the stylesheets. pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) { self.viewport_size = constraints.size; } /// Return the media type of the current device. pub fn media_type(&self) -> MediaType { self.media_type.clone() } /// Returns whether document colors are enabled. pub fn use_document_colors(&self) -> bool { true } /// Returns the default background color. pub fn default_background_color(&self) -> RGBA { RGBA::new(255, 255, 255, 255) } } /// A expression kind servo understands and parses. /// /// Only `pub` for unit testing, please don't use it directly! #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum ExpressionKind { /// <http://dev.w3.org/csswg/mediaqueries-3/#width> Width(Range<specified::Length>), } /// A single expression a per: /// /// <http://dev.w3.org/csswg/mediaqueries-3/#media1> #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub struct Expression(pub ExpressionKind); impl Expression { /// The kind of expression we're, just for unit testing. /// /// Eventually this will become servo-only. pub fn kind_for_testing(&self) -> &ExpressionKind { &self.0 } /// Parse a media expression of the form: /// /// ``` /// (media-feature: media-value) /// ``` /// /// Only supports width and width ranges for now. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.expect_parenthesis_block()?; input.parse_nested_block(|input| { let name = input.expect_ident_cloned()?; input.expect_colon()?; // TODO: Handle other media features Ok(Expression(match_ignore_ascii_case! { &name, "min-width" => { ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?)) }, "max-width" => { ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?)) }, "width" => { ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?)) }, _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))) })) }) } /// Evaluate this expression and return whether it matches the current /// device. pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool { let viewport_size = device.au_viewport_size(); let value = viewport_size.width; match self.0 { ExpressionKind::Width(ref range) => { match range.to_computed_range(device, quirks_mode) { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, Range::Eq(ref width) =>
, } } } } } impl ToCss for Expression { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let (s, l) = match self.0 { ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l), ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l), ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l), }; dest.write_str(s)?; l.to_css(dest)?; dest.write_char(')') } } /// An enumeration that represents a ranged value. /// /// Only public for testing, implementation details of `Expression` may change /// for Stylo. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum Range<T> { /// At least the inner value. Min(T), /// At most the inner value. Max(T), /// Exactly the inner value. Eq(T), } impl Range<specified::Length> { fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> { computed::Context::for_media_query_evaluation(device, quirks_mode, |context| { match *self { Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))), Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))), Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context))) } }) } }
{ value == *width }
conditional_block
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use cssparser::{Parser, RGBA}; use euclid::{TypedScale, Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError}; use style_traits::viewport::ViewportConstraints; use values::{specified, KeyframesName}; use values::computed::{self, ToComputedValue}; use values::computed::font::FontSize; /// A device is a structure that represents the current media a given document /// is displayed in. /// /// This is the struct against which media queries are evaluated. #[derive(MallocSizeOf)] pub struct Device { /// The current media type used by de device. media_type: MediaType, /// The current viewport size, in CSS pixels. viewport_size: TypedSize2D<f32, CSSPixel>, /// The current device pixel ratio, from CSS pixels to device pixels. device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, /// The font size of the root element /// This is set when computing the style of the root /// element, and used for rem units in other elements /// /// When computing the style of the root element, there can't be any /// other style being computed at the same time, given we need the style of /// the parent to compute everything else. So it is correct to just use /// a relaxed atomic here. #[ignore_malloc_size_of = "Pure stack type"] root_font_size: AtomicIsize, /// Whether any styles computed in the document relied on the root font-size /// by using rem units. #[ignore_malloc_size_of = "Pure stack type"] used_root_font_size: AtomicBool, /// Whether any styles computed in the document relied on the viewport size. #[ignore_malloc_size_of = "Pure stack type"] used_viewport_units: AtomicBool, } impl Device { /// Trivially construct a new `Device`. pub fn new( media_type: MediaType, viewport_size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel> ) -> Device { Device { media_type, viewport_size, device_pixel_ratio, // FIXME(bz): Seems dubious? root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize), used_root_font_size: AtomicBool::new(false), used_viewport_units: AtomicBool::new(false), } } /// Return the default computed values for this device. pub fn default_computed_values(&self) -> &ComputedValues { // FIXME(bz): This isn't really right, but it's no more wrong // than what we used to do. See // https://github.com/servo/servo/issues/14773 for fixing it properly. ComputedValues::initial_values() } /// Get the font size of the root element (for rem) pub fn root_font_size(&self) -> Au { self.used_root_font_size.store(true, Ordering::Relaxed); Au::new(self.root_font_size.load(Ordering::Relaxed) as i32) } /// Set the font size of the root element (for rem) pub fn set_root_font_size(&self, size: Au) { self.root_font_size.store(size.0 as isize, Ordering::Relaxed) } /// Sets the body text color for the "inherit color from body" quirk. /// /// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk> pub fn set_body_text_color(&self, _color: RGBA) { // Servo doesn't implement this quirk (yet) } /// Whether a given animation name may be referenced from style. pub fn animation_name_may_be_referenced(&self, _: &KeyframesName) -> bool { // Assume it is, since we don't have any good way to prove it's not. true } /// Returns whether we ever looked up the root font size of the Device. pub fn used_root_font_size(&self) -> bool { self.used_root_font_size.load(Ordering::Relaxed) } /// Returns the viewport size of the current device in app units, needed, /// among other things, to resolve viewport units. #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new(Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height)) } /// Like the above, but records that we've used viewport units. pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.used_viewport_units.store(true, Ordering::Relaxed); self.au_viewport_size() } /// Whether viewport units were used since the last device change. pub fn used_viewport_units(&self) -> bool { self.used_viewport_units.load(Ordering::Relaxed) } /// Returns the device pixel ratio. pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { self.device_pixel_ratio } /// Take into account a viewport rule taken from the stylesheets. pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) { self.viewport_size = constraints.size; } /// Return the media type of the current device. pub fn media_type(&self) -> MediaType { self.media_type.clone() } /// Returns whether document colors are enabled. pub fn use_document_colors(&self) -> bool { true } /// Returns the default background color. pub fn default_background_color(&self) -> RGBA { RGBA::new(255, 255, 255, 255) } } /// A expression kind servo understands and parses. /// /// Only `pub` for unit testing, please don't use it directly! #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum ExpressionKind { /// <http://dev.w3.org/csswg/mediaqueries-3/#width> Width(Range<specified::Length>), } /// A single expression a per: /// /// <http://dev.w3.org/csswg/mediaqueries-3/#media1> #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub struct Expression(pub ExpressionKind); impl Expression { /// The kind of expression we're, just for unit testing. /// /// Eventually this will become servo-only. pub fn kind_for_testing(&self) -> &ExpressionKind { &self.0 } /// Parse a media expression of the form: /// /// ``` /// (media-feature: media-value) /// ``` /// /// Only supports width and width ranges for now. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.expect_parenthesis_block()?; input.parse_nested_block(|input| { let name = input.expect_ident_cloned()?; input.expect_colon()?; // TODO: Handle other media features Ok(Expression(match_ignore_ascii_case! { &name, "min-width" => { ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?)) }, "max-width" => {
"width" => { ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?)) }, _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))) })) }) } /// Evaluate this expression and return whether it matches the current /// device. pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool { let viewport_size = device.au_viewport_size(); let value = viewport_size.width; match self.0 { ExpressionKind::Width(ref range) => { match range.to_computed_range(device, quirks_mode) { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, Range::Eq(ref width) => { value == *width }, } } } } } impl ToCss for Expression { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let (s, l) = match self.0 { ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l), ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l), ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l), }; dest.write_str(s)?; l.to_css(dest)?; dest.write_char(')') } } /// An enumeration that represents a ranged value. /// /// Only public for testing, implementation details of `Expression` may change /// for Stylo. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum Range<T> { /// At least the inner value. Min(T), /// At most the inner value. Max(T), /// Exactly the inner value. Eq(T), } impl Range<specified::Length> { fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> { computed::Context::for_media_query_evaluation(device, quirks_mode, |context| { match *self { Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))), Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))), Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context))) } }) } }
ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?)) },
random_line_split
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use cssparser::{Parser, RGBA}; use euclid::{TypedScale, Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError}; use style_traits::viewport::ViewportConstraints; use values::{specified, KeyframesName}; use values::computed::{self, ToComputedValue}; use values::computed::font::FontSize; /// A device is a structure that represents the current media a given document /// is displayed in. /// /// This is the struct against which media queries are evaluated. #[derive(MallocSizeOf)] pub struct Device { /// The current media type used by de device. media_type: MediaType, /// The current viewport size, in CSS pixels. viewport_size: TypedSize2D<f32, CSSPixel>, /// The current device pixel ratio, from CSS pixels to device pixels. device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, /// The font size of the root element /// This is set when computing the style of the root /// element, and used for rem units in other elements /// /// When computing the style of the root element, there can't be any /// other style being computed at the same time, given we need the style of /// the parent to compute everything else. So it is correct to just use /// a relaxed atomic here. #[ignore_malloc_size_of = "Pure stack type"] root_font_size: AtomicIsize, /// Whether any styles computed in the document relied on the root font-size /// by using rem units. #[ignore_malloc_size_of = "Pure stack type"] used_root_font_size: AtomicBool, /// Whether any styles computed in the document relied on the viewport size. #[ignore_malloc_size_of = "Pure stack type"] used_viewport_units: AtomicBool, } impl Device { /// Trivially construct a new `Device`. pub fn new( media_type: MediaType, viewport_size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel> ) -> Device { Device { media_type, viewport_size, device_pixel_ratio, // FIXME(bz): Seems dubious? root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize), used_root_font_size: AtomicBool::new(false), used_viewport_units: AtomicBool::new(false), } } /// Return the default computed values for this device. pub fn default_computed_values(&self) -> &ComputedValues { // FIXME(bz): This isn't really right, but it's no more wrong // than what we used to do. See // https://github.com/servo/servo/issues/14773 for fixing it properly. ComputedValues::initial_values() } /// Get the font size of the root element (for rem) pub fn root_font_size(&self) -> Au { self.used_root_font_size.store(true, Ordering::Relaxed); Au::new(self.root_font_size.load(Ordering::Relaxed) as i32) } /// Set the font size of the root element (for rem) pub fn set_root_font_size(&self, size: Au) { self.root_font_size.store(size.0 as isize, Ordering::Relaxed) } /// Sets the body text color for the "inherit color from body" quirk. /// /// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk> pub fn set_body_text_color(&self, _color: RGBA) { // Servo doesn't implement this quirk (yet) } /// Whether a given animation name may be referenced from style. pub fn animation_name_may_be_referenced(&self, _: &KeyframesName) -> bool { // Assume it is, since we don't have any good way to prove it's not. true } /// Returns whether we ever looked up the root font size of the Device. pub fn used_root_font_size(&self) -> bool { self.used_root_font_size.load(Ordering::Relaxed) } /// Returns the viewport size of the current device in app units, needed, /// among other things, to resolve viewport units. #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new(Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height)) } /// Like the above, but records that we've used viewport units. pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.used_viewport_units.store(true, Ordering::Relaxed); self.au_viewport_size() } /// Whether viewport units were used since the last device change. pub fn used_viewport_units(&self) -> bool { self.used_viewport_units.load(Ordering::Relaxed) } /// Returns the device pixel ratio. pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel>
/// Take into account a viewport rule taken from the stylesheets. pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) { self.viewport_size = constraints.size; } /// Return the media type of the current device. pub fn media_type(&self) -> MediaType { self.media_type.clone() } /// Returns whether document colors are enabled. pub fn use_document_colors(&self) -> bool { true } /// Returns the default background color. pub fn default_background_color(&self) -> RGBA { RGBA::new(255, 255, 255, 255) } } /// A expression kind servo understands and parses. /// /// Only `pub` for unit testing, please don't use it directly! #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum ExpressionKind { /// <http://dev.w3.org/csswg/mediaqueries-3/#width> Width(Range<specified::Length>), } /// A single expression a per: /// /// <http://dev.w3.org/csswg/mediaqueries-3/#media1> #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub struct Expression(pub ExpressionKind); impl Expression { /// The kind of expression we're, just for unit testing. /// /// Eventually this will become servo-only. pub fn kind_for_testing(&self) -> &ExpressionKind { &self.0 } /// Parse a media expression of the form: /// /// ``` /// (media-feature: media-value) /// ``` /// /// Only supports width and width ranges for now. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.expect_parenthesis_block()?; input.parse_nested_block(|input| { let name = input.expect_ident_cloned()?; input.expect_colon()?; // TODO: Handle other media features Ok(Expression(match_ignore_ascii_case! { &name, "min-width" => { ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?)) }, "max-width" => { ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?)) }, "width" => { ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?)) }, _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))) })) }) } /// Evaluate this expression and return whether it matches the current /// device. pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool { let viewport_size = device.au_viewport_size(); let value = viewport_size.width; match self.0 { ExpressionKind::Width(ref range) => { match range.to_computed_range(device, quirks_mode) { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, Range::Eq(ref width) => { value == *width }, } } } } } impl ToCss for Expression { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let (s, l) = match self.0 { ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l), ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l), ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l), }; dest.write_str(s)?; l.to_css(dest)?; dest.write_char(')') } } /// An enumeration that represents a ranged value. /// /// Only public for testing, implementation details of `Expression` may change /// for Stylo. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum Range<T> { /// At least the inner value. Min(T), /// At most the inner value. Max(T), /// Exactly the inner value. Eq(T), } impl Range<specified::Length> { fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> { computed::Context::for_media_query_evaluation(device, quirks_mode, |context| { match *self { Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))), Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))), Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context))) } }) } }
{ self.device_pixel_ratio }
identifier_body
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use cssparser::{Parser, RGBA}; use euclid::{TypedScale, Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError}; use style_traits::viewport::ViewportConstraints; use values::{specified, KeyframesName}; use values::computed::{self, ToComputedValue}; use values::computed::font::FontSize; /// A device is a structure that represents the current media a given document /// is displayed in. /// /// This is the struct against which media queries are evaluated. #[derive(MallocSizeOf)] pub struct Device { /// The current media type used by de device. media_type: MediaType, /// The current viewport size, in CSS pixels. viewport_size: TypedSize2D<f32, CSSPixel>, /// The current device pixel ratio, from CSS pixels to device pixels. device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, /// The font size of the root element /// This is set when computing the style of the root /// element, and used for rem units in other elements /// /// When computing the style of the root element, there can't be any /// other style being computed at the same time, given we need the style of /// the parent to compute everything else. So it is correct to just use /// a relaxed atomic here. #[ignore_malloc_size_of = "Pure stack type"] root_font_size: AtomicIsize, /// Whether any styles computed in the document relied on the root font-size /// by using rem units. #[ignore_malloc_size_of = "Pure stack type"] used_root_font_size: AtomicBool, /// Whether any styles computed in the document relied on the viewport size. #[ignore_malloc_size_of = "Pure stack type"] used_viewport_units: AtomicBool, } impl Device { /// Trivially construct a new `Device`. pub fn new( media_type: MediaType, viewport_size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel> ) -> Device { Device { media_type, viewport_size, device_pixel_ratio, // FIXME(bz): Seems dubious? root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize), used_root_font_size: AtomicBool::new(false), used_viewport_units: AtomicBool::new(false), } } /// Return the default computed values for this device. pub fn default_computed_values(&self) -> &ComputedValues { // FIXME(bz): This isn't really right, but it's no more wrong // than what we used to do. See // https://github.com/servo/servo/issues/14773 for fixing it properly. ComputedValues::initial_values() } /// Get the font size of the root element (for rem) pub fn root_font_size(&self) -> Au { self.used_root_font_size.store(true, Ordering::Relaxed); Au::new(self.root_font_size.load(Ordering::Relaxed) as i32) } /// Set the font size of the root element (for rem) pub fn set_root_font_size(&self, size: Au) { self.root_font_size.store(size.0 as isize, Ordering::Relaxed) } /// Sets the body text color for the "inherit color from body" quirk. /// /// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk> pub fn
(&self, _color: RGBA) { // Servo doesn't implement this quirk (yet) } /// Whether a given animation name may be referenced from style. pub fn animation_name_may_be_referenced(&self, _: &KeyframesName) -> bool { // Assume it is, since we don't have any good way to prove it's not. true } /// Returns whether we ever looked up the root font size of the Device. pub fn used_root_font_size(&self) -> bool { self.used_root_font_size.load(Ordering::Relaxed) } /// Returns the viewport size of the current device in app units, needed, /// among other things, to resolve viewport units. #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new(Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height)) } /// Like the above, but records that we've used viewport units. pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.used_viewport_units.store(true, Ordering::Relaxed); self.au_viewport_size() } /// Whether viewport units were used since the last device change. pub fn used_viewport_units(&self) -> bool { self.used_viewport_units.load(Ordering::Relaxed) } /// Returns the device pixel ratio. pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { self.device_pixel_ratio } /// Take into account a viewport rule taken from the stylesheets. pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) { self.viewport_size = constraints.size; } /// Return the media type of the current device. pub fn media_type(&self) -> MediaType { self.media_type.clone() } /// Returns whether document colors are enabled. pub fn use_document_colors(&self) -> bool { true } /// Returns the default background color. pub fn default_background_color(&self) -> RGBA { RGBA::new(255, 255, 255, 255) } } /// A expression kind servo understands and parses. /// /// Only `pub` for unit testing, please don't use it directly! #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum ExpressionKind { /// <http://dev.w3.org/csswg/mediaqueries-3/#width> Width(Range<specified::Length>), } /// A single expression a per: /// /// <http://dev.w3.org/csswg/mediaqueries-3/#media1> #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub struct Expression(pub ExpressionKind); impl Expression { /// The kind of expression we're, just for unit testing. /// /// Eventually this will become servo-only. pub fn kind_for_testing(&self) -> &ExpressionKind { &self.0 } /// Parse a media expression of the form: /// /// ``` /// (media-feature: media-value) /// ``` /// /// Only supports width and width ranges for now. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.expect_parenthesis_block()?; input.parse_nested_block(|input| { let name = input.expect_ident_cloned()?; input.expect_colon()?; // TODO: Handle other media features Ok(Expression(match_ignore_ascii_case! { &name, "min-width" => { ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?)) }, "max-width" => { ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?)) }, "width" => { ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?)) }, _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))) })) }) } /// Evaluate this expression and return whether it matches the current /// device. pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool { let viewport_size = device.au_viewport_size(); let value = viewport_size.width; match self.0 { ExpressionKind::Width(ref range) => { match range.to_computed_range(device, quirks_mode) { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, Range::Eq(ref width) => { value == *width }, } } } } } impl ToCss for Expression { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let (s, l) = match self.0 { ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l), ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l), ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l), }; dest.write_str(s)?; l.to_css(dest)?; dest.write_char(')') } } /// An enumeration that represents a ranged value. /// /// Only public for testing, implementation details of `Expression` may change /// for Stylo. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub enum Range<T> { /// At least the inner value. Min(T), /// At most the inner value. Max(T), /// Exactly the inner value. Eq(T), } impl Range<specified::Length> { fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> { computed::Context::for_media_query_evaluation(device, quirks_mode, |context| { match *self { Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))), Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))), Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context))) } }) } }
set_body_text_color
identifier_name
domstringmap.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use crate::dom::bindings::error::ErrorResult; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::window_from_node; use dom_struct::dom_struct; #[dom_struct] pub struct DOMStringMap { reflector_: Reflector, element: Dom<HTMLElement>, } impl DOMStringMap { fn new_inherited(element: &HTMLElement) -> DOMStringMap { DOMStringMap { reflector_: Reflector::new(), element: Dom::from_ref(element), } } pub fn new(element: &HTMLElement) -> DomRoot<DOMStringMap> { let window = window_from_node(element); reflect_dom_object( Box::new(DOMStringMap::new_inherited(element)), &*window, DOMStringMapBinding::Wrap, ) } } // https://html.spec.whatwg.org/multipage/#domstringmap impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem fn NamedDeleter(&self, name: DOMString) { self.element.delete_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult
// https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString) -> Option<DOMString> { self.element.get_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.element .supported_prop_names_custom_attr() .iter() .cloned() .collect() } }
{ self.element.set_custom_attr(name, value) }
identifier_body
domstringmap.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use crate::dom::bindings::error::ErrorResult; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::window_from_node; use dom_struct::dom_struct; #[dom_struct] pub struct DOMStringMap { reflector_: Reflector, element: Dom<HTMLElement>, } impl DOMStringMap { fn new_inherited(element: &HTMLElement) -> DOMStringMap { DOMStringMap { reflector_: Reflector::new(), element: Dom::from_ref(element), } } pub fn new(element: &HTMLElement) -> DomRoot<DOMStringMap> { let window = window_from_node(element); reflect_dom_object( Box::new(DOMStringMap::new_inherited(element)), &*window, DOMStringMapBinding::Wrap, ) } } // https://html.spec.whatwg.org/multipage/#domstringmap impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem fn NamedDeleter(&self, name: DOMString) { self.element.delete_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult { self.element.set_custom_attr(name, value) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString) -> Option<DOMString> { self.element.get_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names
.cloned() .collect() } }
fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.element .supported_prop_names_custom_attr() .iter()
random_line_split
domstringmap.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use crate::dom::bindings::error::ErrorResult; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::window_from_node; use dom_struct::dom_struct; #[dom_struct] pub struct DOMStringMap { reflector_: Reflector, element: Dom<HTMLElement>, } impl DOMStringMap { fn new_inherited(element: &HTMLElement) -> DOMStringMap { DOMStringMap { reflector_: Reflector::new(), element: Dom::from_ref(element), } } pub fn
(element: &HTMLElement) -> DomRoot<DOMStringMap> { let window = window_from_node(element); reflect_dom_object( Box::new(DOMStringMap::new_inherited(element)), &*window, DOMStringMapBinding::Wrap, ) } } // https://html.spec.whatwg.org/multipage/#domstringmap impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem fn NamedDeleter(&self, name: DOMString) { self.element.delete_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult { self.element.set_custom_attr(name, value) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString) -> Option<DOMString> { self.element.get_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.element .supported_prop_names_custom_attr() .iter() .cloned() .collect() } }
new
identifier_name
tostr.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. use crate::{ bif::NativeFunc, path::ConcretePath, tree::Tree, value::{Value, ValueData}, }; use failure::{bail, Fallible}; #[derive(Clone, Debug)] pub(crate) struct
; impl NativeFunc for ToStr { fn compute(&self, value: Value, tree: &Tree) -> Fallible<Value> { Ok(Value::from_string(match value.data { ValueData::String(s) => s, ValueData::Integer(i) => format!("{}", i), ValueData::Float(f) => format!("{}", f), ValueData::Boolean(b) => format!("{}", b), ValueData::Path(p) => { let (noderef, _gen) = tree.lookup_dynamic_path(0, &p)?; self.compute(noderef.compute(tree)?, tree)?.as_string()? } ValueData::InputFlag => bail!("runtime error: InputFlag in ToStr"), })) } fn find_all_possible_inputs( &self, _value_type: (), _tree: &Tree, _out: &mut Vec<ConcretePath>, ) -> Fallible<()> { Ok(()) } fn box_clone(&self) -> Box<dyn NativeFunc + Send + Sync> { Box::new((*self).clone()) } }
ToStr
identifier_name
tostr.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. use crate::{ bif::NativeFunc, path::ConcretePath, tree::Tree, value::{Value, ValueData}, }; use failure::{bail, Fallible}; #[derive(Clone, Debug)] pub(crate) struct ToStr; impl NativeFunc for ToStr { fn compute(&self, value: Value, tree: &Tree) -> Fallible<Value> { Ok(Value::from_string(match value.data { ValueData::String(s) => s, ValueData::Integer(i) => format!("{}", i), ValueData::Float(f) => format!("{}", f), ValueData::Boolean(b) => format!("{}", b), ValueData::Path(p) => { let (noderef, _gen) = tree.lookup_dynamic_path(0, &p)?; self.compute(noderef.compute(tree)?, tree)?.as_string()? } ValueData::InputFlag => bail!("runtime error: InputFlag in ToStr"),
} fn find_all_possible_inputs( &self, _value_type: (), _tree: &Tree, _out: &mut Vec<ConcretePath>, ) -> Fallible<()> { Ok(()) } fn box_clone(&self) -> Box<dyn NativeFunc + Send + Sync> { Box::new((*self).clone()) } }
}))
random_line_split
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection; // Internal Dependencies ------------------------------------------------------ use ::command::{Command, CommandHandler}; use ::action::{ActionGroup, MessageActions}; // Command Implementation ----------------------------------------------------- pub struct Handler; impl CommandHandler for Handler { delete_command_message!(); fn run(&self, command: Command) -> ActionGroup { let response = match resolve_ip() { Ok(ip) => format!( "{} has requested my public IP address which is: {}.", command.member.nickname, ip ), Err(_) => "{} has requested my public IP address, but the lookup failed.".to_string() }; MessageActions::Send::public( &command.message, response ) } fn help(&self) -> &str { "Post the bot's current IP address onto the channel." } fn
(&self, command: Command) -> ActionGroup { MessageActions::Send::private( &command.message, "Usage: `!ip`".to_string() ) } } // Helpers -------------------------------------------------------------------- fn resolve_ip() -> Result<String, String> { let client = Client::new(); client.get("https://icanhazip.com/") .header(Connection::close()) .send() .map_err(|err| err.to_string()) .and_then(|mut res| { let mut body = String::new(); res.read_to_string(&mut body) .map_err(|err| err.to_string()) .map(|_| body) }).and_then(|body| { Ok(body.trim().to_string()) }) }
usage
identifier_name
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection; // Internal Dependencies ------------------------------------------------------ use ::command::{Command, CommandHandler}; use ::action::{ActionGroup, MessageActions}; // Command Implementation ----------------------------------------------------- pub struct Handler; impl CommandHandler for Handler { delete_command_message!(); fn run(&self, command: Command) -> ActionGroup
fn help(&self) -> &str { "Post the bot's current IP address onto the channel." } fn usage(&self, command: Command) -> ActionGroup { MessageActions::Send::private( &command.message, "Usage: `!ip`".to_string() ) } } // Helpers -------------------------------------------------------------------- fn resolve_ip() -> Result<String, String> { let client = Client::new(); client.get("https://icanhazip.com/") .header(Connection::close()) .send() .map_err(|err| err.to_string()) .and_then(|mut res| { let mut body = String::new(); res.read_to_string(&mut body) .map_err(|err| err.to_string()) .map(|_| body) }).and_then(|body| { Ok(body.trim().to_string()) }) }
{ let response = match resolve_ip() { Ok(ip) => format!( "{} has requested my public IP address which is: {}.", command.member.nickname, ip ), Err(_) => "{} has requested my public IP address, but the lookup failed.".to_string() }; MessageActions::Send::public( &command.message, response ) }
identifier_body
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection;
use ::action::{ActionGroup, MessageActions}; // Command Implementation ----------------------------------------------------- pub struct Handler; impl CommandHandler for Handler { delete_command_message!(); fn run(&self, command: Command) -> ActionGroup { let response = match resolve_ip() { Ok(ip) => format!( "{} has requested my public IP address which is: {}.", command.member.nickname, ip ), Err(_) => "{} has requested my public IP address, but the lookup failed.".to_string() }; MessageActions::Send::public( &command.message, response ) } fn help(&self) -> &str { "Post the bot's current IP address onto the channel." } fn usage(&self, command: Command) -> ActionGroup { MessageActions::Send::private( &command.message, "Usage: `!ip`".to_string() ) } } // Helpers -------------------------------------------------------------------- fn resolve_ip() -> Result<String, String> { let client = Client::new(); client.get("https://icanhazip.com/") .header(Connection::close()) .send() .map_err(|err| err.to_string()) .and_then(|mut res| { let mut body = String::new(); res.read_to_string(&mut body) .map_err(|err| err.to_string()) .map(|_| body) }).and_then(|body| { Ok(body.trim().to_string()) }) }
// Internal Dependencies ------------------------------------------------------ use ::command::{Command, CommandHandler};
random_line_split
activation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::str::DOMString; use crate::dom::element::Element; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::window_from_node; use crate::dom::window::ReflowReason; use script_layout_interface::message::ReflowGoal; use script_traits::MouseButton; /// Trait for elements with defined activation behavior pub trait Activatable { fn as_element(&self) -> &Element; // Is this particular instance of the element activatable? fn is_instance_activatable(&self) -> bool; // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps fn pre_click_activation(&self); // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps fn canceled_activation(&self); // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, event: &Event, target: &EventTarget); // https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool); // https://html.spec.whatwg.org/multipage/#concept-selector-active fn enter_formal_activation_state(&self)
fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } } /// Whether an activation was initiated via the click() method #[derive(PartialEq)] pub enum ActivationSource { FromClick, NotFromClick, } // https://html.spec.whatwg.org/multipage/#run-synthetic-click-activation-steps pub fn synthetic_click_activation( element: &Element, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool, source: ActivationSource, ) { // Step 1 if element.click_in_progress() { return; } // Step 2 element.set_click_in_progress(true); // Step 3 let activatable = element.as_maybe_activatable(); if let Some(a) = activatable { a.pre_click_activation(); } // Step 4 // https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event let win = window_from_node(element); let target = element.upcast::<EventTarget>(); let mouse = MouseEvent::new( &win, DOMString::from("click"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, Some(&win), 1, 0, 0, 0, 0, ctrl_key, shift_key, alt_key, meta_key, 0, MouseButton::Left as u16, None, None, ); let event = mouse.upcast::<Event>(); if source == ActivationSource::FromClick { event.set_trusted(false); } target.dispatch_event(event); // Step 5 if let Some(a) = activatable { if event.DefaultPrevented() { a.canceled_activation(); } else { // post click activation a.activation_behavior(event, target); } } // Step 6 element.set_click_in_progress(false); }
{ self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); }
identifier_body
activation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::Castable;
use crate::dom::element::Element; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::window_from_node; use crate::dom::window::ReflowReason; use script_layout_interface::message::ReflowGoal; use script_traits::MouseButton; /// Trait for elements with defined activation behavior pub trait Activatable { fn as_element(&self) -> &Element; // Is this particular instance of the element activatable? fn is_instance_activatable(&self) -> bool; // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps fn pre_click_activation(&self); // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps fn canceled_activation(&self); // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, event: &Event, target: &EventTarget); // https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool); // https://html.spec.whatwg.org/multipage/#concept-selector-active fn enter_formal_activation_state(&self) { self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } } /// Whether an activation was initiated via the click() method #[derive(PartialEq)] pub enum ActivationSource { FromClick, NotFromClick, } // https://html.spec.whatwg.org/multipage/#run-synthetic-click-activation-steps pub fn synthetic_click_activation( element: &Element, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool, source: ActivationSource, ) { // Step 1 if element.click_in_progress() { return; } // Step 2 element.set_click_in_progress(true); // Step 3 let activatable = element.as_maybe_activatable(); if let Some(a) = activatable { a.pre_click_activation(); } // Step 4 // https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event let win = window_from_node(element); let target = element.upcast::<EventTarget>(); let mouse = MouseEvent::new( &win, DOMString::from("click"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, Some(&win), 1, 0, 0, 0, 0, ctrl_key, shift_key, alt_key, meta_key, 0, MouseButton::Left as u16, None, None, ); let event = mouse.upcast::<Event>(); if source == ActivationSource::FromClick { event.set_trusted(false); } target.dispatch_event(event); // Step 5 if let Some(a) = activatable { if event.DefaultPrevented() { a.canceled_activation(); } else { // post click activation a.activation_behavior(event, target); } } // Step 6 element.set_click_in_progress(false); }
use crate::dom::bindings::str::DOMString;
random_line_split
activation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::str::DOMString; use crate::dom::element::Element; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::window_from_node; use crate::dom::window::ReflowReason; use script_layout_interface::message::ReflowGoal; use script_traits::MouseButton; /// Trait for elements with defined activation behavior pub trait Activatable { fn as_element(&self) -> &Element; // Is this particular instance of the element activatable? fn is_instance_activatable(&self) -> bool; // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps fn pre_click_activation(&self); // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps fn canceled_activation(&self); // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, event: &Event, target: &EventTarget); // https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool); // https://html.spec.whatwg.org/multipage/#concept-selector-active fn enter_formal_activation_state(&self) { self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } } /// Whether an activation was initiated via the click() method #[derive(PartialEq)] pub enum ActivationSource { FromClick, NotFromClick, } // https://html.spec.whatwg.org/multipage/#run-synthetic-click-activation-steps pub fn synthetic_click_activation( element: &Element, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool, source: ActivationSource, ) { // Step 1 if element.click_in_progress() { return; } // Step 2 element.set_click_in_progress(true); // Step 3 let activatable = element.as_maybe_activatable(); if let Some(a) = activatable { a.pre_click_activation(); } // Step 4 // https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event let win = window_from_node(element); let target = element.upcast::<EventTarget>(); let mouse = MouseEvent::new( &win, DOMString::from("click"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, Some(&win), 1, 0, 0, 0, 0, ctrl_key, shift_key, alt_key, meta_key, 0, MouseButton::Left as u16, None, None, ); let event = mouse.upcast::<Event>(); if source == ActivationSource::FromClick
target.dispatch_event(event); // Step 5 if let Some(a) = activatable { if event.DefaultPrevented() { a.canceled_activation(); } else { // post click activation a.activation_behavior(event, target); } } // Step 6 element.set_click_in_progress(false); }
{ event.set_trusted(false); }
conditional_block
activation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::str::DOMString; use crate::dom::element::Element; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::window_from_node; use crate::dom::window::ReflowReason; use script_layout_interface::message::ReflowGoal; use script_traits::MouseButton; /// Trait for elements with defined activation behavior pub trait Activatable { fn as_element(&self) -> &Element; // Is this particular instance of the element activatable? fn is_instance_activatable(&self) -> bool; // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps fn pre_click_activation(&self); // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps fn canceled_activation(&self); // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, event: &Event, target: &EventTarget); // https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool); // https://html.spec.whatwg.org/multipage/#concept-selector-active fn
(&self) { self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } } /// Whether an activation was initiated via the click() method #[derive(PartialEq)] pub enum ActivationSource { FromClick, NotFromClick, } // https://html.spec.whatwg.org/multipage/#run-synthetic-click-activation-steps pub fn synthetic_click_activation( element: &Element, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool, source: ActivationSource, ) { // Step 1 if element.click_in_progress() { return; } // Step 2 element.set_click_in_progress(true); // Step 3 let activatable = element.as_maybe_activatable(); if let Some(a) = activatable { a.pre_click_activation(); } // Step 4 // https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event let win = window_from_node(element); let target = element.upcast::<EventTarget>(); let mouse = MouseEvent::new( &win, DOMString::from("click"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, Some(&win), 1, 0, 0, 0, 0, ctrl_key, shift_key, alt_key, meta_key, 0, MouseButton::Left as u16, None, None, ); let event = mouse.upcast::<Event>(); if source == ActivationSource::FromClick { event.set_trusted(false); } target.dispatch_event(event); // Step 5 if let Some(a) = activatable { if event.DefaultPrevented() { a.canceled_activation(); } else { // post click activation a.activation_behavior(event, target); } } // Step 6 element.set_click_in_progress(false); }
enter_formal_activation_state
identifier_name
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport#JSON_Packets). use rustc_serialize::{json, Encodable}; use rustc_serialize::json::{Json, EncodeResult, Encoder, encode}; use std::io::{self, Read, Write}; use std::net::TcpStream; use std::string; pub trait JsonPacketStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T); fn read_json_packet(&mut self) -> io::Result<Option<Json>>; } impl JsonPacketStream for TcpStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T) { let s = encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); } fn read_json_packet<'a>(&mut self) -> io::Result<Option<Json>> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0];
}; match byte { b':' => { let packet_len_str = String::from_utf8(buffer).unwrap(); let packet_len = u64::from_str_radix(&packet_len_str, 10).unwrap(); let mut packet = String::new(); self.take(packet_len).read_to_string(&mut packet).unwrap(); println!("{}", packet); return Ok(Some(Json::from_str(&packet).unwrap())) }, c => buffer.push(c), } } } }
let byte = match try!(self.read(&mut buf)) { 0 => return Ok(None), // EOF 1 => buf[0], _ => unreachable!(),
random_line_split
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport#JSON_Packets). use rustc_serialize::{json, Encodable}; use rustc_serialize::json::{Json, EncodeResult, Encoder, encode}; use std::io::{self, Read, Write}; use std::net::TcpStream; use std::string; pub trait JsonPacketStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T); fn read_json_packet(&mut self) -> io::Result<Option<Json>>; } impl JsonPacketStream for TcpStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T) { let s = encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); } fn
<'a>(&mut self) -> io::Result<Option<Json>> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; let byte = match try!(self.read(&mut buf)) { 0 => return Ok(None), // EOF 1 => buf[0], _ => unreachable!(), }; match byte { b':' => { let packet_len_str = String::from_utf8(buffer).unwrap(); let packet_len = u64::from_str_radix(&packet_len_str, 10).unwrap(); let mut packet = String::new(); self.take(packet_len).read_to_string(&mut packet).unwrap(); println!("{}", packet); return Ok(Some(Json::from_str(&packet).unwrap())) }, c => buffer.push(c), } } } }
read_json_packet
identifier_name
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport#JSON_Packets). use rustc_serialize::{json, Encodable}; use rustc_serialize::json::{Json, EncodeResult, Encoder, encode}; use std::io::{self, Read, Write}; use std::net::TcpStream; use std::string; pub trait JsonPacketStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T); fn read_json_packet(&mut self) -> io::Result<Option<Json>>; } impl JsonPacketStream for TcpStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T)
fn read_json_packet<'a>(&mut self) -> io::Result<Option<Json>> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; let byte = match try!(self.read(&mut buf)) { 0 => return Ok(None), // EOF 1 => buf[0], _ => unreachable!(), }; match byte { b':' => { let packet_len_str = String::from_utf8(buffer).unwrap(); let packet_len = u64::from_str_radix(&packet_len_str, 10).unwrap(); let mut packet = String::new(); self.take(packet_len).read_to_string(&mut packet).unwrap(); println!("{}", packet); return Ok(Some(Json::from_str(&packet).unwrap())) }, c => buffer.push(c), } } } }
{ let s = encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); }
identifier_body
provenance.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Request Provenance use std::fmt; use ethcore::account_provider::DappId as EthDappId; use v1::types::H256; /// RPC request origin #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub enum Origin { /// RPC server (includes request origin) #[serde(rename="rpc")] Rpc(String), /// Dapps server (includes DappId) #[serde(rename="dapp")] Dapps(DappId), /// IPC server (includes session hash) #[serde(rename="ipc")] Ipc(H256), /// WS server #[serde(rename="ws")] Ws { /// Dapp id dapp: DappId, /// Session id session: H256, }, /// Signer (authorized WS server) #[serde(rename="signer")] Signer { /// Dapp id dapp: DappId, /// Session id session: H256 }, /// Unknown #[serde(rename="unknown")] Unknown, } impl Default for Origin { fn default() -> Self { Origin::Unknown } } impl fmt::Display for Origin { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Origin::Rpc(ref origin) => write!(f, "{} via RPC", origin), Origin::Dapps(ref origin) => write!(f, "Dapp {}", origin), Origin::Ipc(ref session) => write!(f, "IPC (session: {})", session), Origin::Ws { ref session, ref dapp } => write!(f, "{} via WebSocket (session: {})", dapp, session), Origin::Signer { ref session, ref dapp } => write!(f, "{} via UI (session: {})", dapp, session), Origin::Unknown => write!(f, "unknown origin"), } } } /// Dapplication Internal Id #[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)] pub struct DappId(pub String); impl fmt::Display for DappId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl Into<String> for DappId { fn into(self) -> String { self.0 } } impl From<String> for DappId { fn from(s: String) -> Self { DappId(s) } } impl<'a> From<&'a str> for DappId { fn from(s: &'a str) -> Self { DappId(s.to_owned()) } } impl From<EthDappId> for DappId { fn
(id: EthDappId) -> Self { DappId(id.into()) } } impl Into<EthDappId> for DappId { fn into(self) -> EthDappId { Into::<String>::into(self).into() } } #[cfg(test)] mod tests { use serde_json; use super::{DappId, Origin}; #[test] fn should_serialize_origin() { // given let o1 = Origin::Rpc("test service".into()); let o2 = Origin::Dapps("http://parity.io".into()); let o3 = Origin::Ipc(5.into()); let o4 = Origin::Signer { dapp: "http://parity.io".into(), session: 10.into(), }; let o5 = Origin::Unknown; let o6 = Origin::Ws { dapp: "http://parity.io".into(), session: 5.into(), }; // when let res1 = serde_json::to_string(&o1).unwrap(); let res2 = serde_json::to_string(&o2).unwrap(); let res3 = serde_json::to_string(&o3).unwrap(); let res4 = serde_json::to_string(&o4).unwrap(); let res5 = serde_json::to_string(&o5).unwrap(); let res6 = serde_json::to_string(&o6).unwrap(); // then assert_eq!(res1, r#"{"rpc":"test service"}"#); assert_eq!(res2, r#"{"dapp":"http://parity.io"}"#); assert_eq!(res3, r#"{"ipc":"0x0000000000000000000000000000000000000000000000000000000000000005"}"#); assert_eq!(res4, r#"{"signer":{"dapp":"http://parity.io","session":"0x000000000000000000000000000000000000000000000000000000000000000a"}}"#); assert_eq!(res5, r#""unknown""#); assert_eq!(res6, r#"{"ws":{"dapp":"http://parity.io","session":"0x0000000000000000000000000000000000000000000000000000000000000005"}}"#); } #[test] fn should_serialize_dapp_id() { // given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // given let id = r#""testapp""#; // when let res: DappId = serde_json::from_str(id).unwrap(); // then assert_eq!(res, DappId("testapp".into())); } }
from
identifier_name
provenance.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Request Provenance use std::fmt; use ethcore::account_provider::DappId as EthDappId; use v1::types::H256; /// RPC request origin #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub enum Origin { /// RPC server (includes request origin) #[serde(rename="rpc")] Rpc(String), /// Dapps server (includes DappId) #[serde(rename="dapp")] Dapps(DappId), /// IPC server (includes session hash) #[serde(rename="ipc")] Ipc(H256), /// WS server #[serde(rename="ws")] Ws { /// Dapp id dapp: DappId, /// Session id session: H256, }, /// Signer (authorized WS server) #[serde(rename="signer")] Signer { /// Dapp id dapp: DappId, /// Session id session: H256 }, /// Unknown #[serde(rename="unknown")] Unknown, } impl Default for Origin { fn default() -> Self { Origin::Unknown } } impl fmt::Display for Origin { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Origin::Rpc(ref origin) => write!(f, "{} via RPC", origin), Origin::Dapps(ref origin) => write!(f, "Dapp {}", origin), Origin::Ipc(ref session) => write!(f, "IPC (session: {})", session), Origin::Ws { ref session, ref dapp } => write!(f, "{} via WebSocket (session: {})", dapp, session), Origin::Signer { ref session, ref dapp } => write!(f, "{} via UI (session: {})", dapp, session), Origin::Unknown => write!(f, "unknown origin"), } } } /// Dapplication Internal Id #[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)] pub struct DappId(pub String); impl fmt::Display for DappId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl Into<String> for DappId { fn into(self) -> String { self.0 } } impl From<String> for DappId { fn from(s: String) -> Self { DappId(s) } } impl<'a> From<&'a str> for DappId { fn from(s: &'a str) -> Self { DappId(s.to_owned()) } } impl From<EthDappId> for DappId { fn from(id: EthDappId) -> Self { DappId(id.into()) } } impl Into<EthDappId> for DappId { fn into(self) -> EthDappId { Into::<String>::into(self).into() } } #[cfg(test)] mod tests { use serde_json; use super::{DappId, Origin}; #[test] fn should_serialize_origin() { // given let o1 = Origin::Rpc("test service".into()); let o2 = Origin::Dapps("http://parity.io".into()); let o3 = Origin::Ipc(5.into()); let o4 = Origin::Signer { dapp: "http://parity.io".into(), session: 10.into(), }; let o5 = Origin::Unknown; let o6 = Origin::Ws { dapp: "http://parity.io".into(), session: 5.into(), }; // when let res1 = serde_json::to_string(&o1).unwrap(); let res2 = serde_json::to_string(&o2).unwrap(); let res3 = serde_json::to_string(&o3).unwrap(); let res4 = serde_json::to_string(&o4).unwrap(); let res5 = serde_json::to_string(&o5).unwrap(); let res6 = serde_json::to_string(&o6).unwrap(); // then assert_eq!(res1, r#"{"rpc":"test service"}"#); assert_eq!(res2, r#"{"dapp":"http://parity.io"}"#); assert_eq!(res3, r#"{"ipc":"0x0000000000000000000000000000000000000000000000000000000000000005"}"#); assert_eq!(res4, r#"{"signer":{"dapp":"http://parity.io","session":"0x000000000000000000000000000000000000000000000000000000000000000a"}}"#); assert_eq!(res5, r#""unknown""#); assert_eq!(res6, r#"{"ws":{"dapp":"http://parity.io","session":"0x0000000000000000000000000000000000000000000000000000000000000005"}}"#); } #[test]
// given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // given let id = r#""testapp""#; // when let res: DappId = serde_json::from_str(id).unwrap(); // then assert_eq!(res, DappId("testapp".into())); } }
fn should_serialize_dapp_id() {
random_line_split