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
associated-types-eq-hr.rs
// Check testing of equality constraints in a higher-ranked context. pub trait TheTrait<T> { type A; fn get(&self, t: T) -> Self::A; } struct IntStruct { x: isize, } impl<'a> TheTrait<&'a isize> for IntStruct { type A = &'a isize; fn get(&self, t: &'a isize) -> &'a isize { t } } struct UintStruct { x: isize, } impl<'a> TheTrait<&'a isize> for UintStruct { type A = &'a usize; fn get(&self, t: &'a isize) -> &'a usize { panic!() } } struct Tuple {} impl<'a> TheTrait<(&'a isize, &'a isize)> for Tuple { type A = &'a isize; fn get(&self, t: (&'a isize, &'a isize)) -> &'a isize { t.0 } } fn foo<T>() where T: for<'x> TheTrait<&'x isize, A = &'x isize>, { // ok for IntStruct, but not UintStruct } fn bar<T>() where T: for<'x> TheTrait<&'x isize, A = &'x usize>, { // ok for UintStruct, but not IntStruct } fn tuple_one<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'x isize>, { // not ok for tuple, two lifetimes and we pick first } fn tuple_two<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'y isize>, { // not ok for tuple, two lifetimes and we pick second } fn tuple_three<T>() where T: for<'x> TheTrait<(&'x isize, &'x isize), A = &'x isize>, {
fn tuple_four<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize)>, { // not ok for tuple, two lifetimes, and lifetime matching is invariant } pub fn call_foo() { foo::<IntStruct>(); foo::<UintStruct>(); //~ ERROR type mismatch } pub fn call_bar() { bar::<IntStruct>(); //~ ERROR type mismatch bar::<UintStruct>(); } pub fn call_tuple_one() { tuple_one::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough //~| ERROR implementation of `TheTrait` is not general enough } pub fn call_tuple_two() { tuple_two::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough //~| ERROR implementation of `TheTrait` is not general enough } pub fn call_tuple_three() { tuple_three::<Tuple>(); } pub fn call_tuple_four() { tuple_four::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough } fn main() {}
// ok for tuple }
random_line_split
associated-types-eq-hr.rs
// Check testing of equality constraints in a higher-ranked context. pub trait TheTrait<T> { type A; fn get(&self, t: T) -> Self::A; } struct IntStruct { x: isize, } impl<'a> TheTrait<&'a isize> for IntStruct { type A = &'a isize; fn get(&self, t: &'a isize) -> &'a isize { t } } struct UintStruct { x: isize, } impl<'a> TheTrait<&'a isize> for UintStruct { type A = &'a usize; fn get(&self, t: &'a isize) -> &'a usize { panic!() } } struct Tuple {} impl<'a> TheTrait<(&'a isize, &'a isize)> for Tuple { type A = &'a isize; fn get(&self, t: (&'a isize, &'a isize)) -> &'a isize { t.0 } } fn foo<T>() where T: for<'x> TheTrait<&'x isize, A = &'x isize>, { // ok for IntStruct, but not UintStruct } fn bar<T>() where T: for<'x> TheTrait<&'x isize, A = &'x usize>, { // ok for UintStruct, but not IntStruct } fn
<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'x isize>, { // not ok for tuple, two lifetimes and we pick first } fn tuple_two<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'y isize>, { // not ok for tuple, two lifetimes and we pick second } fn tuple_three<T>() where T: for<'x> TheTrait<(&'x isize, &'x isize), A = &'x isize>, { // ok for tuple } fn tuple_four<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize)>, { // not ok for tuple, two lifetimes, and lifetime matching is invariant } pub fn call_foo() { foo::<IntStruct>(); foo::<UintStruct>(); //~ ERROR type mismatch } pub fn call_bar() { bar::<IntStruct>(); //~ ERROR type mismatch bar::<UintStruct>(); } pub fn call_tuple_one() { tuple_one::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough //~| ERROR implementation of `TheTrait` is not general enough } pub fn call_tuple_two() { tuple_two::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough //~| ERROR implementation of `TheTrait` is not general enough } pub fn call_tuple_three() { tuple_three::<Tuple>(); } pub fn call_tuple_four() { tuple_four::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough } fn main() {}
tuple_one
identifier_name
gameboy.rs
use super::cpu::*; use super::mmu::*; use super::mem_map; use std::str; pub struct Gameboy { cpu: CPU, mmu: MMU, } impl Gameboy { pub fn new(boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy { Gameboy { cpu: CPU::new(), mmu: MMU::new(boot_rom, cart_rom), } } pub fn power_up(&mut self) { println!(""); println!("####################"); // Read Name let buffer = &[ self.mmu.read(0x0134), self.mmu.read(0x0135), self.mmu.read(0x0136), self.mmu.read(0x0137), self.mmu.read(0x0138), self.mmu.read(0x0139), self.mmu.read(0x013A), self.mmu.read(0x013B), self.mmu.read(0x013C), self.mmu.read(0x013D), self.mmu.read(0x013E), self.mmu.read(0x013F), self.mmu.read(0x0140), self.mmu.read(0x0141), self.mmu.read(0x0142), self.mmu.read(0x0143) ]; let s = str::from_utf8(buffer).unwrap(); println!("Title: {}", s); // SGB Flag let sgb_flag = self.mmu.read(0x0146);
println!("Cartridge Type: {0}", mem_map::cartridge_type(cart_type)); // Cart ROM size let rom_size = self.mmu.read(0x0148); println!("ROM Size: {0}", mem_map::rom_size(rom_size)); // Cart RAM size let ram_size = self.mmu.read(0x0149); println!("RAM Size: {0}", mem_map::ram_size(ram_size)); // Destination Code let dest_code = self.mmu.read(0x014A); println!("Destination Code: {0:#x}", dest_code); // Licensee Code (New | Old) let old_code = self.mmu.read(0x014B); println!("License Code: {0:#x}", old_code); // Mask ROM Version let version = self.mmu.read(0x014C); println!("Version: {0:#x}", version); // Complement Checksum let header_check = self.mmu.read(0x014D); println!("Header Checksum: {0:#x}", header_check); // Global Checksum let global_check = (self.mmu.read(0x014E) as u16) << 8 | self.mmu.read(0x014F) as u16; println!("Global Checksum: {0:#x}", global_check); println!("####################"); println!(""); // panic!("") // Show Cartridge Information } pub fn step(&mut self) { self.cpu.step(&mut self.mmu); } }
println!("SBG Flag: {0:#x}", sgb_flag); // Cart Type let cart_type = self.mmu.read(0x0147);
random_line_split
gameboy.rs
use super::cpu::*; use super::mmu::*; use super::mem_map; use std::str; pub struct Gameboy { cpu: CPU, mmu: MMU, } impl Gameboy { pub fn
(boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy { Gameboy { cpu: CPU::new(), mmu: MMU::new(boot_rom, cart_rom), } } pub fn power_up(&mut self) { println!(""); println!("####################"); // Read Name let buffer = &[ self.mmu.read(0x0134), self.mmu.read(0x0135), self.mmu.read(0x0136), self.mmu.read(0x0137), self.mmu.read(0x0138), self.mmu.read(0x0139), self.mmu.read(0x013A), self.mmu.read(0x013B), self.mmu.read(0x013C), self.mmu.read(0x013D), self.mmu.read(0x013E), self.mmu.read(0x013F), self.mmu.read(0x0140), self.mmu.read(0x0141), self.mmu.read(0x0142), self.mmu.read(0x0143) ]; let s = str::from_utf8(buffer).unwrap(); println!("Title: {}", s); // SGB Flag let sgb_flag = self.mmu.read(0x0146); println!("SBG Flag: {0:#x}", sgb_flag); // Cart Type let cart_type = self.mmu.read(0x0147); println!("Cartridge Type: {0}", mem_map::cartridge_type(cart_type)); // Cart ROM size let rom_size = self.mmu.read(0x0148); println!("ROM Size: {0}", mem_map::rom_size(rom_size)); // Cart RAM size let ram_size = self.mmu.read(0x0149); println!("RAM Size: {0}", mem_map::ram_size(ram_size)); // Destination Code let dest_code = self.mmu.read(0x014A); println!("Destination Code: {0:#x}", dest_code); // Licensee Code (New | Old) let old_code = self.mmu.read(0x014B); println!("License Code: {0:#x}", old_code); // Mask ROM Version let version = self.mmu.read(0x014C); println!("Version: {0:#x}", version); // Complement Checksum let header_check = self.mmu.read(0x014D); println!("Header Checksum: {0:#x}", header_check); // Global Checksum let global_check = (self.mmu.read(0x014E) as u16) << 8 | self.mmu.read(0x014F) as u16; println!("Global Checksum: {0:#x}", global_check); println!("####################"); println!(""); // panic!("") // Show Cartridge Information } pub fn step(&mut self) { self.cpu.step(&mut self.mmu); } }
new
identifier_name
gameboy.rs
use super::cpu::*; use super::mmu::*; use super::mem_map; use std::str; pub struct Gameboy { cpu: CPU, mmu: MMU, } impl Gameboy { pub fn new(boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy { Gameboy { cpu: CPU::new(), mmu: MMU::new(boot_rom, cart_rom), } } pub fn power_up(&mut self) { println!(""); println!("####################"); // Read Name let buffer = &[ self.mmu.read(0x0134), self.mmu.read(0x0135), self.mmu.read(0x0136), self.mmu.read(0x0137), self.mmu.read(0x0138), self.mmu.read(0x0139), self.mmu.read(0x013A), self.mmu.read(0x013B), self.mmu.read(0x013C), self.mmu.read(0x013D), self.mmu.read(0x013E), self.mmu.read(0x013F), self.mmu.read(0x0140), self.mmu.read(0x0141), self.mmu.read(0x0142), self.mmu.read(0x0143) ]; let s = str::from_utf8(buffer).unwrap(); println!("Title: {}", s); // SGB Flag let sgb_flag = self.mmu.read(0x0146); println!("SBG Flag: {0:#x}", sgb_flag); // Cart Type let cart_type = self.mmu.read(0x0147); println!("Cartridge Type: {0}", mem_map::cartridge_type(cart_type)); // Cart ROM size let rom_size = self.mmu.read(0x0148); println!("ROM Size: {0}", mem_map::rom_size(rom_size)); // Cart RAM size let ram_size = self.mmu.read(0x0149); println!("RAM Size: {0}", mem_map::ram_size(ram_size)); // Destination Code let dest_code = self.mmu.read(0x014A); println!("Destination Code: {0:#x}", dest_code); // Licensee Code (New | Old) let old_code = self.mmu.read(0x014B); println!("License Code: {0:#x}", old_code); // Mask ROM Version let version = self.mmu.read(0x014C); println!("Version: {0:#x}", version); // Complement Checksum let header_check = self.mmu.read(0x014D); println!("Header Checksum: {0:#x}", header_check); // Global Checksum let global_check = (self.mmu.read(0x014E) as u16) << 8 | self.mmu.read(0x014F) as u16; println!("Global Checksum: {0:#x}", global_check); println!("####################"); println!(""); // panic!("") // Show Cartridge Information } pub fn step(&mut self)
}
{ self.cpu.step(&mut self.mmu); }
identifier_body
main.rs
/* * SPKI - Simple Public Key Infrastructure * * Copyright © 2014 Senso-Rezo * All rigths reserved. * * See LICENSE file for licensing information. * See http://github/olemaire/spki for more information. */ fn main() { Usage(); } fn Usage() {
Exemples: spki --issue server www.senso-rezo.org spki --issue user [email protected] spki --info www.senso-rezo.org spki --revoke ldap.senso-rezo.org spki --revoke www.senso-rezo.org keyCompromise spki --renew [email protected] spki --crl spki --print crl "; println(message); } /* This Is The End */
let message = "Copyright (C) Senso-Rezo - SPKI (http://github.com/olemaire/spki) Usage: spki <option> (<subject>) Available options are: --initialize Initialize a new Certificate Authority --issue <type> <subject> Issue a certificate of <type> for <subject> server <fqdn> issue a Server certificate user <email> issue an User certificate --verify <email,fqdn> Verify a given certificate --renew <email,fqdn> (reason) Renew a given certificate --revoke <email,fqdn> (reason) Revoke a given certificate --crl Generate a Certificate Revocation List --print <email,fqdn,ca,crl> Will display a raw print of certificate/CRL --info (email,fqdn,ca,crl) Will give human readable information on SPKI certificate/CA/CRL --status Will give SPKI overall operational status --help Display this short help message --version Will display the SPKI version
identifier_body
main.rs
/* * SPKI - Simple Public Key Infrastructure * * Copyright © 2014 Senso-Rezo * All rigths reserved. * * See LICENSE file for licensing information. * See http://github/olemaire/spki for more information. */ fn main() { Usage(); } fn U
) { let message = "Copyright (C) Senso-Rezo - SPKI (http://github.com/olemaire/spki) Usage: spki <option> (<subject>) Available options are: --initialize Initialize a new Certificate Authority --issue <type> <subject> Issue a certificate of <type> for <subject> server <fqdn> issue a Server certificate user <email> issue an User certificate --verify <email,fqdn> Verify a given certificate --renew <email,fqdn> (reason) Renew a given certificate --revoke <email,fqdn> (reason) Revoke a given certificate --crl Generate a Certificate Revocation List --print <email,fqdn,ca,crl> Will display a raw print of certificate/CRL --info (email,fqdn,ca,crl) Will give human readable information on SPKI certificate/CA/CRL --status Will give SPKI overall operational status --help Display this short help message --version Will display the SPKI version Exemples: spki --issue server www.senso-rezo.org spki --issue user [email protected] spki --info www.senso-rezo.org spki --revoke ldap.senso-rezo.org spki --revoke www.senso-rezo.org keyCompromise spki --renew [email protected] spki --crl spki --print crl "; println(message); } /* This Is The End */
sage(
identifier_name
main.rs
/* * SPKI - Simple Public Key Infrastructure * * Copyright © 2014 Senso-Rezo * All rigths reserved. * * See LICENSE file for licensing information. * See http://github/olemaire/spki for more information. */ fn main() { Usage(); } fn Usage() { let message = "Copyright (C) Senso-Rezo - SPKI (http://github.com/olemaire/spki) Usage: spki <option> (<subject>) Available options are: --initialize Initialize a new Certificate Authority --issue <type> <subject> Issue a certificate of <type> for <subject> server <fqdn> issue a Server certificate user <email> issue an User certificate --verify <email,fqdn> Verify a given certificate --renew <email,fqdn> (reason) Renew a given certificate
--revoke <email,fqdn> (reason) Revoke a given certificate --crl Generate a Certificate Revocation List --print <email,fqdn,ca,crl> Will display a raw print of certificate/CRL --info (email,fqdn,ca,crl) Will give human readable information on SPKI certificate/CA/CRL --status Will give SPKI overall operational status --help Display this short help message --version Will display the SPKI version Exemples: spki --issue server www.senso-rezo.org spki --issue user [email protected] spki --info www.senso-rezo.org spki --revoke ldap.senso-rezo.org spki --revoke www.senso-rezo.org keyCompromise spki --renew [email protected] spki --crl spki --print crl "; println(message); } /* This Is The End */
random_line_split
find_requires_correct_type.rs
#[macro_use] extern crate diesel; use diesel::*; use diesel::pg::PgConnection; table! { int_primary_key { id -> Integer, } } table! { string_primary_key { id -> VarChar, }
let connection = PgConnection::establish("").unwrap(); int_primary_key::table.find("1").first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::id, &str>>` in the current scope //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 string_primary_key::table.find(1).first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<string_primary_key::table, diesel::expression::predicates::Eq<string_primary_key::columns::id, _>>` in the current scope //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 }
} fn main() {
random_line_split
find_requires_correct_type.rs
#[macro_use] extern crate diesel; use diesel::*; use diesel::pg::PgConnection; table! { int_primary_key { id -> Integer, } } table! { string_primary_key { id -> VarChar, } } fn
() { let connection = PgConnection::establish("").unwrap(); int_primary_key::table.find("1").first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::id, &str>>` in the current scope //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 string_primary_key::table.find(1).first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<string_primary_key::table, diesel::expression::predicates::Eq<string_primary_key::columns::id, _>>` in the current scope //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 }
main
identifier_name
find_requires_correct_type.rs
#[macro_use] extern crate diesel; use diesel::*; use diesel::pg::PgConnection; table! { int_primary_key { id -> Integer, } } table! { string_primary_key { id -> VarChar, } } fn main()
{ let connection = PgConnection::establish("").unwrap(); int_primary_key::table.find("1").first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::id, &str>>` in the current scope //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 string_primary_key::table.find(1).first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<string_primary_key::table, diesel::expression::predicates::Eq<string_primary_key::columns::id, _>>` in the current scope //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 //~| ERROR E0277 }
identifier_body
stylist.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 html5ever_atoms::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Selector; use servo_atoms::Atom; use std::sync::Arc; use style::properties::{PropertyDeclarationBlock, PropertyDeclaration}; use style::properties::{longhands, Importance}; use style::rule_tree::CascadeLevel; use style::selector_parser::{SelectorImpl, SelectorParser}; use style::shared_lock::SharedRwLock; use style::stylesheets::StyleRule; use style::stylist::{Rule, SelectorMap}; use style::stylist::needs_revalidation; use style::thread_state; /// Helper method to get some Rules from selector strings. /// Each sublist of the result contains the Rules for one StyleRule. fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { let shared_lock = SharedRwLock::new(); (css_selectors.iter().enumerate().map(|(i, selectors)| { let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); let locked = Arc::new(shared_lock.wrap(StyleRule { selectors: selectors, block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( PropertyDeclaration::Display( longhands::display::SpecifiedValue::block), Importance::Normal ))), })); let guard = shared_lock.read(); let rule = locked.read_with(&guard); rule.selectors.0.iter().map(|s| { Rule::new(&guard, s.inner.clone(), locked.clone(), i, s.specificity) }).collect() }).collect(), shared_lock) } fn get_mock_map(selectors: &[&str]) -> (SelectorMap, SharedRwLock) { let mut map = SelectorMap::new(); let (selector_rules, shared_lock) = get_mock_rules(selectors); for rules in selector_rules.into_iter() { for rule in rules.into_iter() { map.insert(rule) } } (map, shared_lock) } fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> { selectors.iter() .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 .into_iter() .nth(0) .unwrap()) .collect() } #[test] fn test_revalidation_selectors() { let test = parse_selectors(&[ // Not revalidation selectors. "div", "#bar", "div:not(.foo)", "div span", "div > span", // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)",
"div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( // Sibling combinators. "span + div", "span ~ div", // Revalidation selectors that will get sliced. "td > h1[dir]", "td > span + h1[dir]", "table td > span + div ~ h1[dir]", ]).into_iter() .filter(|s| needs_revalidation(&s)) .map(|s| s.inner.slice_to_first_ancestor_combinator().complex) .collect::<Vec<_>>(); let reference = parse_selectors(&[ // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Sibling combinators. "span + div", "span ~ div", // Revalidation selectors that got sliced. "h1[dir]", "span + h1[dir]", "span + div ~ h1[dir]", ]).into_iter() .map(|s| s.inner.complex) .collect::<Vec<_>>(); assert_eq!(test.len(), reference.len()); for (t, r) in test.into_iter().zip(reference.into_iter()) { assert_eq!(t, r) } } #[test] fn test_rule_ordering_same_specificity() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), "The rule that comes later should win."); } #[test] fn test_get_id_name() { let (rules_list, _) = get_mock_rules(&[".intro", "#top"]); assert_eq!(SelectorMap::get_id_name(&rules_list[0][0]), None); assert_eq!(SelectorMap::get_id_name(&rules_list[1][0]), Some(Atom::from("top"))); } #[test] fn test_get_class_name() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); assert_eq!(SelectorMap::get_class_name(&rules_list[0][0]), Some(Atom::from("foo"))); assert_eq!(SelectorMap::get_class_name(&rules_list[1][0]), None); } #[test] fn test_get_local_name() { let (rules_list, _) = get_mock_rules(&["img.foo", "#top", "IMG", "ImG"]); let check = |i: usize, names: Option<(&str, &str)>| { assert!(SelectorMap::get_local_name(&rules_list[i][0]) == names.map(|(name, lower_name)| LocalNameSelector { name: LocalName::from(name), lower_name: LocalName::from(lower_name) })) }; check(0, Some(("img", "img"))); check(1, None); check(2, Some(("IMG", "img"))); check(3, Some(("ImG", "img"))); } #[test] fn test_insert() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); let mut selector_map = SelectorMap::new(); selector_map.insert(rules_list[1][0].clone()); assert_eq!(1, selector_map.id_hash.get(&Atom::from("top")).unwrap()[0].source_order); selector_map.insert(rules_list[0][0].clone()); assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo")).unwrap()[0].source_order); assert!(selector_map.class_hash.get(&Atom::from("intro")).is_none()); } #[test] fn test_get_universal_rules() { thread_state::initialize(thread_state::LAYOUT); let (map, shared_lock) = get_mock_map(&["*|*", "#foo > *|*", ".klass", "#id"]); let guard = shared_lock.read(); let decls = map.get_universal_rules( &guard, CascadeLevel::UserNormal, CascadeLevel::UserImportant); assert_eq!(decls.len(), 1); }
random_line_split
stylist.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 html5ever_atoms::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Selector; use servo_atoms::Atom; use std::sync::Arc; use style::properties::{PropertyDeclarationBlock, PropertyDeclaration}; use style::properties::{longhands, Importance}; use style::rule_tree::CascadeLevel; use style::selector_parser::{SelectorImpl, SelectorParser}; use style::shared_lock::SharedRwLock; use style::stylesheets::StyleRule; use style::stylist::{Rule, SelectorMap}; use style::stylist::needs_revalidation; use style::thread_state; /// Helper method to get some Rules from selector strings. /// Each sublist of the result contains the Rules for one StyleRule. fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { let shared_lock = SharedRwLock::new(); (css_selectors.iter().enumerate().map(|(i, selectors)| { let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); let locked = Arc::new(shared_lock.wrap(StyleRule { selectors: selectors, block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( PropertyDeclaration::Display( longhands::display::SpecifiedValue::block), Importance::Normal ))), })); let guard = shared_lock.read(); let rule = locked.read_with(&guard); rule.selectors.0.iter().map(|s| { Rule::new(&guard, s.inner.clone(), locked.clone(), i, s.specificity) }).collect() }).collect(), shared_lock) } fn get_mock_map(selectors: &[&str]) -> (SelectorMap, SharedRwLock) { let mut map = SelectorMap::new(); let (selector_rules, shared_lock) = get_mock_rules(selectors); for rules in selector_rules.into_iter() { for rule in rules.into_iter() { map.insert(rule) } } (map, shared_lock) } fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> { selectors.iter() .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 .into_iter() .nth(0) .unwrap()) .collect() } #[test] fn test_revalidation_selectors() { let test = parse_selectors(&[ // Not revalidation selectors. "div", "#bar", "div:not(.foo)", "div span", "div > span", // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( // Sibling combinators. "span + div", "span ~ div", // Revalidation selectors that will get sliced. "td > h1[dir]", "td > span + h1[dir]", "table td > span + div ~ h1[dir]", ]).into_iter() .filter(|s| needs_revalidation(&s)) .map(|s| s.inner.slice_to_first_ancestor_combinator().complex) .collect::<Vec<_>>(); let reference = parse_selectors(&[ // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Sibling combinators. "span + div", "span ~ div", // Revalidation selectors that got sliced. "h1[dir]", "span + h1[dir]", "span + div ~ h1[dir]", ]).into_iter() .map(|s| s.inner.complex) .collect::<Vec<_>>(); assert_eq!(test.len(), reference.len()); for (t, r) in test.into_iter().zip(reference.into_iter()) { assert_eq!(t, r) } } #[test] fn test_rule_ordering_same_specificity() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), "The rule that comes later should win."); } #[test] fn test_get_id_name()
#[test] fn test_get_class_name() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); assert_eq!(SelectorMap::get_class_name(&rules_list[0][0]), Some(Atom::from("foo"))); assert_eq!(SelectorMap::get_class_name(&rules_list[1][0]), None); } #[test] fn test_get_local_name() { let (rules_list, _) = get_mock_rules(&["img.foo", "#top", "IMG", "ImG"]); let check = |i: usize, names: Option<(&str, &str)>| { assert!(SelectorMap::get_local_name(&rules_list[i][0]) == names.map(|(name, lower_name)| LocalNameSelector { name: LocalName::from(name), lower_name: LocalName::from(lower_name) })) }; check(0, Some(("img", "img"))); check(1, None); check(2, Some(("IMG", "img"))); check(3, Some(("ImG", "img"))); } #[test] fn test_insert() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); let mut selector_map = SelectorMap::new(); selector_map.insert(rules_list[1][0].clone()); assert_eq!(1, selector_map.id_hash.get(&Atom::from("top")).unwrap()[0].source_order); selector_map.insert(rules_list[0][0].clone()); assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo")).unwrap()[0].source_order); assert!(selector_map.class_hash.get(&Atom::from("intro")).is_none()); } #[test] fn test_get_universal_rules() { thread_state::initialize(thread_state::LAYOUT); let (map, shared_lock) = get_mock_map(&["*|*", "#foo > *|*", ".klass", "#id"]); let guard = shared_lock.read(); let decls = map.get_universal_rules( &guard, CascadeLevel::UserNormal, CascadeLevel::UserImportant); assert_eq!(decls.len(), 1); }
{ let (rules_list, _) = get_mock_rules(&[".intro", "#top"]); assert_eq!(SelectorMap::get_id_name(&rules_list[0][0]), None); assert_eq!(SelectorMap::get_id_name(&rules_list[1][0]), Some(Atom::from("top"))); }
identifier_body
stylist.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 html5ever_atoms::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Selector; use servo_atoms::Atom; use std::sync::Arc; use style::properties::{PropertyDeclarationBlock, PropertyDeclaration}; use style::properties::{longhands, Importance}; use style::rule_tree::CascadeLevel; use style::selector_parser::{SelectorImpl, SelectorParser}; use style::shared_lock::SharedRwLock; use style::stylesheets::StyleRule; use style::stylist::{Rule, SelectorMap}; use style::stylist::needs_revalidation; use style::thread_state; /// Helper method to get some Rules from selector strings. /// Each sublist of the result contains the Rules for one StyleRule. fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { let shared_lock = SharedRwLock::new(); (css_selectors.iter().enumerate().map(|(i, selectors)| { let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); let locked = Arc::new(shared_lock.wrap(StyleRule { selectors: selectors, block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( PropertyDeclaration::Display( longhands::display::SpecifiedValue::block), Importance::Normal ))), })); let guard = shared_lock.read(); let rule = locked.read_with(&guard); rule.selectors.0.iter().map(|s| { Rule::new(&guard, s.inner.clone(), locked.clone(), i, s.specificity) }).collect() }).collect(), shared_lock) } fn get_mock_map(selectors: &[&str]) -> (SelectorMap, SharedRwLock) { let mut map = SelectorMap::new(); let (selector_rules, shared_lock) = get_mock_rules(selectors); for rules in selector_rules.into_iter() { for rule in rules.into_iter() { map.insert(rule) } } (map, shared_lock) } fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> { selectors.iter() .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 .into_iter() .nth(0) .unwrap()) .collect() } #[test] fn test_revalidation_selectors() { let test = parse_selectors(&[ // Not revalidation selectors. "div", "#bar", "div:not(.foo)", "div span", "div > span", // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( // Sibling combinators. "span + div", "span ~ div", // Revalidation selectors that will get sliced. "td > h1[dir]", "td > span + h1[dir]", "table td > span + div ~ h1[dir]", ]).into_iter() .filter(|s| needs_revalidation(&s)) .map(|s| s.inner.slice_to_first_ancestor_combinator().complex) .collect::<Vec<_>>(); let reference = parse_selectors(&[ // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Sibling combinators. "span + div", "span ~ div", // Revalidation selectors that got sliced. "h1[dir]", "span + h1[dir]", "span + div ~ h1[dir]", ]).into_iter() .map(|s| s.inner.complex) .collect::<Vec<_>>(); assert_eq!(test.len(), reference.len()); for (t, r) in test.into_iter().zip(reference.into_iter()) { assert_eq!(t, r) } } #[test] fn
() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), "The rule that comes later should win."); } #[test] fn test_get_id_name() { let (rules_list, _) = get_mock_rules(&[".intro", "#top"]); assert_eq!(SelectorMap::get_id_name(&rules_list[0][0]), None); assert_eq!(SelectorMap::get_id_name(&rules_list[1][0]), Some(Atom::from("top"))); } #[test] fn test_get_class_name() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); assert_eq!(SelectorMap::get_class_name(&rules_list[0][0]), Some(Atom::from("foo"))); assert_eq!(SelectorMap::get_class_name(&rules_list[1][0]), None); } #[test] fn test_get_local_name() { let (rules_list, _) = get_mock_rules(&["img.foo", "#top", "IMG", "ImG"]); let check = |i: usize, names: Option<(&str, &str)>| { assert!(SelectorMap::get_local_name(&rules_list[i][0]) == names.map(|(name, lower_name)| LocalNameSelector { name: LocalName::from(name), lower_name: LocalName::from(lower_name) })) }; check(0, Some(("img", "img"))); check(1, None); check(2, Some(("IMG", "img"))); check(3, Some(("ImG", "img"))); } #[test] fn test_insert() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); let mut selector_map = SelectorMap::new(); selector_map.insert(rules_list[1][0].clone()); assert_eq!(1, selector_map.id_hash.get(&Atom::from("top")).unwrap()[0].source_order); selector_map.insert(rules_list[0][0].clone()); assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo")).unwrap()[0].source_order); assert!(selector_map.class_hash.get(&Atom::from("intro")).is_none()); } #[test] fn test_get_universal_rules() { thread_state::initialize(thread_state::LAYOUT); let (map, shared_lock) = get_mock_map(&["*|*", "#foo > *|*", ".klass", "#id"]); let guard = shared_lock.read(); let decls = map.get_universal_rules( &guard, CascadeLevel::UserNormal, CascadeLevel::UserImportant); assert_eq!(decls.len(), 1); }
test_rule_ordering_same_specificity
identifier_name
deriving-primitive.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
use std::num::FromPrimitive; use std::isize; #[derive(FromPrimitive)] struct A { x: isize } //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] struct B(isize); //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] enum C { Foo(isize), Bar(usize) } //~^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments //~^^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments #[derive(FromPrimitive)] enum D { Baz { x: isize } } //~^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants //~^^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants pub fn main() {}
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
deriving-primitive.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. use std::num::FromPrimitive; use std::isize; #[derive(FromPrimitive)] struct
{ x: isize } //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] struct B(isize); //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] enum C { Foo(isize), Bar(usize) } //~^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments //~^^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments #[derive(FromPrimitive)] enum D { Baz { x: isize } } //~^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants //~^^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants pub fn main() {}
A
identifier_name
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. This replicates legacy Relay Compiler /// behavior, but is not according to spec. Removing this would need some care /// as there are small differences between not-passed and explicit null values wrt. /// default values. pub fn skip_null_arguments_transform(program: &Program) -> Program
struct SkipNullArgumentsTransform; impl Transformer for SkipNullArgumentsTransform { const NAME: &'static str = "SkipNullArgumentsTransform"; const VISIT_ARGUMENTS: bool = true; const VISIT_DIRECTIVES: bool = true; fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { if matches!(argument.value.item, Value::Constant(ConstantValue::Null())) { Transformed::Delete } else { Transformed::Keep } } }
{ SkipNullArgumentsTransform .transform_program(program) .replace_or_else(|| program.clone()) }
identifier_body
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. This replicates legacy Relay Compiler /// behavior, but is not according to spec. Removing this would need some care /// as there are small differences between not-passed and explicit null values wrt. /// default values. pub fn skip_null_arguments_transform(program: &Program) -> Program { SkipNullArgumentsTransform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipNullArgumentsTransform; impl Transformer for SkipNullArgumentsTransform { const NAME: &'static str = "SkipNullArgumentsTransform"; const VISIT_ARGUMENTS: bool = true; const VISIT_DIRECTIVES: bool = true; fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { if matches!(argument.value.item, Value::Constant(ConstantValue::Null())) { Transformed::Delete } else { Transformed::Keep }
}
}
random_line_split
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. This replicates legacy Relay Compiler /// behavior, but is not according to spec. Removing this would need some care /// as there are small differences between not-passed and explicit null values wrt. /// default values. pub fn
(program: &Program) -> Program { SkipNullArgumentsTransform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipNullArgumentsTransform; impl Transformer for SkipNullArgumentsTransform { const NAME: &'static str = "SkipNullArgumentsTransform"; const VISIT_ARGUMENTS: bool = true; const VISIT_DIRECTIVES: bool = true; fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { if matches!(argument.value.item, Value::Constant(ConstantValue::Null())) { Transformed::Delete } else { Transformed::Keep } } }
skip_null_arguments_transform
identifier_name
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. This replicates legacy Relay Compiler /// behavior, but is not according to spec. Removing this would need some care /// as there are small differences between not-passed and explicit null values wrt. /// default values. pub fn skip_null_arguments_transform(program: &Program) -> Program { SkipNullArgumentsTransform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipNullArgumentsTransform; impl Transformer for SkipNullArgumentsTransform { const NAME: &'static str = "SkipNullArgumentsTransform"; const VISIT_ARGUMENTS: bool = true; const VISIT_DIRECTIVES: bool = true; fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { if matches!(argument.value.item, Value::Constant(ConstantValue::Null()))
else { Transformed::Keep } } }
{ Transformed::Delete }
conditional_block
command.rs
use std::error; use clap; use crate::config; use super::executer::Executer; use super::{Arguments, Program}; pub struct Command<'c> { config: &'c config::command::Config, program: Program<'c>, args: Arguments<'c>, } impl<'c> Command<'c> { pub fn from_args( config: &'c config::command::Config, clap_args: &'c clap::ArgMatches<'c>, ) -> Self { trace!("command::params::exec::Command::from_args"); let program = clap_args.value_of("PROGRAM").unwrap(); let args = match clap_args.values_of("ARGS") { Some(args) => args.collect(), None => Vec::new(), }; Command { config: config, program: program, args: args, } } pub fn new( config: &'c config::command::Config, program: &'c Program<'c>, args: &'c Arguments<'c>, ) -> Self { trace!("command::params::exec::Command::new"); Command { config: config, program: program, args: args.to_owned(), } } pub async fn run(&self) -> Result<(), Box<dyn error::Error>>
}
{ trace!("command::params::exec::Command::run"); if let Some(params_config) = self.config.params.as_ref() { let exec = Executer::from_config(params_config); exec.run(&self.program, &self.args).await?; } Ok(()) }
identifier_body
command.rs
use std::error; use clap; use crate::config; use super::executer::Executer; use super::{Arguments, Program}; pub struct Command<'c> { config: &'c config::command::Config, program: Program<'c>, args: Arguments<'c>, } impl<'c> Command<'c> { pub fn from_args( config: &'c config::command::Config, clap_args: &'c clap::ArgMatches<'c>, ) -> Self { trace!("command::params::exec::Command::from_args"); let program = clap_args.value_of("PROGRAM").unwrap(); let args = match clap_args.values_of("ARGS") { Some(args) => args.collect(), None => Vec::new(), }; Command { config: config, program: program, args: args, } } pub fn new( config: &'c config::command::Config, program: &'c Program<'c>, args: &'c Arguments<'c>, ) -> Self { trace!("command::params::exec::Command::new"); Command { config: config, program: program, args: args.to_owned(), } } pub async fn
(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::params::exec::Command::run"); if let Some(params_config) = self.config.params.as_ref() { let exec = Executer::from_config(params_config); exec.run(&self.program, &self.args).await?; } Ok(()) } }
run
identifier_name
command.rs
use std::error; use clap; use crate::config; use super::executer::Executer; use super::{Arguments, Program}; pub struct Command<'c> { config: &'c config::command::Config, program: Program<'c>, args: Arguments<'c>, } impl<'c> Command<'c> { pub fn from_args( config: &'c config::command::Config, clap_args: &'c clap::ArgMatches<'c>, ) -> Self { trace!("command::params::exec::Command::from_args"); let program = clap_args.value_of("PROGRAM").unwrap(); let args = match clap_args.values_of("ARGS") { Some(args) => args.collect(), None => Vec::new(), }; Command { config: config, program: program, args: args, } } pub fn new( config: &'c config::command::Config, program: &'c Program<'c>, args: &'c Arguments<'c>, ) -> Self { trace!("command::params::exec::Command::new"); Command { config: config, program: program, args: args.to_owned(), } }
} Ok(()) } }
pub async fn run(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::params::exec::Command::run"); if let Some(params_config) = self.config.params.as_ref() { let exec = Executer::from_config(params_config); exec.run(&self.program, &self.args).await?;
random_line_split
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32, } impl Duration { /// Create a new duration pub fn new(mut secs: i64, mut nanos: i32) -> Self { while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) { secs += 1; nanos -= NANOS_PER_SEC; } while nanos < 0 && secs > 0 { secs -= 1; nanos += NANOS_PER_SEC; } Duration { secs: secs, nanos: nanos, } } /// Get the current duration pub fn monotonic() -> Self { ::env().clock_monotonic.lock().clone() } /// Get the realtime pub fn realtime() -> Self { ::env().clock_realtime.lock().clone() } } impl Add for Duration { type Output = Duration; fn
(self, other: Self) -> Self { Duration::new(self.secs + other.secs, self.nanos + other.nanos) } } impl Sub for Duration { type Output = Duration; fn sub(self, other: Self) -> Self { Duration::new(self.secs - other.secs, self.nanos - other.nanos) } } impl PartialEq for Duration { fn eq(&self, other: &Self) -> bool { let dif = *self - *other; dif.secs == 0 && dif.nanos == 0 } } impl PartialOrd for Duration { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let dif = *self - *other; if dif.secs > 0 { Some(Ordering::Greater) } else if dif.secs < 0 { Some(Ordering::Less) } else if dif.nanos > 0 { Some(Ordering::Greater) } else if dif.nanos < 0 { Some(Ordering::Less) } else { Some(Ordering::Equal) } } }
add
identifier_name
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32, } impl Duration {
} while nanos < 0 && secs > 0 { secs -= 1; nanos += NANOS_PER_SEC; } Duration { secs: secs, nanos: nanos, } } /// Get the current duration pub fn monotonic() -> Self { ::env().clock_monotonic.lock().clone() } /// Get the realtime pub fn realtime() -> Self { ::env().clock_realtime.lock().clone() } } impl Add for Duration { type Output = Duration; fn add(self, other: Self) -> Self { Duration::new(self.secs + other.secs, self.nanos + other.nanos) } } impl Sub for Duration { type Output = Duration; fn sub(self, other: Self) -> Self { Duration::new(self.secs - other.secs, self.nanos - other.nanos) } } impl PartialEq for Duration { fn eq(&self, other: &Self) -> bool { let dif = *self - *other; dif.secs == 0 && dif.nanos == 0 } } impl PartialOrd for Duration { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let dif = *self - *other; if dif.secs > 0 { Some(Ordering::Greater) } else if dif.secs < 0 { Some(Ordering::Less) } else if dif.nanos > 0 { Some(Ordering::Greater) } else if dif.nanos < 0 { Some(Ordering::Less) } else { Some(Ordering::Equal) } } }
/// Create a new duration pub fn new(mut secs: i64, mut nanos: i32) -> Self { while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) { secs += 1; nanos -= NANOS_PER_SEC;
random_line_split
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32, } impl Duration { /// Create a new duration pub fn new(mut secs: i64, mut nanos: i32) -> Self
/// Get the current duration pub fn monotonic() -> Self { ::env().clock_monotonic.lock().clone() } /// Get the realtime pub fn realtime() -> Self { ::env().clock_realtime.lock().clone() } } impl Add for Duration { type Output = Duration; fn add(self, other: Self) -> Self { Duration::new(self.secs + other.secs, self.nanos + other.nanos) } } impl Sub for Duration { type Output = Duration; fn sub(self, other: Self) -> Self { Duration::new(self.secs - other.secs, self.nanos - other.nanos) } } impl PartialEq for Duration { fn eq(&self, other: &Self) -> bool { let dif = *self - *other; dif.secs == 0 && dif.nanos == 0 } } impl PartialOrd for Duration { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let dif = *self - *other; if dif.secs > 0 { Some(Ordering::Greater) } else if dif.secs < 0 { Some(Ordering::Less) } else if dif.nanos > 0 { Some(Ordering::Greater) } else if dif.nanos < 0 { Some(Ordering::Less) } else { Some(Ordering::Equal) } } }
{ while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) { secs += 1; nanos -= NANOS_PER_SEC; } while nanos < 0 && secs > 0 { secs -= 1; nanos += NANOS_PER_SEC; } Duration { secs: secs, nanos: nanos, } }
identifier_body
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32, } impl Duration { /// Create a new duration pub fn new(mut secs: i64, mut nanos: i32) -> Self { while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) { secs += 1; nanos -= NANOS_PER_SEC; } while nanos < 0 && secs > 0 { secs -= 1; nanos += NANOS_PER_SEC; } Duration { secs: secs, nanos: nanos, } } /// Get the current duration pub fn monotonic() -> Self { ::env().clock_monotonic.lock().clone() } /// Get the realtime pub fn realtime() -> Self { ::env().clock_realtime.lock().clone() } } impl Add for Duration { type Output = Duration; fn add(self, other: Self) -> Self { Duration::new(self.secs + other.secs, self.nanos + other.nanos) } } impl Sub for Duration { type Output = Duration; fn sub(self, other: Self) -> Self { Duration::new(self.secs - other.secs, self.nanos - other.nanos) } } impl PartialEq for Duration { fn eq(&self, other: &Self) -> bool { let dif = *self - *other; dif.secs == 0 && dif.nanos == 0 } } impl PartialOrd for Duration { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let dif = *self - *other; if dif.secs > 0 { Some(Ordering::Greater) } else if dif.secs < 0 { Some(Ordering::Less) } else if dif.nanos > 0 { Some(Ordering::Greater) } else if dif.nanos < 0 { Some(Ordering::Less) } else
} }
{ Some(Ordering::Equal) }
conditional_block
ai_qoff_player.rs
//! offline reinforcement learning (q learning after match is over) #![allow(dead_code)] extern crate rand; extern crate nn; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use self::rand::Rng; use self::nn::{NN, HaltCondition, Activation}; use super::Player; use super::super::field::Field; const GAMMA:f64 = 0.95; //temporal sureness (->1 means more sure about early actions always lead to win) const LR:f64 = 0.1; //neural net learning rate const LR_DECAY:f64 = 10000f64; //NN learning rate decrease (half every DECAY games) const LR_MIN:f64 = 0.01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //number of games to collect before learning pub struct PlayerAIQOff { initialized: bool, fixed: bool, //should the agent learn or not (fixed => dont learn) filename: String, pid: i32, //player ID nn: Option<NN>, //neural network games_played: u32, lr: f64, exploration: f64, play_buffer: Vec<(Vec<f64>, Vec<f64>)>, num_buffered: i32, } impl PlayerAIQOff { pub fn new(fix:bool) -> Box<PlayerAIQOff> { Box::new(PlayerAIQOff { initialized: false, fixed: fix, filename: String::new(), pid: 0, nn: None, games_played: 0, lr: LR, exploration: RND_PICK_START, play_buffer: Vec::new(), num_buffered: 0 }) } fn get_exploration(&self) -> f64 { RND_PICK_START * (2f64).powf(-(self.games_played as f64)/RND_PICK_DEC) } fn get_lr(&self) -> f64 { LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY)) } fn argmax(slice:&[f64]) -> u32 { let mut x:u32 = 0; let mut max = slice[0]; for i in 1..slice.len() { if max<slice[i] { x = i as u32; max = slice[i]; } } x } fn field_to_input(field:&mut Field, p:i32) -> Vec<f64> { let op:i32 = if p == 1 { 2 } else { 1 }; //other player let mut input:Vec<f64> = Vec::with_capacity((2*field.get_size() + field.get_w()) as usize);
for (i, val) in field.get_field().iter().enumerate() { //2 nodes for every square: -1 enemy, 0 free, 1 own; 0 square will not be reached with one move, 1 square can be directly filled if *val == p { input.push(1f64); input.push(0f64); } else if *val == op { input.push(-1f64); input.push(0f64); } else { //empty square input.push(0f64); if (i as u32) < (field.get_size()-field.get_w()) { input.push(if field.get_field()[i+field.get_w() as usize]!= 0 { 1f64 } else { 0f64 }); } else { input.push(1f64); } } } for x in 0..field.get_w() { //1 node for every column: 1 own win, -1 enemy win, 0 none (which consistent order of the nodes does not matter, fully connected) if field.play(p, x) { //valid play match field.get_state() { -1 | 0 => input.push(0f64), pid => input.push(if pid == p {1f64} else {-1f64}), } field.undo(); } else { input.push(0f64); } //illegal move, nobody can win } input } fn learn(&mut self) { let nn = self.nn.as_mut().unwrap(); nn.train(&self.play_buffer) .halt_condition(HaltCondition::Epochs(EPOCHS_PER_STEP)) .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); self.play_buffer.clear(); self.num_buffered = 0; } } impl Player for PlayerAIQOff { fn init(&mut self, field:&Field, p:i32) -> bool { self.pid = p; self.filename = format!("AIQOff-{}x{}.NN", field.get_w(), field.get_h()); let file = File::open(&self.filename); if file.is_err() { //create new neural net, is it could not be loaded let n = field.get_size(); let w = field.get_w(); self.nn = Some(NN::new(&[2*n+w, 4*n, 2*n, n, n, n/2, w], Activation::Sigmoid, Activation::Sigmoid)); //set size of NN layers here //games_played, exploration, lr already set } else { //load neural net from file (and games played) let mut reader = BufReader::new(file.unwrap()); let mut datas = String::new(); let mut nns = String::new(); let res1 = reader.read_line(&mut datas); let res2 = reader.read_to_string(&mut nns); if res1.is_err() || res2.is_err() { return false; } let res = datas.trim().parse::<u32>(); if res.is_err() { return false; } self.games_played = res.unwrap(); self.nn = Some(NN::from_json(&nns)); self.lr = self.get_lr(); self.exploration = self.get_exploration(); } self.initialized = true; true } #[allow(unused_variables)] fn startp(&mut self, p:i32) { //nothing } fn play(&mut self, field:&mut Field) -> bool { if!self.initialized { return false; } //variables let mut rng = rand::thread_rng(); let nn = self.nn.as_mut().unwrap(); let mut res = false; //choose an action (try again until it meets the rules) while!res { //get current state formatted for the neural net (in loop because ownerships gets moved later) let state = PlayerAIQOff::field_to_input(field, self.pid); //choose action by e-greedy let mut qval = nn.run(&state); let mut x = PlayerAIQOff::argmax(&qval); if rng.gen::<f64>() < self.exploration //random exploration { x = rng.gen::<u32>() % field.get_w(); } //perform action res = field.play(self.pid, x); //save play data if not fixed, but learn if move did not was rule-conform if!self.fixed ||!res { //calculate q update or collect data for later learn if!res { qval[x as usize] = 0f64; } //invalid play instant learn else { qval[x as usize] = -1f64; } //mark field to set values later for learning //initiate training or save data if res { //add latest experience to replay_buffer self.play_buffer.push((state, qval)); } else { let training = [(state, qval)]; nn.train(&training) .halt_condition(HaltCondition::Epochs(1)) //only one epoch for rule mistakes .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); } } } //field.print(); //debug res } #[allow(unused_variables)] fn outcome(&mut self, field:&mut Field, state:i32) { if self.initialized &&!self.fixed //learning { //get reward let otherp = if self.pid == 1 {2} else {1}; let mut reward = 0f64; //draw (or running, should not happen) if state == self.pid { reward = 1f64; } else if state == otherp { reward = -1f64; } //compute learning data let w:usize = field.get_w() as usize; let len = self.play_buffer.len() as i32; let mut start = 0; if len > (field.get_w() * field.get_h()) as i32 { start = len - (field.get_w() * field.get_h()) as i32; } for count in start..len { let mut qval = &mut self.play_buffer[count as usize].1; for i in 0..w { if qval[i] == -1f64 { qval[i] = (GAMMA.powi(len - count) * reward + 1f64) / 2f64; // (+1)/2 => accumulate for sigmoid break; } } } //learn self.num_buffered += 1; if self.num_buffered >= LEARNING_SET { self.learn(); } } //set parameters self.games_played += 1; self.lr = self.get_lr(); self.exploration = self.get_exploration(); } } impl Drop for PlayerAIQOff { fn drop(&mut self) { //write neural net to file, if it may has learned and was initialized if self.initialized &&!self.fixed { //learn if self.num_buffered > 0 { self.learn(); } //save NN let file = File::create(&self.filename); if file.is_err() { println!("Warning: Could not write AIQ NN file!"); return; } let mut writer = BufWriter::new(file.unwrap()); let res1 = writeln!(&mut writer, "{}", self.games_played); let res2 = write!(&mut writer, "{}", self.nn.as_mut().unwrap().to_json()); if res1.is_err() || res2.is_err() { println!("Warning: There was an error while writing AIQ NN file!"); return; } } } }
random_line_split
ai_qoff_player.rs
//! offline reinforcement learning (q learning after match is over) #![allow(dead_code)] extern crate rand; extern crate nn; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use self::rand::Rng; use self::nn::{NN, HaltCondition, Activation}; use super::Player; use super::super::field::Field; const GAMMA:f64 = 0.95; //temporal sureness (->1 means more sure about early actions always lead to win) const LR:f64 = 0.1; //neural net learning rate const LR_DECAY:f64 = 10000f64; //NN learning rate decrease (half every DECAY games) const LR_MIN:f64 = 0.01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //number of games to collect before learning pub struct PlayerAIQOff { initialized: bool, fixed: bool, //should the agent learn or not (fixed => dont learn) filename: String, pid: i32, //player ID nn: Option<NN>, //neural network games_played: u32, lr: f64, exploration: f64, play_buffer: Vec<(Vec<f64>, Vec<f64>)>, num_buffered: i32, } impl PlayerAIQOff { pub fn new(fix:bool) -> Box<PlayerAIQOff> { Box::new(PlayerAIQOff { initialized: false, fixed: fix, filename: String::new(), pid: 0, nn: None, games_played: 0, lr: LR, exploration: RND_PICK_START, play_buffer: Vec::new(), num_buffered: 0 }) } fn get_exploration(&self) -> f64 { RND_PICK_START * (2f64).powf(-(self.games_played as f64)/RND_PICK_DEC) } fn get_lr(&self) -> f64 { LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY)) } fn argmax(slice:&[f64]) -> u32 { let mut x:u32 = 0; let mut max = slice[0]; for i in 1..slice.len() { if max<slice[i] { x = i as u32; max = slice[i]; } } x } fn field_to_input(field:&mut Field, p:i32) -> Vec<f64> { let op:i32 = if p == 1 { 2 } else { 1 }; //other player let mut input:Vec<f64> = Vec::with_capacity((2*field.get_size() + field.get_w()) as usize); for (i, val) in field.get_field().iter().enumerate() { //2 nodes for every square: -1 enemy, 0 free, 1 own; 0 square will not be reached with one move, 1 square can be directly filled if *val == p { input.push(1f64); input.push(0f64); } else if *val == op { input.push(-1f64); input.push(0f64); } else { //empty square input.push(0f64); if (i as u32) < (field.get_size()-field.get_w()) { input.push(if field.get_field()[i+field.get_w() as usize]!= 0 { 1f64 } else { 0f64 }); } else { input.push(1f64); } } } for x in 0..field.get_w() { //1 node for every column: 1 own win, -1 enemy win, 0 none (which consistent order of the nodes does not matter, fully connected) if field.play(p, x) { //valid play match field.get_state() { -1 | 0 => input.push(0f64), pid => input.push(if pid == p {1f64} else {-1f64}), } field.undo(); } else { input.push(0f64); } //illegal move, nobody can win } input } fn learn(&mut self) { let nn = self.nn.as_mut().unwrap(); nn.train(&self.play_buffer) .halt_condition(HaltCondition::Epochs(EPOCHS_PER_STEP)) .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); self.play_buffer.clear(); self.num_buffered = 0; } } impl Player for PlayerAIQOff { fn init(&mut self, field:&Field, p:i32) -> bool { self.pid = p; self.filename = format!("AIQOff-{}x{}.NN", field.get_w(), field.get_h()); let file = File::open(&self.filename); if file.is_err() { //create new neural net, is it could not be loaded let n = field.get_size(); let w = field.get_w(); self.nn = Some(NN::new(&[2*n+w, 4*n, 2*n, n, n, n/2, w], Activation::Sigmoid, Activation::Sigmoid)); //set size of NN layers here //games_played, exploration, lr already set } else { //load neural net from file (and games played) let mut reader = BufReader::new(file.unwrap()); let mut datas = String::new(); let mut nns = String::new(); let res1 = reader.read_line(&mut datas); let res2 = reader.read_to_string(&mut nns); if res1.is_err() || res2.is_err() { return false; } let res = datas.trim().parse::<u32>(); if res.is_err() { return false; } self.games_played = res.unwrap(); self.nn = Some(NN::from_json(&nns)); self.lr = self.get_lr(); self.exploration = self.get_exploration(); } self.initialized = true; true } #[allow(unused_variables)] fn startp(&mut self, p:i32) { //nothing } fn play(&mut self, field:&mut Field) -> bool { if!self.initialized { return false; } //variables let mut rng = rand::thread_rng(); let nn = self.nn.as_mut().unwrap(); let mut res = false; //choose an action (try again until it meets the rules) while!res { //get current state formatted for the neural net (in loop because ownerships gets moved later) let state = PlayerAIQOff::field_to_input(field, self.pid); //choose action by e-greedy let mut qval = nn.run(&state); let mut x = PlayerAIQOff::argmax(&qval); if rng.gen::<f64>() < self.exploration //random exploration
//perform action res = field.play(self.pid, x); //save play data if not fixed, but learn if move did not was rule-conform if!self.fixed ||!res { //calculate q update or collect data for later learn if!res { qval[x as usize] = 0f64; } //invalid play instant learn else { qval[x as usize] = -1f64; } //mark field to set values later for learning //initiate training or save data if res { //add latest experience to replay_buffer self.play_buffer.push((state, qval)); } else { let training = [(state, qval)]; nn.train(&training) .halt_condition(HaltCondition::Epochs(1)) //only one epoch for rule mistakes .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); } } } //field.print(); //debug res } #[allow(unused_variables)] fn outcome(&mut self, field:&mut Field, state:i32) { if self.initialized &&!self.fixed //learning { //get reward let otherp = if self.pid == 1 {2} else {1}; let mut reward = 0f64; //draw (or running, should not happen) if state == self.pid { reward = 1f64; } else if state == otherp { reward = -1f64; } //compute learning data let w:usize = field.get_w() as usize; let len = self.play_buffer.len() as i32; let mut start = 0; if len > (field.get_w() * field.get_h()) as i32 { start = len - (field.get_w() * field.get_h()) as i32; } for count in start..len { let mut qval = &mut self.play_buffer[count as usize].1; for i in 0..w { if qval[i] == -1f64 { qval[i] = (GAMMA.powi(len - count) * reward + 1f64) / 2f64; // (+1)/2 => accumulate for sigmoid break; } } } //learn self.num_buffered += 1; if self.num_buffered >= LEARNING_SET { self.learn(); } } //set parameters self.games_played += 1; self.lr = self.get_lr(); self.exploration = self.get_exploration(); } } impl Drop for PlayerAIQOff { fn drop(&mut self) { //write neural net to file, if it may has learned and was initialized if self.initialized &&!self.fixed { //learn if self.num_buffered > 0 { self.learn(); } //save NN let file = File::create(&self.filename); if file.is_err() { println!("Warning: Could not write AIQ NN file!"); return; } let mut writer = BufWriter::new(file.unwrap()); let res1 = writeln!(&mut writer, "{}", self.games_played); let res2 = write!(&mut writer, "{}", self.nn.as_mut().unwrap().to_json()); if res1.is_err() || res2.is_err() { println!("Warning: There was an error while writing AIQ NN file!"); return; } } } }
{ x = rng.gen::<u32>() % field.get_w(); }
conditional_block
ai_qoff_player.rs
//! offline reinforcement learning (q learning after match is over) #![allow(dead_code)] extern crate rand; extern crate nn; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use self::rand::Rng; use self::nn::{NN, HaltCondition, Activation}; use super::Player; use super::super::field::Field; const GAMMA:f64 = 0.95; //temporal sureness (->1 means more sure about early actions always lead to win) const LR:f64 = 0.1; //neural net learning rate const LR_DECAY:f64 = 10000f64; //NN learning rate decrease (half every DECAY games) const LR_MIN:f64 = 0.01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //number of games to collect before learning pub struct PlayerAIQOff { initialized: bool, fixed: bool, //should the agent learn or not (fixed => dont learn) filename: String, pid: i32, //player ID nn: Option<NN>, //neural network games_played: u32, lr: f64, exploration: f64, play_buffer: Vec<(Vec<f64>, Vec<f64>)>, num_buffered: i32, } impl PlayerAIQOff { pub fn new(fix:bool) -> Box<PlayerAIQOff> { Box::new(PlayerAIQOff { initialized: false, fixed: fix, filename: String::new(), pid: 0, nn: None, games_played: 0, lr: LR, exploration: RND_PICK_START, play_buffer: Vec::new(), num_buffered: 0 }) } fn get_exploration(&self) -> f64 { RND_PICK_START * (2f64).powf(-(self.games_played as f64)/RND_PICK_DEC) } fn
(&self) -> f64 { LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY)) } fn argmax(slice:&[f64]) -> u32 { let mut x:u32 = 0; let mut max = slice[0]; for i in 1..slice.len() { if max<slice[i] { x = i as u32; max = slice[i]; } } x } fn field_to_input(field:&mut Field, p:i32) -> Vec<f64> { let op:i32 = if p == 1 { 2 } else { 1 }; //other player let mut input:Vec<f64> = Vec::with_capacity((2*field.get_size() + field.get_w()) as usize); for (i, val) in field.get_field().iter().enumerate() { //2 nodes for every square: -1 enemy, 0 free, 1 own; 0 square will not be reached with one move, 1 square can be directly filled if *val == p { input.push(1f64); input.push(0f64); } else if *val == op { input.push(-1f64); input.push(0f64); } else { //empty square input.push(0f64); if (i as u32) < (field.get_size()-field.get_w()) { input.push(if field.get_field()[i+field.get_w() as usize]!= 0 { 1f64 } else { 0f64 }); } else { input.push(1f64); } } } for x in 0..field.get_w() { //1 node for every column: 1 own win, -1 enemy win, 0 none (which consistent order of the nodes does not matter, fully connected) if field.play(p, x) { //valid play match field.get_state() { -1 | 0 => input.push(0f64), pid => input.push(if pid == p {1f64} else {-1f64}), } field.undo(); } else { input.push(0f64); } //illegal move, nobody can win } input } fn learn(&mut self) { let nn = self.nn.as_mut().unwrap(); nn.train(&self.play_buffer) .halt_condition(HaltCondition::Epochs(EPOCHS_PER_STEP)) .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); self.play_buffer.clear(); self.num_buffered = 0; } } impl Player for PlayerAIQOff { fn init(&mut self, field:&Field, p:i32) -> bool { self.pid = p; self.filename = format!("AIQOff-{}x{}.NN", field.get_w(), field.get_h()); let file = File::open(&self.filename); if file.is_err() { //create new neural net, is it could not be loaded let n = field.get_size(); let w = field.get_w(); self.nn = Some(NN::new(&[2*n+w, 4*n, 2*n, n, n, n/2, w], Activation::Sigmoid, Activation::Sigmoid)); //set size of NN layers here //games_played, exploration, lr already set } else { //load neural net from file (and games played) let mut reader = BufReader::new(file.unwrap()); let mut datas = String::new(); let mut nns = String::new(); let res1 = reader.read_line(&mut datas); let res2 = reader.read_to_string(&mut nns); if res1.is_err() || res2.is_err() { return false; } let res = datas.trim().parse::<u32>(); if res.is_err() { return false; } self.games_played = res.unwrap(); self.nn = Some(NN::from_json(&nns)); self.lr = self.get_lr(); self.exploration = self.get_exploration(); } self.initialized = true; true } #[allow(unused_variables)] fn startp(&mut self, p:i32) { //nothing } fn play(&mut self, field:&mut Field) -> bool { if!self.initialized { return false; } //variables let mut rng = rand::thread_rng(); let nn = self.nn.as_mut().unwrap(); let mut res = false; //choose an action (try again until it meets the rules) while!res { //get current state formatted for the neural net (in loop because ownerships gets moved later) let state = PlayerAIQOff::field_to_input(field, self.pid); //choose action by e-greedy let mut qval = nn.run(&state); let mut x = PlayerAIQOff::argmax(&qval); if rng.gen::<f64>() < self.exploration //random exploration { x = rng.gen::<u32>() % field.get_w(); } //perform action res = field.play(self.pid, x); //save play data if not fixed, but learn if move did not was rule-conform if!self.fixed ||!res { //calculate q update or collect data for later learn if!res { qval[x as usize] = 0f64; } //invalid play instant learn else { qval[x as usize] = -1f64; } //mark field to set values later for learning //initiate training or save data if res { //add latest experience to replay_buffer self.play_buffer.push((state, qval)); } else { let training = [(state, qval)]; nn.train(&training) .halt_condition(HaltCondition::Epochs(1)) //only one epoch for rule mistakes .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); } } } //field.print(); //debug res } #[allow(unused_variables)] fn outcome(&mut self, field:&mut Field, state:i32) { if self.initialized &&!self.fixed //learning { //get reward let otherp = if self.pid == 1 {2} else {1}; let mut reward = 0f64; //draw (or running, should not happen) if state == self.pid { reward = 1f64; } else if state == otherp { reward = -1f64; } //compute learning data let w:usize = field.get_w() as usize; let len = self.play_buffer.len() as i32; let mut start = 0; if len > (field.get_w() * field.get_h()) as i32 { start = len - (field.get_w() * field.get_h()) as i32; } for count in start..len { let mut qval = &mut self.play_buffer[count as usize].1; for i in 0..w { if qval[i] == -1f64 { qval[i] = (GAMMA.powi(len - count) * reward + 1f64) / 2f64; // (+1)/2 => accumulate for sigmoid break; } } } //learn self.num_buffered += 1; if self.num_buffered >= LEARNING_SET { self.learn(); } } //set parameters self.games_played += 1; self.lr = self.get_lr(); self.exploration = self.get_exploration(); } } impl Drop for PlayerAIQOff { fn drop(&mut self) { //write neural net to file, if it may has learned and was initialized if self.initialized &&!self.fixed { //learn if self.num_buffered > 0 { self.learn(); } //save NN let file = File::create(&self.filename); if file.is_err() { println!("Warning: Could not write AIQ NN file!"); return; } let mut writer = BufWriter::new(file.unwrap()); let res1 = writeln!(&mut writer, "{}", self.games_played); let res2 = write!(&mut writer, "{}", self.nn.as_mut().unwrap().to_json()); if res1.is_err() || res2.is_err() { println!("Warning: There was an error while writing AIQ NN file!"); return; } } } }
get_lr
identifier_name
ai_qoff_player.rs
//! offline reinforcement learning (q learning after match is over) #![allow(dead_code)] extern crate rand; extern crate nn; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use self::rand::Rng; use self::nn::{NN, HaltCondition, Activation}; use super::Player; use super::super::field::Field; const GAMMA:f64 = 0.95; //temporal sureness (->1 means more sure about early actions always lead to win) const LR:f64 = 0.1; //neural net learning rate const LR_DECAY:f64 = 10000f64; //NN learning rate decrease (half every DECAY games) const LR_MIN:f64 = 0.01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //number of games to collect before learning pub struct PlayerAIQOff { initialized: bool, fixed: bool, //should the agent learn or not (fixed => dont learn) filename: String, pid: i32, //player ID nn: Option<NN>, //neural network games_played: u32, lr: f64, exploration: f64, play_buffer: Vec<(Vec<f64>, Vec<f64>)>, num_buffered: i32, } impl PlayerAIQOff { pub fn new(fix:bool) -> Box<PlayerAIQOff>
fn get_exploration(&self) -> f64 { RND_PICK_START * (2f64).powf(-(self.games_played as f64)/RND_PICK_DEC) } fn get_lr(&self) -> f64 { LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY)) } fn argmax(slice:&[f64]) -> u32 { let mut x:u32 = 0; let mut max = slice[0]; for i in 1..slice.len() { if max<slice[i] { x = i as u32; max = slice[i]; } } x } fn field_to_input(field:&mut Field, p:i32) -> Vec<f64> { let op:i32 = if p == 1 { 2 } else { 1 }; //other player let mut input:Vec<f64> = Vec::with_capacity((2*field.get_size() + field.get_w()) as usize); for (i, val) in field.get_field().iter().enumerate() { //2 nodes for every square: -1 enemy, 0 free, 1 own; 0 square will not be reached with one move, 1 square can be directly filled if *val == p { input.push(1f64); input.push(0f64); } else if *val == op { input.push(-1f64); input.push(0f64); } else { //empty square input.push(0f64); if (i as u32) < (field.get_size()-field.get_w()) { input.push(if field.get_field()[i+field.get_w() as usize]!= 0 { 1f64 } else { 0f64 }); } else { input.push(1f64); } } } for x in 0..field.get_w() { //1 node for every column: 1 own win, -1 enemy win, 0 none (which consistent order of the nodes does not matter, fully connected) if field.play(p, x) { //valid play match field.get_state() { -1 | 0 => input.push(0f64), pid => input.push(if pid == p {1f64} else {-1f64}), } field.undo(); } else { input.push(0f64); } //illegal move, nobody can win } input } fn learn(&mut self) { let nn = self.nn.as_mut().unwrap(); nn.train(&self.play_buffer) .halt_condition(HaltCondition::Epochs(EPOCHS_PER_STEP)) .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); self.play_buffer.clear(); self.num_buffered = 0; } } impl Player for PlayerAIQOff { fn init(&mut self, field:&Field, p:i32) -> bool { self.pid = p; self.filename = format!("AIQOff-{}x{}.NN", field.get_w(), field.get_h()); let file = File::open(&self.filename); if file.is_err() { //create new neural net, is it could not be loaded let n = field.get_size(); let w = field.get_w(); self.nn = Some(NN::new(&[2*n+w, 4*n, 2*n, n, n, n/2, w], Activation::Sigmoid, Activation::Sigmoid)); //set size of NN layers here //games_played, exploration, lr already set } else { //load neural net from file (and games played) let mut reader = BufReader::new(file.unwrap()); let mut datas = String::new(); let mut nns = String::new(); let res1 = reader.read_line(&mut datas); let res2 = reader.read_to_string(&mut nns); if res1.is_err() || res2.is_err() { return false; } let res = datas.trim().parse::<u32>(); if res.is_err() { return false; } self.games_played = res.unwrap(); self.nn = Some(NN::from_json(&nns)); self.lr = self.get_lr(); self.exploration = self.get_exploration(); } self.initialized = true; true } #[allow(unused_variables)] fn startp(&mut self, p:i32) { //nothing } fn play(&mut self, field:&mut Field) -> bool { if!self.initialized { return false; } //variables let mut rng = rand::thread_rng(); let nn = self.nn.as_mut().unwrap(); let mut res = false; //choose an action (try again until it meets the rules) while!res { //get current state formatted for the neural net (in loop because ownerships gets moved later) let state = PlayerAIQOff::field_to_input(field, self.pid); //choose action by e-greedy let mut qval = nn.run(&state); let mut x = PlayerAIQOff::argmax(&qval); if rng.gen::<f64>() < self.exploration //random exploration { x = rng.gen::<u32>() % field.get_w(); } //perform action res = field.play(self.pid, x); //save play data if not fixed, but learn if move did not was rule-conform if!self.fixed ||!res { //calculate q update or collect data for later learn if!res { qval[x as usize] = 0f64; } //invalid play instant learn else { qval[x as usize] = -1f64; } //mark field to set values later for learning //initiate training or save data if res { //add latest experience to replay_buffer self.play_buffer.push((state, qval)); } else { let training = [(state, qval)]; nn.train(&training) .halt_condition(HaltCondition::Epochs(1)) //only one epoch for rule mistakes .log_interval(None) //.log_interval(Some(2)) //debug .momentum(MOM) .rate(self.lr) .go(); } } } //field.print(); //debug res } #[allow(unused_variables)] fn outcome(&mut self, field:&mut Field, state:i32) { if self.initialized &&!self.fixed //learning { //get reward let otherp = if self.pid == 1 {2} else {1}; let mut reward = 0f64; //draw (or running, should not happen) if state == self.pid { reward = 1f64; } else if state == otherp { reward = -1f64; } //compute learning data let w:usize = field.get_w() as usize; let len = self.play_buffer.len() as i32; let mut start = 0; if len > (field.get_w() * field.get_h()) as i32 { start = len - (field.get_w() * field.get_h()) as i32; } for count in start..len { let mut qval = &mut self.play_buffer[count as usize].1; for i in 0..w { if qval[i] == -1f64 { qval[i] = (GAMMA.powi(len - count) * reward + 1f64) / 2f64; // (+1)/2 => accumulate for sigmoid break; } } } //learn self.num_buffered += 1; if self.num_buffered >= LEARNING_SET { self.learn(); } } //set parameters self.games_played += 1; self.lr = self.get_lr(); self.exploration = self.get_exploration(); } } impl Drop for PlayerAIQOff { fn drop(&mut self) { //write neural net to file, if it may has learned and was initialized if self.initialized &&!self.fixed { //learn if self.num_buffered > 0 { self.learn(); } //save NN let file = File::create(&self.filename); if file.is_err() { println!("Warning: Could not write AIQ NN file!"); return; } let mut writer = BufWriter::new(file.unwrap()); let res1 = writeln!(&mut writer, "{}", self.games_played); let res2 = write!(&mut writer, "{}", self.nn.as_mut().unwrap().to_json()); if res1.is_err() || res2.is_err() { println!("Warning: There was an error while writing AIQ NN file!"); return; } } } }
{ Box::new(PlayerAIQOff { initialized: false, fixed: fix, filename: String::new(), pid: 0, nn: None, games_played: 0, lr: LR, exploration: RND_PICK_START, play_buffer: Vec::new(), num_buffered: 0 }) }
identifier_body
builtin-superkinds-capabilities-xc.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:trait_superkinds_in_metadata.rs // Tests "capabilities" granted by traits with super-builtin-kinds, // even when using them cross-crate. extern crate trait_superkinds_in_metadata; use std::sync::mpsc::{channel, Sender, Receiver}; use trait_superkinds_in_metadata::{RequiresRequiresShareAndSend, RequiresShare}; #[derive(PartialEq, Debug)] struct X<T>(T); impl <T: Sync> RequiresShare for X<T> { } impl <T: Sync+Send> RequiresRequiresShareAndSend for X<T> { } fn
<T: RequiresRequiresShareAndSend +'static>(val: T, chan: Sender<T>) { chan.send(val).unwrap(); } pub fn main() { let (tx, rx): (Sender<X<isize>>, Receiver<X<isize>>) = channel(); foo(X(31337), tx); assert_eq!(rx.recv().unwrap(), X(31337)); }
foo
identifier_name
builtin-superkinds-capabilities-xc.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:trait_superkinds_in_metadata.rs // Tests "capabilities" granted by traits with super-builtin-kinds, // even when using them cross-crate. extern crate trait_superkinds_in_metadata; use std::sync::mpsc::{channel, Sender, Receiver}; use trait_superkinds_in_metadata::{RequiresRequiresShareAndSend, RequiresShare}; #[derive(PartialEq, Debug)] struct X<T>(T); impl <T: Sync> RequiresShare for X<T> { }
fn foo<T: RequiresRequiresShareAndSend +'static>(val: T, chan: Sender<T>) { chan.send(val).unwrap(); } pub fn main() { let (tx, rx): (Sender<X<isize>>, Receiver<X<isize>>) = channel(); foo(X(31337), tx); assert_eq!(rx.recv().unwrap(), X(31337)); }
impl <T: Sync+Send> RequiresRequiresShareAndSend for X<T> { }
random_line_split
ai.rs
use level::*; pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) { let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enemies.push((x,y)); }, _ => {} } x+=1; } y+=1; x=0; } let (px, py) = player_pos; for e in enemies { let (x,y) = e; let dx = (px-x) as f32; let dy = (py-y) as f32;
if distance<6f32 { let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right } else if dy<0f32 { Direction::Up } else { Direction::Down }; level.interact((x,y), dir); } } }
let distance = (dx*dx + dy*dy).sqrt();
random_line_split
ai.rs
use level::*; pub fn
(level : &mut Level, player_pos: (i32,i32)) { let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enemies.push((x,y)); }, _ => {} } x+=1; } y+=1; x=0; } let (px, py) = player_pos; for e in enemies { let (x,y) = e; let dx = (px-x) as f32; let dy = (py-y) as f32; let distance = (dx*dx + dy*dy).sqrt(); if distance<6f32 { let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right } else if dy<0f32 { Direction::Up } else { Direction::Down }; level.interact((x,y), dir); } } }
ai_step
identifier_name
ai.rs
use level::*; pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) { let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enemies.push((x,y)); }, _ => {} } x+=1; } y+=1; x=0; } let (px, py) = player_pos; for e in enemies { let (x,y) = e; let dx = (px-x) as f32; let dy = (py-y) as f32; let distance = (dx*dx + dy*dy).sqrt(); if distance<6f32
} }
{ let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right } else if dy<0f32 { Direction::Up } else { Direction::Down }; level.interact((x,y), dir); }
conditional_block
ai.rs
use level::*; pub fn ai_step(level : &mut Level, player_pos: (i32,i32))
for e in enemies { let (x,y) = e; let dx = (px-x) as f32; let dy = (py-y) as f32; let distance = (dx*dx + dy*dy).sqrt(); if distance<6f32 { let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right } else if dy<0f32 { Direction::Up } else { Direction::Down }; level.interact((x,y), dir); } } }
{ let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enemies.push((x,y)); }, _ => {} } x+=1; } y+=1; x=0; } let (px, py) = player_pos;
identifier_body
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::InheritTypes::HTMLAreaElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLAreaElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, NodeHelpers, ElementNodeTypeId}; use servo_util::str::DOMString; #[jstraceable] #[must_root] #[privatize] pub struct HTMLAreaElement { htmlelement: HTMLElement } impl HTMLAreaElementDerived for EventTarget { fn is_htmlareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId)) } } impl HTMLAreaElement { fn
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap) } } impl Reflectable for HTMLAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
new_inherited
identifier_name
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::InheritTypes::HTMLAreaElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLAreaElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use servo_util::str::DOMString; #[jstraceable] #[must_root] #[privatize] pub struct HTMLAreaElement { htmlelement: HTMLElement } impl HTMLAreaElementDerived for EventTarget { fn is_htmlareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId)) } } impl HTMLAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap) } } impl Reflectable for HTMLAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
use dom::htmlelement::HTMLElement; use dom::node::{Node, NodeHelpers, ElementNodeTypeId};
random_line_split
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::InheritTypes::HTMLAreaElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLAreaElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, NodeHelpers, ElementNodeTypeId}; use servo_util::str::DOMString; #[jstraceable] #[must_root] #[privatize] pub struct HTMLAreaElement { htmlelement: HTMLElement } impl HTMLAreaElementDerived for EventTarget { fn is_htmlareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId)) } } impl HTMLAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAreaElement
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap) } } impl Reflectable for HTMLAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ HTMLAreaElement { htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document) } }
identifier_body
option.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. use core::option::*; use core::kinds::marker; use core::mem; use core::clone::Clone; #[test] fn test_get_ptr() { unsafe { let x = box 0i; let addr_x: *const int = mem::transmute(&*x); let opt = Some(x); let y = opt.unwrap(); let addr_y: *const int = mem::transmute(&*y); assert_eq!(addr_x, addr_y); } } #[test] fn test_get_str() { let x = "test".to_string(); let addr_x = x.as_slice().as_ptr(); let opt = Some(x); let y = opt.unwrap(); let addr_y = y.as_slice().as_ptr(); assert_eq!(addr_x, addr_y); } #[test] fn test_get_resource() { use std::rc::Rc; use core::cell::RefCell; struct R { i: Rc<RefCell<int>>, } #[unsafe_destructor] impl Drop for R { fn drop(&mut self) { let ii = &*self.i; let i = *ii.borrow(); *ii.borrow_mut() = i + 1; } } fn r(i: Rc<RefCell<int>>) -> R { R { i: i } } let i = Rc::new(RefCell::new(0i)); { let x = r(i.clone()); let opt = Some(x); let _y = opt.unwrap(); } assert_eq!(*i.borrow(), 1); } #[test] fn test_option_dance() { let x = Some(()); let mut y = Some(5i); let mut y2 = 0; for _x in x.iter() { y2 = y.take().unwrap(); }
#[test] #[should_fail] fn test_option_too_much_dance() { let mut y = Some(marker::NoCopy); let _y2 = y.take().unwrap(); let _y3 = y.take().unwrap(); } #[test] fn test_and() { let x: Option<int> = Some(1i); assert_eq!(x.and(Some(2i)), Some(2)); assert_eq!(x.and(None::<int>), None); let x: Option<int> = None; assert_eq!(x.and(Some(2i)), None); assert_eq!(x.and(None::<int>), None); } #[test] fn test_and_then() { let x: Option<int> = Some(1); assert_eq!(x.and_then(|x| Some(x + 1)), Some(2)); assert_eq!(x.and_then(|_| None::<int>), None); let x: Option<int> = None; assert_eq!(x.and_then(|x| Some(x + 1)), None); assert_eq!(x.and_then(|_| None::<int>), None); } #[test] fn test_or() { let x: Option<int> = Some(1); assert_eq!(x.or(Some(2)), Some(1)); assert_eq!(x.or(None), Some(1)); let x: Option<int> = None; assert_eq!(x.or(Some(2)), Some(2)); assert_eq!(x.or(None), None); } #[test] fn test_or_else() { let x: Option<int> = Some(1); assert_eq!(x.or_else(|| Some(2)), Some(1)); assert_eq!(x.or_else(|| None), Some(1)); let x: Option<int> = None; assert_eq!(x.or_else(|| Some(2)), Some(2)); assert_eq!(x.or_else(|| None), None); } #[test] fn test_unwrap() { assert_eq!(Some(1i).unwrap(), 1); let s = Some("hello".to_string()).unwrap(); assert_eq!(s.as_slice(), "hello"); } #[test] #[should_fail] fn test_unwrap_panic1() { let x: Option<int> = None; x.unwrap(); } #[test] #[should_fail] fn test_unwrap_panic2() { let x: Option<String> = None; x.unwrap(); } #[test] fn test_unwrap_or() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or(2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or(2), 2); } #[test] fn test_unwrap_or_else() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or_else(|| 2), 2); } #[test] fn test_iter() { let val = 5i; let x = Some(val); let mut it = x.iter(); assert_eq!(it.size_hint(), (1, Some(1))); assert_eq!(it.next(), Some(&val)); assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } #[test] fn test_mut_iter() { let val = 5i; let new_val = 11i; let mut x = Some(val); { let mut it = x.iter_mut(); assert_eq!(it.size_hint(), (1, Some(1))); match it.next() { Some(interior) => { assert_eq!(*interior, val); *interior = new_val; } None => assert!(false), } assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } assert_eq!(x, Some(new_val)); } #[test] fn test_ord() { let small = Some(1.0f64); let big = Some(5.0f64); let nan = Some(0.0f64/0.0); assert!(!(nan < big)); assert!(!(nan > big)); assert!(small < big); assert!(None < big); assert!(big > None); } #[test] fn test_collect() { let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect(); assert!(v == Some(vec![])); let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect(); assert!(v == Some(vec![0, 1, 2])); let v: Option<Vec<int>> = range(0i, 3).map(|x| { if x > 1 { None } else { Some(x) } }).collect(); assert!(v == None); // test that it does not take more elements than it needs let mut functions = [|| Some(()), || None, || panic!()]; let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect(); assert!(v == None); } #[test] fn test_cloned() { let val1 = 1u32; let mut val2 = 2u32; let val1_ref = &val1; let opt_none: Option<&'static u32> = None; let opt_ref = Some(&val1); let opt_ref_ref = Some(&val1_ref); let opt_mut_ref = Some(&mut val2); // None works assert_eq!(opt_none.clone(), None); assert_eq!(opt_none.cloned(), None); // Mutable refs work assert_eq!(opt_mut_ref.cloned(), Some(2u32)); // Immutable ref works assert_eq!(opt_ref.clone(), Some(&val1)); assert_eq!(opt_ref.cloned(), Some(1u32)); // Double Immutable ref works assert_eq!(opt_ref_ref.clone(), Some(&val1_ref)); assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1)); assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32)); }
assert_eq!(y2, 5); assert!(y.is_none()); }
random_line_split
option.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. use core::option::*; use core::kinds::marker; use core::mem; use core::clone::Clone; #[test] fn test_get_ptr() { unsafe { let x = box 0i; let addr_x: *const int = mem::transmute(&*x); let opt = Some(x); let y = opt.unwrap(); let addr_y: *const int = mem::transmute(&*y); assert_eq!(addr_x, addr_y); } } #[test] fn test_get_str() { let x = "test".to_string(); let addr_x = x.as_slice().as_ptr(); let opt = Some(x); let y = opt.unwrap(); let addr_y = y.as_slice().as_ptr(); assert_eq!(addr_x, addr_y); } #[test] fn test_get_resource() { use std::rc::Rc; use core::cell::RefCell; struct R { i: Rc<RefCell<int>>, } #[unsafe_destructor] impl Drop for R { fn drop(&mut self) { let ii = &*self.i; let i = *ii.borrow(); *ii.borrow_mut() = i + 1; } } fn r(i: Rc<RefCell<int>>) -> R { R { i: i } } let i = Rc::new(RefCell::new(0i)); { let x = r(i.clone()); let opt = Some(x); let _y = opt.unwrap(); } assert_eq!(*i.borrow(), 1); } #[test] fn test_option_dance() { let x = Some(()); let mut y = Some(5i); let mut y2 = 0; for _x in x.iter() { y2 = y.take().unwrap(); } assert_eq!(y2, 5); assert!(y.is_none()); } #[test] #[should_fail] fn test_option_too_much_dance() { let mut y = Some(marker::NoCopy); let _y2 = y.take().unwrap(); let _y3 = y.take().unwrap(); } #[test] fn test_and() { let x: Option<int> = Some(1i); assert_eq!(x.and(Some(2i)), Some(2)); assert_eq!(x.and(None::<int>), None); let x: Option<int> = None; assert_eq!(x.and(Some(2i)), None); assert_eq!(x.and(None::<int>), None); } #[test] fn test_and_then() { let x: Option<int> = Some(1); assert_eq!(x.and_then(|x| Some(x + 1)), Some(2)); assert_eq!(x.and_then(|_| None::<int>), None); let x: Option<int> = None; assert_eq!(x.and_then(|x| Some(x + 1)), None); assert_eq!(x.and_then(|_| None::<int>), None); } #[test] fn test_or() { let x: Option<int> = Some(1); assert_eq!(x.or(Some(2)), Some(1)); assert_eq!(x.or(None), Some(1)); let x: Option<int> = None; assert_eq!(x.or(Some(2)), Some(2)); assert_eq!(x.or(None), None); } #[test] fn test_or_else() { let x: Option<int> = Some(1); assert_eq!(x.or_else(|| Some(2)), Some(1)); assert_eq!(x.or_else(|| None), Some(1)); let x: Option<int> = None; assert_eq!(x.or_else(|| Some(2)), Some(2)); assert_eq!(x.or_else(|| None), None); } #[test] fn test_unwrap() { assert_eq!(Some(1i).unwrap(), 1); let s = Some("hello".to_string()).unwrap(); assert_eq!(s.as_slice(), "hello"); } #[test] #[should_fail] fn test_unwrap_panic1() { let x: Option<int> = None; x.unwrap(); } #[test] #[should_fail] fn test_unwrap_panic2() { let x: Option<String> = None; x.unwrap(); } #[test] fn test_unwrap_or() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or(2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or(2), 2); } #[test] fn test_unwrap_or_else() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or_else(|| 2), 2); } #[test] fn test_iter() { let val = 5i; let x = Some(val); let mut it = x.iter(); assert_eq!(it.size_hint(), (1, Some(1))); assert_eq!(it.next(), Some(&val)); assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } #[test] fn test_mut_iter() { let val = 5i; let new_val = 11i; let mut x = Some(val); { let mut it = x.iter_mut(); assert_eq!(it.size_hint(), (1, Some(1))); match it.next() { Some(interior) =>
None => assert!(false), } assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } assert_eq!(x, Some(new_val)); } #[test] fn test_ord() { let small = Some(1.0f64); let big = Some(5.0f64); let nan = Some(0.0f64/0.0); assert!(!(nan < big)); assert!(!(nan > big)); assert!(small < big); assert!(None < big); assert!(big > None); } #[test] fn test_collect() { let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect(); assert!(v == Some(vec![])); let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect(); assert!(v == Some(vec![0, 1, 2])); let v: Option<Vec<int>> = range(0i, 3).map(|x| { if x > 1 { None } else { Some(x) } }).collect(); assert!(v == None); // test that it does not take more elements than it needs let mut functions = [|| Some(()), || None, || panic!()]; let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect(); assert!(v == None); } #[test] fn test_cloned() { let val1 = 1u32; let mut val2 = 2u32; let val1_ref = &val1; let opt_none: Option<&'static u32> = None; let opt_ref = Some(&val1); let opt_ref_ref = Some(&val1_ref); let opt_mut_ref = Some(&mut val2); // None works assert_eq!(opt_none.clone(), None); assert_eq!(opt_none.cloned(), None); // Mutable refs work assert_eq!(opt_mut_ref.cloned(), Some(2u32)); // Immutable ref works assert_eq!(opt_ref.clone(), Some(&val1)); assert_eq!(opt_ref.cloned(), Some(1u32)); // Double Immutable ref works assert_eq!(opt_ref_ref.clone(), Some(&val1_ref)); assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1)); assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32)); }
{ assert_eq!(*interior, val); *interior = new_val; }
conditional_block
option.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. use core::option::*; use core::kinds::marker; use core::mem; use core::clone::Clone; #[test] fn test_get_ptr() { unsafe { let x = box 0i; let addr_x: *const int = mem::transmute(&*x); let opt = Some(x); let y = opt.unwrap(); let addr_y: *const int = mem::transmute(&*y); assert_eq!(addr_x, addr_y); } } #[test] fn test_get_str() { let x = "test".to_string(); let addr_x = x.as_slice().as_ptr(); let opt = Some(x); let y = opt.unwrap(); let addr_y = y.as_slice().as_ptr(); assert_eq!(addr_x, addr_y); } #[test] fn test_get_resource() { use std::rc::Rc; use core::cell::RefCell; struct R { i: Rc<RefCell<int>>, } #[unsafe_destructor] impl Drop for R { fn drop(&mut self) { let ii = &*self.i; let i = *ii.borrow(); *ii.borrow_mut() = i + 1; } } fn r(i: Rc<RefCell<int>>) -> R { R { i: i } } let i = Rc::new(RefCell::new(0i)); { let x = r(i.clone()); let opt = Some(x); let _y = opt.unwrap(); } assert_eq!(*i.borrow(), 1); } #[test] fn test_option_dance() { let x = Some(()); let mut y = Some(5i); let mut y2 = 0; for _x in x.iter() { y2 = y.take().unwrap(); } assert_eq!(y2, 5); assert!(y.is_none()); } #[test] #[should_fail] fn test_option_too_much_dance() { let mut y = Some(marker::NoCopy); let _y2 = y.take().unwrap(); let _y3 = y.take().unwrap(); } #[test] fn test_and() { let x: Option<int> = Some(1i); assert_eq!(x.and(Some(2i)), Some(2)); assert_eq!(x.and(None::<int>), None); let x: Option<int> = None; assert_eq!(x.and(Some(2i)), None); assert_eq!(x.and(None::<int>), None); } #[test] fn test_and_then() { let x: Option<int> = Some(1); assert_eq!(x.and_then(|x| Some(x + 1)), Some(2)); assert_eq!(x.and_then(|_| None::<int>), None); let x: Option<int> = None; assert_eq!(x.and_then(|x| Some(x + 1)), None); assert_eq!(x.and_then(|_| None::<int>), None); } #[test] fn test_or() { let x: Option<int> = Some(1); assert_eq!(x.or(Some(2)), Some(1)); assert_eq!(x.or(None), Some(1)); let x: Option<int> = None; assert_eq!(x.or(Some(2)), Some(2)); assert_eq!(x.or(None), None); } #[test] fn
() { let x: Option<int> = Some(1); assert_eq!(x.or_else(|| Some(2)), Some(1)); assert_eq!(x.or_else(|| None), Some(1)); let x: Option<int> = None; assert_eq!(x.or_else(|| Some(2)), Some(2)); assert_eq!(x.or_else(|| None), None); } #[test] fn test_unwrap() { assert_eq!(Some(1i).unwrap(), 1); let s = Some("hello".to_string()).unwrap(); assert_eq!(s.as_slice(), "hello"); } #[test] #[should_fail] fn test_unwrap_panic1() { let x: Option<int> = None; x.unwrap(); } #[test] #[should_fail] fn test_unwrap_panic2() { let x: Option<String> = None; x.unwrap(); } #[test] fn test_unwrap_or() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or(2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or(2), 2); } #[test] fn test_unwrap_or_else() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or_else(|| 2), 2); } #[test] fn test_iter() { let val = 5i; let x = Some(val); let mut it = x.iter(); assert_eq!(it.size_hint(), (1, Some(1))); assert_eq!(it.next(), Some(&val)); assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } #[test] fn test_mut_iter() { let val = 5i; let new_val = 11i; let mut x = Some(val); { let mut it = x.iter_mut(); assert_eq!(it.size_hint(), (1, Some(1))); match it.next() { Some(interior) => { assert_eq!(*interior, val); *interior = new_val; } None => assert!(false), } assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } assert_eq!(x, Some(new_val)); } #[test] fn test_ord() { let small = Some(1.0f64); let big = Some(5.0f64); let nan = Some(0.0f64/0.0); assert!(!(nan < big)); assert!(!(nan > big)); assert!(small < big); assert!(None < big); assert!(big > None); } #[test] fn test_collect() { let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect(); assert!(v == Some(vec![])); let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect(); assert!(v == Some(vec![0, 1, 2])); let v: Option<Vec<int>> = range(0i, 3).map(|x| { if x > 1 { None } else { Some(x) } }).collect(); assert!(v == None); // test that it does not take more elements than it needs let mut functions = [|| Some(()), || None, || panic!()]; let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect(); assert!(v == None); } #[test] fn test_cloned() { let val1 = 1u32; let mut val2 = 2u32; let val1_ref = &val1; let opt_none: Option<&'static u32> = None; let opt_ref = Some(&val1); let opt_ref_ref = Some(&val1_ref); let opt_mut_ref = Some(&mut val2); // None works assert_eq!(opt_none.clone(), None); assert_eq!(opt_none.cloned(), None); // Mutable refs work assert_eq!(opt_mut_ref.cloned(), Some(2u32)); // Immutable ref works assert_eq!(opt_ref.clone(), Some(&val1)); assert_eq!(opt_ref.cloned(), Some(1u32)); // Double Immutable ref works assert_eq!(opt_ref_ref.clone(), Some(&val1_ref)); assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1)); assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32)); }
test_or_else
identifier_name
global.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. /*! Global data An interface for creating and retrieving values with global (per-runtime) scope. Global values are stored in a map and protected by a single global mutex. Operations are provided for accessing and cloning the value under the mutex. Because all globals go through a single mutex, they should be used sparingly. The interface is intended to be used with clonable, atomically reference counted synchronization types, like ARCs, in which case the value should be cached locally whenever possible to avoid hitting the mutex. */ use cast::{transmute}; use clone::Clone; use kinds::Send; use libc::{c_void}; use option::{Option, Some, None}; use ops::Drop; use unstable::sync::{Exclusive, exclusive}; use unstable::at_exit::at_exit; use unstable::intrinsics::atomic_cxchg; use hashmap::HashMap; use sys::Closure; #[cfg(test)] use unstable::sync::{UnsafeAtomicRcBox}; #[cfg(test)] use task::spawn; #[cfg(test)] use uint; pub type GlobalDataKey<'self,T> = &'self fn(v: T); pub unsafe fn global_data_clone_create<T:Send + Clone>( key: GlobalDataKey<T>, create: &fn() -> ~T) -> T { /*! * Clone a global value or, if it has not been created, * first construct the value then return a clone. * * # Safety note * * Both the clone operation and the constructor are * called while the global lock is held. Recursive * use of the global interface in either of these * operations will result in deadlock. */ global_data_clone_create_(key_ptr(key), create) } unsafe fn global_data_clone_create_<T:Send + Clone>( key: uint, create: &fn() -> ~T) -> T { let mut clone_value: Option<T> = None; do global_data_modify_(key) |value: Option<~T>| { match value { None => { let value = create(); clone_value = Some((*value).clone()); Some(value) } Some(value) => { clone_value = Some((*value).clone()); Some(value) } } } return clone_value.unwrap(); } unsafe fn global_data_modify<T:Send>( key: GlobalDataKey<T>, op: &fn(Option<~T>) -> Option<~T>) { global_data_modify_(key_ptr(key), op) } unsafe fn global_data_modify_<T:Send>( key: uint, op: &fn(Option<~T>) -> Option<~T>) { let mut old_dtor = None; do get_global_state().with |gs| { let (maybe_new_value, maybe_dtor) = match gs.map.pop(&key) { Some((ptr, dtor)) => { let value: ~T = transmute(ptr); (op(Some(value)), Some(dtor)) } None => { (op(None), None) } }; match maybe_new_value { Some(value) => { let data: *c_void = transmute(value); let dtor: ~fn() = match maybe_dtor { Some(dtor) => dtor, None => { let dtor: ~fn() = || { let _destroy_value: ~T = transmute(data); }; dtor } }; let value = (data, dtor); gs.map.insert(key, value); } None => { match maybe_dtor { Some(dtor) => old_dtor = Some(dtor), None => () } } } } } pub unsafe fn global_data_clone<T:Send + Clone>( key: GlobalDataKey<T>) -> Option<T> {
let mut maybe_clone: Option<T> = None; do global_data_modify(key) |current| { match &current { &Some(~ref value) => { maybe_clone = Some(value.clone()); } &None => () } current } return maybe_clone; } // GlobalState is a map from keys to unique pointers and a // destructor. Keys are pointers derived from the type of the // global value. There is a single GlobalState instance per runtime. struct GlobalState { map: HashMap<uint, (*c_void, ~fn())> } impl Drop for GlobalState { fn drop(&self) { for self.map.each_value |v| { match v { &(_, ref dtor) => (*dtor)() } } } } fn get_global_state() -> Exclusive<GlobalState> { static POISON: int = -1; // FIXME #4728: Doing atomic_cxchg to initialize the global state // lazily, which wouldn't be necessary with a runtime written // in Rust let global_ptr = unsafe { rust_get_global_data_ptr() }; if unsafe { *global_ptr } == 0 { // Global state doesn't exist yet, probably // The global state object let state = GlobalState { map: HashMap::new() }; // It's under a reference-counted mutex let state = ~exclusive(state); // Convert it to an integer let state_i: int = unsafe { let state_ptr: &Exclusive<GlobalState> = state; transmute(state_ptr) }; // Swap our structure into the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, 0, state_i) }; // Sanity check that we're not trying to reinitialize after shutdown assert!(prev_i!= POISON); if prev_i == 0 { // Successfully installed the global pointer // Take a handle to return let clone = (*state).clone(); // Install a runtime exit function to destroy the global object do at_exit { // Poison the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, state_i, POISON) }; assert_eq!(prev_i, state_i); // Capture the global state object in the at_exit closure // so that it is destroyed at the right time let _capture_global_state = &state; }; return clone; } else { // Somebody else initialized the globals first let state: &Exclusive<GlobalState> = unsafe { transmute(prev_i) }; return state.clone(); } } else { let state: &Exclusive<GlobalState> = unsafe { transmute(*global_ptr) }; return state.clone(); } } fn key_ptr<T:Send>(key: GlobalDataKey<T>) -> uint { unsafe { let closure: Closure = transmute(key); return transmute(closure.code); } } extern { fn rust_get_global_data_ptr() -> *mut int; } #[test] fn test_clone_rc() { fn key(_v: UnsafeAtomicRcBox<int>) { } for uint::range(0, 100) |_| { do spawn { unsafe { let val = do global_data_clone_create(key) { ~UnsafeAtomicRcBox::new(10) }; assert!(val.get() == &10); } } } } #[test] fn test_modify() { fn key(_v: UnsafeAtomicRcBox<int>) { } unsafe { do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } do global_data_modify(key) |v| { match v { Some(sms) => { let v = sms.get(); assert!(*v == 10); None }, _ => fail!() } } do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } } }
random_line_split
global.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. /*! Global data An interface for creating and retrieving values with global (per-runtime) scope. Global values are stored in a map and protected by a single global mutex. Operations are provided for accessing and cloning the value under the mutex. Because all globals go through a single mutex, they should be used sparingly. The interface is intended to be used with clonable, atomically reference counted synchronization types, like ARCs, in which case the value should be cached locally whenever possible to avoid hitting the mutex. */ use cast::{transmute}; use clone::Clone; use kinds::Send; use libc::{c_void}; use option::{Option, Some, None}; use ops::Drop; use unstable::sync::{Exclusive, exclusive}; use unstable::at_exit::at_exit; use unstable::intrinsics::atomic_cxchg; use hashmap::HashMap; use sys::Closure; #[cfg(test)] use unstable::sync::{UnsafeAtomicRcBox}; #[cfg(test)] use task::spawn; #[cfg(test)] use uint; pub type GlobalDataKey<'self,T> = &'self fn(v: T); pub unsafe fn global_data_clone_create<T:Send + Clone>( key: GlobalDataKey<T>, create: &fn() -> ~T) -> T { /*! * Clone a global value or, if it has not been created, * first construct the value then return a clone. * * # Safety note * * Both the clone operation and the constructor are * called while the global lock is held. Recursive * use of the global interface in either of these * operations will result in deadlock. */ global_data_clone_create_(key_ptr(key), create) } unsafe fn global_data_clone_create_<T:Send + Clone>( key: uint, create: &fn() -> ~T) -> T { let mut clone_value: Option<T> = None; do global_data_modify_(key) |value: Option<~T>| { match value { None => { let value = create(); clone_value = Some((*value).clone()); Some(value) } Some(value) => { clone_value = Some((*value).clone()); Some(value) } } } return clone_value.unwrap(); } unsafe fn global_data_modify<T:Send>( key: GlobalDataKey<T>, op: &fn(Option<~T>) -> Option<~T>) { global_data_modify_(key_ptr(key), op) } unsafe fn global_data_modify_<T:Send>( key: uint, op: &fn(Option<~T>) -> Option<~T>) { let mut old_dtor = None; do get_global_state().with |gs| { let (maybe_new_value, maybe_dtor) = match gs.map.pop(&key) { Some((ptr, dtor)) => { let value: ~T = transmute(ptr); (op(Some(value)), Some(dtor)) } None =>
}; match maybe_new_value { Some(value) => { let data: *c_void = transmute(value); let dtor: ~fn() = match maybe_dtor { Some(dtor) => dtor, None => { let dtor: ~fn() = || { let _destroy_value: ~T = transmute(data); }; dtor } }; let value = (data, dtor); gs.map.insert(key, value); } None => { match maybe_dtor { Some(dtor) => old_dtor = Some(dtor), None => () } } } } } pub unsafe fn global_data_clone<T:Send + Clone>( key: GlobalDataKey<T>) -> Option<T> { let mut maybe_clone: Option<T> = None; do global_data_modify(key) |current| { match &current { &Some(~ref value) => { maybe_clone = Some(value.clone()); } &None => () } current } return maybe_clone; } // GlobalState is a map from keys to unique pointers and a // destructor. Keys are pointers derived from the type of the // global value. There is a single GlobalState instance per runtime. struct GlobalState { map: HashMap<uint, (*c_void, ~fn())> } impl Drop for GlobalState { fn drop(&self) { for self.map.each_value |v| { match v { &(_, ref dtor) => (*dtor)() } } } } fn get_global_state() -> Exclusive<GlobalState> { static POISON: int = -1; // FIXME #4728: Doing atomic_cxchg to initialize the global state // lazily, which wouldn't be necessary with a runtime written // in Rust let global_ptr = unsafe { rust_get_global_data_ptr() }; if unsafe { *global_ptr } == 0 { // Global state doesn't exist yet, probably // The global state object let state = GlobalState { map: HashMap::new() }; // It's under a reference-counted mutex let state = ~exclusive(state); // Convert it to an integer let state_i: int = unsafe { let state_ptr: &Exclusive<GlobalState> = state; transmute(state_ptr) }; // Swap our structure into the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, 0, state_i) }; // Sanity check that we're not trying to reinitialize after shutdown assert!(prev_i!= POISON); if prev_i == 0 { // Successfully installed the global pointer // Take a handle to return let clone = (*state).clone(); // Install a runtime exit function to destroy the global object do at_exit { // Poison the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, state_i, POISON) }; assert_eq!(prev_i, state_i); // Capture the global state object in the at_exit closure // so that it is destroyed at the right time let _capture_global_state = &state; }; return clone; } else { // Somebody else initialized the globals first let state: &Exclusive<GlobalState> = unsafe { transmute(prev_i) }; return state.clone(); } } else { let state: &Exclusive<GlobalState> = unsafe { transmute(*global_ptr) }; return state.clone(); } } fn key_ptr<T:Send>(key: GlobalDataKey<T>) -> uint { unsafe { let closure: Closure = transmute(key); return transmute(closure.code); } } extern { fn rust_get_global_data_ptr() -> *mut int; } #[test] fn test_clone_rc() { fn key(_v: UnsafeAtomicRcBox<int>) { } for uint::range(0, 100) |_| { do spawn { unsafe { let val = do global_data_clone_create(key) { ~UnsafeAtomicRcBox::new(10) }; assert!(val.get() == &10); } } } } #[test] fn test_modify() { fn key(_v: UnsafeAtomicRcBox<int>) { } unsafe { do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } do global_data_modify(key) |v| { match v { Some(sms) => { let v = sms.get(); assert!(*v == 10); None }, _ => fail!() } } do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } } }
{ (op(None), None) }
conditional_block
global.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. /*! Global data An interface for creating and retrieving values with global (per-runtime) scope. Global values are stored in a map and protected by a single global mutex. Operations are provided for accessing and cloning the value under the mutex. Because all globals go through a single mutex, they should be used sparingly. The interface is intended to be used with clonable, atomically reference counted synchronization types, like ARCs, in which case the value should be cached locally whenever possible to avoid hitting the mutex. */ use cast::{transmute}; use clone::Clone; use kinds::Send; use libc::{c_void}; use option::{Option, Some, None}; use ops::Drop; use unstable::sync::{Exclusive, exclusive}; use unstable::at_exit::at_exit; use unstable::intrinsics::atomic_cxchg; use hashmap::HashMap; use sys::Closure; #[cfg(test)] use unstable::sync::{UnsafeAtomicRcBox}; #[cfg(test)] use task::spawn; #[cfg(test)] use uint; pub type GlobalDataKey<'self,T> = &'self fn(v: T); pub unsafe fn global_data_clone_create<T:Send + Clone>( key: GlobalDataKey<T>, create: &fn() -> ~T) -> T { /*! * Clone a global value or, if it has not been created, * first construct the value then return a clone. * * # Safety note * * Both the clone operation and the constructor are * called while the global lock is held. Recursive * use of the global interface in either of these * operations will result in deadlock. */ global_data_clone_create_(key_ptr(key), create) } unsafe fn global_data_clone_create_<T:Send + Clone>( key: uint, create: &fn() -> ~T) -> T { let mut clone_value: Option<T> = None; do global_data_modify_(key) |value: Option<~T>| { match value { None => { let value = create(); clone_value = Some((*value).clone()); Some(value) } Some(value) => { clone_value = Some((*value).clone()); Some(value) } } } return clone_value.unwrap(); } unsafe fn global_data_modify<T:Send>( key: GlobalDataKey<T>, op: &fn(Option<~T>) -> Option<~T>) { global_data_modify_(key_ptr(key), op) } unsafe fn global_data_modify_<T:Send>( key: uint, op: &fn(Option<~T>) -> Option<~T>) { let mut old_dtor = None; do get_global_state().with |gs| { let (maybe_new_value, maybe_dtor) = match gs.map.pop(&key) { Some((ptr, dtor)) => { let value: ~T = transmute(ptr); (op(Some(value)), Some(dtor)) } None => { (op(None), None) } }; match maybe_new_value { Some(value) => { let data: *c_void = transmute(value); let dtor: ~fn() = match maybe_dtor { Some(dtor) => dtor, None => { let dtor: ~fn() = || { let _destroy_value: ~T = transmute(data); }; dtor } }; let value = (data, dtor); gs.map.insert(key, value); } None => { match maybe_dtor { Some(dtor) => old_dtor = Some(dtor), None => () } } } } } pub unsafe fn global_data_clone<T:Send + Clone>( key: GlobalDataKey<T>) -> Option<T> { let mut maybe_clone: Option<T> = None; do global_data_modify(key) |current| { match &current { &Some(~ref value) => { maybe_clone = Some(value.clone()); } &None => () } current } return maybe_clone; } // GlobalState is a map from keys to unique pointers and a // destructor. Keys are pointers derived from the type of the // global value. There is a single GlobalState instance per runtime. struct GlobalState { map: HashMap<uint, (*c_void, ~fn())> } impl Drop for GlobalState { fn drop(&self) { for self.map.each_value |v| { match v { &(_, ref dtor) => (*dtor)() } } } } fn get_global_state() -> Exclusive<GlobalState> { static POISON: int = -1; // FIXME #4728: Doing atomic_cxchg to initialize the global state // lazily, which wouldn't be necessary with a runtime written // in Rust let global_ptr = unsafe { rust_get_global_data_ptr() }; if unsafe { *global_ptr } == 0 { // Global state doesn't exist yet, probably // The global state object let state = GlobalState { map: HashMap::new() }; // It's under a reference-counted mutex let state = ~exclusive(state); // Convert it to an integer let state_i: int = unsafe { let state_ptr: &Exclusive<GlobalState> = state; transmute(state_ptr) }; // Swap our structure into the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, 0, state_i) }; // Sanity check that we're not trying to reinitialize after shutdown assert!(prev_i!= POISON); if prev_i == 0 { // Successfully installed the global pointer // Take a handle to return let clone = (*state).clone(); // Install a runtime exit function to destroy the global object do at_exit { // Poison the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, state_i, POISON) }; assert_eq!(prev_i, state_i); // Capture the global state object in the at_exit closure // so that it is destroyed at the right time let _capture_global_state = &state; }; return clone; } else { // Somebody else initialized the globals first let state: &Exclusive<GlobalState> = unsafe { transmute(prev_i) }; return state.clone(); } } else { let state: &Exclusive<GlobalState> = unsafe { transmute(*global_ptr) }; return state.clone(); } } fn key_ptr<T:Send>(key: GlobalDataKey<T>) -> uint { unsafe { let closure: Closure = transmute(key); return transmute(closure.code); } } extern { fn rust_get_global_data_ptr() -> *mut int; } #[test] fn test_clone_rc()
#[test] fn test_modify() { fn key(_v: UnsafeAtomicRcBox<int>) { } unsafe { do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } do global_data_modify(key) |v| { match v { Some(sms) => { let v = sms.get(); assert!(*v == 10); None }, _ => fail!() } } do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } } }
{ fn key(_v: UnsafeAtomicRcBox<int>) { } for uint::range(0, 100) |_| { do spawn { unsafe { let val = do global_data_clone_create(key) { ~UnsafeAtomicRcBox::new(10) }; assert!(val.get() == &10); } } } }
identifier_body
global.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. /*! Global data An interface for creating and retrieving values with global (per-runtime) scope. Global values are stored in a map and protected by a single global mutex. Operations are provided for accessing and cloning the value under the mutex. Because all globals go through a single mutex, they should be used sparingly. The interface is intended to be used with clonable, atomically reference counted synchronization types, like ARCs, in which case the value should be cached locally whenever possible to avoid hitting the mutex. */ use cast::{transmute}; use clone::Clone; use kinds::Send; use libc::{c_void}; use option::{Option, Some, None}; use ops::Drop; use unstable::sync::{Exclusive, exclusive}; use unstable::at_exit::at_exit; use unstable::intrinsics::atomic_cxchg; use hashmap::HashMap; use sys::Closure; #[cfg(test)] use unstable::sync::{UnsafeAtomicRcBox}; #[cfg(test)] use task::spawn; #[cfg(test)] use uint; pub type GlobalDataKey<'self,T> = &'self fn(v: T); pub unsafe fn global_data_clone_create<T:Send + Clone>( key: GlobalDataKey<T>, create: &fn() -> ~T) -> T { /*! * Clone a global value or, if it has not been created, * first construct the value then return a clone. * * # Safety note * * Both the clone operation and the constructor are * called while the global lock is held. Recursive * use of the global interface in either of these * operations will result in deadlock. */ global_data_clone_create_(key_ptr(key), create) } unsafe fn global_data_clone_create_<T:Send + Clone>( key: uint, create: &fn() -> ~T) -> T { let mut clone_value: Option<T> = None; do global_data_modify_(key) |value: Option<~T>| { match value { None => { let value = create(); clone_value = Some((*value).clone()); Some(value) } Some(value) => { clone_value = Some((*value).clone()); Some(value) } } } return clone_value.unwrap(); } unsafe fn global_data_modify<T:Send>( key: GlobalDataKey<T>, op: &fn(Option<~T>) -> Option<~T>) { global_data_modify_(key_ptr(key), op) } unsafe fn global_data_modify_<T:Send>( key: uint, op: &fn(Option<~T>) -> Option<~T>) { let mut old_dtor = None; do get_global_state().with |gs| { let (maybe_new_value, maybe_dtor) = match gs.map.pop(&key) { Some((ptr, dtor)) => { let value: ~T = transmute(ptr); (op(Some(value)), Some(dtor)) } None => { (op(None), None) } }; match maybe_new_value { Some(value) => { let data: *c_void = transmute(value); let dtor: ~fn() = match maybe_dtor { Some(dtor) => dtor, None => { let dtor: ~fn() = || { let _destroy_value: ~T = transmute(data); }; dtor } }; let value = (data, dtor); gs.map.insert(key, value); } None => { match maybe_dtor { Some(dtor) => old_dtor = Some(dtor), None => () } } } } } pub unsafe fn global_data_clone<T:Send + Clone>( key: GlobalDataKey<T>) -> Option<T> { let mut maybe_clone: Option<T> = None; do global_data_modify(key) |current| { match &current { &Some(~ref value) => { maybe_clone = Some(value.clone()); } &None => () } current } return maybe_clone; } // GlobalState is a map from keys to unique pointers and a // destructor. Keys are pointers derived from the type of the // global value. There is a single GlobalState instance per runtime. struct GlobalState { map: HashMap<uint, (*c_void, ~fn())> } impl Drop for GlobalState { fn drop(&self) { for self.map.each_value |v| { match v { &(_, ref dtor) => (*dtor)() } } } } fn
() -> Exclusive<GlobalState> { static POISON: int = -1; // FIXME #4728: Doing atomic_cxchg to initialize the global state // lazily, which wouldn't be necessary with a runtime written // in Rust let global_ptr = unsafe { rust_get_global_data_ptr() }; if unsafe { *global_ptr } == 0 { // Global state doesn't exist yet, probably // The global state object let state = GlobalState { map: HashMap::new() }; // It's under a reference-counted mutex let state = ~exclusive(state); // Convert it to an integer let state_i: int = unsafe { let state_ptr: &Exclusive<GlobalState> = state; transmute(state_ptr) }; // Swap our structure into the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, 0, state_i) }; // Sanity check that we're not trying to reinitialize after shutdown assert!(prev_i!= POISON); if prev_i == 0 { // Successfully installed the global pointer // Take a handle to return let clone = (*state).clone(); // Install a runtime exit function to destroy the global object do at_exit { // Poison the global pointer let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, state_i, POISON) }; assert_eq!(prev_i, state_i); // Capture the global state object in the at_exit closure // so that it is destroyed at the right time let _capture_global_state = &state; }; return clone; } else { // Somebody else initialized the globals first let state: &Exclusive<GlobalState> = unsafe { transmute(prev_i) }; return state.clone(); } } else { let state: &Exclusive<GlobalState> = unsafe { transmute(*global_ptr) }; return state.clone(); } } fn key_ptr<T:Send>(key: GlobalDataKey<T>) -> uint { unsafe { let closure: Closure = transmute(key); return transmute(closure.code); } } extern { fn rust_get_global_data_ptr() -> *mut int; } #[test] fn test_clone_rc() { fn key(_v: UnsafeAtomicRcBox<int>) { } for uint::range(0, 100) |_| { do spawn { unsafe { let val = do global_data_clone_create(key) { ~UnsafeAtomicRcBox::new(10) }; assert!(val.get() == &10); } } } } #[test] fn test_modify() { fn key(_v: UnsafeAtomicRcBox<int>) { } unsafe { do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } do global_data_modify(key) |v| { match v { Some(sms) => { let v = sms.get(); assert!(*v == 10); None }, _ => fail!() } } do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } } }
get_global_state
identifier_name
test_cargo_clean.rs
use support::{project, execs, main_file, basic_bin_manifest, cargo_dir}; use hamcrest::{assert_that, existing_dir, is_not}; fn setup()
test!(cargo_clean_simple { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()); assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()); assert_that(p.process(cargo_dir().join("cargo")).arg("clean"), execs().with_status(0)); assert_that(&p.build_dir(), is_not(existing_dir())); }) test!(different_dir { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()) .file("src/bar/a.rs", ""); assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()); assert_that(p.process(cargo_dir().join("cargo")).arg("clean") .cwd(p.root().join("src")), execs().with_status(0).with_stdout("")); assert_that(&p.build_dir(), is_not(existing_dir())); })
{ }
identifier_body
test_cargo_clean.rs
use support::{project, execs, main_file, basic_bin_manifest, cargo_dir}; use hamcrest::{assert_that, existing_dir, is_not}; fn
() { } test!(cargo_clean_simple { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()); assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()); assert_that(p.process(cargo_dir().join("cargo")).arg("clean"), execs().with_status(0)); assert_that(&p.build_dir(), is_not(existing_dir())); }) test!(different_dir { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()) .file("src/bar/a.rs", ""); assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()); assert_that(p.process(cargo_dir().join("cargo")).arg("clean") .cwd(p.root().join("src")), execs().with_status(0).with_stdout("")); assert_that(&p.build_dir(), is_not(existing_dir())); })
setup
identifier_name
test_cargo_clean.rs
use support::{project, execs, main_file, basic_bin_manifest, cargo_dir}; use hamcrest::{assert_that, existing_dir, is_not}; fn setup() { } test!(cargo_clean_simple { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice());
execs().with_status(0)); assert_that(&p.build_dir(), is_not(existing_dir())); }) test!(different_dir { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()) .file("src/bar/a.rs", ""); assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()); assert_that(p.process(cargo_dir().join("cargo")).arg("clean") .cwd(p.root().join("src")), execs().with_status(0).with_stdout("")); assert_that(&p.build_dir(), is_not(existing_dir())); })
assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()); assert_that(p.process(cargo_dir().join("cargo")).arg("clean"),
random_line_split
autoderef-method-priority.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. #![allow(unknown_features)] #![feature(box_syntax)] trait double { fn double(self) -> uint; } impl double for uint { fn double(self) -> uint
} impl double for Box<uint> { fn double(self) -> uint { *self * 2_usize } } pub fn main() { let x = box 3_usize; assert_eq!(x.double(), 6_usize); }
{ self }
identifier_body
autoderef-method-priority.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. #![allow(unknown_features)] #![feature(box_syntax)]
trait double { fn double(self) -> uint; } impl double for uint { fn double(self) -> uint { self } } impl double for Box<uint> { fn double(self) -> uint { *self * 2_usize } } pub fn main() { let x = box 3_usize; assert_eq!(x.double(), 6_usize); }
random_line_split
autoderef-method-priority.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. #![allow(unknown_features)] #![feature(box_syntax)] trait double { fn double(self) -> uint; } impl double for uint { fn
(self) -> uint { self } } impl double for Box<uint> { fn double(self) -> uint { *self * 2_usize } } pub fn main() { let x = box 3_usize; assert_eq!(x.double(), 6_usize); }
double
identifier_name
tessellation.rs
#[macro_use] extern crate glium; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod support; fn
() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new(); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], } implement_vertex!(Vertex, position); glium::VertexBuffer::new(&display, &[ Vertex { position: [-0.5, -0.5] }, Vertex { position: [ 0.0, 0.5] }, Vertex { position: [ 0.5, -0.5] }, ] ).unwrap() }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::Patches { vertices_per_patch: 3 }, &[0u16, 1, 2]).unwrap(); // compiling shaders and linking them together let program = glium::Program::new(&display, glium::program::SourceCode { vertex_shader: " #version 140 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } ", fragment_shader: " #version 140 in vec3 color; out vec4 f_color; void main() { f_color = vec4(color, 1.0); } ", geometry_shader: Some(" #version 330 uniform mat4 matrix; layout(triangles) in; layout(triangle_strip, max_vertices=3) out; out vec3 color; float rand(vec2 co) { return fract(sin(dot(co.xy,vec2(12.9898,78.233))) * 43758.5453); } void main() { vec3 all_color = vec3( rand(gl_in[0].gl_Position.xy + gl_in[1].gl_Position.yz), rand(gl_in[1].gl_Position.yx + gl_in[2].gl_Position.zx), rand(gl_in[0].gl_Position.xz + gl_in[2].gl_Position.zy) ); gl_Position = matrix * gl_in[0].gl_Position; color = all_color; EmitVertex(); gl_Position = matrix * gl_in[1].gl_Position; color = all_color; EmitVertex(); gl_Position = matrix * gl_in[2].gl_Position; color = all_color; EmitVertex(); } "), tessellation_control_shader: Some(" #version 400 layout(vertices = 3) out; uniform int tess_level = 5; void main() { gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; gl_TessLevelOuter[0] = tess_level; gl_TessLevelOuter[1] = tess_level; gl_TessLevelOuter[2] = tess_level; gl_TessLevelInner[0] = tess_level; } "), tessellation_evaluation_shader: Some(" #version 400 layout(triangles, equal_spacing) in; void main() { vec3 position = vec3(gl_TessCoord.x) * gl_in[0].gl_Position.xyz + vec3(gl_TessCoord.y) * gl_in[1].gl_Position.xyz + vec3(gl_TessCoord.z) * gl_in[2].gl_Position.xyz; gl_Position = vec4(position, 1.0); } "), }).unwrap(); // level of tessellation let mut tess_level: i32 = 5; println!("The current tessellation level is {} ; use the Up and Down keys to change it", tess_level); // the main loop support::start_loop(event_loop, move |events| { // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ], tess_level: tess_level }; // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap(); target.finish().unwrap(); let mut action = support::Action::Continue; // polling and handling the events received by the window for event in events { match event { glutin::event::Event::WindowEvent { event,.. } => match event { glutin::event::WindowEvent::CloseRequested => action = support::Action::Stop, glutin::event::WindowEvent::KeyboardInput { input,.. } => match input.state { glutin::event::ElementState::Pressed => match input.virtual_keycode { Some(glutin::event::VirtualKeyCode::Up) => { tess_level += 1; println!("New tessellation level: {}", tess_level); }, Some(glutin::event::VirtualKeyCode::Down) => { if tess_level >= 2 { tess_level -= 1; println!("New tessellation level: {}", tess_level); } }, _ => (), }, _ => (), }, _ => (), }, _ => (), } }; action }); }
main
identifier_name
tessellation.rs
#[macro_use] extern crate glium; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod support; fn main() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new(); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], } implement_vertex!(Vertex, position); glium::VertexBuffer::new(&display, &[ Vertex { position: [-0.5, -0.5] }, Vertex { position: [ 0.0, 0.5] }, Vertex { position: [ 0.5, -0.5] }, ] ).unwrap() }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::Patches { vertices_per_patch: 3 }, &[0u16, 1, 2]).unwrap(); // compiling shaders and linking them together let program = glium::Program::new(&display, glium::program::SourceCode { vertex_shader: " #version 140 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } ", fragment_shader: " #version 140 in vec3 color; out vec4 f_color; void main() { f_color = vec4(color, 1.0); } ", geometry_shader: Some(" #version 330 uniform mat4 matrix; layout(triangles) in; layout(triangle_strip, max_vertices=3) out; out vec3 color; float rand(vec2 co) { return fract(sin(dot(co.xy,vec2(12.9898,78.233))) * 43758.5453); } void main() { vec3 all_color = vec3( rand(gl_in[0].gl_Position.xy + gl_in[1].gl_Position.yz), rand(gl_in[1].gl_Position.yx + gl_in[2].gl_Position.zx), rand(gl_in[0].gl_Position.xz + gl_in[2].gl_Position.zy) ); gl_Position = matrix * gl_in[0].gl_Position; color = all_color; EmitVertex(); gl_Position = matrix * gl_in[1].gl_Position; color = all_color; EmitVertex(); gl_Position = matrix * gl_in[2].gl_Position; color = all_color; EmitVertex(); } "), tessellation_control_shader: Some(" #version 400 layout(vertices = 3) out; uniform int tess_level = 5; void main() { gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; gl_TessLevelOuter[0] = tess_level; gl_TessLevelOuter[1] = tess_level; gl_TessLevelOuter[2] = tess_level; gl_TessLevelInner[0] = tess_level; } "), tessellation_evaluation_shader: Some(" #version 400 layout(triangles, equal_spacing) in; void main() { vec3 position = vec3(gl_TessCoord.x) * gl_in[0].gl_Position.xyz + vec3(gl_TessCoord.y) * gl_in[1].gl_Position.xyz + vec3(gl_TessCoord.z) * gl_in[2].gl_Position.xyz; gl_Position = vec4(position, 1.0); } "), }).unwrap(); // level of tessellation let mut tess_level: i32 = 5; println!("The current tessellation level is {} ; use the Up and Down keys to change it", tess_level); // the main loop support::start_loop(event_loop, move |events| { // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ], tess_level: tess_level }; // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap(); target.finish().unwrap(); let mut action = support::Action::Continue; // polling and handling the events received by the window for event in events { match event { glutin::event::Event::WindowEvent { event,.. } => match event { glutin::event::WindowEvent::CloseRequested => action = support::Action::Stop, glutin::event::WindowEvent::KeyboardInput { input,.. } => match input.state { glutin::event::ElementState::Pressed => match input.virtual_keycode { Some(glutin::event::VirtualKeyCode::Up) => { tess_level += 1; println!("New tessellation level: {}", tess_level); }, Some(glutin::event::VirtualKeyCode::Down) => { if tess_level >= 2 { tess_level -= 1; println!("New tessellation level: {}", tess_level); } }, _ => (), }, _ => (), }, _ => (), }, _ => (), } }; action
}
});
random_line_split
mediaquerylistevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding::MediaQueryListEventInit; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding::MediaQueryListEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; use std::cell::Cell; // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-mediaquerylistevent #[dom_struct] pub struct MediaQueryListEvent { event: Event, media: DOMString, matches: Cell<bool>, } impl MediaQueryListEvent { pub fn new_initialized( global: &GlobalScope, media: DOMString, matches: bool, ) -> DomRoot<MediaQueryListEvent> { let ev = Box::new(MediaQueryListEvent { event: Event::new_inherited(), media: media, matches: Cell::new(matches), }); reflect_dom_object(ev, global, MediaQueryListEventBinding::Wrap) } pub fn new( global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, media: DOMString, matches: bool, ) -> DomRoot<MediaQueryListEvent> { let ev = MediaQueryListEvent::new_initialized(global, media, matches); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor( window: &Window, type_: DOMString, init: &MediaQueryListEventInit, ) -> Fallible<DomRoot<MediaQueryListEvent>>
} impl MediaQueryListEventMethods for MediaQueryListEvent { // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-media fn Media(&self) -> DOMString { self.media.clone() } // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-matches fn Matches(&self) -> bool { self.matches.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.upcast::<Event>().IsTrusted() } }
{ let global = window.upcast::<GlobalScope>(); Ok(MediaQueryListEvent::new( global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.media.clone(), init.matches, )) }
identifier_body
mediaquerylistevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding::MediaQueryListEventInit; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding::MediaQueryListEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; use std::cell::Cell; // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-mediaquerylistevent #[dom_struct] pub struct MediaQueryListEvent { event: Event, media: DOMString, matches: Cell<bool>, } impl MediaQueryListEvent { pub fn
( global: &GlobalScope, media: DOMString, matches: bool, ) -> DomRoot<MediaQueryListEvent> { let ev = Box::new(MediaQueryListEvent { event: Event::new_inherited(), media: media, matches: Cell::new(matches), }); reflect_dom_object(ev, global, MediaQueryListEventBinding::Wrap) } pub fn new( global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, media: DOMString, matches: bool, ) -> DomRoot<MediaQueryListEvent> { let ev = MediaQueryListEvent::new_initialized(global, media, matches); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor( window: &Window, type_: DOMString, init: &MediaQueryListEventInit, ) -> Fallible<DomRoot<MediaQueryListEvent>> { let global = window.upcast::<GlobalScope>(); Ok(MediaQueryListEvent::new( global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.media.clone(), init.matches, )) } } impl MediaQueryListEventMethods for MediaQueryListEvent { // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-media fn Media(&self) -> DOMString { self.media.clone() } // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-matches fn Matches(&self) -> bool { self.matches.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.upcast::<Event>().IsTrusted() } }
new_initialized
identifier_name
mediaquerylistevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding::MediaQueryListEventInit; use crate::dom::bindings::codegen::Bindings::MediaQueryListEventBinding::MediaQueryListEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; use std::cell::Cell; // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-mediaquerylistevent #[dom_struct] pub struct MediaQueryListEvent { event: Event, media: DOMString, matches: Cell<bool>, } impl MediaQueryListEvent { pub fn new_initialized( global: &GlobalScope, media: DOMString, matches: bool, ) -> DomRoot<MediaQueryListEvent> { let ev = Box::new(MediaQueryListEvent { event: Event::new_inherited(), media: media, matches: Cell::new(matches), }); reflect_dom_object(ev, global, MediaQueryListEventBinding::Wrap) } pub fn new( global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, media: DOMString, matches: bool, ) -> DomRoot<MediaQueryListEvent> { let ev = MediaQueryListEvent::new_initialized(global, media, matches); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor( window: &Window, type_: DOMString, init: &MediaQueryListEventInit, ) -> Fallible<DomRoot<MediaQueryListEvent>> { let global = window.upcast::<GlobalScope>(); Ok(MediaQueryListEvent::new( global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.media.clone(), init.matches, )) } } impl MediaQueryListEventMethods for MediaQueryListEvent { // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-media fn Media(&self) -> DOMString {
fn Matches(&self) -> bool { self.matches.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.upcast::<Event>().IsTrusted() } }
self.media.clone() } // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-matches
random_line_split
hello.rs
#![feature(proc_macro)] extern crate hayaku_http; extern crate hayaku_path; #[macro_use] extern crate serde_derive;
use hayaku_http::{Http, Request, Response}; use hayaku_path::Router; use std::sync::Arc; fn main() { let addr = "127.0.0.1:3000".parse().unwrap(); let mut router = Router::new(); router.get("/", Arc::new(hello_handler)).unwrap(); router.get("/plaintext", Arc::new(plain_handler)).unwrap(); router.get("/json", Arc::new(json_handler)).unwrap(); Http::new(router, ()).threads(4).listen_and_serve(addr); } fn hello_handler(_req: &Request, res: &mut Response, _ctx: &()) { res.body(b"hello, world!"); } fn plain_handler(_req: &Request, res: &mut Response, _ctx: &()) { res.add_header("Content-Type".to_string(), "text/plain".to_string()); res.body(b"hello, world!"); } #[derive(Serialize, Deserialize)] struct Message { message: String, } fn json_handler(_req: &Request, res: &mut Response, _ctx: &()) { let msg = Message { message: "Hello, World!".to_string() }; let data = serde_json::to_vec(&msg).unwrap(); res.add_header("Content-Type".to_string(), "application/json".to_string()); res.body(&data); }
extern crate serde_json;
random_line_split
hello.rs
#![feature(proc_macro)] extern crate hayaku_http; extern crate hayaku_path; #[macro_use] extern crate serde_derive; extern crate serde_json; use hayaku_http::{Http, Request, Response}; use hayaku_path::Router; use std::sync::Arc; fn main() { let addr = "127.0.0.1:3000".parse().unwrap(); let mut router = Router::new(); router.get("/", Arc::new(hello_handler)).unwrap(); router.get("/plaintext", Arc::new(plain_handler)).unwrap(); router.get("/json", Arc::new(json_handler)).unwrap(); Http::new(router, ()).threads(4).listen_and_serve(addr); } fn hello_handler(_req: &Request, res: &mut Response, _ctx: &()) { res.body(b"hello, world!"); } fn plain_handler(_req: &Request, res: &mut Response, _ctx: &()) { res.add_header("Content-Type".to_string(), "text/plain".to_string()); res.body(b"hello, world!"); } #[derive(Serialize, Deserialize)] struct
{ message: String, } fn json_handler(_req: &Request, res: &mut Response, _ctx: &()) { let msg = Message { message: "Hello, World!".to_string() }; let data = serde_json::to_vec(&msg).unwrap(); res.add_header("Content-Type".to_string(), "application/json".to_string()); res.body(&data); }
Message
identifier_name
hello.rs
#![feature(proc_macro)] extern crate hayaku_http; extern crate hayaku_path; #[macro_use] extern crate serde_derive; extern crate serde_json; use hayaku_http::{Http, Request, Response}; use hayaku_path::Router; use std::sync::Arc; fn main() { let addr = "127.0.0.1:3000".parse().unwrap(); let mut router = Router::new(); router.get("/", Arc::new(hello_handler)).unwrap(); router.get("/plaintext", Arc::new(plain_handler)).unwrap(); router.get("/json", Arc::new(json_handler)).unwrap(); Http::new(router, ()).threads(4).listen_and_serve(addr); } fn hello_handler(_req: &Request, res: &mut Response, _ctx: &()) { res.body(b"hello, world!"); } fn plain_handler(_req: &Request, res: &mut Response, _ctx: &()) { res.add_header("Content-Type".to_string(), "text/plain".to_string()); res.body(b"hello, world!"); } #[derive(Serialize, Deserialize)] struct Message { message: String, } fn json_handler(_req: &Request, res: &mut Response, _ctx: &())
{ let msg = Message { message: "Hello, World!".to_string() }; let data = serde_json::to_vec(&msg).unwrap(); res.add_header("Content-Type".to_string(), "application/json".to_string()); res.body(&data); }
identifier_body
buffer.rs
use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError}; use buffer::Mapping as BufferMapping; use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
#[derive(Debug)] pub struct UniformBuffer<T> where T: Copy + Send +'static { buffer: BufferView<T>, } /// Mapping of a buffer in memory. pub struct Mapping<'a, T> { mapping: BufferMapping<'a, T>, } /// Same as `UniformBuffer` but doesn't contain any information about the type. #[derive(Debug)] pub struct TypelessUniformBuffer { buffer: BufferViewAny, } impl<T> UniformBuffer<T> where T: Copy + Send +'static { /// Uploads data in the uniforms buffer. /// /// # Features /// /// Only available if the `gl_uniform_blocks` feature is enabled. #[cfg(feature = "gl_uniform_blocks")] pub fn new<F>(facade: &F, data: T) -> UniformBuffer<T> where F: Facade { UniformBuffer::new_if_supported(facade, data).unwrap() } /// Uploads data in the uniforms buffer. pub fn new_if_supported<F>(facade: &F, data: T) -> Option<UniformBuffer<T>> where F: Facade { let buffer = match BufferView::new(facade, &[data], BufferType::UniformBuffer, true) { Ok(b) => b, Err(BufferCreationError::BufferTypeNotSupported) => return None, e @ Err(_) => e.unwrap(), }; Some(UniformBuffer { buffer: buffer, }) } /// Modifies the content of the buffer. pub fn upload(&mut self, data: T) { self.write(&[data]); } /// Reads the content of the buffer if supported. pub fn read_if_supported(&self) -> Option<T> { self.buffer.read_if_supported().and_then(|buf| buf.into_iter().next()) } /// Reads the content of the buffer. /// /// # Features /// /// Only available if the 'gl_read_buffer' feature is enabled. #[cfg(feature = "gl_read_buffer")] pub fn read(&self) -> T { self.read_if_supported().unwrap() } /// Maps the buffer in memory. pub fn map(&mut self) -> Mapping<T> { Mapping { mapping: self.buffer.map() } } } impl<T> Deref for UniformBuffer<T> where T: Send + Copy +'static { type Target = BufferView<T>; fn deref(&self) -> &BufferView<T> { &self.buffer } } impl<'a, D> Deref for Mapping<'a, D> { type Target = D; fn deref(&self) -> &D { &self.mapping.deref()[0] } } impl<'a, D> DerefMut for Mapping<'a, D> { fn deref_mut(&mut self) -> &mut D { &mut self.mapping.deref_mut()[0] } } impl<T> DerefMut for UniformBuffer<T> where T: Send + Copy +'static { fn deref_mut(&mut self) -> &mut BufferView<T> { &mut self.buffer } } impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Send + Copy +'static { fn as_uniform_value(&self) -> UniformValue { UniformValue::Block(self.buffer.as_slice_any(), <T as UniformBlock>::matches) } fn matches(_: &UniformType) -> bool { false } }
use std::ops::{Deref, DerefMut}; use backend::Facade; /// Buffer that contains a uniform block.
random_line_split
buffer.rs
use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError}; use buffer::Mapping as BufferMapping; use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType}; use std::ops::{Deref, DerefMut}; use backend::Facade; /// Buffer that contains a uniform block. #[derive(Debug)] pub struct UniformBuffer<T> where T: Copy + Send +'static { buffer: BufferView<T>, } /// Mapping of a buffer in memory. pub struct Mapping<'a, T> { mapping: BufferMapping<'a, T>, } /// Same as `UniformBuffer` but doesn't contain any information about the type. #[derive(Debug)] pub struct TypelessUniformBuffer { buffer: BufferViewAny, } impl<T> UniformBuffer<T> where T: Copy + Send +'static { /// Uploads data in the uniforms buffer. /// /// # Features /// /// Only available if the `gl_uniform_blocks` feature is enabled. #[cfg(feature = "gl_uniform_blocks")] pub fn new<F>(facade: &F, data: T) -> UniformBuffer<T> where F: Facade { UniformBuffer::new_if_supported(facade, data).unwrap() } /// Uploads data in the uniforms buffer. pub fn new_if_supported<F>(facade: &F, data: T) -> Option<UniformBuffer<T>> where F: Facade { let buffer = match BufferView::new(facade, &[data], BufferType::UniformBuffer, true) { Ok(b) => b, Err(BufferCreationError::BufferTypeNotSupported) => return None, e @ Err(_) => e.unwrap(), }; Some(UniformBuffer { buffer: buffer, }) } /// Modifies the content of the buffer. pub fn upload(&mut self, data: T) { self.write(&[data]); } /// Reads the content of the buffer if supported. pub fn read_if_supported(&self) -> Option<T> { self.buffer.read_if_supported().and_then(|buf| buf.into_iter().next()) } /// Reads the content of the buffer. /// /// # Features /// /// Only available if the 'gl_read_buffer' feature is enabled. #[cfg(feature = "gl_read_buffer")] pub fn read(&self) -> T { self.read_if_supported().unwrap() } /// Maps the buffer in memory. pub fn map(&mut self) -> Mapping<T> { Mapping { mapping: self.buffer.map() } } } impl<T> Deref for UniformBuffer<T> where T: Send + Copy +'static { type Target = BufferView<T>; fn deref(&self) -> &BufferView<T> { &self.buffer } } impl<'a, D> Deref for Mapping<'a, D> { type Target = D; fn deref(&self) -> &D { &self.mapping.deref()[0] } } impl<'a, D> DerefMut for Mapping<'a, D> { fn
(&mut self) -> &mut D { &mut self.mapping.deref_mut()[0] } } impl<T> DerefMut for UniformBuffer<T> where T: Send + Copy +'static { fn deref_mut(&mut self) -> &mut BufferView<T> { &mut self.buffer } } impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Send + Copy +'static { fn as_uniform_value(&self) -> UniformValue { UniformValue::Block(self.buffer.as_slice_any(), <T as UniformBlock>::matches) } fn matches(_: &UniformType) -> bool { false } }
deref_mut
identifier_name
buffer.rs
use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError}; use buffer::Mapping as BufferMapping; use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType}; use std::ops::{Deref, DerefMut}; use backend::Facade; /// Buffer that contains a uniform block. #[derive(Debug)] pub struct UniformBuffer<T> where T: Copy + Send +'static { buffer: BufferView<T>, } /// Mapping of a buffer in memory. pub struct Mapping<'a, T> { mapping: BufferMapping<'a, T>, } /// Same as `UniformBuffer` but doesn't contain any information about the type. #[derive(Debug)] pub struct TypelessUniformBuffer { buffer: BufferViewAny, } impl<T> UniformBuffer<T> where T: Copy + Send +'static { /// Uploads data in the uniforms buffer. /// /// # Features /// /// Only available if the `gl_uniform_blocks` feature is enabled. #[cfg(feature = "gl_uniform_blocks")] pub fn new<F>(facade: &F, data: T) -> UniformBuffer<T> where F: Facade { UniformBuffer::new_if_supported(facade, data).unwrap() } /// Uploads data in the uniforms buffer. pub fn new_if_supported<F>(facade: &F, data: T) -> Option<UniformBuffer<T>> where F: Facade { let buffer = match BufferView::new(facade, &[data], BufferType::UniformBuffer, true) { Ok(b) => b, Err(BufferCreationError::BufferTypeNotSupported) => return None, e @ Err(_) => e.unwrap(), }; Some(UniformBuffer { buffer: buffer, }) } /// Modifies the content of the buffer. pub fn upload(&mut self, data: T) { self.write(&[data]); } /// Reads the content of the buffer if supported. pub fn read_if_supported(&self) -> Option<T> { self.buffer.read_if_supported().and_then(|buf| buf.into_iter().next()) } /// Reads the content of the buffer. /// /// # Features /// /// Only available if the 'gl_read_buffer' feature is enabled. #[cfg(feature = "gl_read_buffer")] pub fn read(&self) -> T { self.read_if_supported().unwrap() } /// Maps the buffer in memory. pub fn map(&mut self) -> Mapping<T> { Mapping { mapping: self.buffer.map() } } } impl<T> Deref for UniformBuffer<T> where T: Send + Copy +'static { type Target = BufferView<T>; fn deref(&self) -> &BufferView<T> { &self.buffer } } impl<'a, D> Deref for Mapping<'a, D> { type Target = D; fn deref(&self) -> &D { &self.mapping.deref()[0] } } impl<'a, D> DerefMut for Mapping<'a, D> { fn deref_mut(&mut self) -> &mut D { &mut self.mapping.deref_mut()[0] } } impl<T> DerefMut for UniformBuffer<T> where T: Send + Copy +'static { fn deref_mut(&mut self) -> &mut BufferView<T>
} impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Send + Copy +'static { fn as_uniform_value(&self) -> UniformValue { UniformValue::Block(self.buffer.as_slice_any(), <T as UniformBlock>::matches) } fn matches(_: &UniformType) -> bool { false } }
{ &mut self.buffer }
identifier_body
lib.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //! A library providing high-level abstractions for event loop concurrency, //! heavily borrowing ideas from [KJ](https://capnproto.org/cxxrpc.html#kj-concurrency-framework). //! Allows for coordination of asynchronous tasks using [promises](struct.Promise.html) as //! a basic building block. //! //! # Example //! //! ``` //! use gj::{EventLoop, Promise, ClosedEventPort}; //! EventLoop::top_level(|wait_scope| -> Result<(),()> { //! let (promise1, fulfiller1) = Promise::<(),()>::and_fulfiller(); //! let (promise2, fulfiller2) = Promise::<(),()>::and_fulfiller(); //! let promise3 = promise2.then(|_| { //! println!("world"); //! Promise::ok(()) //! }); //! let promise4 = promise1.then(move |_| { //! println!("hello "); //! fulfiller2.fulfill(()); //! Promise::ok(()) //! }); //! fulfiller1.fulfill(()); //! Promise::all(vec![promise3, promise4].into_iter()) //! .map(|_| Ok(())) //! .wait(wait_scope, &mut ClosedEventPort(())) //! }).expect("top level"); //! ``` use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::result::Result; use private::{promise_node, BoolEvent, PromiseAndFulfillerHub, PromiseAndFulfillerWrapper, EVENT_LOOP, with_current_event_loop, PromiseNode}; /// Like `try!()`, but for functions that return a [`Promise<T, E>`](struct.Promise.html) rather /// than a `Result<T, E>`. /// /// Unwraps a `Result<T, E>`. In the case of an error `Err(e)`, immediately returns from the /// enclosing function with `Promise::err(e)`. #[macro_export] macro_rules! pry { ($expr:expr) => (match $expr { ::std::result::Result::Ok(val) => val, ::std::result::Result::Err(err) => { return $crate::Promise::err(::std::convert::From::from(err)) } }) } mod private; mod handle_table; /// A computation that might eventually resolve to a value of type `T` or to an error /// of type `E`. Dropping the promise cancels the computation. #[must_use] pub struct Promise<T, E> where T:'static, E:'static { node: Box<PromiseNode<T, E>>, } impl<T, E> Promise<T, E> { /// Creates a new promise that has already been fulfilled with the given value. pub fn ok(value: T) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) } } /// Creates a new promise that has already been rejected with the given error. pub fn err(error: E) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Err(error))) } } /// Creates a new promise that never resolves. pub fn never_done() -> Promise<T, E> { Promise { node: Box::new(promise_node::NeverDone::new()) } } /// Creates a new promise/fulfiller pair. pub fn and_fulfiller() -> (Promise<T, E>, PromiseFulfiller<T, E>) where E: FulfillerDropped { let result = Rc::new(RefCell::new(PromiseAndFulfillerHub::new())); let result_promise: Promise<T, E> = Promise { node: Box::new(PromiseAndFulfillerWrapper::new(result.clone())), }; (result_promise, PromiseFulfiller { hub: result, done: false, }) } /// Chains further computation to be executed once the promise resolves. /// When the promise is fulfilled or rejected, invokes `func` on its result. /// /// If the returned promise is dropped before the chained computation runs, the chained /// computation will be cancelled. /// /// Always returns immediately, even if the promise is already resolved. The earliest that /// `func` might be invoked is during the next `turn()` of the event loop. pub fn then_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Promise<T1, E1> { let intermediate = Box::new(promise_node::Transform::new(self.node, |x| Ok(func(x)))); Promise { node: Box::new(promise_node::Chain::new(intermediate)) } } /// Calls `then_else()` with a default error handler that simply propagates all errors. pub fn then<F, T1>(self, func: F) -> Promise<T1, E> where F:'static, F: FnOnce(T) -> Promise<T1, E> { self.then_else(|r| { match r { Ok(v) => func(v), Err(e) => Promise::err(e), } }) } /// Like `then_else()` but for a `func` that returns a direct value rather than a promise. As an /// optimization, execution of `func` is delayed until its result is known to be needed. The /// expectation here is that `func` is just doing some transformation on the results, not /// scheduling any other actions, and therefore the system does not need to be proactive about /// evaluating it. This way, a chain of trivial `map()` transformations can be executed all at /// once without repeated rescheduling through the event loop. Use the `eagerly_evaluate()` /// method to suppress this behavior. pub fn map_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Result<T1, E1> { Promise { node: Box::new(promise_node::Transform::new(self.node, func)) } } /// Calls `map_else()` with a default error handler that simply propagates all errors. pub fn map<F, R>(self, func: F) -> Promise<R, E> where F:'static, F: FnOnce(T) -> Result<R, E>, R:'static { self.map_else(|r| { match r { Ok(v) => func(v), Err(e) => Err(e), } }) } /// Transforms the error branch of the promise. pub fn map_err<E1, F>(self, func: F) -> Promise<T, E1> where F:'static, F: FnOnce(E) -> E1 { self.map_else(|r| { match r { Ok(v) => Ok(v), Err(e) => Err(func(e)), } }) } /// Maps errors into a more general type. pub fn lift<E1>(self) -> Promise<T, E1> where E: Into<E1> { self.map_err(|e| e.into()) } /// Returns a new promise that resolves when either `self` or `other` resolves. The promise that /// doesn't resolve first is cancelled. pub fn exclusive_join(self, other: Promise<T, E>) -> Promise<T, E> { Promise { node: Box::new(private::promise_node::ExclusiveJoin::new(self.node, other.node)) } } /// Transforms a collection of promises into a promise for a vector. If any of /// the promises fails, immediately cancels the remaining promises. pub fn all<I>(promises: I) -> Promise<Vec<T>, E> where I: Iterator<Item = Promise<T, E>> { Promise { node: Box::new(private::promise_node::ArrayJoin::new(promises)) } } /// Forks the promise, so that multiple different clients can independently wait on the result. pub fn fork(self) -> ForkedPromise<T, E> where T: Clone, E: Clone { ForkedPromise::new(self) } /// Holds onto `value` until the promise resolves, then drops `value`. pub fn attach<U>(self, value: U) -> Promise<T, E> where U:'static { self.map_else(move |result| { drop(value); result }) } /// Forces eager evaluation of this promise. Use this if you are going to hold on to the promise /// for a while without consuming the result, but you want to make sure that the system actually /// processes it. pub fn eagerly_evaluate(self) -> Promise<T, E> { self.then(|v| Promise::ok(v)) } /// Runs the event loop until the promise is fulfilled. /// /// The `WaitScope` argument ensures that `wait()` can only be called at the top level of a /// program. Waiting within event callbacks is disallowed. pub fn wait<E1>(mut self, wait_scope: &WaitScope, event_source: &mut EventPort<E1>) -> Result<T, E> where E: From<E1> { drop(wait_scope); with_current_event_loop(move |event_loop| { let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false)); let done_event = BoolEvent::new(fired.clone()); let (handle, _dropper) = private::GuardedEventHandle::new(); handle.set(Box::new(done_event)); self.node.on_ready(handle); while!fired.get() { if!event_loop.turn() { // No events in the queue. try!(event_source.wait()); } } self.node.get() }) } } /// A scope in which asynchronous programming can occur. Corresponds to the top level scope of some /// [event loop](struct.EventLoop.html). Can be used to [wait](struct.Promise.html#method.wait) for /// the result of a promise. pub struct WaitScope(::std::marker::PhantomData<*mut u8>); // impl!Sync for WaitScope {} /// The result of `Promise::fork()`. Allows branches to be created. Dropping the `ForkedPromise` /// along with any branches created through `add_branch()` will cancel the computation. pub struct ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { hub: Rc<RefCell<promise_node::ForkHub<T, E>>>, } impl<T, E> ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { fn new(inner: Promise<T, E>) -> ForkedPromise<T, E> { ForkedPromise { hub: Rc::new(RefCell::new(promise_node::ForkHub::new(inner.node))) } } /// Creates a new promise that will resolve when the originally forked promise resolves. pub fn add_branch(&mut self) -> Promise<T, E> { promise_node::ForkHub::add_branch(&self.hub) } } /// Interface between an `EventLoop` and events originating from outside of the loop's thread. /// Needed in [`Promise::wait()`](struct.Promise.html#method.wait). pub trait EventPort<E> { /// Waits for an external event to arrive, blocking the thread if necessary. fn wait(&mut self) -> Result<(), E>; } /// An event port that never emits any events. On wait() it returns the error it was constructed /// with. pub struct ClosedEventPort<E: Clone>(pub E); impl<E: Clone> EventPort<E> for ClosedEventPort<E> { fn wait(&mut self) -> Result<(), E>
} /// A queue of events being executed in a loop on a single thread. pub struct EventLoop { // daemons: TaskSetImpl, _last_runnable_state: bool, events: RefCell<handle_table::HandleTable<private::EventNode>>, head: private::EventHandle, tail: Cell<private::EventHandle>, depth_first_insertion_point: Cell<private::EventHandle>, currently_firing: Cell<Option<private::EventHandle>>, to_destroy: Cell<Option<private::EventHandle>>, } impl EventLoop { /// Creates an event loop for the current thread, panicking if one already exists. Runs the /// given closure and then drops the event loop. pub fn top_level<R, F>(main: F) -> R where F: FnOnce(&WaitScope) -> R { let mut events = handle_table::HandleTable::<private::EventNode>::new(); let dummy = private::EventNode { event: None, next: None, prev: None, }; let head_handle = private::EventHandle(events.push(dummy)); EVENT_LOOP.with(move |maybe_event_loop| { let event_loop = EventLoop { _last_runnable_state: false, events: RefCell::new(events), head: head_handle, tail: Cell::new(head_handle), depth_first_insertion_point: Cell::new(head_handle), // insert after this node currently_firing: Cell::new(None), to_destroy: Cell::new(None), }; assert!(maybe_event_loop.borrow().is_none()); *maybe_event_loop.borrow_mut() = Some(event_loop); }); let wait_scope = WaitScope(::std::marker::PhantomData); let result = main(&wait_scope); EVENT_LOOP.with(move |maybe_event_loop| { let el = ::std::mem::replace(&mut *maybe_event_loop.borrow_mut(), None); match el { None => unreachable!(), Some(event_loop) => { // If there is still an event other than the head event, then there must have // been a memory leak. let remaining_events = event_loop.events.borrow().len(); if remaining_events > 1 { ::std::mem::forget(event_loop); // Prevent double panic. panic!("{} leaked events found when cleaning up event loop. \ Perhaps there is a reference cycle containing promises?", remaining_events - 1) } } } }); result } fn arm_depth_first(&self, event_handle: private::EventHandle) { let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0] .next; match insertion_node_next { Some(next_handle) => { self.events.borrow_mut()[next_handle.0].prev = Some(event_handle); self.events.borrow_mut()[event_handle.0].next = Some(next_handle); } None => { self.tail.set(event_handle); } } self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point .get()); self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle); self.depth_first_insertion_point.set(event_handle); } fn arm_breadth_first(&self, event_handle: private::EventHandle) { let events = &mut *self.events.borrow_mut(); events[self.tail.get().0].next = Some(event_handle); events[event_handle.0].prev = Some(self.tail.get()); self.tail.set(event_handle); } /// Runs the event loop for a single step. fn turn(&self) -> bool { let event_handle = match self.events.borrow()[self.head.0].next { None => return false, Some(event_handle) => event_handle, }; self.depth_first_insertion_point.set(event_handle); self.currently_firing.set(Some(event_handle)); let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None) .expect("No event to fire?"); event.fire(); self.currently_firing.set(None); let maybe_next = self.events.borrow()[event_handle.0].next; self.events.borrow_mut()[self.head.0].next = maybe_next; if let Some(e) = maybe_next { self.events.borrow_mut()[e.0].prev = Some(self.head); } self.events.borrow_mut()[event_handle.0].next = None; self.events.borrow_mut()[event_handle.0].prev = None; if self.tail.get() == event_handle { self.tail.set(self.head); } self.depth_first_insertion_point.set(self.head); if let Some(event_handle) = self.to_destroy.get() { self.events.borrow_mut().remove(event_handle.0); self.to_destroy.set(None); } true } } /// Specifies an error to generate when a [`PromiseFulfiller`](struct.PromiseFulfiller.html) is /// dropped. pub trait FulfillerDropped { fn fulfiller_dropped() -> Self; } /// A handle that can be used to fulfill or reject a promise. If you think of a promise /// as the receiving end of a oneshot channel, then this is the sending end. /// /// When a `PromiseFulfiller<T,E>` is dropped without first receiving a `fulfill()`, `reject()`, or /// `resolve()` call, its promise is rejected with the error value `E::fulfiller_dropped()`. pub struct PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { hub: Rc<RefCell<private::PromiseAndFulfillerHub<T, E>>>, done: bool, } impl<T, E> PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { pub fn fulfill(mut self, value: T) { self.hub.borrow_mut().resolve(Ok(value)); self.done = true; } pub fn reject(mut self, error: E) { self.hub.borrow_mut().resolve(Err(error)); self.done = true; } pub fn resolve(mut self, result: Result<T, E>) { self.hub.borrow_mut().resolve(result); self.done = true; } } impl<T, E> Drop for PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { fn drop(&mut self) { if!self.done { self.hub.borrow_mut().resolve(Err(E::fulfiller_dropped())); } } } impl FulfillerDropped for () { fn fulfiller_dropped() -> () { () } } impl FulfillerDropped for ::std::io::Error { fn fulfiller_dropped() -> ::std::io::Error { ::std::io::Error::new(::std::io::ErrorKind::Other, "Promise fulfiller was dropped.") } } /// Holds a collection of `Promise<T, E>`s and ensures that each executes to completion. /// Destroying a `TaskSet` automatically cancels all of its unfinished promises. pub struct TaskSet<T, E> where T:'static, E:'static { task_set_impl: private::TaskSetImpl<T, E>, } impl<T, E> TaskSet<T, E> { pub fn new(reaper: Box<TaskReaper<T, E>>) -> TaskSet<T, E> { TaskSet { task_set_impl: private::TaskSetImpl::new(reaper) } } pub fn add(&mut self, promise: Promise<T, E>) { self.task_set_impl.add(promise.node); } } /// Callbacks to be invoked when a task in a [`TaskSet`](struct.TaskSet.html) finishes. You are /// required to implement at least the failure case. pub trait TaskReaper<T, E> where T:'static, E:'static { fn task_succeeded(&mut self, _value: T) {} fn task_failed(&mut self, error: E); }
{ Err(self.0.clone()) }
identifier_body
lib.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //! A library providing high-level abstractions for event loop concurrency, //! heavily borrowing ideas from [KJ](https://capnproto.org/cxxrpc.html#kj-concurrency-framework). //! Allows for coordination of asynchronous tasks using [promises](struct.Promise.html) as //! a basic building block. //! //! # Example //! //! ``` //! use gj::{EventLoop, Promise, ClosedEventPort}; //! EventLoop::top_level(|wait_scope| -> Result<(),()> { //! let (promise1, fulfiller1) = Promise::<(),()>::and_fulfiller(); //! let (promise2, fulfiller2) = Promise::<(),()>::and_fulfiller(); //! let promise3 = promise2.then(|_| { //! println!("world"); //! Promise::ok(()) //! }); //! let promise4 = promise1.then(move |_| { //! println!("hello "); //! fulfiller2.fulfill(()); //! Promise::ok(()) //! }); //! fulfiller1.fulfill(()); //! Promise::all(vec![promise3, promise4].into_iter()) //! .map(|_| Ok(())) //! .wait(wait_scope, &mut ClosedEventPort(())) //! }).expect("top level"); //! ``` use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::result::Result; use private::{promise_node, BoolEvent, PromiseAndFulfillerHub, PromiseAndFulfillerWrapper, EVENT_LOOP, with_current_event_loop, PromiseNode}; /// Like `try!()`, but for functions that return a [`Promise<T, E>`](struct.Promise.html) rather /// than a `Result<T, E>`. /// /// Unwraps a `Result<T, E>`. In the case of an error `Err(e)`, immediately returns from the /// enclosing function with `Promise::err(e)`. #[macro_export] macro_rules! pry { ($expr:expr) => (match $expr { ::std::result::Result::Ok(val) => val, ::std::result::Result::Err(err) => { return $crate::Promise::err(::std::convert::From::from(err)) } }) } mod private; mod handle_table; /// A computation that might eventually resolve to a value of type `T` or to an error /// of type `E`. Dropping the promise cancels the computation. #[must_use] pub struct Promise<T, E> where T:'static, E:'static { node: Box<PromiseNode<T, E>>, } impl<T, E> Promise<T, E> { /// Creates a new promise that has already been fulfilled with the given value. pub fn ok(value: T) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) } } /// Creates a new promise that has already been rejected with the given error. pub fn err(error: E) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Err(error))) } } /// Creates a new promise that never resolves. pub fn never_done() -> Promise<T, E> { Promise { node: Box::new(promise_node::NeverDone::new()) } } /// Creates a new promise/fulfiller pair. pub fn and_fulfiller() -> (Promise<T, E>, PromiseFulfiller<T, E>) where E: FulfillerDropped { let result = Rc::new(RefCell::new(PromiseAndFulfillerHub::new())); let result_promise: Promise<T, E> = Promise { node: Box::new(PromiseAndFulfillerWrapper::new(result.clone())), }; (result_promise, PromiseFulfiller { hub: result, done: false, }) } /// Chains further computation to be executed once the promise resolves. /// When the promise is fulfilled or rejected, invokes `func` on its result. /// /// If the returned promise is dropped before the chained computation runs, the chained /// computation will be cancelled. /// /// Always returns immediately, even if the promise is already resolved. The earliest that /// `func` might be invoked is during the next `turn()` of the event loop. pub fn then_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Promise<T1, E1> { let intermediate = Box::new(promise_node::Transform::new(self.node, |x| Ok(func(x)))); Promise { node: Box::new(promise_node::Chain::new(intermediate)) } } /// Calls `then_else()` with a default error handler that simply propagates all errors. pub fn then<F, T1>(self, func: F) -> Promise<T1, E> where F:'static, F: FnOnce(T) -> Promise<T1, E> { self.then_else(|r| { match r { Ok(v) => func(v), Err(e) => Promise::err(e), } }) } /// Like `then_else()` but for a `func` that returns a direct value rather than a promise. As an /// optimization, execution of `func` is delayed until its result is known to be needed. The /// expectation here is that `func` is just doing some transformation on the results, not /// scheduling any other actions, and therefore the system does not need to be proactive about /// evaluating it. This way, a chain of trivial `map()` transformations can be executed all at /// once without repeated rescheduling through the event loop. Use the `eagerly_evaluate()` /// method to suppress this behavior. pub fn map_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Result<T1, E1> { Promise { node: Box::new(promise_node::Transform::new(self.node, func)) } } /// Calls `map_else()` with a default error handler that simply propagates all errors. pub fn map<F, R>(self, func: F) -> Promise<R, E> where F:'static, F: FnOnce(T) -> Result<R, E>, R:'static { self.map_else(|r| { match r { Ok(v) => func(v), Err(e) => Err(e), } }) } /// Transforms the error branch of the promise. pub fn map_err<E1, F>(self, func: F) -> Promise<T, E1> where F:'static, F: FnOnce(E) -> E1 { self.map_else(|r| { match r { Ok(v) => Ok(v), Err(e) => Err(func(e)), } }) } /// Maps errors into a more general type. pub fn lift<E1>(self) -> Promise<T, E1> where E: Into<E1> { self.map_err(|e| e.into()) } /// Returns a new promise that resolves when either `self` or `other` resolves. The promise that /// doesn't resolve first is cancelled. pub fn exclusive_join(self, other: Promise<T, E>) -> Promise<T, E> { Promise { node: Box::new(private::promise_node::ExclusiveJoin::new(self.node, other.node)) } } /// Transforms a collection of promises into a promise for a vector. If any of /// the promises fails, immediately cancels the remaining promises. pub fn all<I>(promises: I) -> Promise<Vec<T>, E> where I: Iterator<Item = Promise<T, E>> { Promise { node: Box::new(private::promise_node::ArrayJoin::new(promises)) } } /// Forks the promise, so that multiple different clients can independently wait on the result. pub fn fork(self) -> ForkedPromise<T, E> where T: Clone, E: Clone { ForkedPromise::new(self) } /// Holds onto `value` until the promise resolves, then drops `value`. pub fn attach<U>(self, value: U) -> Promise<T, E> where U:'static { self.map_else(move |result| { drop(value); result }) } /// Forces eager evaluation of this promise. Use this if you are going to hold on to the promise /// for a while without consuming the result, but you want to make sure that the system actually /// processes it. pub fn eagerly_evaluate(self) -> Promise<T, E> { self.then(|v| Promise::ok(v)) } /// Runs the event loop until the promise is fulfilled. /// /// The `WaitScope` argument ensures that `wait()` can only be called at the top level of a /// program. Waiting within event callbacks is disallowed. pub fn wait<E1>(mut self, wait_scope: &WaitScope, event_source: &mut EventPort<E1>) -> Result<T, E> where E: From<E1> { drop(wait_scope); with_current_event_loop(move |event_loop| { let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false)); let done_event = BoolEvent::new(fired.clone()); let (handle, _dropper) = private::GuardedEventHandle::new(); handle.set(Box::new(done_event)); self.node.on_ready(handle); while!fired.get() { if!event_loop.turn() { // No events in the queue. try!(event_source.wait()); } } self.node.get() }) } } /// A scope in which asynchronous programming can occur. Corresponds to the top level scope of some /// [event loop](struct.EventLoop.html). Can be used to [wait](struct.Promise.html#method.wait) for /// the result of a promise. pub struct WaitScope(::std::marker::PhantomData<*mut u8>); // impl!Sync for WaitScope {} /// The result of `Promise::fork()`. Allows branches to be created. Dropping the `ForkedPromise` /// along with any branches created through `add_branch()` will cancel the computation. pub struct ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { hub: Rc<RefCell<promise_node::ForkHub<T, E>>>, } impl<T, E> ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { fn new(inner: Promise<T, E>) -> ForkedPromise<T, E> { ForkedPromise { hub: Rc::new(RefCell::new(promise_node::ForkHub::new(inner.node))) } } /// Creates a new promise that will resolve when the originally forked promise resolves. pub fn add_branch(&mut self) -> Promise<T, E> { promise_node::ForkHub::add_branch(&self.hub) } } /// Interface between an `EventLoop` and events originating from outside of the loop's thread. /// Needed in [`Promise::wait()`](struct.Promise.html#method.wait). pub trait EventPort<E> { /// Waits for an external event to arrive, blocking the thread if necessary. fn wait(&mut self) -> Result<(), E>; } /// An event port that never emits any events. On wait() it returns the error it was constructed /// with. pub struct ClosedEventPort<E: Clone>(pub E); impl<E: Clone> EventPort<E> for ClosedEventPort<E> { fn wait(&mut self) -> Result<(), E> { Err(self.0.clone()) } } /// A queue of events being executed in a loop on a single thread. pub struct EventLoop { // daemons: TaskSetImpl, _last_runnable_state: bool, events: RefCell<handle_table::HandleTable<private::EventNode>>, head: private::EventHandle, tail: Cell<private::EventHandle>, depth_first_insertion_point: Cell<private::EventHandle>, currently_firing: Cell<Option<private::EventHandle>>, to_destroy: Cell<Option<private::EventHandle>>, } impl EventLoop { /// Creates an event loop for the current thread, panicking if one already exists. Runs the /// given closure and then drops the event loop. pub fn top_level<R, F>(main: F) -> R where F: FnOnce(&WaitScope) -> R { let mut events = handle_table::HandleTable::<private::EventNode>::new(); let dummy = private::EventNode { event: None, next: None, prev: None, }; let head_handle = private::EventHandle(events.push(dummy)); EVENT_LOOP.with(move |maybe_event_loop| { let event_loop = EventLoop { _last_runnable_state: false, events: RefCell::new(events), head: head_handle, tail: Cell::new(head_handle), depth_first_insertion_point: Cell::new(head_handle), // insert after this node currently_firing: Cell::new(None), to_destroy: Cell::new(None), }; assert!(maybe_event_loop.borrow().is_none()); *maybe_event_loop.borrow_mut() = Some(event_loop); }); let wait_scope = WaitScope(::std::marker::PhantomData); let result = main(&wait_scope); EVENT_LOOP.with(move |maybe_event_loop| { let el = ::std::mem::replace(&mut *maybe_event_loop.borrow_mut(), None); match el { None => unreachable!(), Some(event_loop) =>
} }); result } fn arm_depth_first(&self, event_handle: private::EventHandle) { let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0] .next; match insertion_node_next { Some(next_handle) => { self.events.borrow_mut()[next_handle.0].prev = Some(event_handle); self.events.borrow_mut()[event_handle.0].next = Some(next_handle); } None => { self.tail.set(event_handle); } } self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point .get()); self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle); self.depth_first_insertion_point.set(event_handle); } fn arm_breadth_first(&self, event_handle: private::EventHandle) { let events = &mut *self.events.borrow_mut(); events[self.tail.get().0].next = Some(event_handle); events[event_handle.0].prev = Some(self.tail.get()); self.tail.set(event_handle); } /// Runs the event loop for a single step. fn turn(&self) -> bool { let event_handle = match self.events.borrow()[self.head.0].next { None => return false, Some(event_handle) => event_handle, }; self.depth_first_insertion_point.set(event_handle); self.currently_firing.set(Some(event_handle)); let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None) .expect("No event to fire?"); event.fire(); self.currently_firing.set(None); let maybe_next = self.events.borrow()[event_handle.0].next; self.events.borrow_mut()[self.head.0].next = maybe_next; if let Some(e) = maybe_next { self.events.borrow_mut()[e.0].prev = Some(self.head); } self.events.borrow_mut()[event_handle.0].next = None; self.events.borrow_mut()[event_handle.0].prev = None; if self.tail.get() == event_handle { self.tail.set(self.head); } self.depth_first_insertion_point.set(self.head); if let Some(event_handle) = self.to_destroy.get() { self.events.borrow_mut().remove(event_handle.0); self.to_destroy.set(None); } true } } /// Specifies an error to generate when a [`PromiseFulfiller`](struct.PromiseFulfiller.html) is /// dropped. pub trait FulfillerDropped { fn fulfiller_dropped() -> Self; } /// A handle that can be used to fulfill or reject a promise. If you think of a promise /// as the receiving end of a oneshot channel, then this is the sending end. /// /// When a `PromiseFulfiller<T,E>` is dropped without first receiving a `fulfill()`, `reject()`, or /// `resolve()` call, its promise is rejected with the error value `E::fulfiller_dropped()`. pub struct PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { hub: Rc<RefCell<private::PromiseAndFulfillerHub<T, E>>>, done: bool, } impl<T, E> PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { pub fn fulfill(mut self, value: T) { self.hub.borrow_mut().resolve(Ok(value)); self.done = true; } pub fn reject(mut self, error: E) { self.hub.borrow_mut().resolve(Err(error)); self.done = true; } pub fn resolve(mut self, result: Result<T, E>) { self.hub.borrow_mut().resolve(result); self.done = true; } } impl<T, E> Drop for PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { fn drop(&mut self) { if!self.done { self.hub.borrow_mut().resolve(Err(E::fulfiller_dropped())); } } } impl FulfillerDropped for () { fn fulfiller_dropped() -> () { () } } impl FulfillerDropped for ::std::io::Error { fn fulfiller_dropped() -> ::std::io::Error { ::std::io::Error::new(::std::io::ErrorKind::Other, "Promise fulfiller was dropped.") } } /// Holds a collection of `Promise<T, E>`s and ensures that each executes to completion. /// Destroying a `TaskSet` automatically cancels all of its unfinished promises. pub struct TaskSet<T, E> where T:'static, E:'static { task_set_impl: private::TaskSetImpl<T, E>, } impl<T, E> TaskSet<T, E> { pub fn new(reaper: Box<TaskReaper<T, E>>) -> TaskSet<T, E> { TaskSet { task_set_impl: private::TaskSetImpl::new(reaper) } } pub fn add(&mut self, promise: Promise<T, E>) { self.task_set_impl.add(promise.node); } } /// Callbacks to be invoked when a task in a [`TaskSet`](struct.TaskSet.html) finishes. You are /// required to implement at least the failure case. pub trait TaskReaper<T, E> where T:'static, E:'static { fn task_succeeded(&mut self, _value: T) {} fn task_failed(&mut self, error: E); }
{ // If there is still an event other than the head event, then there must have // been a memory leak. let remaining_events = event_loop.events.borrow().len(); if remaining_events > 1 { ::std::mem::forget(event_loop); // Prevent double panic. panic!("{} leaked events found when cleaning up event loop. \ Perhaps there is a reference cycle containing promises?", remaining_events - 1) } }
conditional_block
lib.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //! A library providing high-level abstractions for event loop concurrency, //! heavily borrowing ideas from [KJ](https://capnproto.org/cxxrpc.html#kj-concurrency-framework). //! Allows for coordination of asynchronous tasks using [promises](struct.Promise.html) as //! a basic building block. //! //! # Example //! //! ``` //! use gj::{EventLoop, Promise, ClosedEventPort}; //! EventLoop::top_level(|wait_scope| -> Result<(),()> { //! let (promise1, fulfiller1) = Promise::<(),()>::and_fulfiller(); //! let (promise2, fulfiller2) = Promise::<(),()>::and_fulfiller(); //! let promise3 = promise2.then(|_| { //! println!("world"); //! Promise::ok(()) //! }); //! let promise4 = promise1.then(move |_| { //! println!("hello "); //! fulfiller2.fulfill(()); //! Promise::ok(()) //! }); //! fulfiller1.fulfill(()); //! Promise::all(vec![promise3, promise4].into_iter()) //! .map(|_| Ok(())) //! .wait(wait_scope, &mut ClosedEventPort(())) //! }).expect("top level"); //! ``` use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::result::Result; use private::{promise_node, BoolEvent, PromiseAndFulfillerHub, PromiseAndFulfillerWrapper, EVENT_LOOP, with_current_event_loop, PromiseNode}; /// Like `try!()`, but for functions that return a [`Promise<T, E>`](struct.Promise.html) rather /// than a `Result<T, E>`. /// /// Unwraps a `Result<T, E>`. In the case of an error `Err(e)`, immediately returns from the /// enclosing function with `Promise::err(e)`. #[macro_export] macro_rules! pry { ($expr:expr) => (match $expr { ::std::result::Result::Ok(val) => val, ::std::result::Result::Err(err) => { return $crate::Promise::err(::std::convert::From::from(err)) } }) } mod private; mod handle_table; /// A computation that might eventually resolve to a value of type `T` or to an error /// of type `E`. Dropping the promise cancels the computation. #[must_use] pub struct Promise<T, E> where T:'static, E:'static { node: Box<PromiseNode<T, E>>, } impl<T, E> Promise<T, E> { /// Creates a new promise that has already been fulfilled with the given value. pub fn ok(value: T) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) } } /// Creates a new promise that has already been rejected with the given error. pub fn err(error: E) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Err(error))) } } /// Creates a new promise that never resolves. pub fn never_done() -> Promise<T, E> { Promise { node: Box::new(promise_node::NeverDone::new()) } } /// Creates a new promise/fulfiller pair. pub fn and_fulfiller() -> (Promise<T, E>, PromiseFulfiller<T, E>) where E: FulfillerDropped { let result = Rc::new(RefCell::new(PromiseAndFulfillerHub::new())); let result_promise: Promise<T, E> = Promise { node: Box::new(PromiseAndFulfillerWrapper::new(result.clone())), }; (result_promise, PromiseFulfiller { hub: result, done: false, }) } /// Chains further computation to be executed once the promise resolves. /// When the promise is fulfilled or rejected, invokes `func` on its result. /// /// If the returned promise is dropped before the chained computation runs, the chained /// computation will be cancelled. /// /// Always returns immediately, even if the promise is already resolved. The earliest that /// `func` might be invoked is during the next `turn()` of the event loop. pub fn then_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Promise<T1, E1> { let intermediate = Box::new(promise_node::Transform::new(self.node, |x| Ok(func(x)))); Promise { node: Box::new(promise_node::Chain::new(intermediate)) } } /// Calls `then_else()` with a default error handler that simply propagates all errors. pub fn then<F, T1>(self, func: F) -> Promise<T1, E> where F:'static, F: FnOnce(T) -> Promise<T1, E> { self.then_else(|r| { match r { Ok(v) => func(v), Err(e) => Promise::err(e), } }) } /// Like `then_else()` but for a `func` that returns a direct value rather than a promise. As an /// optimization, execution of `func` is delayed until its result is known to be needed. The /// expectation here is that `func` is just doing some transformation on the results, not /// scheduling any other actions, and therefore the system does not need to be proactive about /// evaluating it. This way, a chain of trivial `map()` transformations can be executed all at /// once without repeated rescheduling through the event loop. Use the `eagerly_evaluate()` /// method to suppress this behavior. pub fn map_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Result<T1, E1> { Promise { node: Box::new(promise_node::Transform::new(self.node, func)) } } /// Calls `map_else()` with a default error handler that simply propagates all errors. pub fn map<F, R>(self, func: F) -> Promise<R, E> where F:'static, F: FnOnce(T) -> Result<R, E>, R:'static { self.map_else(|r| { match r { Ok(v) => func(v), Err(e) => Err(e), } }) } /// Transforms the error branch of the promise. pub fn map_err<E1, F>(self, func: F) -> Promise<T, E1> where F:'static, F: FnOnce(E) -> E1 { self.map_else(|r| { match r { Ok(v) => Ok(v),
Err(e) => Err(func(e)), } }) } /// Maps errors into a more general type. pub fn lift<E1>(self) -> Promise<T, E1> where E: Into<E1> { self.map_err(|e| e.into()) } /// Returns a new promise that resolves when either `self` or `other` resolves. The promise that /// doesn't resolve first is cancelled. pub fn exclusive_join(self, other: Promise<T, E>) -> Promise<T, E> { Promise { node: Box::new(private::promise_node::ExclusiveJoin::new(self.node, other.node)) } } /// Transforms a collection of promises into a promise for a vector. If any of /// the promises fails, immediately cancels the remaining promises. pub fn all<I>(promises: I) -> Promise<Vec<T>, E> where I: Iterator<Item = Promise<T, E>> { Promise { node: Box::new(private::promise_node::ArrayJoin::new(promises)) } } /// Forks the promise, so that multiple different clients can independently wait on the result. pub fn fork(self) -> ForkedPromise<T, E> where T: Clone, E: Clone { ForkedPromise::new(self) } /// Holds onto `value` until the promise resolves, then drops `value`. pub fn attach<U>(self, value: U) -> Promise<T, E> where U:'static { self.map_else(move |result| { drop(value); result }) } /// Forces eager evaluation of this promise. Use this if you are going to hold on to the promise /// for a while without consuming the result, but you want to make sure that the system actually /// processes it. pub fn eagerly_evaluate(self) -> Promise<T, E> { self.then(|v| Promise::ok(v)) } /// Runs the event loop until the promise is fulfilled. /// /// The `WaitScope` argument ensures that `wait()` can only be called at the top level of a /// program. Waiting within event callbacks is disallowed. pub fn wait<E1>(mut self, wait_scope: &WaitScope, event_source: &mut EventPort<E1>) -> Result<T, E> where E: From<E1> { drop(wait_scope); with_current_event_loop(move |event_loop| { let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false)); let done_event = BoolEvent::new(fired.clone()); let (handle, _dropper) = private::GuardedEventHandle::new(); handle.set(Box::new(done_event)); self.node.on_ready(handle); while!fired.get() { if!event_loop.turn() { // No events in the queue. try!(event_source.wait()); } } self.node.get() }) } } /// A scope in which asynchronous programming can occur. Corresponds to the top level scope of some /// [event loop](struct.EventLoop.html). Can be used to [wait](struct.Promise.html#method.wait) for /// the result of a promise. pub struct WaitScope(::std::marker::PhantomData<*mut u8>); // impl!Sync for WaitScope {} /// The result of `Promise::fork()`. Allows branches to be created. Dropping the `ForkedPromise` /// along with any branches created through `add_branch()` will cancel the computation. pub struct ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { hub: Rc<RefCell<promise_node::ForkHub<T, E>>>, } impl<T, E> ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { fn new(inner: Promise<T, E>) -> ForkedPromise<T, E> { ForkedPromise { hub: Rc::new(RefCell::new(promise_node::ForkHub::new(inner.node))) } } /// Creates a new promise that will resolve when the originally forked promise resolves. pub fn add_branch(&mut self) -> Promise<T, E> { promise_node::ForkHub::add_branch(&self.hub) } } /// Interface between an `EventLoop` and events originating from outside of the loop's thread. /// Needed in [`Promise::wait()`](struct.Promise.html#method.wait). pub trait EventPort<E> { /// Waits for an external event to arrive, blocking the thread if necessary. fn wait(&mut self) -> Result<(), E>; } /// An event port that never emits any events. On wait() it returns the error it was constructed /// with. pub struct ClosedEventPort<E: Clone>(pub E); impl<E: Clone> EventPort<E> for ClosedEventPort<E> { fn wait(&mut self) -> Result<(), E> { Err(self.0.clone()) } } /// A queue of events being executed in a loop on a single thread. pub struct EventLoop { // daemons: TaskSetImpl, _last_runnable_state: bool, events: RefCell<handle_table::HandleTable<private::EventNode>>, head: private::EventHandle, tail: Cell<private::EventHandle>, depth_first_insertion_point: Cell<private::EventHandle>, currently_firing: Cell<Option<private::EventHandle>>, to_destroy: Cell<Option<private::EventHandle>>, } impl EventLoop { /// Creates an event loop for the current thread, panicking if one already exists. Runs the /// given closure and then drops the event loop. pub fn top_level<R, F>(main: F) -> R where F: FnOnce(&WaitScope) -> R { let mut events = handle_table::HandleTable::<private::EventNode>::new(); let dummy = private::EventNode { event: None, next: None, prev: None, }; let head_handle = private::EventHandle(events.push(dummy)); EVENT_LOOP.with(move |maybe_event_loop| { let event_loop = EventLoop { _last_runnable_state: false, events: RefCell::new(events), head: head_handle, tail: Cell::new(head_handle), depth_first_insertion_point: Cell::new(head_handle), // insert after this node currently_firing: Cell::new(None), to_destroy: Cell::new(None), }; assert!(maybe_event_loop.borrow().is_none()); *maybe_event_loop.borrow_mut() = Some(event_loop); }); let wait_scope = WaitScope(::std::marker::PhantomData); let result = main(&wait_scope); EVENT_LOOP.with(move |maybe_event_loop| { let el = ::std::mem::replace(&mut *maybe_event_loop.borrow_mut(), None); match el { None => unreachable!(), Some(event_loop) => { // If there is still an event other than the head event, then there must have // been a memory leak. let remaining_events = event_loop.events.borrow().len(); if remaining_events > 1 { ::std::mem::forget(event_loop); // Prevent double panic. panic!("{} leaked events found when cleaning up event loop. \ Perhaps there is a reference cycle containing promises?", remaining_events - 1) } } } }); result } fn arm_depth_first(&self, event_handle: private::EventHandle) { let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0] .next; match insertion_node_next { Some(next_handle) => { self.events.borrow_mut()[next_handle.0].prev = Some(event_handle); self.events.borrow_mut()[event_handle.0].next = Some(next_handle); } None => { self.tail.set(event_handle); } } self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point .get()); self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle); self.depth_first_insertion_point.set(event_handle); } fn arm_breadth_first(&self, event_handle: private::EventHandle) { let events = &mut *self.events.borrow_mut(); events[self.tail.get().0].next = Some(event_handle); events[event_handle.0].prev = Some(self.tail.get()); self.tail.set(event_handle); } /// Runs the event loop for a single step. fn turn(&self) -> bool { let event_handle = match self.events.borrow()[self.head.0].next { None => return false, Some(event_handle) => event_handle, }; self.depth_first_insertion_point.set(event_handle); self.currently_firing.set(Some(event_handle)); let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None) .expect("No event to fire?"); event.fire(); self.currently_firing.set(None); let maybe_next = self.events.borrow()[event_handle.0].next; self.events.borrow_mut()[self.head.0].next = maybe_next; if let Some(e) = maybe_next { self.events.borrow_mut()[e.0].prev = Some(self.head); } self.events.borrow_mut()[event_handle.0].next = None; self.events.borrow_mut()[event_handle.0].prev = None; if self.tail.get() == event_handle { self.tail.set(self.head); } self.depth_first_insertion_point.set(self.head); if let Some(event_handle) = self.to_destroy.get() { self.events.borrow_mut().remove(event_handle.0); self.to_destroy.set(None); } true } } /// Specifies an error to generate when a [`PromiseFulfiller`](struct.PromiseFulfiller.html) is /// dropped. pub trait FulfillerDropped { fn fulfiller_dropped() -> Self; } /// A handle that can be used to fulfill or reject a promise. If you think of a promise /// as the receiving end of a oneshot channel, then this is the sending end. /// /// When a `PromiseFulfiller<T,E>` is dropped without first receiving a `fulfill()`, `reject()`, or /// `resolve()` call, its promise is rejected with the error value `E::fulfiller_dropped()`. pub struct PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { hub: Rc<RefCell<private::PromiseAndFulfillerHub<T, E>>>, done: bool, } impl<T, E> PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { pub fn fulfill(mut self, value: T) { self.hub.borrow_mut().resolve(Ok(value)); self.done = true; } pub fn reject(mut self, error: E) { self.hub.borrow_mut().resolve(Err(error)); self.done = true; } pub fn resolve(mut self, result: Result<T, E>) { self.hub.borrow_mut().resolve(result); self.done = true; } } impl<T, E> Drop for PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { fn drop(&mut self) { if!self.done { self.hub.borrow_mut().resolve(Err(E::fulfiller_dropped())); } } } impl FulfillerDropped for () { fn fulfiller_dropped() -> () { () } } impl FulfillerDropped for ::std::io::Error { fn fulfiller_dropped() -> ::std::io::Error { ::std::io::Error::new(::std::io::ErrorKind::Other, "Promise fulfiller was dropped.") } } /// Holds a collection of `Promise<T, E>`s and ensures that each executes to completion. /// Destroying a `TaskSet` automatically cancels all of its unfinished promises. pub struct TaskSet<T, E> where T:'static, E:'static { task_set_impl: private::TaskSetImpl<T, E>, } impl<T, E> TaskSet<T, E> { pub fn new(reaper: Box<TaskReaper<T, E>>) -> TaskSet<T, E> { TaskSet { task_set_impl: private::TaskSetImpl::new(reaper) } } pub fn add(&mut self, promise: Promise<T, E>) { self.task_set_impl.add(promise.node); } } /// Callbacks to be invoked when a task in a [`TaskSet`](struct.TaskSet.html) finishes. You are /// required to implement at least the failure case. pub trait TaskReaper<T, E> where T:'static, E:'static { fn task_succeeded(&mut self, _value: T) {} fn task_failed(&mut self, error: E); }
random_line_split
lib.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //! A library providing high-level abstractions for event loop concurrency, //! heavily borrowing ideas from [KJ](https://capnproto.org/cxxrpc.html#kj-concurrency-framework). //! Allows for coordination of asynchronous tasks using [promises](struct.Promise.html) as //! a basic building block. //! //! # Example //! //! ``` //! use gj::{EventLoop, Promise, ClosedEventPort}; //! EventLoop::top_level(|wait_scope| -> Result<(),()> { //! let (promise1, fulfiller1) = Promise::<(),()>::and_fulfiller(); //! let (promise2, fulfiller2) = Promise::<(),()>::and_fulfiller(); //! let promise3 = promise2.then(|_| { //! println!("world"); //! Promise::ok(()) //! }); //! let promise4 = promise1.then(move |_| { //! println!("hello "); //! fulfiller2.fulfill(()); //! Promise::ok(()) //! }); //! fulfiller1.fulfill(()); //! Promise::all(vec![promise3, promise4].into_iter()) //! .map(|_| Ok(())) //! .wait(wait_scope, &mut ClosedEventPort(())) //! }).expect("top level"); //! ``` use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::result::Result; use private::{promise_node, BoolEvent, PromiseAndFulfillerHub, PromiseAndFulfillerWrapper, EVENT_LOOP, with_current_event_loop, PromiseNode}; /// Like `try!()`, but for functions that return a [`Promise<T, E>`](struct.Promise.html) rather /// than a `Result<T, E>`. /// /// Unwraps a `Result<T, E>`. In the case of an error `Err(e)`, immediately returns from the /// enclosing function with `Promise::err(e)`. #[macro_export] macro_rules! pry { ($expr:expr) => (match $expr { ::std::result::Result::Ok(val) => val, ::std::result::Result::Err(err) => { return $crate::Promise::err(::std::convert::From::from(err)) } }) } mod private; mod handle_table; /// A computation that might eventually resolve to a value of type `T` or to an error /// of type `E`. Dropping the promise cancels the computation. #[must_use] pub struct Promise<T, E> where T:'static, E:'static { node: Box<PromiseNode<T, E>>, } impl<T, E> Promise<T, E> { /// Creates a new promise that has already been fulfilled with the given value. pub fn ok(value: T) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) } } /// Creates a new promise that has already been rejected with the given error. pub fn err(error: E) -> Promise<T, E> { Promise { node: Box::new(promise_node::Immediate::new(Err(error))) } } /// Creates a new promise that never resolves. pub fn never_done() -> Promise<T, E> { Promise { node: Box::new(promise_node::NeverDone::new()) } } /// Creates a new promise/fulfiller pair. pub fn and_fulfiller() -> (Promise<T, E>, PromiseFulfiller<T, E>) where E: FulfillerDropped { let result = Rc::new(RefCell::new(PromiseAndFulfillerHub::new())); let result_promise: Promise<T, E> = Promise { node: Box::new(PromiseAndFulfillerWrapper::new(result.clone())), }; (result_promise, PromiseFulfiller { hub: result, done: false, }) } /// Chains further computation to be executed once the promise resolves. /// When the promise is fulfilled or rejected, invokes `func` on its result. /// /// If the returned promise is dropped before the chained computation runs, the chained /// computation will be cancelled. /// /// Always returns immediately, even if the promise is already resolved. The earliest that /// `func` might be invoked is during the next `turn()` of the event loop. pub fn then_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Promise<T1, E1> { let intermediate = Box::new(promise_node::Transform::new(self.node, |x| Ok(func(x)))); Promise { node: Box::new(promise_node::Chain::new(intermediate)) } } /// Calls `then_else()` with a default error handler that simply propagates all errors. pub fn then<F, T1>(self, func: F) -> Promise<T1, E> where F:'static, F: FnOnce(T) -> Promise<T1, E> { self.then_else(|r| { match r { Ok(v) => func(v), Err(e) => Promise::err(e), } }) } /// Like `then_else()` but for a `func` that returns a direct value rather than a promise. As an /// optimization, execution of `func` is delayed until its result is known to be needed. The /// expectation here is that `func` is just doing some transformation on the results, not /// scheduling any other actions, and therefore the system does not need to be proactive about /// evaluating it. This way, a chain of trivial `map()` transformations can be executed all at /// once without repeated rescheduling through the event loop. Use the `eagerly_evaluate()` /// method to suppress this behavior. pub fn map_else<F, T1, E1>(self, func: F) -> Promise<T1, E1> where F:'static, F: FnOnce(Result<T, E>) -> Result<T1, E1> { Promise { node: Box::new(promise_node::Transform::new(self.node, func)) } } /// Calls `map_else()` with a default error handler that simply propagates all errors. pub fn map<F, R>(self, func: F) -> Promise<R, E> where F:'static, F: FnOnce(T) -> Result<R, E>, R:'static { self.map_else(|r| { match r { Ok(v) => func(v), Err(e) => Err(e), } }) } /// Transforms the error branch of the promise. pub fn map_err<E1, F>(self, func: F) -> Promise<T, E1> where F:'static, F: FnOnce(E) -> E1 { self.map_else(|r| { match r { Ok(v) => Ok(v), Err(e) => Err(func(e)), } }) } /// Maps errors into a more general type. pub fn lift<E1>(self) -> Promise<T, E1> where E: Into<E1> { self.map_err(|e| e.into()) } /// Returns a new promise that resolves when either `self` or `other` resolves. The promise that /// doesn't resolve first is cancelled. pub fn exclusive_join(self, other: Promise<T, E>) -> Promise<T, E> { Promise { node: Box::new(private::promise_node::ExclusiveJoin::new(self.node, other.node)) } } /// Transforms a collection of promises into a promise for a vector. If any of /// the promises fails, immediately cancels the remaining promises. pub fn all<I>(promises: I) -> Promise<Vec<T>, E> where I: Iterator<Item = Promise<T, E>> { Promise { node: Box::new(private::promise_node::ArrayJoin::new(promises)) } } /// Forks the promise, so that multiple different clients can independently wait on the result. pub fn fork(self) -> ForkedPromise<T, E> where T: Clone, E: Clone { ForkedPromise::new(self) } /// Holds onto `value` until the promise resolves, then drops `value`. pub fn attach<U>(self, value: U) -> Promise<T, E> where U:'static { self.map_else(move |result| { drop(value); result }) } /// Forces eager evaluation of this promise. Use this if you are going to hold on to the promise /// for a while without consuming the result, but you want to make sure that the system actually /// processes it. pub fn eagerly_evaluate(self) -> Promise<T, E> { self.then(|v| Promise::ok(v)) } /// Runs the event loop until the promise is fulfilled. /// /// The `WaitScope` argument ensures that `wait()` can only be called at the top level of a /// program. Waiting within event callbacks is disallowed. pub fn wait<E1>(mut self, wait_scope: &WaitScope, event_source: &mut EventPort<E1>) -> Result<T, E> where E: From<E1> { drop(wait_scope); with_current_event_loop(move |event_loop| { let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false)); let done_event = BoolEvent::new(fired.clone()); let (handle, _dropper) = private::GuardedEventHandle::new(); handle.set(Box::new(done_event)); self.node.on_ready(handle); while!fired.get() { if!event_loop.turn() { // No events in the queue. try!(event_source.wait()); } } self.node.get() }) } } /// A scope in which asynchronous programming can occur. Corresponds to the top level scope of some /// [event loop](struct.EventLoop.html). Can be used to [wait](struct.Promise.html#method.wait) for /// the result of a promise. pub struct
(::std::marker::PhantomData<*mut u8>); // impl!Sync for WaitScope {} /// The result of `Promise::fork()`. Allows branches to be created. Dropping the `ForkedPromise` /// along with any branches created through `add_branch()` will cancel the computation. pub struct ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { hub: Rc<RefCell<promise_node::ForkHub<T, E>>>, } impl<T, E> ForkedPromise<T, E> where T:'static + Clone, E:'static + Clone { fn new(inner: Promise<T, E>) -> ForkedPromise<T, E> { ForkedPromise { hub: Rc::new(RefCell::new(promise_node::ForkHub::new(inner.node))) } } /// Creates a new promise that will resolve when the originally forked promise resolves. pub fn add_branch(&mut self) -> Promise<T, E> { promise_node::ForkHub::add_branch(&self.hub) } } /// Interface between an `EventLoop` and events originating from outside of the loop's thread. /// Needed in [`Promise::wait()`](struct.Promise.html#method.wait). pub trait EventPort<E> { /// Waits for an external event to arrive, blocking the thread if necessary. fn wait(&mut self) -> Result<(), E>; } /// An event port that never emits any events. On wait() it returns the error it was constructed /// with. pub struct ClosedEventPort<E: Clone>(pub E); impl<E: Clone> EventPort<E> for ClosedEventPort<E> { fn wait(&mut self) -> Result<(), E> { Err(self.0.clone()) } } /// A queue of events being executed in a loop on a single thread. pub struct EventLoop { // daemons: TaskSetImpl, _last_runnable_state: bool, events: RefCell<handle_table::HandleTable<private::EventNode>>, head: private::EventHandle, tail: Cell<private::EventHandle>, depth_first_insertion_point: Cell<private::EventHandle>, currently_firing: Cell<Option<private::EventHandle>>, to_destroy: Cell<Option<private::EventHandle>>, } impl EventLoop { /// Creates an event loop for the current thread, panicking if one already exists. Runs the /// given closure and then drops the event loop. pub fn top_level<R, F>(main: F) -> R where F: FnOnce(&WaitScope) -> R { let mut events = handle_table::HandleTable::<private::EventNode>::new(); let dummy = private::EventNode { event: None, next: None, prev: None, }; let head_handle = private::EventHandle(events.push(dummy)); EVENT_LOOP.with(move |maybe_event_loop| { let event_loop = EventLoop { _last_runnable_state: false, events: RefCell::new(events), head: head_handle, tail: Cell::new(head_handle), depth_first_insertion_point: Cell::new(head_handle), // insert after this node currently_firing: Cell::new(None), to_destroy: Cell::new(None), }; assert!(maybe_event_loop.borrow().is_none()); *maybe_event_loop.borrow_mut() = Some(event_loop); }); let wait_scope = WaitScope(::std::marker::PhantomData); let result = main(&wait_scope); EVENT_LOOP.with(move |maybe_event_loop| { let el = ::std::mem::replace(&mut *maybe_event_loop.borrow_mut(), None); match el { None => unreachable!(), Some(event_loop) => { // If there is still an event other than the head event, then there must have // been a memory leak. let remaining_events = event_loop.events.borrow().len(); if remaining_events > 1 { ::std::mem::forget(event_loop); // Prevent double panic. panic!("{} leaked events found when cleaning up event loop. \ Perhaps there is a reference cycle containing promises?", remaining_events - 1) } } } }); result } fn arm_depth_first(&self, event_handle: private::EventHandle) { let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0] .next; match insertion_node_next { Some(next_handle) => { self.events.borrow_mut()[next_handle.0].prev = Some(event_handle); self.events.borrow_mut()[event_handle.0].next = Some(next_handle); } None => { self.tail.set(event_handle); } } self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point .get()); self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle); self.depth_first_insertion_point.set(event_handle); } fn arm_breadth_first(&self, event_handle: private::EventHandle) { let events = &mut *self.events.borrow_mut(); events[self.tail.get().0].next = Some(event_handle); events[event_handle.0].prev = Some(self.tail.get()); self.tail.set(event_handle); } /// Runs the event loop for a single step. fn turn(&self) -> bool { let event_handle = match self.events.borrow()[self.head.0].next { None => return false, Some(event_handle) => event_handle, }; self.depth_first_insertion_point.set(event_handle); self.currently_firing.set(Some(event_handle)); let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None) .expect("No event to fire?"); event.fire(); self.currently_firing.set(None); let maybe_next = self.events.borrow()[event_handle.0].next; self.events.borrow_mut()[self.head.0].next = maybe_next; if let Some(e) = maybe_next { self.events.borrow_mut()[e.0].prev = Some(self.head); } self.events.borrow_mut()[event_handle.0].next = None; self.events.borrow_mut()[event_handle.0].prev = None; if self.tail.get() == event_handle { self.tail.set(self.head); } self.depth_first_insertion_point.set(self.head); if let Some(event_handle) = self.to_destroy.get() { self.events.borrow_mut().remove(event_handle.0); self.to_destroy.set(None); } true } } /// Specifies an error to generate when a [`PromiseFulfiller`](struct.PromiseFulfiller.html) is /// dropped. pub trait FulfillerDropped { fn fulfiller_dropped() -> Self; } /// A handle that can be used to fulfill or reject a promise. If you think of a promise /// as the receiving end of a oneshot channel, then this is the sending end. /// /// When a `PromiseFulfiller<T,E>` is dropped without first receiving a `fulfill()`, `reject()`, or /// `resolve()` call, its promise is rejected with the error value `E::fulfiller_dropped()`. pub struct PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { hub: Rc<RefCell<private::PromiseAndFulfillerHub<T, E>>>, done: bool, } impl<T, E> PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { pub fn fulfill(mut self, value: T) { self.hub.borrow_mut().resolve(Ok(value)); self.done = true; } pub fn reject(mut self, error: E) { self.hub.borrow_mut().resolve(Err(error)); self.done = true; } pub fn resolve(mut self, result: Result<T, E>) { self.hub.borrow_mut().resolve(result); self.done = true; } } impl<T, E> Drop for PromiseFulfiller<T, E> where T:'static, E:'static + FulfillerDropped { fn drop(&mut self) { if!self.done { self.hub.borrow_mut().resolve(Err(E::fulfiller_dropped())); } } } impl FulfillerDropped for () { fn fulfiller_dropped() -> () { () } } impl FulfillerDropped for ::std::io::Error { fn fulfiller_dropped() -> ::std::io::Error { ::std::io::Error::new(::std::io::ErrorKind::Other, "Promise fulfiller was dropped.") } } /// Holds a collection of `Promise<T, E>`s and ensures that each executes to completion. /// Destroying a `TaskSet` automatically cancels all of its unfinished promises. pub struct TaskSet<T, E> where T:'static, E:'static { task_set_impl: private::TaskSetImpl<T, E>, } impl<T, E> TaskSet<T, E> { pub fn new(reaper: Box<TaskReaper<T, E>>) -> TaskSet<T, E> { TaskSet { task_set_impl: private::TaskSetImpl::new(reaper) } } pub fn add(&mut self, promise: Promise<T, E>) { self.task_set_impl.add(promise.node); } } /// Callbacks to be invoked when a task in a [`TaskSet`](struct.TaskSet.html) finishes. You are /// required to implement at least the failure case. pub trait TaskReaper<T, E> where T:'static, E:'static { fn task_succeeded(&mut self, _value: T) {} fn task_failed(&mut self, error: E); }
WaitScope
identifier_name
facility.rs
#[cfg(feature = "serde-serialize")] use serde::{Serialize, Serializer}; use std::convert::TryFrom; use thiserror::Error; #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] #[allow(non_camel_case_types)] /// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around. /// Names are from Linux. pub enum SyslogFacility { LOG_KERN = 0, LOG_USER = 1, LOG_MAIL = 2, LOG_DAEMON = 3, LOG_AUTH = 4, LOG_SYSLOG = 5, LOG_LPR = 6, LOG_NEWS = 7, LOG_UUCP = 8, LOG_CRON = 9, LOG_AUTHPRIV = 10, LOG_FTP = 11, LOG_NTP = 12, LOG_AUDIT = 13, LOG_ALERT = 14, LOG_CLOCKD = 15, LOG_LOCAL0 = 16, LOG_LOCAL1 = 17, LOG_LOCAL2 = 18, LOG_LOCAL3 = 19, LOG_LOCAL4 = 20, LOG_LOCAL5 = 21, LOG_LOCAL6 = 22, LOG_LOCAL7 = 23, } #[derive(Debug, Error)] pub enum SyslogFacilityError { #[error("integer does not correspond to a known facility")] InvalidInteger, } impl TryFrom<i32> for SyslogFacility { type Error = SyslogFacilityError; #[inline(always)] fn try_from(i: i32) -> Result<SyslogFacility, Self::Error> { Ok(match i { 0 => SyslogFacility::LOG_KERN, 1 => SyslogFacility::LOG_USER, 2 => SyslogFacility::LOG_MAIL, 3 => SyslogFacility::LOG_DAEMON, 4 => SyslogFacility::LOG_AUTH, 5 => SyslogFacility::LOG_SYSLOG, 6 => SyslogFacility::LOG_LPR, 7 => SyslogFacility::LOG_NEWS, 8 => SyslogFacility::LOG_UUCP, 9 => SyslogFacility::LOG_CRON, 10 => SyslogFacility::LOG_AUTHPRIV, 11 => SyslogFacility::LOG_FTP, 12 => SyslogFacility::LOG_NTP, 13 => SyslogFacility::LOG_AUDIT, 14 => SyslogFacility::LOG_ALERT, 15 => SyslogFacility::LOG_CLOCKD, 16 => SyslogFacility::LOG_LOCAL0, 17 => SyslogFacility::LOG_LOCAL1, 18 => SyslogFacility::LOG_LOCAL2, 19 => SyslogFacility::LOG_LOCAL3, 20 => SyslogFacility::LOG_LOCAL4, 21 => SyslogFacility::LOG_LOCAL5, 22 => SyslogFacility::LOG_LOCAL6, 23 => SyslogFacility::LOG_LOCAL7, _ => return Err(SyslogFacilityError::InvalidInteger), }) } } impl SyslogFacility { /// Convert an int (as used in the wire serialization) into a `SyslogFacility` pub(crate) fn from_int(i: i32) -> Option<Self>
/// Convert a syslog facility into a unique string representation pub fn as_str(self) -> &'static str { match self { SyslogFacility::LOG_KERN => "kern", SyslogFacility::LOG_USER => "user", SyslogFacility::LOG_MAIL => "mail", SyslogFacility::LOG_DAEMON => "daemon", SyslogFacility::LOG_AUTH => "auth", SyslogFacility::LOG_SYSLOG => "syslog", SyslogFacility::LOG_LPR => "lpr", SyslogFacility::LOG_NEWS => "news", SyslogFacility::LOG_UUCP => "uucp", SyslogFacility::LOG_CRON => "cron", SyslogFacility::LOG_AUTHPRIV => "authpriv", SyslogFacility::LOG_FTP => "ftp", SyslogFacility::LOG_NTP => "ntp", SyslogFacility::LOG_AUDIT => "audit", SyslogFacility::LOG_ALERT => "alert", SyslogFacility::LOG_CLOCKD => "clockd", SyslogFacility::LOG_LOCAL0 => "local0", SyslogFacility::LOG_LOCAL1 => "local1", SyslogFacility::LOG_LOCAL2 => "local2", SyslogFacility::LOG_LOCAL3 => "local3", SyslogFacility::LOG_LOCAL4 => "local4", SyslogFacility::LOG_LOCAL5 => "local5", SyslogFacility::LOG_LOCAL6 => "local6", SyslogFacility::LOG_LOCAL7 => "local7", } } } #[cfg(feature = "serde-serialize")] impl Serialize for SyslogFacility { fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> { ser.serialize_str(self.as_str()) } } #[cfg(test)] mod tests { use super::SyslogFacility; #[test] fn test_deref() { assert_eq!(SyslogFacility::LOG_KERN.as_str(), "kern"); } }
{ Self::try_from(i).ok() }
identifier_body
facility.rs
#[cfg(feature = "serde-serialize")] use serde::{Serialize, Serializer}; use std::convert::TryFrom; use thiserror::Error; #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] #[allow(non_camel_case_types)] /// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around. /// Names are from Linux. pub enum SyslogFacility { LOG_KERN = 0, LOG_USER = 1, LOG_MAIL = 2, LOG_DAEMON = 3, LOG_AUTH = 4, LOG_SYSLOG = 5, LOG_LPR = 6, LOG_NEWS = 7, LOG_UUCP = 8, LOG_CRON = 9,
LOG_CLOCKD = 15, LOG_LOCAL0 = 16, LOG_LOCAL1 = 17, LOG_LOCAL2 = 18, LOG_LOCAL3 = 19, LOG_LOCAL4 = 20, LOG_LOCAL5 = 21, LOG_LOCAL6 = 22, LOG_LOCAL7 = 23, } #[derive(Debug, Error)] pub enum SyslogFacilityError { #[error("integer does not correspond to a known facility")] InvalidInteger, } impl TryFrom<i32> for SyslogFacility { type Error = SyslogFacilityError; #[inline(always)] fn try_from(i: i32) -> Result<SyslogFacility, Self::Error> { Ok(match i { 0 => SyslogFacility::LOG_KERN, 1 => SyslogFacility::LOG_USER, 2 => SyslogFacility::LOG_MAIL, 3 => SyslogFacility::LOG_DAEMON, 4 => SyslogFacility::LOG_AUTH, 5 => SyslogFacility::LOG_SYSLOG, 6 => SyslogFacility::LOG_LPR, 7 => SyslogFacility::LOG_NEWS, 8 => SyslogFacility::LOG_UUCP, 9 => SyslogFacility::LOG_CRON, 10 => SyslogFacility::LOG_AUTHPRIV, 11 => SyslogFacility::LOG_FTP, 12 => SyslogFacility::LOG_NTP, 13 => SyslogFacility::LOG_AUDIT, 14 => SyslogFacility::LOG_ALERT, 15 => SyslogFacility::LOG_CLOCKD, 16 => SyslogFacility::LOG_LOCAL0, 17 => SyslogFacility::LOG_LOCAL1, 18 => SyslogFacility::LOG_LOCAL2, 19 => SyslogFacility::LOG_LOCAL3, 20 => SyslogFacility::LOG_LOCAL4, 21 => SyslogFacility::LOG_LOCAL5, 22 => SyslogFacility::LOG_LOCAL6, 23 => SyslogFacility::LOG_LOCAL7, _ => return Err(SyslogFacilityError::InvalidInteger), }) } } impl SyslogFacility { /// Convert an int (as used in the wire serialization) into a `SyslogFacility` pub(crate) fn from_int(i: i32) -> Option<Self> { Self::try_from(i).ok() } /// Convert a syslog facility into a unique string representation pub fn as_str(self) -> &'static str { match self { SyslogFacility::LOG_KERN => "kern", SyslogFacility::LOG_USER => "user", SyslogFacility::LOG_MAIL => "mail", SyslogFacility::LOG_DAEMON => "daemon", SyslogFacility::LOG_AUTH => "auth", SyslogFacility::LOG_SYSLOG => "syslog", SyslogFacility::LOG_LPR => "lpr", SyslogFacility::LOG_NEWS => "news", SyslogFacility::LOG_UUCP => "uucp", SyslogFacility::LOG_CRON => "cron", SyslogFacility::LOG_AUTHPRIV => "authpriv", SyslogFacility::LOG_FTP => "ftp", SyslogFacility::LOG_NTP => "ntp", SyslogFacility::LOG_AUDIT => "audit", SyslogFacility::LOG_ALERT => "alert", SyslogFacility::LOG_CLOCKD => "clockd", SyslogFacility::LOG_LOCAL0 => "local0", SyslogFacility::LOG_LOCAL1 => "local1", SyslogFacility::LOG_LOCAL2 => "local2", SyslogFacility::LOG_LOCAL3 => "local3", SyslogFacility::LOG_LOCAL4 => "local4", SyslogFacility::LOG_LOCAL5 => "local5", SyslogFacility::LOG_LOCAL6 => "local6", SyslogFacility::LOG_LOCAL7 => "local7", } } } #[cfg(feature = "serde-serialize")] impl Serialize for SyslogFacility { fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> { ser.serialize_str(self.as_str()) } } #[cfg(test)] mod tests { use super::SyslogFacility; #[test] fn test_deref() { assert_eq!(SyslogFacility::LOG_KERN.as_str(), "kern"); } }
LOG_AUTHPRIV = 10, LOG_FTP = 11, LOG_NTP = 12, LOG_AUDIT = 13, LOG_ALERT = 14,
random_line_split
facility.rs
#[cfg(feature = "serde-serialize")] use serde::{Serialize, Serializer}; use std::convert::TryFrom; use thiserror::Error; #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] #[allow(non_camel_case_types)] /// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around. /// Names are from Linux. pub enum SyslogFacility { LOG_KERN = 0, LOG_USER = 1, LOG_MAIL = 2, LOG_DAEMON = 3, LOG_AUTH = 4, LOG_SYSLOG = 5, LOG_LPR = 6, LOG_NEWS = 7, LOG_UUCP = 8, LOG_CRON = 9, LOG_AUTHPRIV = 10, LOG_FTP = 11, LOG_NTP = 12, LOG_AUDIT = 13, LOG_ALERT = 14, LOG_CLOCKD = 15, LOG_LOCAL0 = 16, LOG_LOCAL1 = 17, LOG_LOCAL2 = 18, LOG_LOCAL3 = 19, LOG_LOCAL4 = 20, LOG_LOCAL5 = 21, LOG_LOCAL6 = 22, LOG_LOCAL7 = 23, } #[derive(Debug, Error)] pub enum
{ #[error("integer does not correspond to a known facility")] InvalidInteger, } impl TryFrom<i32> for SyslogFacility { type Error = SyslogFacilityError; #[inline(always)] fn try_from(i: i32) -> Result<SyslogFacility, Self::Error> { Ok(match i { 0 => SyslogFacility::LOG_KERN, 1 => SyslogFacility::LOG_USER, 2 => SyslogFacility::LOG_MAIL, 3 => SyslogFacility::LOG_DAEMON, 4 => SyslogFacility::LOG_AUTH, 5 => SyslogFacility::LOG_SYSLOG, 6 => SyslogFacility::LOG_LPR, 7 => SyslogFacility::LOG_NEWS, 8 => SyslogFacility::LOG_UUCP, 9 => SyslogFacility::LOG_CRON, 10 => SyslogFacility::LOG_AUTHPRIV, 11 => SyslogFacility::LOG_FTP, 12 => SyslogFacility::LOG_NTP, 13 => SyslogFacility::LOG_AUDIT, 14 => SyslogFacility::LOG_ALERT, 15 => SyslogFacility::LOG_CLOCKD, 16 => SyslogFacility::LOG_LOCAL0, 17 => SyslogFacility::LOG_LOCAL1, 18 => SyslogFacility::LOG_LOCAL2, 19 => SyslogFacility::LOG_LOCAL3, 20 => SyslogFacility::LOG_LOCAL4, 21 => SyslogFacility::LOG_LOCAL5, 22 => SyslogFacility::LOG_LOCAL6, 23 => SyslogFacility::LOG_LOCAL7, _ => return Err(SyslogFacilityError::InvalidInteger), }) } } impl SyslogFacility { /// Convert an int (as used in the wire serialization) into a `SyslogFacility` pub(crate) fn from_int(i: i32) -> Option<Self> { Self::try_from(i).ok() } /// Convert a syslog facility into a unique string representation pub fn as_str(self) -> &'static str { match self { SyslogFacility::LOG_KERN => "kern", SyslogFacility::LOG_USER => "user", SyslogFacility::LOG_MAIL => "mail", SyslogFacility::LOG_DAEMON => "daemon", SyslogFacility::LOG_AUTH => "auth", SyslogFacility::LOG_SYSLOG => "syslog", SyslogFacility::LOG_LPR => "lpr", SyslogFacility::LOG_NEWS => "news", SyslogFacility::LOG_UUCP => "uucp", SyslogFacility::LOG_CRON => "cron", SyslogFacility::LOG_AUTHPRIV => "authpriv", SyslogFacility::LOG_FTP => "ftp", SyslogFacility::LOG_NTP => "ntp", SyslogFacility::LOG_AUDIT => "audit", SyslogFacility::LOG_ALERT => "alert", SyslogFacility::LOG_CLOCKD => "clockd", SyslogFacility::LOG_LOCAL0 => "local0", SyslogFacility::LOG_LOCAL1 => "local1", SyslogFacility::LOG_LOCAL2 => "local2", SyslogFacility::LOG_LOCAL3 => "local3", SyslogFacility::LOG_LOCAL4 => "local4", SyslogFacility::LOG_LOCAL5 => "local5", SyslogFacility::LOG_LOCAL6 => "local6", SyslogFacility::LOG_LOCAL7 => "local7", } } } #[cfg(feature = "serde-serialize")] impl Serialize for SyslogFacility { fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> { ser.serialize_str(self.as_str()) } } #[cfg(test)] mod tests { use super::SyslogFacility; #[test] fn test_deref() { assert_eq!(SyslogFacility::LOG_KERN.as_str(), "kern"); } }
SyslogFacilityError
identifier_name
struct-namespace.rs
// Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-gdb // compile-flags:-g // min-lldb-version: 310 // Check that structs get placed in the correct namespace // lldb-command:run // lldb-command:p struct1 // lldbg-check:(struct_namespace::Struct1) $0 = [...] // lldbr-check:(struct_namespace::Struct1) struct1 = Struct1 { a: 0, b: 1 } // lldb-command:p struct2 // lldbg-check:(struct_namespace::Struct2) $1 = [...] // lldbr-check:(struct_namespace::Struct2) struct2 = { = 2 } // lldb-command:p mod1_struct1 // lldbg-check:(struct_namespace::mod1::Struct1) $2 = [...] // lldbr-check:(struct_namespace::mod1::Struct1) mod1_struct1 = Struct1 { a: 3, b: 4 } // lldb-command:p mod1_struct2 // lldbg-check:(struct_namespace::mod1::Struct2) $3 = [...] // lldbr-check:(struct_namespace::mod1::Struct2) mod1_struct2 = { = 5 } #![allow(unused_variables)] #![allow(dead_code)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] struct Struct1 { a: u32, b: u64, } struct Struct2(u32); mod mod1 { pub struct Struct1 { pub a: u32,
pub struct Struct2(pub u32); } fn main() { let struct1 = Struct1 { a: 0, b: 1, }; let struct2 = Struct2(2); let mod1_struct1 = mod1::Struct1 { a: 3, b: 4, }; let mod1_struct2 = mod1::Struct2(5); zzz(); // #break } #[inline(never)] fn zzz() {()}
pub b: u64, }
random_line_split
struct-namespace.rs
// Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-gdb // compile-flags:-g // min-lldb-version: 310 // Check that structs get placed in the correct namespace // lldb-command:run // lldb-command:p struct1 // lldbg-check:(struct_namespace::Struct1) $0 = [...] // lldbr-check:(struct_namespace::Struct1) struct1 = Struct1 { a: 0, b: 1 } // lldb-command:p struct2 // lldbg-check:(struct_namespace::Struct2) $1 = [...] // lldbr-check:(struct_namespace::Struct2) struct2 = { = 2 } // lldb-command:p mod1_struct1 // lldbg-check:(struct_namespace::mod1::Struct1) $2 = [...] // lldbr-check:(struct_namespace::mod1::Struct1) mod1_struct1 = Struct1 { a: 3, b: 4 } // lldb-command:p mod1_struct2 // lldbg-check:(struct_namespace::mod1::Struct2) $3 = [...] // lldbr-check:(struct_namespace::mod1::Struct2) mod1_struct2 = { = 5 } #![allow(unused_variables)] #![allow(dead_code)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] struct Struct1 { a: u32, b: u64, } struct Struct2(u32); mod mod1 { pub struct
{ pub a: u32, pub b: u64, } pub struct Struct2(pub u32); } fn main() { let struct1 = Struct1 { a: 0, b: 1, }; let struct2 = Struct2(2); let mod1_struct1 = mod1::Struct1 { a: 3, b: 4, }; let mod1_struct2 = mod1::Struct2(5); zzz(); // #break } #[inline(never)] fn zzz() {()}
Struct1
identifier_name
monch.rs
#![feature(old_io)] #![feature(std_misc)] #![feature(collections)] #![feature(test)] #![feature(io)] #![feature(libc)] // logging needs this #![feature(rustc_private)] #[macro_use] extern crate log; extern crate env_logger; extern crate getopts; extern crate time; extern crate test; use std::old_io::TcpStream; use std::old_io::BufferedStream; use std::old_io::BufferedReader; use std::old_io::BufferedWriter; use std::old_io::Writer; use std::old_io::Reader; use std::old_io::IoResult; use std::str::from_utf8; use std::time::duration::Duration; use getopts::Options; mod semaphore; use semaphore::Semaphore; use std::sync::Arc; use std::thread; use std::error::Error; use std::sync::Mutex; use std::collections::HashMap; use test::stats::Stats; use time::precise_time_ns; use std::error::FromError; use std::old_io::IoError; use std::io; use std::io::Write; const MESSAGE_TYPE_HELLO: i8 = 0; const MESSAGE_TYPE_HEARTBEAT: i8 = 1; const MESSAGE_TYPE_REQUEST: i8 = 2; const MESSAGE_TYPE_RESPONSE: i8 = 3; const MESSAGE_TYPE_BYE: i8 = 6; static PROGRAM_NAME: &'static str = "monch"; static KEY_VERSION: &'static str = "version"; static KEY_CLIENT_NAME: &'static str = "client-name"; static KEY_MAX_LENGTH: &'static str = "max-length"; static PROTOCOL_VERSION: i8 = 1; static HEARTBEAT_INTERVAL_SEC: i64 = 5; static REQUEST_TIMEOUT_SEC: i64 = 5; static BUFFER_SIZE_KB: usize = 256; fn send_attributes(sock: &mut Writer, attributes: &Vec<(String, String)>) -> IoResult<()> { try!(sock.write_u8(attributes.len() as u8)); for &(ref name, ref value) in attributes { try!(sock.write_u8(name.len() as u8)); try!(sock.write_str(name)); try!(sock.write_be_u16(value.len() as u16)); try!(sock.write_str(&value)); } Ok(()) } fn calc_attribute_length(attributes: &Vec<(String, String)>) -> i32 { let mut length: i32 = 1; for &(ref name, ref value) in attributes { length += 1; length += name.len() as i32; length += 2; length += value.len() as i32; } length } fn recv_attributes(sock: &mut Reader) -> IoResult<(Vec<(String, String)>, i32)> { let attr_qtty = try!(sock.read_byte()); let mut bytes_len = 1i32; // length byte let mut res: Vec<(String, String)> = Vec::with_capacity(attr_qtty as usize); for _ in 0.. attr_qtty { bytes_len += 3; // 1 (name size) + 2 (value size) let len_name = try!(sock.read_byte()); let name_bytes = try!(sock.read_exact(len_name as usize)); bytes_len += len_name as i32; let name = String::from_utf8(name_bytes).ok().unwrap(); // do better let len_value = try!(sock.read_be_u16()); let value_bytes = try!(sock.read_exact(len_value as usize)); bytes_len += len_value as i32; let value = String::from_utf8(value_bytes).ok().unwrap(); // do better res.push((name, value)); } Ok((res, bytes_len)) } fn send_client_hello(sock: &mut Writer, max_length: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HELLO)); let attributes = vec![ (KEY_VERSION.to_string(), PROTOCOL_VERSION.to_string()), (KEY_CLIENT_NAME.to_string(), PROGRAM_NAME.to_string()), (KEY_MAX_LENGTH.to_string(), max_length.to_string()) ]; let message_length = calc_attribute_length(&attributes); try!(sock.write_be_i32(message_length as i32)); try!(send_attributes(sock, &attributes)); try!(sock.flush()); Ok(()) } fn recv_server_hello(sock: &mut Reader) -> Result<Frame, MyError> { let (attributes, attr_len) = try!(recv_attributes(sock)); let res = HelloData { attributes: attributes, attr_len: attr_len }; Ok(Frame::Hello(res)) } fn send_request(sock: &mut Writer, request: &StaticRequestData, request_id: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_REQUEST)); let fixed_part = 12; // 4 + 4 + 4 let length = fixed_part + request.attr_len + request.msg.len() as i32; try!(sock.write_be_i32(length)); try!(sock.write_be_i32(request_id)); try!(sock.write_be_i32(0)); // flow id try!(sock.write_be_i32(request.timeout.num_milliseconds() as i32)); try!(send_attributes(sock, &request.attributes)); try!(sock.write_str(&request.msg)); try!(sock.flush()); Ok(()) } fn send_bye(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_BYE)); let length = 0; try!(sock.write_be_i32(length)); try!(sock.flush()); Ok(()) } fn
(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HEARTBEAT)); try!(sock.write_be_i32(0)); try!(sock.flush()); Ok(()) } #[derive(Debug)] enum MyError { Io(IoError), Other(String) } impl FromError<IoError> for MyError { fn from_error(err: IoError) -> MyError { MyError::Io(err) } } impl FromError<String> for MyError { fn from_error(err: String) -> MyError { MyError::Other(err) } } // only received message types needed #[derive(Debug)] enum Frame { HeartBeat, Hello(HelloData), Response(ResponseData) } #[derive(Debug)] struct HelloData { attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct StaticRequestData { msg: String, timeout: Duration, attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct ResponseData { reference: i32, attributes: Vec<(String, String)>, body: Vec<u8> } fn recv_frame(sock: &mut Reader) -> Result<Frame, MyError> { let message_type = try!(sock.read_byte()) as i8; let length = try!(sock.read_be_i32()); match message_type { MESSAGE_TYPE_HEARTBEAT => Ok(Frame::HeartBeat), MESSAGE_TYPE_RESPONSE => Ok(try!(recv_response(sock, length))), MESSAGE_TYPE_HELLO => Ok(try!(recv_server_hello(sock))), other => Err(MyError::Other(format!("Invalid message type, received: {}", other))), } } fn recv_response(sock: &mut Reader, length: i32) -> Result<Frame, MyError> { let reference = try!(sock.read_be_u32()); let (attr, attr_len) = try!(recv_attributes(sock)); let remaining_length = length - 4 - attr_len; let response = try!(sock.read_exact(remaining_length as usize)); let frame = ResponseData { reference: reference as i32, attributes: attr, body: response }; Ok(Frame::Response(frame)) } fn connect(host: &str, port: u16, timeout: Duration) -> IoResult<TcpStream> { //log("resolving %s..." % host) //let address = socket.gethostbyname(host) let sock = try!(TcpStream::connect_timeout((host, port), timeout)); Ok(sock) } fn parse_attributes(str: &Vec<String>) -> Result<Vec<(String, String)>, String> { let mut res: Vec<(String, String)> = vec![]; for attr_string in str { let parts = attr_string.split(":").collect::<Vec<&str>>(); if parts.len()!= 2 { return Err(format!("invalid attribute specification: {} -- must be of the form 'name: value'", attr_string)); } res.push((parts[0].to_string(), parts[1].to_string())); } Ok(res) } fn sender_thread( sock: &mut Writer, semaphore: Arc<Semaphore>, start_time: u64, timeout_total: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, max_length: u32, finished: Arc<Semaphore>, request: StaticRequestData) -> IoResult<()> { try!(send_client_hello(sock, max_length as i32)); let timeout = Duration::seconds(HEARTBEAT_INTERVAL_SEC); let mut i = 0; while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout_total { let success = semaphore.acquire_timeout(timeout); if success { { let mut st = sent_times.lock().unwrap(); st.insert(i as i32, precise_time_ns()); } try!(send_request(sock, &request, i as i32)); i += 1; } else { try!(send_heartbeat(sock)); } } // The receiver will signal the finalization let mut fin = false; while!fin { let success = finished.acquire_timeout(timeout); if success { fin = true; } else { try!(send_heartbeat(sock)); } } Ok(()) } struct ReceiverResult { first_response: Option<Vec<u8>>, response_times: HashMap<u32, f32>, ok_count: u32, same_size_count: u32, } fn receiver_thread( sock: &mut Reader, semaphore: Arc<Semaphore>, start_time: u64, timeout: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, finished: Arc<Semaphore>) -> Result<ReceiverResult, MyError> { let frame = try!(recv_frame(sock)); let server_attributes = match frame { Frame::Hello(hello) => hello.attributes, other => return Err(MyError::Other(format!("Invalid message type. Expecting hello, received: {:?}", other))), }; println!("Received server hello message: {:?}", server_attributes); let mut response_times = HashMap::<u32, f32>::with_capacity(send_count as usize); let mut first_response: Option<Vec<u8>> = None; let mut first_size: Option<i32> = None; let mut first = true; let mut i = 0; let mut ok_count = 0u32; let mut same_size_count = 1u32; // first response has always the same size as itself while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout { let frame = try!(recv_frame(sock)); match frame { Frame::HeartBeat => {}, // pass Frame::Response(ResponseData { reference, attributes, body }) => { let reception_time = precise_time_ns(); // as soon as possible semaphore.release(); let sent_time = { let mut st = sent_times.lock().unwrap(); st.remove(&reference).unwrap() }; let delay = ((reception_time - sent_time) / 1000) as u32; response_times.insert(i, delay as f32); for &(ref name, ref value) in attributes.iter() { if *name == "status" { if *value == "ok" { ok_count += 1; } break; } } if first { println!("First response attributes {:?}", attributes); first_response = Some(body.clone()); first_size = Some(body.len() as i32) } else { if body.len() as i32 == first_size.unwrap() { same_size_count += 1; } } if i % 1000 == 0 { print!("\rCompleted {} requests.", i); io::stdout().flush(); } i += 1; first = false; }, other => return Err(MyError::Other(format!("Invalid message type. Expecting heart-beat or response, received: {:?}", other))), } } finished.release(); println!("\rCompleted all {} requests.", send_count); let res = ReceiverResult { first_response: first_response, response_times: response_times, ok_count: ok_count, same_size_count: same_size_count, }; Ok(res) } fn main_impl(options: &MonchOptions) -> IoResult<()> { println!("This is Mot Benchmark (monch)."); println!(""); println!("Benchmarking {}:{}...", &options.host, options.port); let start = precise_time_ns(); print!("Establishing TCP connection..."); io::stdout().flush(); let mut sock = try!(connect(&options.host, options.port, options.connect_timeout)); sock.set_timeout(Some(10000)); println!("done"); let connection_time = (precise_time_ns() - start) / 1000; let mut bye_writer_sock = BufferedStream::new(sock.clone()); let mut reader_sock = BufferedReader::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let mut writer_sock = BufferedWriter::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let semaphore = Arc::new(Semaphore::new(options.concurrency as isize)); let finished = Arc::new(Semaphore::new(0)); let mut times = Vec::<u32>::new(); let sent_times = Arc::new(Mutex::new(HashMap::<i32, u64>::new())); times.resize(options.concurrency as usize, 0); let (finished_snd, finished_rcv) = (finished.clone(), finished.clone()); let (semaphore_snd, semaphore_rcv) = (semaphore.clone(), semaphore.clone()); let (sent_times_snd, sent_times_rcv) = (sent_times.clone(), sent_times.clone()); let sender = thread::scoped(move || { let attr_len = calc_attribute_length(&options.attributes); let request = StaticRequestData { msg: options.message.clone(), timeout: Duration::seconds(REQUEST_TIMEOUT_SEC), attributes: options.attributes.clone(), attr_len: attr_len, }; sender_thread( &mut writer_sock, semaphore_snd, start, options.timeout, sent_times_snd, options.number, options.max_length, finished_snd, request).unwrap(); }); let receiver = thread::scoped(move || { receiver_thread( &mut reader_sock, semaphore_rcv, start, options.timeout, sent_times_rcv, options.number, finished_rcv).unwrap() }); sender.join(); let result = receiver.join(); try!(send_bye(&mut bye_writer_sock)); let total_time = (precise_time_ns() - start) / (1000 * 1000); let received_count = result.response_times.len(); let times: Vec<f32> = result.response_times.values().map(|x| *x).collect(); let response_size = result.first_response.map(|r| r.len() as i32); println!(""); println!("Total time taken for tests: {:>7} ms", total_time); println!("Connection time: {:>7} µs", connection_time); println!("Response size: {:>7} bytes", response_size.unwrap_or(-1)); println!("Received responses: {:>7} requests", received_count); println!("Time outs: {:>7} requests", options.number - received_count as u32); println!("OK responses: {:>7} requests", result.ok_count); println!("Same size responses: {:>7} requests", result.same_size_count); println!(""); println!("Percentage of the requests served within a certain time (µs):"); println!(" {:>8.0} (shortest request)", times.min()); for p in vec![50.0, 80.0, 95.0, 99.0, 99.9] { println!(" {:>5.1}% {:>8.0}", p, times.percentile(p)); } println!(" {:>5.1}% {:>8.0} (longest request)", 100.0, times.max()); Ok(()) } struct MonchOptions { host: String, port: u16, attributes: Vec<(String, String)>, message: String, timeout: Duration, connect_timeout: Duration, number: u32, concurrency: u16, max_length: u32, } fn get_options() -> MonchOptions { let args: Vec<String> = std::env::args().collect(); let mut opts = Options::new(); opts.optmulti("a", "attributes", "set a request attribute ('name: value')", "ATTRIBUTE"); opts.reqopt("n", "number", "determine how many request to send", "QUANTITY"); opts.optopt("c", "concurrency", "determine how many request to send at the same time (default 1)", "QUANTITY"); opts.optopt("t", "timeout", "hoy much time to wait for the completion of the test, in seconds (default: 60)", "TIMEOUT"); opts.optopt("T", "connect-timeout", "hoy much time to wait for the establishment of the TCP connection, in milliseconds (default: 5000)", "TIMEOUT"); opts.reqopt("h", "host", "host to connect to", "HOST"); opts.reqopt("p", "port", "port to connect to", "PORT"); opts.optopt("m", "message", "message to send in the body (default: empty message)", "MESSAGE"); opts.optopt("x", "message", "maximum response length allowed, inbytes (default: 10 MB)", "MAX-LENGTH"); let options = opts.parse(args.tail()).unwrap_or_else( |fail| print_usage(&fail.to_string(), &opts) ); let attributes = parse_attributes(&options.opt_strs("a")).unwrap_or_else( |error| print_usage(&error.to_string(), &opts) ); let number_str = options.opt_str("n").unwrap(); // mandatory at getopts level let number = number_str.parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let concurrency = options.opt_str("c").unwrap_or("1".to_string()).parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let timeout_sec = options.opt_str("t").unwrap_or("60".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let connect_timeout_ms = options.opt_str("T").unwrap_or("5000".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let host = options.opt_str("h").unwrap(); // mandatory at getopts level let port_str = options.opt_str("p").unwrap(); // mandatory at getopts level let port = port_str.parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let message = options.opt_str("m").unwrap_or("".to_string()); let max_length = options.opt_str("x").unwrap_or((10 * 1024 * 1024).to_string()).parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); MonchOptions { host: host, port: port, attributes: attributes, message: message, timeout: Duration::seconds(timeout_sec), connect_timeout: Duration::milliseconds(connect_timeout_ms), number: number, concurrency: concurrency, max_length: max_length, } } fn exit(exit_code: i32) ->! { extern crate libc; unsafe { libc::exit(exit_code); } } fn print_usage(error: &str, opts: &Options) ->! { println!("{}", error); print!("{}", opts.usage(&format!("Usage {} [options]", PROGRAM_NAME))); exit(2); } fn main() { env_logger::init().unwrap(); let opt = get_options(); let res = main_impl(&opt); match res { Ok(()) => (), Err(err) => { println!("{}", err); exit(1); } } }
send_heartbeat
identifier_name
monch.rs
#![feature(old_io)] #![feature(std_misc)] #![feature(collections)] #![feature(test)] #![feature(io)] #![feature(libc)] // logging needs this #![feature(rustc_private)] #[macro_use] extern crate log; extern crate env_logger; extern crate getopts; extern crate time; extern crate test; use std::old_io::TcpStream; use std::old_io::BufferedStream; use std::old_io::BufferedReader; use std::old_io::BufferedWriter; use std::old_io::Writer; use std::old_io::Reader; use std::old_io::IoResult; use std::str::from_utf8; use std::time::duration::Duration; use getopts::Options; mod semaphore; use semaphore::Semaphore; use std::sync::Arc; use std::thread; use std::error::Error; use std::sync::Mutex; use std::collections::HashMap; use test::stats::Stats; use time::precise_time_ns; use std::error::FromError; use std::old_io::IoError; use std::io; use std::io::Write; const MESSAGE_TYPE_HELLO: i8 = 0; const MESSAGE_TYPE_HEARTBEAT: i8 = 1; const MESSAGE_TYPE_REQUEST: i8 = 2; const MESSAGE_TYPE_RESPONSE: i8 = 3; const MESSAGE_TYPE_BYE: i8 = 6; static PROGRAM_NAME: &'static str = "monch"; static KEY_VERSION: &'static str = "version"; static KEY_CLIENT_NAME: &'static str = "client-name"; static KEY_MAX_LENGTH: &'static str = "max-length"; static PROTOCOL_VERSION: i8 = 1; static HEARTBEAT_INTERVAL_SEC: i64 = 5; static REQUEST_TIMEOUT_SEC: i64 = 5; static BUFFER_SIZE_KB: usize = 256; fn send_attributes(sock: &mut Writer, attributes: &Vec<(String, String)>) -> IoResult<()> { try!(sock.write_u8(attributes.len() as u8)); for &(ref name, ref value) in attributes { try!(sock.write_u8(name.len() as u8)); try!(sock.write_str(name)); try!(sock.write_be_u16(value.len() as u16)); try!(sock.write_str(&value)); } Ok(()) } fn calc_attribute_length(attributes: &Vec<(String, String)>) -> i32 { let mut length: i32 = 1; for &(ref name, ref value) in attributes { length += 1; length += name.len() as i32; length += 2; length += value.len() as i32; } length } fn recv_attributes(sock: &mut Reader) -> IoResult<(Vec<(String, String)>, i32)> { let attr_qtty = try!(sock.read_byte()); let mut bytes_len = 1i32; // length byte let mut res: Vec<(String, String)> = Vec::with_capacity(attr_qtty as usize); for _ in 0.. attr_qtty { bytes_len += 3; // 1 (name size) + 2 (value size) let len_name = try!(sock.read_byte()); let name_bytes = try!(sock.read_exact(len_name as usize)); bytes_len += len_name as i32; let name = String::from_utf8(name_bytes).ok().unwrap(); // do better let len_value = try!(sock.read_be_u16()); let value_bytes = try!(sock.read_exact(len_value as usize)); bytes_len += len_value as i32; let value = String::from_utf8(value_bytes).ok().unwrap(); // do better res.push((name, value)); } Ok((res, bytes_len)) } fn send_client_hello(sock: &mut Writer, max_length: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HELLO)); let attributes = vec![ (KEY_VERSION.to_string(), PROTOCOL_VERSION.to_string()), (KEY_CLIENT_NAME.to_string(), PROGRAM_NAME.to_string()), (KEY_MAX_LENGTH.to_string(), max_length.to_string()) ]; let message_length = calc_attribute_length(&attributes); try!(sock.write_be_i32(message_length as i32)); try!(send_attributes(sock, &attributes)); try!(sock.flush()); Ok(()) } fn recv_server_hello(sock: &mut Reader) -> Result<Frame, MyError> { let (attributes, attr_len) = try!(recv_attributes(sock)); let res = HelloData { attributes: attributes, attr_len: attr_len }; Ok(Frame::Hello(res)) } fn send_request(sock: &mut Writer, request: &StaticRequestData, request_id: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_REQUEST)); let fixed_part = 12; // 4 + 4 + 4 let length = fixed_part + request.attr_len + request.msg.len() as i32; try!(sock.write_be_i32(length)); try!(sock.write_be_i32(request_id)); try!(sock.write_be_i32(0)); // flow id try!(sock.write_be_i32(request.timeout.num_milliseconds() as i32)); try!(send_attributes(sock, &request.attributes)); try!(sock.write_str(&request.msg)); try!(sock.flush()); Ok(()) } fn send_bye(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_BYE)); let length = 0; try!(sock.write_be_i32(length)); try!(sock.flush()); Ok(()) } fn send_heartbeat(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HEARTBEAT)); try!(sock.write_be_i32(0)); try!(sock.flush()); Ok(()) } #[derive(Debug)] enum MyError { Io(IoError), Other(String) } impl FromError<IoError> for MyError { fn from_error(err: IoError) -> MyError { MyError::Io(err) } } impl FromError<String> for MyError { fn from_error(err: String) -> MyError { MyError::Other(err) } } // only received message types needed #[derive(Debug)] enum Frame { HeartBeat, Hello(HelloData), Response(ResponseData) } #[derive(Debug)] struct HelloData { attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct StaticRequestData { msg: String, timeout: Duration, attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct ResponseData { reference: i32, attributes: Vec<(String, String)>, body: Vec<u8> } fn recv_frame(sock: &mut Reader) -> Result<Frame, MyError> { let message_type = try!(sock.read_byte()) as i8; let length = try!(sock.read_be_i32()); match message_type { MESSAGE_TYPE_HEARTBEAT => Ok(Frame::HeartBeat), MESSAGE_TYPE_RESPONSE => Ok(try!(recv_response(sock, length))), MESSAGE_TYPE_HELLO => Ok(try!(recv_server_hello(sock))), other => Err(MyError::Other(format!("Invalid message type, received: {}", other))), } } fn recv_response(sock: &mut Reader, length: i32) -> Result<Frame, MyError> { let reference = try!(sock.read_be_u32()); let (attr, attr_len) = try!(recv_attributes(sock)); let remaining_length = length - 4 - attr_len; let response = try!(sock.read_exact(remaining_length as usize)); let frame = ResponseData { reference: reference as i32, attributes: attr, body: response }; Ok(Frame::Response(frame)) } fn connect(host: &str, port: u16, timeout: Duration) -> IoResult<TcpStream> { //log("resolving %s..." % host) //let address = socket.gethostbyname(host) let sock = try!(TcpStream::connect_timeout((host, port), timeout)); Ok(sock) } fn parse_attributes(str: &Vec<String>) -> Result<Vec<(String, String)>, String> { let mut res: Vec<(String, String)> = vec![]; for attr_string in str { let parts = attr_string.split(":").collect::<Vec<&str>>(); if parts.len()!= 2 { return Err(format!("invalid attribute specification: {} -- must be of the form 'name: value'", attr_string)); } res.push((parts[0].to_string(), parts[1].to_string())); } Ok(res) } fn sender_thread( sock: &mut Writer, semaphore: Arc<Semaphore>, start_time: u64, timeout_total: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, max_length: u32, finished: Arc<Semaphore>, request: StaticRequestData) -> IoResult<()> { try!(send_client_hello(sock, max_length as i32)); let timeout = Duration::seconds(HEARTBEAT_INTERVAL_SEC); let mut i = 0; while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout_total { let success = semaphore.acquire_timeout(timeout); if success { { let mut st = sent_times.lock().unwrap(); st.insert(i as i32, precise_time_ns()); } try!(send_request(sock, &request, i as i32)); i += 1; } else { try!(send_heartbeat(sock)); } } // The receiver will signal the finalization let mut fin = false; while!fin { let success = finished.acquire_timeout(timeout); if success { fin = true; } else { try!(send_heartbeat(sock)); } } Ok(()) } struct ReceiverResult { first_response: Option<Vec<u8>>, response_times: HashMap<u32, f32>, ok_count: u32, same_size_count: u32, } fn receiver_thread( sock: &mut Reader, semaphore: Arc<Semaphore>, start_time: u64, timeout: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, finished: Arc<Semaphore>) -> Result<ReceiverResult, MyError> { let frame = try!(recv_frame(sock)); let server_attributes = match frame { Frame::Hello(hello) => hello.attributes, other => return Err(MyError::Other(format!("Invalid message type. Expecting hello, received: {:?}", other))), }; println!("Received server hello message: {:?}", server_attributes); let mut response_times = HashMap::<u32, f32>::with_capacity(send_count as usize); let mut first_response: Option<Vec<u8>> = None; let mut first_size: Option<i32> = None; let mut first = true; let mut i = 0; let mut ok_count = 0u32; let mut same_size_count = 1u32; // first response has always the same size as itself while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout { let frame = try!(recv_frame(sock)); match frame { Frame::HeartBeat => {}, // pass Frame::Response(ResponseData { reference, attributes, body }) => { let reception_time = precise_time_ns(); // as soon as possible semaphore.release(); let sent_time = { let mut st = sent_times.lock().unwrap(); st.remove(&reference).unwrap() }; let delay = ((reception_time - sent_time) / 1000) as u32; response_times.insert(i, delay as f32); for &(ref name, ref value) in attributes.iter() { if *name == "status" { if *value == "ok" { ok_count += 1; } break; } } if first
else { if body.len() as i32 == first_size.unwrap() { same_size_count += 1; } } if i % 1000 == 0 { print!("\rCompleted {} requests.", i); io::stdout().flush(); } i += 1; first = false; }, other => return Err(MyError::Other(format!("Invalid message type. Expecting heart-beat or response, received: {:?}", other))), } } finished.release(); println!("\rCompleted all {} requests.", send_count); let res = ReceiverResult { first_response: first_response, response_times: response_times, ok_count: ok_count, same_size_count: same_size_count, }; Ok(res) } fn main_impl(options: &MonchOptions) -> IoResult<()> { println!("This is Mot Benchmark (monch)."); println!(""); println!("Benchmarking {}:{}...", &options.host, options.port); let start = precise_time_ns(); print!("Establishing TCP connection..."); io::stdout().flush(); let mut sock = try!(connect(&options.host, options.port, options.connect_timeout)); sock.set_timeout(Some(10000)); println!("done"); let connection_time = (precise_time_ns() - start) / 1000; let mut bye_writer_sock = BufferedStream::new(sock.clone()); let mut reader_sock = BufferedReader::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let mut writer_sock = BufferedWriter::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let semaphore = Arc::new(Semaphore::new(options.concurrency as isize)); let finished = Arc::new(Semaphore::new(0)); let mut times = Vec::<u32>::new(); let sent_times = Arc::new(Mutex::new(HashMap::<i32, u64>::new())); times.resize(options.concurrency as usize, 0); let (finished_snd, finished_rcv) = (finished.clone(), finished.clone()); let (semaphore_snd, semaphore_rcv) = (semaphore.clone(), semaphore.clone()); let (sent_times_snd, sent_times_rcv) = (sent_times.clone(), sent_times.clone()); let sender = thread::scoped(move || { let attr_len = calc_attribute_length(&options.attributes); let request = StaticRequestData { msg: options.message.clone(), timeout: Duration::seconds(REQUEST_TIMEOUT_SEC), attributes: options.attributes.clone(), attr_len: attr_len, }; sender_thread( &mut writer_sock, semaphore_snd, start, options.timeout, sent_times_snd, options.number, options.max_length, finished_snd, request).unwrap(); }); let receiver = thread::scoped(move || { receiver_thread( &mut reader_sock, semaphore_rcv, start, options.timeout, sent_times_rcv, options.number, finished_rcv).unwrap() }); sender.join(); let result = receiver.join(); try!(send_bye(&mut bye_writer_sock)); let total_time = (precise_time_ns() - start) / (1000 * 1000); let received_count = result.response_times.len(); let times: Vec<f32> = result.response_times.values().map(|x| *x).collect(); let response_size = result.first_response.map(|r| r.len() as i32); println!(""); println!("Total time taken for tests: {:>7} ms", total_time); println!("Connection time: {:>7} µs", connection_time); println!("Response size: {:>7} bytes", response_size.unwrap_or(-1)); println!("Received responses: {:>7} requests", received_count); println!("Time outs: {:>7} requests", options.number - received_count as u32); println!("OK responses: {:>7} requests", result.ok_count); println!("Same size responses: {:>7} requests", result.same_size_count); println!(""); println!("Percentage of the requests served within a certain time (µs):"); println!(" {:>8.0} (shortest request)", times.min()); for p in vec![50.0, 80.0, 95.0, 99.0, 99.9] { println!(" {:>5.1}% {:>8.0}", p, times.percentile(p)); } println!(" {:>5.1}% {:>8.0} (longest request)", 100.0, times.max()); Ok(()) } struct MonchOptions { host: String, port: u16, attributes: Vec<(String, String)>, message: String, timeout: Duration, connect_timeout: Duration, number: u32, concurrency: u16, max_length: u32, } fn get_options() -> MonchOptions { let args: Vec<String> = std::env::args().collect(); let mut opts = Options::new(); opts.optmulti("a", "attributes", "set a request attribute ('name: value')", "ATTRIBUTE"); opts.reqopt("n", "number", "determine how many request to send", "QUANTITY"); opts.optopt("c", "concurrency", "determine how many request to send at the same time (default 1)", "QUANTITY"); opts.optopt("t", "timeout", "hoy much time to wait for the completion of the test, in seconds (default: 60)", "TIMEOUT"); opts.optopt("T", "connect-timeout", "hoy much time to wait for the establishment of the TCP connection, in milliseconds (default: 5000)", "TIMEOUT"); opts.reqopt("h", "host", "host to connect to", "HOST"); opts.reqopt("p", "port", "port to connect to", "PORT"); opts.optopt("m", "message", "message to send in the body (default: empty message)", "MESSAGE"); opts.optopt("x", "message", "maximum response length allowed, inbytes (default: 10 MB)", "MAX-LENGTH"); let options = opts.parse(args.tail()).unwrap_or_else( |fail| print_usage(&fail.to_string(), &opts) ); let attributes = parse_attributes(&options.opt_strs("a")).unwrap_or_else( |error| print_usage(&error.to_string(), &opts) ); let number_str = options.opt_str("n").unwrap(); // mandatory at getopts level let number = number_str.parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let concurrency = options.opt_str("c").unwrap_or("1".to_string()).parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let timeout_sec = options.opt_str("t").unwrap_or("60".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let connect_timeout_ms = options.opt_str("T").unwrap_or("5000".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let host = options.opt_str("h").unwrap(); // mandatory at getopts level let port_str = options.opt_str("p").unwrap(); // mandatory at getopts level let port = port_str.parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let message = options.opt_str("m").unwrap_or("".to_string()); let max_length = options.opt_str("x").unwrap_or((10 * 1024 * 1024).to_string()).parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); MonchOptions { host: host, port: port, attributes: attributes, message: message, timeout: Duration::seconds(timeout_sec), connect_timeout: Duration::milliseconds(connect_timeout_ms), number: number, concurrency: concurrency, max_length: max_length, } } fn exit(exit_code: i32) ->! { extern crate libc; unsafe { libc::exit(exit_code); } } fn print_usage(error: &str, opts: &Options) ->! { println!("{}", error); print!("{}", opts.usage(&format!("Usage {} [options]", PROGRAM_NAME))); exit(2); } fn main() { env_logger::init().unwrap(); let opt = get_options(); let res = main_impl(&opt); match res { Ok(()) => (), Err(err) => { println!("{}", err); exit(1); } } }
{ println!("First response attributes {:?}", attributes); first_response = Some(body.clone()); first_size = Some(body.len() as i32) }
conditional_block
monch.rs
#![feature(old_io)] #![feature(std_misc)] #![feature(collections)] #![feature(test)] #![feature(io)] #![feature(libc)] // logging needs this #![feature(rustc_private)] #[macro_use] extern crate log; extern crate env_logger; extern crate getopts; extern crate time; extern crate test; use std::old_io::TcpStream; use std::old_io::BufferedStream; use std::old_io::BufferedReader; use std::old_io::BufferedWriter; use std::old_io::Writer; use std::old_io::Reader; use std::old_io::IoResult; use std::str::from_utf8; use std::time::duration::Duration; use getopts::Options; mod semaphore; use semaphore::Semaphore; use std::sync::Arc; use std::thread; use std::error::Error; use std::sync::Mutex; use std::collections::HashMap; use test::stats::Stats; use time::precise_time_ns; use std::error::FromError; use std::old_io::IoError; use std::io; use std::io::Write; const MESSAGE_TYPE_HELLO: i8 = 0; const MESSAGE_TYPE_HEARTBEAT: i8 = 1; const MESSAGE_TYPE_REQUEST: i8 = 2; const MESSAGE_TYPE_RESPONSE: i8 = 3; const MESSAGE_TYPE_BYE: i8 = 6; static PROGRAM_NAME: &'static str = "monch"; static KEY_VERSION: &'static str = "version"; static KEY_CLIENT_NAME: &'static str = "client-name"; static KEY_MAX_LENGTH: &'static str = "max-length"; static PROTOCOL_VERSION: i8 = 1; static HEARTBEAT_INTERVAL_SEC: i64 = 5; static REQUEST_TIMEOUT_SEC: i64 = 5; static BUFFER_SIZE_KB: usize = 256; fn send_attributes(sock: &mut Writer, attributes: &Vec<(String, String)>) -> IoResult<()> { try!(sock.write_u8(attributes.len() as u8)); for &(ref name, ref value) in attributes { try!(sock.write_u8(name.len() as u8)); try!(sock.write_str(name)); try!(sock.write_be_u16(value.len() as u16)); try!(sock.write_str(&value)); } Ok(()) } fn calc_attribute_length(attributes: &Vec<(String, String)>) -> i32 { let mut length: i32 = 1; for &(ref name, ref value) in attributes { length += 1; length += name.len() as i32; length += 2; length += value.len() as i32; } length } fn recv_attributes(sock: &mut Reader) -> IoResult<(Vec<(String, String)>, i32)> { let attr_qtty = try!(sock.read_byte()); let mut bytes_len = 1i32; // length byte let mut res: Vec<(String, String)> = Vec::with_capacity(attr_qtty as usize); for _ in 0.. attr_qtty { bytes_len += 3; // 1 (name size) + 2 (value size) let len_name = try!(sock.read_byte()); let name_bytes = try!(sock.read_exact(len_name as usize)); bytes_len += len_name as i32; let name = String::from_utf8(name_bytes).ok().unwrap(); // do better let len_value = try!(sock.read_be_u16()); let value_bytes = try!(sock.read_exact(len_value as usize)); bytes_len += len_value as i32; let value = String::from_utf8(value_bytes).ok().unwrap(); // do better res.push((name, value)); } Ok((res, bytes_len)) } fn send_client_hello(sock: &mut Writer, max_length: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HELLO)); let attributes = vec![ (KEY_VERSION.to_string(), PROTOCOL_VERSION.to_string()), (KEY_CLIENT_NAME.to_string(), PROGRAM_NAME.to_string()), (KEY_MAX_LENGTH.to_string(), max_length.to_string()) ]; let message_length = calc_attribute_length(&attributes); try!(sock.write_be_i32(message_length as i32)); try!(send_attributes(sock, &attributes)); try!(sock.flush()); Ok(()) } fn recv_server_hello(sock: &mut Reader) -> Result<Frame, MyError> { let (attributes, attr_len) = try!(recv_attributes(sock)); let res = HelloData { attributes: attributes, attr_len: attr_len }; Ok(Frame::Hello(res)) } fn send_request(sock: &mut Writer, request: &StaticRequestData, request_id: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_REQUEST)); let fixed_part = 12; // 4 + 4 + 4 let length = fixed_part + request.attr_len + request.msg.len() as i32; try!(sock.write_be_i32(length)); try!(sock.write_be_i32(request_id)); try!(sock.write_be_i32(0)); // flow id try!(sock.write_be_i32(request.timeout.num_milliseconds() as i32)); try!(send_attributes(sock, &request.attributes)); try!(sock.write_str(&request.msg)); try!(sock.flush()); Ok(()) } fn send_bye(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_BYE)); let length = 0; try!(sock.write_be_i32(length)); try!(sock.flush()); Ok(()) } fn send_heartbeat(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HEARTBEAT)); try!(sock.write_be_i32(0)); try!(sock.flush()); Ok(()) } #[derive(Debug)] enum MyError { Io(IoError), Other(String) } impl FromError<IoError> for MyError { fn from_error(err: IoError) -> MyError { MyError::Io(err) } } impl FromError<String> for MyError { fn from_error(err: String) -> MyError { MyError::Other(err) } } // only received message types needed #[derive(Debug)] enum Frame { HeartBeat, Hello(HelloData), Response(ResponseData) } #[derive(Debug)] struct HelloData { attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct StaticRequestData { msg: String, timeout: Duration, attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct ResponseData { reference: i32, attributes: Vec<(String, String)>, body: Vec<u8> } fn recv_frame(sock: &mut Reader) -> Result<Frame, MyError> { let message_type = try!(sock.read_byte()) as i8; let length = try!(sock.read_be_i32()); match message_type { MESSAGE_TYPE_HEARTBEAT => Ok(Frame::HeartBeat), MESSAGE_TYPE_RESPONSE => Ok(try!(recv_response(sock, length))), MESSAGE_TYPE_HELLO => Ok(try!(recv_server_hello(sock))), other => Err(MyError::Other(format!("Invalid message type, received: {}", other))), } } fn recv_response(sock: &mut Reader, length: i32) -> Result<Frame, MyError>
fn connect(host: &str, port: u16, timeout: Duration) -> IoResult<TcpStream> { //log("resolving %s..." % host) //let address = socket.gethostbyname(host) let sock = try!(TcpStream::connect_timeout((host, port), timeout)); Ok(sock) } fn parse_attributes(str: &Vec<String>) -> Result<Vec<(String, String)>, String> { let mut res: Vec<(String, String)> = vec![]; for attr_string in str { let parts = attr_string.split(":").collect::<Vec<&str>>(); if parts.len()!= 2 { return Err(format!("invalid attribute specification: {} -- must be of the form 'name: value'", attr_string)); } res.push((parts[0].to_string(), parts[1].to_string())); } Ok(res) } fn sender_thread( sock: &mut Writer, semaphore: Arc<Semaphore>, start_time: u64, timeout_total: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, max_length: u32, finished: Arc<Semaphore>, request: StaticRequestData) -> IoResult<()> { try!(send_client_hello(sock, max_length as i32)); let timeout = Duration::seconds(HEARTBEAT_INTERVAL_SEC); let mut i = 0; while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout_total { let success = semaphore.acquire_timeout(timeout); if success { { let mut st = sent_times.lock().unwrap(); st.insert(i as i32, precise_time_ns()); } try!(send_request(sock, &request, i as i32)); i += 1; } else { try!(send_heartbeat(sock)); } } // The receiver will signal the finalization let mut fin = false; while!fin { let success = finished.acquire_timeout(timeout); if success { fin = true; } else { try!(send_heartbeat(sock)); } } Ok(()) } struct ReceiverResult { first_response: Option<Vec<u8>>, response_times: HashMap<u32, f32>, ok_count: u32, same_size_count: u32, } fn receiver_thread( sock: &mut Reader, semaphore: Arc<Semaphore>, start_time: u64, timeout: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, finished: Arc<Semaphore>) -> Result<ReceiverResult, MyError> { let frame = try!(recv_frame(sock)); let server_attributes = match frame { Frame::Hello(hello) => hello.attributes, other => return Err(MyError::Other(format!("Invalid message type. Expecting hello, received: {:?}", other))), }; println!("Received server hello message: {:?}", server_attributes); let mut response_times = HashMap::<u32, f32>::with_capacity(send_count as usize); let mut first_response: Option<Vec<u8>> = None; let mut first_size: Option<i32> = None; let mut first = true; let mut i = 0; let mut ok_count = 0u32; let mut same_size_count = 1u32; // first response has always the same size as itself while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout { let frame = try!(recv_frame(sock)); match frame { Frame::HeartBeat => {}, // pass Frame::Response(ResponseData { reference, attributes, body }) => { let reception_time = precise_time_ns(); // as soon as possible semaphore.release(); let sent_time = { let mut st = sent_times.lock().unwrap(); st.remove(&reference).unwrap() }; let delay = ((reception_time - sent_time) / 1000) as u32; response_times.insert(i, delay as f32); for &(ref name, ref value) in attributes.iter() { if *name == "status" { if *value == "ok" { ok_count += 1; } break; } } if first { println!("First response attributes {:?}", attributes); first_response = Some(body.clone()); first_size = Some(body.len() as i32) } else { if body.len() as i32 == first_size.unwrap() { same_size_count += 1; } } if i % 1000 == 0 { print!("\rCompleted {} requests.", i); io::stdout().flush(); } i += 1; first = false; }, other => return Err(MyError::Other(format!("Invalid message type. Expecting heart-beat or response, received: {:?}", other))), } } finished.release(); println!("\rCompleted all {} requests.", send_count); let res = ReceiverResult { first_response: first_response, response_times: response_times, ok_count: ok_count, same_size_count: same_size_count, }; Ok(res) } fn main_impl(options: &MonchOptions) -> IoResult<()> { println!("This is Mot Benchmark (monch)."); println!(""); println!("Benchmarking {}:{}...", &options.host, options.port); let start = precise_time_ns(); print!("Establishing TCP connection..."); io::stdout().flush(); let mut sock = try!(connect(&options.host, options.port, options.connect_timeout)); sock.set_timeout(Some(10000)); println!("done"); let connection_time = (precise_time_ns() - start) / 1000; let mut bye_writer_sock = BufferedStream::new(sock.clone()); let mut reader_sock = BufferedReader::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let mut writer_sock = BufferedWriter::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let semaphore = Arc::new(Semaphore::new(options.concurrency as isize)); let finished = Arc::new(Semaphore::new(0)); let mut times = Vec::<u32>::new(); let sent_times = Arc::new(Mutex::new(HashMap::<i32, u64>::new())); times.resize(options.concurrency as usize, 0); let (finished_snd, finished_rcv) = (finished.clone(), finished.clone()); let (semaphore_snd, semaphore_rcv) = (semaphore.clone(), semaphore.clone()); let (sent_times_snd, sent_times_rcv) = (sent_times.clone(), sent_times.clone()); let sender = thread::scoped(move || { let attr_len = calc_attribute_length(&options.attributes); let request = StaticRequestData { msg: options.message.clone(), timeout: Duration::seconds(REQUEST_TIMEOUT_SEC), attributes: options.attributes.clone(), attr_len: attr_len, }; sender_thread( &mut writer_sock, semaphore_snd, start, options.timeout, sent_times_snd, options.number, options.max_length, finished_snd, request).unwrap(); }); let receiver = thread::scoped(move || { receiver_thread( &mut reader_sock, semaphore_rcv, start, options.timeout, sent_times_rcv, options.number, finished_rcv).unwrap() }); sender.join(); let result = receiver.join(); try!(send_bye(&mut bye_writer_sock)); let total_time = (precise_time_ns() - start) / (1000 * 1000); let received_count = result.response_times.len(); let times: Vec<f32> = result.response_times.values().map(|x| *x).collect(); let response_size = result.first_response.map(|r| r.len() as i32); println!(""); println!("Total time taken for tests: {:>7} ms", total_time); println!("Connection time: {:>7} µs", connection_time); println!("Response size: {:>7} bytes", response_size.unwrap_or(-1)); println!("Received responses: {:>7} requests", received_count); println!("Time outs: {:>7} requests", options.number - received_count as u32); println!("OK responses: {:>7} requests", result.ok_count); println!("Same size responses: {:>7} requests", result.same_size_count); println!(""); println!("Percentage of the requests served within a certain time (µs):"); println!(" {:>8.0} (shortest request)", times.min()); for p in vec![50.0, 80.0, 95.0, 99.0, 99.9] { println!(" {:>5.1}% {:>8.0}", p, times.percentile(p)); } println!(" {:>5.1}% {:>8.0} (longest request)", 100.0, times.max()); Ok(()) } struct MonchOptions { host: String, port: u16, attributes: Vec<(String, String)>, message: String, timeout: Duration, connect_timeout: Duration, number: u32, concurrency: u16, max_length: u32, } fn get_options() -> MonchOptions { let args: Vec<String> = std::env::args().collect(); let mut opts = Options::new(); opts.optmulti("a", "attributes", "set a request attribute ('name: value')", "ATTRIBUTE"); opts.reqopt("n", "number", "determine how many request to send", "QUANTITY"); opts.optopt("c", "concurrency", "determine how many request to send at the same time (default 1)", "QUANTITY"); opts.optopt("t", "timeout", "hoy much time to wait for the completion of the test, in seconds (default: 60)", "TIMEOUT"); opts.optopt("T", "connect-timeout", "hoy much time to wait for the establishment of the TCP connection, in milliseconds (default: 5000)", "TIMEOUT"); opts.reqopt("h", "host", "host to connect to", "HOST"); opts.reqopt("p", "port", "port to connect to", "PORT"); opts.optopt("m", "message", "message to send in the body (default: empty message)", "MESSAGE"); opts.optopt("x", "message", "maximum response length allowed, inbytes (default: 10 MB)", "MAX-LENGTH"); let options = opts.parse(args.tail()).unwrap_or_else( |fail| print_usage(&fail.to_string(), &opts) ); let attributes = parse_attributes(&options.opt_strs("a")).unwrap_or_else( |error| print_usage(&error.to_string(), &opts) ); let number_str = options.opt_str("n").unwrap(); // mandatory at getopts level let number = number_str.parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let concurrency = options.opt_str("c").unwrap_or("1".to_string()).parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let timeout_sec = options.opt_str("t").unwrap_or("60".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let connect_timeout_ms = options.opt_str("T").unwrap_or("5000".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let host = options.opt_str("h").unwrap(); // mandatory at getopts level let port_str = options.opt_str("p").unwrap(); // mandatory at getopts level let port = port_str.parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let message = options.opt_str("m").unwrap_or("".to_string()); let max_length = options.opt_str("x").unwrap_or((10 * 1024 * 1024).to_string()).parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); MonchOptions { host: host, port: port, attributes: attributes, message: message, timeout: Duration::seconds(timeout_sec), connect_timeout: Duration::milliseconds(connect_timeout_ms), number: number, concurrency: concurrency, max_length: max_length, } } fn exit(exit_code: i32) ->! { extern crate libc; unsafe { libc::exit(exit_code); } } fn print_usage(error: &str, opts: &Options) ->! { println!("{}", error); print!("{}", opts.usage(&format!("Usage {} [options]", PROGRAM_NAME))); exit(2); } fn main() { env_logger::init().unwrap(); let opt = get_options(); let res = main_impl(&opt); match res { Ok(()) => (), Err(err) => { println!("{}", err); exit(1); } } }
{ let reference = try!(sock.read_be_u32()); let (attr, attr_len) = try!(recv_attributes(sock)); let remaining_length = length - 4 - attr_len; let response = try!(sock.read_exact(remaining_length as usize)); let frame = ResponseData { reference: reference as i32, attributes: attr, body: response }; Ok(Frame::Response(frame)) }
identifier_body
monch.rs
#![feature(old_io)] #![feature(std_misc)] #![feature(collections)] #![feature(test)] #![feature(io)] #![feature(libc)] // logging needs this #![feature(rustc_private)] #[macro_use] extern crate log; extern crate env_logger; extern crate getopts; extern crate time; extern crate test; use std::old_io::TcpStream; use std::old_io::BufferedStream; use std::old_io::BufferedReader; use std::old_io::BufferedWriter; use std::old_io::Writer; use std::old_io::Reader; use std::old_io::IoResult; use std::str::from_utf8; use std::time::duration::Duration; use getopts::Options; mod semaphore; use semaphore::Semaphore; use std::sync::Arc; use std::thread; use std::error::Error; use std::sync::Mutex; use std::collections::HashMap; use test::stats::Stats; use time::precise_time_ns; use std::error::FromError; use std::old_io::IoError; use std::io; use std::io::Write; const MESSAGE_TYPE_HELLO: i8 = 0; const MESSAGE_TYPE_HEARTBEAT: i8 = 1; const MESSAGE_TYPE_REQUEST: i8 = 2; const MESSAGE_TYPE_RESPONSE: i8 = 3; const MESSAGE_TYPE_BYE: i8 = 6; static PROGRAM_NAME: &'static str = "monch"; static KEY_VERSION: &'static str = "version"; static KEY_CLIENT_NAME: &'static str = "client-name"; static KEY_MAX_LENGTH: &'static str = "max-length"; static PROTOCOL_VERSION: i8 = 1; static HEARTBEAT_INTERVAL_SEC: i64 = 5; static REQUEST_TIMEOUT_SEC: i64 = 5; static BUFFER_SIZE_KB: usize = 256; fn send_attributes(sock: &mut Writer, attributes: &Vec<(String, String)>) -> IoResult<()> { try!(sock.write_u8(attributes.len() as u8)); for &(ref name, ref value) in attributes { try!(sock.write_u8(name.len() as u8)); try!(sock.write_str(name)); try!(sock.write_be_u16(value.len() as u16)); try!(sock.write_str(&value)); } Ok(()) } fn calc_attribute_length(attributes: &Vec<(String, String)>) -> i32 { let mut length: i32 = 1; for &(ref name, ref value) in attributes { length += 1; length += name.len() as i32; length += 2; length += value.len() as i32; } length } fn recv_attributes(sock: &mut Reader) -> IoResult<(Vec<(String, String)>, i32)> { let attr_qtty = try!(sock.read_byte()); let mut bytes_len = 1i32; // length byte let mut res: Vec<(String, String)> = Vec::with_capacity(attr_qtty as usize); for _ in 0.. attr_qtty { bytes_len += 3; // 1 (name size) + 2 (value size) let len_name = try!(sock.read_byte()); let name_bytes = try!(sock.read_exact(len_name as usize)); bytes_len += len_name as i32; let name = String::from_utf8(name_bytes).ok().unwrap(); // do better let len_value = try!(sock.read_be_u16()); let value_bytes = try!(sock.read_exact(len_value as usize)); bytes_len += len_value as i32; let value = String::from_utf8(value_bytes).ok().unwrap(); // do better res.push((name, value)); } Ok((res, bytes_len)) } fn send_client_hello(sock: &mut Writer, max_length: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HELLO)); let attributes = vec![ (KEY_VERSION.to_string(), PROTOCOL_VERSION.to_string()), (KEY_CLIENT_NAME.to_string(), PROGRAM_NAME.to_string()), (KEY_MAX_LENGTH.to_string(), max_length.to_string()) ]; let message_length = calc_attribute_length(&attributes); try!(sock.write_be_i32(message_length as i32)); try!(send_attributes(sock, &attributes)); try!(sock.flush()); Ok(()) } fn recv_server_hello(sock: &mut Reader) -> Result<Frame, MyError> { let (attributes, attr_len) = try!(recv_attributes(sock)); let res = HelloData { attributes: attributes, attr_len: attr_len }; Ok(Frame::Hello(res)) } fn send_request(sock: &mut Writer, request: &StaticRequestData, request_id: i32) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_REQUEST)); let fixed_part = 12; // 4 + 4 + 4 let length = fixed_part + request.attr_len + request.msg.len() as i32; try!(sock.write_be_i32(length)); try!(sock.write_be_i32(request_id)); try!(sock.write_be_i32(0)); // flow id try!(sock.write_be_i32(request.timeout.num_milliseconds() as i32)); try!(send_attributes(sock, &request.attributes)); try!(sock.write_str(&request.msg)); try!(sock.flush()); Ok(()) } fn send_bye(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_BYE)); let length = 0; try!(sock.write_be_i32(length)); try!(sock.flush()); Ok(()) } fn send_heartbeat(sock: &mut Writer) -> IoResult<()> { try!(sock.write_i8(MESSAGE_TYPE_HEARTBEAT)); try!(sock.write_be_i32(0)); try!(sock.flush()); Ok(()) } #[derive(Debug)] enum MyError { Io(IoError), Other(String) } impl FromError<IoError> for MyError { fn from_error(err: IoError) -> MyError { MyError::Io(err) } } impl FromError<String> for MyError { fn from_error(err: String) -> MyError { MyError::Other(err) } } // only received message types needed #[derive(Debug)] enum Frame { HeartBeat, Hello(HelloData), Response(ResponseData) } #[derive(Debug)] struct HelloData { attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct StaticRequestData { msg: String, timeout: Duration, attributes: Vec<(String, String)>, attr_len: i32, } #[derive(Debug)] struct ResponseData { reference: i32, attributes: Vec<(String, String)>, body: Vec<u8> } fn recv_frame(sock: &mut Reader) -> Result<Frame, MyError> { let message_type = try!(sock.read_byte()) as i8; let length = try!(sock.read_be_i32()); match message_type { MESSAGE_TYPE_HEARTBEAT => Ok(Frame::HeartBeat), MESSAGE_TYPE_RESPONSE => Ok(try!(recv_response(sock, length))), MESSAGE_TYPE_HELLO => Ok(try!(recv_server_hello(sock))), other => Err(MyError::Other(format!("Invalid message type, received: {}", other))), } } fn recv_response(sock: &mut Reader, length: i32) -> Result<Frame, MyError> { let reference = try!(sock.read_be_u32()); let (attr, attr_len) = try!(recv_attributes(sock)); let remaining_length = length - 4 - attr_len; let response = try!(sock.read_exact(remaining_length as usize)); let frame = ResponseData { reference: reference as i32, attributes: attr, body: response }; Ok(Frame::Response(frame)) } fn connect(host: &str, port: u16, timeout: Duration) -> IoResult<TcpStream> { //log("resolving %s..." % host) //let address = socket.gethostbyname(host) let sock = try!(TcpStream::connect_timeout((host, port), timeout)); Ok(sock) } fn parse_attributes(str: &Vec<String>) -> Result<Vec<(String, String)>, String> { let mut res: Vec<(String, String)> = vec![]; for attr_string in str { let parts = attr_string.split(":").collect::<Vec<&str>>(); if parts.len()!= 2 { return Err(format!("invalid attribute specification: {} -- must be of the form 'name: value'", attr_string)); } res.push((parts[0].to_string(), parts[1].to_string())); } Ok(res) } fn sender_thread( sock: &mut Writer, semaphore: Arc<Semaphore>, start_time: u64, timeout_total: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, max_length: u32, finished: Arc<Semaphore>, request: StaticRequestData) -> IoResult<()> { try!(send_client_hello(sock, max_length as i32)); let timeout = Duration::seconds(HEARTBEAT_INTERVAL_SEC); let mut i = 0; while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout_total { let success = semaphore.acquire_timeout(timeout); if success { { let mut st = sent_times.lock().unwrap(); st.insert(i as i32, precise_time_ns()); } try!(send_request(sock, &request, i as i32)); i += 1; } else { try!(send_heartbeat(sock)); } } // The receiver will signal the finalization let mut fin = false; while!fin { let success = finished.acquire_timeout(timeout); if success { fin = true; } else { try!(send_heartbeat(sock)); } } Ok(()) } struct ReceiverResult { first_response: Option<Vec<u8>>, response_times: HashMap<u32, f32>, ok_count: u32, same_size_count: u32, } fn receiver_thread( sock: &mut Reader, semaphore: Arc<Semaphore>, start_time: u64, timeout: Duration, sent_times: Arc<Mutex<HashMap<i32, u64>>>, send_count: u32, finished: Arc<Semaphore>) -> Result<ReceiverResult, MyError> { let frame = try!(recv_frame(sock)); let server_attributes = match frame { Frame::Hello(hello) => hello.attributes, other => return Err(MyError::Other(format!("Invalid message type. Expecting hello, received: {:?}", other))), }; println!("Received server hello message: {:?}", server_attributes); let mut response_times = HashMap::<u32, f32>::with_capacity(send_count as usize); let mut first_response: Option<Vec<u8>> = None; let mut first_size: Option<i32> = None; let mut first = true; let mut i = 0; let mut ok_count = 0u32; let mut same_size_count = 1u32; // first response has always the same size as itself while i < send_count && Duration::nanoseconds((precise_time_ns() - start_time) as i64) < timeout { let frame = try!(recv_frame(sock)); match frame { Frame::HeartBeat => {}, // pass Frame::Response(ResponseData { reference, attributes, body }) => { let reception_time = precise_time_ns(); // as soon as possible semaphore.release(); let sent_time = { let mut st = sent_times.lock().unwrap(); st.remove(&reference).unwrap() }; let delay = ((reception_time - sent_time) / 1000) as u32; response_times.insert(i, delay as f32); for &(ref name, ref value) in attributes.iter() { if *name == "status" { if *value == "ok" { ok_count += 1; } break; } } if first { println!("First response attributes {:?}", attributes); first_response = Some(body.clone()); first_size = Some(body.len() as i32) } else { if body.len() as i32 == first_size.unwrap() { same_size_count += 1; } } if i % 1000 == 0 { print!("\rCompleted {} requests.", i); io::stdout().flush(); } i += 1; first = false; }, other => return Err(MyError::Other(format!("Invalid message type. Expecting heart-beat or response, received: {:?}", other))), } } finished.release(); println!("\rCompleted all {} requests.", send_count); let res = ReceiverResult { first_response: first_response, response_times: response_times, ok_count: ok_count, same_size_count: same_size_count, }; Ok(res) } fn main_impl(options: &MonchOptions) -> IoResult<()> { println!("This is Mot Benchmark (monch)."); println!(""); println!("Benchmarking {}:{}...", &options.host, options.port); let start = precise_time_ns(); print!("Establishing TCP connection..."); io::stdout().flush(); let mut sock = try!(connect(&options.host, options.port, options.connect_timeout)); sock.set_timeout(Some(10000)); println!("done"); let connection_time = (precise_time_ns() - start) / 1000; let mut bye_writer_sock = BufferedStream::new(sock.clone()); let mut reader_sock = BufferedReader::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let mut writer_sock = BufferedWriter::with_capacity(BUFFER_SIZE_KB * 1024, sock.clone()); let semaphore = Arc::new(Semaphore::new(options.concurrency as isize)); let finished = Arc::new(Semaphore::new(0)); let mut times = Vec::<u32>::new(); let sent_times = Arc::new(Mutex::new(HashMap::<i32, u64>::new())); times.resize(options.concurrency as usize, 0); let (finished_snd, finished_rcv) = (finished.clone(), finished.clone()); let (semaphore_snd, semaphore_rcv) = (semaphore.clone(), semaphore.clone()); let (sent_times_snd, sent_times_rcv) = (sent_times.clone(), sent_times.clone()); let sender = thread::scoped(move || { let attr_len = calc_attribute_length(&options.attributes); let request = StaticRequestData { msg: options.message.clone(), timeout: Duration::seconds(REQUEST_TIMEOUT_SEC), attributes: options.attributes.clone(), attr_len: attr_len, }; sender_thread( &mut writer_sock, semaphore_snd, start, options.timeout, sent_times_snd, options.number, options.max_length, finished_snd, request).unwrap(); }); let receiver = thread::scoped(move || { receiver_thread( &mut reader_sock, semaphore_rcv, start, options.timeout, sent_times_rcv, options.number, finished_rcv).unwrap() }); sender.join(); let result = receiver.join(); try!(send_bye(&mut bye_writer_sock)); let total_time = (precise_time_ns() - start) / (1000 * 1000); let received_count = result.response_times.len(); let times: Vec<f32> = result.response_times.values().map(|x| *x).collect(); let response_size = result.first_response.map(|r| r.len() as i32);
println!("Response size: {:>7} bytes", response_size.unwrap_or(-1)); println!("Received responses: {:>7} requests", received_count); println!("Time outs: {:>7} requests", options.number - received_count as u32); println!("OK responses: {:>7} requests", result.ok_count); println!("Same size responses: {:>7} requests", result.same_size_count); println!(""); println!("Percentage of the requests served within a certain time (µs):"); println!(" {:>8.0} (shortest request)", times.min()); for p in vec![50.0, 80.0, 95.0, 99.0, 99.9] { println!(" {:>5.1}% {:>8.0}", p, times.percentile(p)); } println!(" {:>5.1}% {:>8.0} (longest request)", 100.0, times.max()); Ok(()) } struct MonchOptions { host: String, port: u16, attributes: Vec<(String, String)>, message: String, timeout: Duration, connect_timeout: Duration, number: u32, concurrency: u16, max_length: u32, } fn get_options() -> MonchOptions { let args: Vec<String> = std::env::args().collect(); let mut opts = Options::new(); opts.optmulti("a", "attributes", "set a request attribute ('name: value')", "ATTRIBUTE"); opts.reqopt("n", "number", "determine how many request to send", "QUANTITY"); opts.optopt("c", "concurrency", "determine how many request to send at the same time (default 1)", "QUANTITY"); opts.optopt("t", "timeout", "hoy much time to wait for the completion of the test, in seconds (default: 60)", "TIMEOUT"); opts.optopt("T", "connect-timeout", "hoy much time to wait for the establishment of the TCP connection, in milliseconds (default: 5000)", "TIMEOUT"); opts.reqopt("h", "host", "host to connect to", "HOST"); opts.reqopt("p", "port", "port to connect to", "PORT"); opts.optopt("m", "message", "message to send in the body (default: empty message)", "MESSAGE"); opts.optopt("x", "message", "maximum response length allowed, inbytes (default: 10 MB)", "MAX-LENGTH"); let options = opts.parse(args.tail()).unwrap_or_else( |fail| print_usage(&fail.to_string(), &opts) ); let attributes = parse_attributes(&options.opt_strs("a")).unwrap_or_else( |error| print_usage(&error.to_string(), &opts) ); let number_str = options.opt_str("n").unwrap(); // mandatory at getopts level let number = number_str.parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let concurrency = options.opt_str("c").unwrap_or("1".to_string()).parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let timeout_sec = options.opt_str("t").unwrap_or("60".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let connect_timeout_ms = options.opt_str("T").unwrap_or("5000".to_string()).parse::<i64>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let host = options.opt_str("h").unwrap(); // mandatory at getopts level let port_str = options.opt_str("p").unwrap(); // mandatory at getopts level let port = port_str.parse::<u16>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); let message = options.opt_str("m").unwrap_or("".to_string()); let max_length = options.opt_str("x").unwrap_or((10 * 1024 * 1024).to_string()).parse::<u32>().unwrap_or_else( |error| print_usage(&error.description().to_string(), &opts) ); MonchOptions { host: host, port: port, attributes: attributes, message: message, timeout: Duration::seconds(timeout_sec), connect_timeout: Duration::milliseconds(connect_timeout_ms), number: number, concurrency: concurrency, max_length: max_length, } } fn exit(exit_code: i32) ->! { extern crate libc; unsafe { libc::exit(exit_code); } } fn print_usage(error: &str, opts: &Options) ->! { println!("{}", error); print!("{}", opts.usage(&format!("Usage {} [options]", PROGRAM_NAME))); exit(2); } fn main() { env_logger::init().unwrap(); let opt = get_options(); let res = main_impl(&opt); match res { Ok(()) => (), Err(err) => { println!("{}", err); exit(1); } } }
println!(""); println!("Total time taken for tests: {:>7} ms", total_time); println!("Connection time: {:>7} µs", connection_time);
random_line_split
build.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. #[cfg(not(feature = "serde_macros"))] mod inner { extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/lib.rs.in"); let dst = Path::new(&out_dir).join("lib.rs"); serde_codegen::expand(&src, &dst).unwrap(); } } #[cfg(feature = "serde_macros")] mod inner { pub fn main() {} } fn
() { inner::main(); }
main
identifier_name
build.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. #[cfg(not(feature = "serde_macros"))] mod inner { extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/lib.rs.in"); let dst = Path::new(&out_dir).join("lib.rs"); serde_codegen::expand(&src, &dst).unwrap(); } } #[cfg(feature = "serde_macros")] mod inner { pub fn main() {} } fn main()
{ inner::main(); }
identifier_body
build.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful,
// 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/>. #[cfg(not(feature = "serde_macros"))] mod inner { extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/lib.rs.in"); let dst = Path::new(&out_dir).join("lib.rs"); serde_codegen::expand(&src, &dst).unwrap(); } } #[cfg(feature = "serde_macros")] mod inner { pub fn main() {} } fn main() { inner::main(); }
// but WITHOUT ANY WARRANTY; without even the implied warranty of
random_line_split
kdtu.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use base::cell::StaticCell; use base::dtu::*; use base::errors::{Code, Error}; use base::goff; use base::kif::Perm; use base::util; use pes::{VPEId, VPEDesc}; pub struct State { cmd: [Reg; CMD_RCNT], eps: [Reg; EPS_RCNT * EP_COUNT], } impl State { pub fn new() -> State { State { cmd: [0; CMD_RCNT], eps: [0; EPS_RCNT * EP_COUNT], } } pub fn get_ep(&self, ep: EpId) -> &[Reg] { &self.eps[ep * EPS_RCNT..(ep + 1) * EPS_RCNT] } pub fn get_ep_mut(&mut self, ep: EpId) -> &mut [Reg] { &mut self.eps[ep * EPS_RCNT..(ep + 1) * EPS_RCNT] } pub fn config_send(&mut self, ep: EpId, lbl: Label, pe: PEId, _vpe: VPEId, dst_ep: EpId, msg_size: usize, credits: u64) { let regs: &mut [Reg] = self.get_ep_mut(ep); regs[EpReg::LABEL.val as usize] = lbl; regs[EpReg::PE_ID.val as usize] = pe as Reg; regs[EpReg::EP_ID.val as usize] = dst_ep as Reg; regs[EpReg::CREDITS.val as usize] = credits; regs[EpReg::MSGORDER.val as usize] = util::next_log2(msg_size) as Reg; } pub fn config_recv(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32, _header: usize) { let regs: &mut [Reg] = self.get_ep_mut(ep); regs[EpReg::BUF_ADDR.val as usize] = buf as Reg; regs[EpReg::BUF_ORDER.val as usize] = ord as Reg; regs[EpReg::BUF_MSGORDER.val as usize] = msg_ord as Reg; regs[EpReg::BUF_ROFF.val as usize] = 0; regs[EpReg::BUF_WOFF.val as usize] = 0; regs[EpReg::BUF_MSG_CNT.val as usize] = 0; regs[EpReg::BUF_UNREAD.val as usize] = 0; regs[EpReg::BUF_OCCUPIED.val as usize] = 0; } pub fn config_mem(&mut self, ep: EpId, pe: PEId, _vpe: VPEId, addr: goff, size: usize, perm: Perm) { let regs: &mut [Reg] = self.get_ep_mut(ep); assert!((addr & perm.bits() as goff) == 0); regs[EpReg::LABEL.val as usize] = (addr | perm.bits() as goff) as Reg; regs[EpReg::PE_ID.val as usize] = pe as Reg; regs[EpReg::EP_ID.val as usize] = 0; regs[EpReg::CREDITS.val as usize] = size as Reg; regs[EpReg::MSGORDER.val as usize] = 0; } pub fn invalidate(&mut self, ep: EpId, _check: bool) -> Result<(), Error> { let regs: &mut [Reg] = self.get_ep_mut(ep); for r in regs.iter_mut() { *r = 0; } Ok(()) } pub fn restore(&mut self, _vpe: &VPEDesc, _vpe_id: VPEId) { } pub fn reset(&mut self) { } } pub struct KDTU { state: State, } pub const KSYS_EP: EpId = 0; pub const KSRV_EP: EpId = 1; pub const KTMP_EP: EpId = 2; static INST: StaticCell<Option<KDTU>> = StaticCell::new(None); impl KDTU { pub fn init() { INST.set(Some(KDTU { state: State::new(), })); } pub fn get() -> &'static mut KDTU { INST.get_mut().as_mut().unwrap() } pub fn write_ep_local(&mut self, ep: EpId) { DTU::set_ep_regs(ep, self.state.get_ep(ep)); } pub fn invalidate_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId) -> Result<(), Error> { let regs = [0 as Reg; EPS_RCNT * EP_COUNT]; self.write_ep_remote(vpe, ep, &regs) } pub fn read_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *mut u8, size: usize) { assert!(vpe.vpe().is_none()); self.try_read_mem(vpe, addr, data, size).unwrap(); } pub fn try_read_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *mut u8, size: usize) -> Result<(), Error> { self.state.config_mem(KTMP_EP, vpe.pe_id(), vpe.vpe_id(), addr, size, Perm::R); self.write_ep_local(KTMP_EP); DTU::read(KTMP_EP, data, size, 0, CmdFlags::NOPF) } pub fn write_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *const u8, size: usize) { assert!(vpe.vpe().is_none()); self.try_write_mem(vpe, addr, data, size).unwrap(); } pub fn try_write_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *const u8, size: usize) -> Result<(), Error> { self.state.config_mem(KTMP_EP, vpe.pe_id(), vpe.vpe_id(), addr, size, Perm::W); self.write_ep_local(KTMP_EP); DTU::write(KTMP_EP, data, size, 0, CmdFlags::NOPF) } pub fn send_to(&mut self, vpe: &VPEDesc, ep: EpId, lbl: Label, msg: *const u8, size: usize, rpl_lbl: Label, rpl_ep: EpId) -> Result<(), Error> { let msg_size = size + util::size_of::<Header>(); self.state.config_send(KTMP_EP, lbl, vpe.pe_id(), vpe.vpe_id(), ep, msg_size,!0); self.write_ep_local(KTMP_EP); DTU::send(KTMP_EP, msg, size, rpl_lbl, rpl_ep) } pub fn clear(&mut self, _dst_vpe: &VPEDesc, mut _dst_addr: goff, _size: usize) -> Result<(), Error> { Err(Error::new(Code::NotSup)) } pub fn copy(&mut self, _dst_vpe: &VPEDesc, mut _dst_addr: goff, _src_vpe: &VPEDesc, mut _src_addr: goff,
self.state.config_recv(ep, buf, ord, msg_ord, 0); self.write_ep_local(ep); Ok(()) } pub fn write_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId, regs: &[Reg]) -> Result<(), Error> { let eps = vpe.vpe().unwrap().eps_addr(); let addr = eps + ep * EPS_RCNT * util::size_of::<Reg>(); let bytes = EPS_RCNT * util::size_of::<Reg>(); self.try_write_mem(vpe, addr as goff, regs.as_ptr() as *const u8, bytes) } pub fn reset(&mut self, _vpe: &VPEDesc) -> Result<(), Error> { // nothing to do Ok(()) } }
_size: usize) -> Result<(), Error> { Err(Error::new(Code::NotSup)) } pub fn recv_msgs(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32) -> Result<(), Error> {
random_line_split
kdtu.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use base::cell::StaticCell; use base::dtu::*; use base::errors::{Code, Error}; use base::goff; use base::kif::Perm; use base::util; use pes::{VPEId, VPEDesc}; pub struct State { cmd: [Reg; CMD_RCNT], eps: [Reg; EPS_RCNT * EP_COUNT], } impl State { pub fn new() -> State { State { cmd: [0; CMD_RCNT], eps: [0; EPS_RCNT * EP_COUNT], } } pub fn get_ep(&self, ep: EpId) -> &[Reg] { &self.eps[ep * EPS_RCNT..(ep + 1) * EPS_RCNT] } pub fn get_ep_mut(&mut self, ep: EpId) -> &mut [Reg] { &mut self.eps[ep * EPS_RCNT..(ep + 1) * EPS_RCNT] } pub fn config_send(&mut self, ep: EpId, lbl: Label, pe: PEId, _vpe: VPEId, dst_ep: EpId, msg_size: usize, credits: u64) { let regs: &mut [Reg] = self.get_ep_mut(ep); regs[EpReg::LABEL.val as usize] = lbl; regs[EpReg::PE_ID.val as usize] = pe as Reg; regs[EpReg::EP_ID.val as usize] = dst_ep as Reg; regs[EpReg::CREDITS.val as usize] = credits; regs[EpReg::MSGORDER.val as usize] = util::next_log2(msg_size) as Reg; } pub fn config_recv(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32, _header: usize) { let regs: &mut [Reg] = self.get_ep_mut(ep); regs[EpReg::BUF_ADDR.val as usize] = buf as Reg; regs[EpReg::BUF_ORDER.val as usize] = ord as Reg; regs[EpReg::BUF_MSGORDER.val as usize] = msg_ord as Reg; regs[EpReg::BUF_ROFF.val as usize] = 0; regs[EpReg::BUF_WOFF.val as usize] = 0; regs[EpReg::BUF_MSG_CNT.val as usize] = 0; regs[EpReg::BUF_UNREAD.val as usize] = 0; regs[EpReg::BUF_OCCUPIED.val as usize] = 0; } pub fn config_mem(&mut self, ep: EpId, pe: PEId, _vpe: VPEId, addr: goff, size: usize, perm: Perm) { let regs: &mut [Reg] = self.get_ep_mut(ep); assert!((addr & perm.bits() as goff) == 0); regs[EpReg::LABEL.val as usize] = (addr | perm.bits() as goff) as Reg; regs[EpReg::PE_ID.val as usize] = pe as Reg; regs[EpReg::EP_ID.val as usize] = 0; regs[EpReg::CREDITS.val as usize] = size as Reg; regs[EpReg::MSGORDER.val as usize] = 0; } pub fn invalidate(&mut self, ep: EpId, _check: bool) -> Result<(), Error> { let regs: &mut [Reg] = self.get_ep_mut(ep); for r in regs.iter_mut() { *r = 0; } Ok(()) } pub fn restore(&mut self, _vpe: &VPEDesc, _vpe_id: VPEId) { } pub fn reset(&mut self) { } } pub struct KDTU { state: State, } pub const KSYS_EP: EpId = 0; pub const KSRV_EP: EpId = 1; pub const KTMP_EP: EpId = 2; static INST: StaticCell<Option<KDTU>> = StaticCell::new(None); impl KDTU { pub fn
() { INST.set(Some(KDTU { state: State::new(), })); } pub fn get() -> &'static mut KDTU { INST.get_mut().as_mut().unwrap() } pub fn write_ep_local(&mut self, ep: EpId) { DTU::set_ep_regs(ep, self.state.get_ep(ep)); } pub fn invalidate_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId) -> Result<(), Error> { let regs = [0 as Reg; EPS_RCNT * EP_COUNT]; self.write_ep_remote(vpe, ep, &regs) } pub fn read_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *mut u8, size: usize) { assert!(vpe.vpe().is_none()); self.try_read_mem(vpe, addr, data, size).unwrap(); } pub fn try_read_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *mut u8, size: usize) -> Result<(), Error> { self.state.config_mem(KTMP_EP, vpe.pe_id(), vpe.vpe_id(), addr, size, Perm::R); self.write_ep_local(KTMP_EP); DTU::read(KTMP_EP, data, size, 0, CmdFlags::NOPF) } pub fn write_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *const u8, size: usize) { assert!(vpe.vpe().is_none()); self.try_write_mem(vpe, addr, data, size).unwrap(); } pub fn try_write_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *const u8, size: usize) -> Result<(), Error> { self.state.config_mem(KTMP_EP, vpe.pe_id(), vpe.vpe_id(), addr, size, Perm::W); self.write_ep_local(KTMP_EP); DTU::write(KTMP_EP, data, size, 0, CmdFlags::NOPF) } pub fn send_to(&mut self, vpe: &VPEDesc, ep: EpId, lbl: Label, msg: *const u8, size: usize, rpl_lbl: Label, rpl_ep: EpId) -> Result<(), Error> { let msg_size = size + util::size_of::<Header>(); self.state.config_send(KTMP_EP, lbl, vpe.pe_id(), vpe.vpe_id(), ep, msg_size,!0); self.write_ep_local(KTMP_EP); DTU::send(KTMP_EP, msg, size, rpl_lbl, rpl_ep) } pub fn clear(&mut self, _dst_vpe: &VPEDesc, mut _dst_addr: goff, _size: usize) -> Result<(), Error> { Err(Error::new(Code::NotSup)) } pub fn copy(&mut self, _dst_vpe: &VPEDesc, mut _dst_addr: goff, _src_vpe: &VPEDesc, mut _src_addr: goff, _size: usize) -> Result<(), Error> { Err(Error::new(Code::NotSup)) } pub fn recv_msgs(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32) -> Result<(), Error> { self.state.config_recv(ep, buf, ord, msg_ord, 0); self.write_ep_local(ep); Ok(()) } pub fn write_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId, regs: &[Reg]) -> Result<(), Error> { let eps = vpe.vpe().unwrap().eps_addr(); let addr = eps + ep * EPS_RCNT * util::size_of::<Reg>(); let bytes = EPS_RCNT * util::size_of::<Reg>(); self.try_write_mem(vpe, addr as goff, regs.as_ptr() as *const u8, bytes) } pub fn reset(&mut self, _vpe: &VPEDesc) -> Result<(), Error> { // nothing to do Ok(()) } }
init
identifier_name
kdtu.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use base::cell::StaticCell; use base::dtu::*; use base::errors::{Code, Error}; use base::goff; use base::kif::Perm; use base::util; use pes::{VPEId, VPEDesc}; pub struct State { cmd: [Reg; CMD_RCNT], eps: [Reg; EPS_RCNT * EP_COUNT], } impl State { pub fn new() -> State { State { cmd: [0; CMD_RCNT], eps: [0; EPS_RCNT * EP_COUNT], } } pub fn get_ep(&self, ep: EpId) -> &[Reg] { &self.eps[ep * EPS_RCNT..(ep + 1) * EPS_RCNT] } pub fn get_ep_mut(&mut self, ep: EpId) -> &mut [Reg] { &mut self.eps[ep * EPS_RCNT..(ep + 1) * EPS_RCNT] } pub fn config_send(&mut self, ep: EpId, lbl: Label, pe: PEId, _vpe: VPEId, dst_ep: EpId, msg_size: usize, credits: u64) { let regs: &mut [Reg] = self.get_ep_mut(ep); regs[EpReg::LABEL.val as usize] = lbl; regs[EpReg::PE_ID.val as usize] = pe as Reg; regs[EpReg::EP_ID.val as usize] = dst_ep as Reg; regs[EpReg::CREDITS.val as usize] = credits; regs[EpReg::MSGORDER.val as usize] = util::next_log2(msg_size) as Reg; } pub fn config_recv(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32, _header: usize) { let regs: &mut [Reg] = self.get_ep_mut(ep); regs[EpReg::BUF_ADDR.val as usize] = buf as Reg; regs[EpReg::BUF_ORDER.val as usize] = ord as Reg; regs[EpReg::BUF_MSGORDER.val as usize] = msg_ord as Reg; regs[EpReg::BUF_ROFF.val as usize] = 0; regs[EpReg::BUF_WOFF.val as usize] = 0; regs[EpReg::BUF_MSG_CNT.val as usize] = 0; regs[EpReg::BUF_UNREAD.val as usize] = 0; regs[EpReg::BUF_OCCUPIED.val as usize] = 0; } pub fn config_mem(&mut self, ep: EpId, pe: PEId, _vpe: VPEId, addr: goff, size: usize, perm: Perm) { let regs: &mut [Reg] = self.get_ep_mut(ep); assert!((addr & perm.bits() as goff) == 0); regs[EpReg::LABEL.val as usize] = (addr | perm.bits() as goff) as Reg; regs[EpReg::PE_ID.val as usize] = pe as Reg; regs[EpReg::EP_ID.val as usize] = 0; regs[EpReg::CREDITS.val as usize] = size as Reg; regs[EpReg::MSGORDER.val as usize] = 0; } pub fn invalidate(&mut self, ep: EpId, _check: bool) -> Result<(), Error> { let regs: &mut [Reg] = self.get_ep_mut(ep); for r in regs.iter_mut() { *r = 0; } Ok(()) } pub fn restore(&mut self, _vpe: &VPEDesc, _vpe_id: VPEId) { } pub fn reset(&mut self) { } } pub struct KDTU { state: State, } pub const KSYS_EP: EpId = 0; pub const KSRV_EP: EpId = 1; pub const KTMP_EP: EpId = 2; static INST: StaticCell<Option<KDTU>> = StaticCell::new(None); impl KDTU { pub fn init() { INST.set(Some(KDTU { state: State::new(), })); } pub fn get() -> &'static mut KDTU { INST.get_mut().as_mut().unwrap() } pub fn write_ep_local(&mut self, ep: EpId) { DTU::set_ep_regs(ep, self.state.get_ep(ep)); } pub fn invalidate_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId) -> Result<(), Error> { let regs = [0 as Reg; EPS_RCNT * EP_COUNT]; self.write_ep_remote(vpe, ep, &regs) } pub fn read_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *mut u8, size: usize) { assert!(vpe.vpe().is_none()); self.try_read_mem(vpe, addr, data, size).unwrap(); } pub fn try_read_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *mut u8, size: usize) -> Result<(), Error> { self.state.config_mem(KTMP_EP, vpe.pe_id(), vpe.vpe_id(), addr, size, Perm::R); self.write_ep_local(KTMP_EP); DTU::read(KTMP_EP, data, size, 0, CmdFlags::NOPF) } pub fn write_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *const u8, size: usize) { assert!(vpe.vpe().is_none()); self.try_write_mem(vpe, addr, data, size).unwrap(); } pub fn try_write_mem(&mut self, vpe: &VPEDesc, addr: goff, data: *const u8, size: usize) -> Result<(), Error> { self.state.config_mem(KTMP_EP, vpe.pe_id(), vpe.vpe_id(), addr, size, Perm::W); self.write_ep_local(KTMP_EP); DTU::write(KTMP_EP, data, size, 0, CmdFlags::NOPF) } pub fn send_to(&mut self, vpe: &VPEDesc, ep: EpId, lbl: Label, msg: *const u8, size: usize, rpl_lbl: Label, rpl_ep: EpId) -> Result<(), Error> { let msg_size = size + util::size_of::<Header>(); self.state.config_send(KTMP_EP, lbl, vpe.pe_id(), vpe.vpe_id(), ep, msg_size,!0); self.write_ep_local(KTMP_EP); DTU::send(KTMP_EP, msg, size, rpl_lbl, rpl_ep) } pub fn clear(&mut self, _dst_vpe: &VPEDesc, mut _dst_addr: goff, _size: usize) -> Result<(), Error> { Err(Error::new(Code::NotSup)) } pub fn copy(&mut self, _dst_vpe: &VPEDesc, mut _dst_addr: goff, _src_vpe: &VPEDesc, mut _src_addr: goff, _size: usize) -> Result<(), Error> { Err(Error::new(Code::NotSup)) } pub fn recv_msgs(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32) -> Result<(), Error> { self.state.config_recv(ep, buf, ord, msg_ord, 0); self.write_ep_local(ep); Ok(()) } pub fn write_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId, regs: &[Reg]) -> Result<(), Error>
pub fn reset(&mut self, _vpe: &VPEDesc) -> Result<(), Error> { // nothing to do Ok(()) } }
{ let eps = vpe.vpe().unwrap().eps_addr(); let addr = eps + ep * EPS_RCNT * util::size_of::<Reg>(); let bytes = EPS_RCNT * util::size_of::<Reg>(); self.try_write_mem(vpe, addr as goff, regs.as_ptr() as *const u8, bytes) }
identifier_body
timeranges.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding::TimeRangesMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::window::Window; use dom_struct::dom_struct; use std::fmt; use std::rc::Rc; #[derive(JSTraceable, MallocSizeOf)] struct TimeRange { start: f64, end: f64, } impl TimeRange { pub fn union(&mut self, other: &TimeRange) { self.start = f64::min(self.start, other.start); self.end = f64::max(self.end, other.end); } fn contains(&self, time: f64) -> bool { self.start <= time && time < self.end } fn is_overlapping(&self, other: &TimeRange) -> bool { // This also covers the case where `self` is entirely contained within `other`, // for example: `self` = [2,3) and `other` = [1,4). self.contains(other.start) || self.contains(other.end) || other.contains(self.start) } fn is_contiguous(&self, other: &TimeRange) -> bool { other.start == self.end || other.end == self.start } pub fn is_before(&self, other: &TimeRange) -> bool { other.start >= self.end } } impl fmt::Debug for TimeRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "[{},{})", self.start, self.end) } } #[derive(Debug)] pub enum TimeRangesError { EndOlderThanStart, OutOfRange, } #[derive(Debug, JSTraceable, MallocSizeOf)] pub struct TimeRangesContainer { ranges: Vec<TimeRange>, } impl TimeRangesContainer { pub fn new() -> Self { Self { ranges: Vec::new() } } pub fn len(&self) -> u32 { self.ranges.len() as u32 } pub fn start(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.start) .ok_or(TimeRangesError::OutOfRange) } pub fn end(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.end) .ok_or(TimeRangesError::OutOfRange) } pub fn add(&mut self, start: f64, end: f64) -> Result<(), TimeRangesError> { if start > end { return Err(TimeRangesError::EndOlderThanStart); } let mut new_range = TimeRange { start, end }; // For each present range check if we need to: // - merge with the added range, in case we are overlapping or contiguous, // - insert in place, we are completely, not overlapping and not contiguous // in between two ranges. let mut idx = 0; while idx < self.ranges.len() { if new_range.is_overlapping(&self.ranges[idx]) || new_range.is_contiguous(&self.ranges[idx])
else if new_range.is_before(&self.ranges[idx]) && (idx == 0 || self.ranges[idx - 1].is_before(&new_range)) { // We are exactly after the current previous range and before the current // range, while not overlapping with none of them. // Or we are simply at the beginning. self.ranges.insert(idx, new_range); return Ok(()); } else { idx += 1; } } // Insert at the end. self.ranges.insert(idx, new_range); Ok(()) } } #[dom_struct] pub struct TimeRanges { reflector_: Reflector, #[ignore_malloc_size_of = "Rc"] ranges: Rc<DomRefCell<TimeRangesContainer>>, } //XXX(ferjm) We'll get warnings about unused methods until we use this // on the media element implementation. #[allow(dead_code)] impl TimeRanges { fn new_inherited(ranges: Rc<DomRefCell<TimeRangesContainer>>) -> TimeRanges { Self { reflector_: Reflector::new(), ranges, } } pub fn new( window: &Window, ranges: Rc<DomRefCell<TimeRangesContainer>>, ) -> DomRoot<TimeRanges> { reflect_dom_object( Box::new(TimeRanges::new_inherited(ranges)), window, TimeRangesBinding::Wrap, ) } } impl TimeRangesMethods for TimeRanges { // https://html.spec.whatwg.org/multipage/#dom-timeranges-length fn Length(&self) -> u32 { self.ranges.borrow().len() } // https://html.spec.whatwg.org/multipage/#dom-timeranges-start fn Start(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .start(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } // https://html.spec.whatwg.org/multipage/#dom-timeranges-end fn End(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .end(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } }
{ // The ranges are either overlapping or contiguous, // we need to merge the new range with the existing one. new_range.union(&self.ranges[idx]); self.ranges.remove(idx); }
conditional_block
timeranges.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding::TimeRangesMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::window::Window; use dom_struct::dom_struct; use std::fmt; use std::rc::Rc; #[derive(JSTraceable, MallocSizeOf)] struct TimeRange { start: f64, end: f64, } impl TimeRange { pub fn union(&mut self, other: &TimeRange) { self.start = f64::min(self.start, other.start); self.end = f64::max(self.end, other.end); } fn contains(&self, time: f64) -> bool
fn is_overlapping(&self, other: &TimeRange) -> bool { // This also covers the case where `self` is entirely contained within `other`, // for example: `self` = [2,3) and `other` = [1,4). self.contains(other.start) || self.contains(other.end) || other.contains(self.start) } fn is_contiguous(&self, other: &TimeRange) -> bool { other.start == self.end || other.end == self.start } pub fn is_before(&self, other: &TimeRange) -> bool { other.start >= self.end } } impl fmt::Debug for TimeRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "[{},{})", self.start, self.end) } } #[derive(Debug)] pub enum TimeRangesError { EndOlderThanStart, OutOfRange, } #[derive(Debug, JSTraceable, MallocSizeOf)] pub struct TimeRangesContainer { ranges: Vec<TimeRange>, } impl TimeRangesContainer { pub fn new() -> Self { Self { ranges: Vec::new() } } pub fn len(&self) -> u32 { self.ranges.len() as u32 } pub fn start(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.start) .ok_or(TimeRangesError::OutOfRange) } pub fn end(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.end) .ok_or(TimeRangesError::OutOfRange) } pub fn add(&mut self, start: f64, end: f64) -> Result<(), TimeRangesError> { if start > end { return Err(TimeRangesError::EndOlderThanStart); } let mut new_range = TimeRange { start, end }; // For each present range check if we need to: // - merge with the added range, in case we are overlapping or contiguous, // - insert in place, we are completely, not overlapping and not contiguous // in between two ranges. let mut idx = 0; while idx < self.ranges.len() { if new_range.is_overlapping(&self.ranges[idx]) || new_range.is_contiguous(&self.ranges[idx]) { // The ranges are either overlapping or contiguous, // we need to merge the new range with the existing one. new_range.union(&self.ranges[idx]); self.ranges.remove(idx); } else if new_range.is_before(&self.ranges[idx]) && (idx == 0 || self.ranges[idx - 1].is_before(&new_range)) { // We are exactly after the current previous range and before the current // range, while not overlapping with none of them. // Or we are simply at the beginning. self.ranges.insert(idx, new_range); return Ok(()); } else { idx += 1; } } // Insert at the end. self.ranges.insert(idx, new_range); Ok(()) } } #[dom_struct] pub struct TimeRanges { reflector_: Reflector, #[ignore_malloc_size_of = "Rc"] ranges: Rc<DomRefCell<TimeRangesContainer>>, } //XXX(ferjm) We'll get warnings about unused methods until we use this // on the media element implementation. #[allow(dead_code)] impl TimeRanges { fn new_inherited(ranges: Rc<DomRefCell<TimeRangesContainer>>) -> TimeRanges { Self { reflector_: Reflector::new(), ranges, } } pub fn new( window: &Window, ranges: Rc<DomRefCell<TimeRangesContainer>>, ) -> DomRoot<TimeRanges> { reflect_dom_object( Box::new(TimeRanges::new_inherited(ranges)), window, TimeRangesBinding::Wrap, ) } } impl TimeRangesMethods for TimeRanges { // https://html.spec.whatwg.org/multipage/#dom-timeranges-length fn Length(&self) -> u32 { self.ranges.borrow().len() } // https://html.spec.whatwg.org/multipage/#dom-timeranges-start fn Start(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .start(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } // https://html.spec.whatwg.org/multipage/#dom-timeranges-end fn End(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .end(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } }
{ self.start <= time && time < self.end }
identifier_body
timeranges.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding::TimeRangesMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::window::Window; use dom_struct::dom_struct; use std::fmt; use std::rc::Rc; #[derive(JSTraceable, MallocSizeOf)] struct TimeRange { start: f64, end: f64, } impl TimeRange { pub fn union(&mut self, other: &TimeRange) { self.start = f64::min(self.start, other.start); self.end = f64::max(self.end, other.end); } fn contains(&self, time: f64) -> bool { self.start <= time && time < self.end } fn is_overlapping(&self, other: &TimeRange) -> bool { // This also covers the case where `self` is entirely contained within `other`, // for example: `self` = [2,3) and `other` = [1,4).
} pub fn is_before(&self, other: &TimeRange) -> bool { other.start >= self.end } } impl fmt::Debug for TimeRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "[{},{})", self.start, self.end) } } #[derive(Debug)] pub enum TimeRangesError { EndOlderThanStart, OutOfRange, } #[derive(Debug, JSTraceable, MallocSizeOf)] pub struct TimeRangesContainer { ranges: Vec<TimeRange>, } impl TimeRangesContainer { pub fn new() -> Self { Self { ranges: Vec::new() } } pub fn len(&self) -> u32 { self.ranges.len() as u32 } pub fn start(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.start) .ok_or(TimeRangesError::OutOfRange) } pub fn end(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.end) .ok_or(TimeRangesError::OutOfRange) } pub fn add(&mut self, start: f64, end: f64) -> Result<(), TimeRangesError> { if start > end { return Err(TimeRangesError::EndOlderThanStart); } let mut new_range = TimeRange { start, end }; // For each present range check if we need to: // - merge with the added range, in case we are overlapping or contiguous, // - insert in place, we are completely, not overlapping and not contiguous // in between two ranges. let mut idx = 0; while idx < self.ranges.len() { if new_range.is_overlapping(&self.ranges[idx]) || new_range.is_contiguous(&self.ranges[idx]) { // The ranges are either overlapping or contiguous, // we need to merge the new range with the existing one. new_range.union(&self.ranges[idx]); self.ranges.remove(idx); } else if new_range.is_before(&self.ranges[idx]) && (idx == 0 || self.ranges[idx - 1].is_before(&new_range)) { // We are exactly after the current previous range and before the current // range, while not overlapping with none of them. // Or we are simply at the beginning. self.ranges.insert(idx, new_range); return Ok(()); } else { idx += 1; } } // Insert at the end. self.ranges.insert(idx, new_range); Ok(()) } } #[dom_struct] pub struct TimeRanges { reflector_: Reflector, #[ignore_malloc_size_of = "Rc"] ranges: Rc<DomRefCell<TimeRangesContainer>>, } //XXX(ferjm) We'll get warnings about unused methods until we use this // on the media element implementation. #[allow(dead_code)] impl TimeRanges { fn new_inherited(ranges: Rc<DomRefCell<TimeRangesContainer>>) -> TimeRanges { Self { reflector_: Reflector::new(), ranges, } } pub fn new( window: &Window, ranges: Rc<DomRefCell<TimeRangesContainer>>, ) -> DomRoot<TimeRanges> { reflect_dom_object( Box::new(TimeRanges::new_inherited(ranges)), window, TimeRangesBinding::Wrap, ) } } impl TimeRangesMethods for TimeRanges { // https://html.spec.whatwg.org/multipage/#dom-timeranges-length fn Length(&self) -> u32 { self.ranges.borrow().len() } // https://html.spec.whatwg.org/multipage/#dom-timeranges-start fn Start(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .start(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } // https://html.spec.whatwg.org/multipage/#dom-timeranges-end fn End(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .end(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } }
self.contains(other.start) || self.contains(other.end) || other.contains(self.start) } fn is_contiguous(&self, other: &TimeRange) -> bool { other.start == self.end || other.end == self.start
random_line_split
timeranges.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding::TimeRangesMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::window::Window; use dom_struct::dom_struct; use std::fmt; use std::rc::Rc; #[derive(JSTraceable, MallocSizeOf)] struct TimeRange { start: f64, end: f64, } impl TimeRange { pub fn union(&mut self, other: &TimeRange) { self.start = f64::min(self.start, other.start); self.end = f64::max(self.end, other.end); } fn contains(&self, time: f64) -> bool { self.start <= time && time < self.end } fn is_overlapping(&self, other: &TimeRange) -> bool { // This also covers the case where `self` is entirely contained within `other`, // for example: `self` = [2,3) and `other` = [1,4). self.contains(other.start) || self.contains(other.end) || other.contains(self.start) } fn is_contiguous(&self, other: &TimeRange) -> bool { other.start == self.end || other.end == self.start } pub fn is_before(&self, other: &TimeRange) -> bool { other.start >= self.end } } impl fmt::Debug for TimeRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "[{},{})", self.start, self.end) } } #[derive(Debug)] pub enum TimeRangesError { EndOlderThanStart, OutOfRange, } #[derive(Debug, JSTraceable, MallocSizeOf)] pub struct TimeRangesContainer { ranges: Vec<TimeRange>, } impl TimeRangesContainer { pub fn new() -> Self { Self { ranges: Vec::new() } } pub fn len(&self) -> u32 { self.ranges.len() as u32 } pub fn start(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.start) .ok_or(TimeRangesError::OutOfRange) } pub fn
(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.end) .ok_or(TimeRangesError::OutOfRange) } pub fn add(&mut self, start: f64, end: f64) -> Result<(), TimeRangesError> { if start > end { return Err(TimeRangesError::EndOlderThanStart); } let mut new_range = TimeRange { start, end }; // For each present range check if we need to: // - merge with the added range, in case we are overlapping or contiguous, // - insert in place, we are completely, not overlapping and not contiguous // in between two ranges. let mut idx = 0; while idx < self.ranges.len() { if new_range.is_overlapping(&self.ranges[idx]) || new_range.is_contiguous(&self.ranges[idx]) { // The ranges are either overlapping or contiguous, // we need to merge the new range with the existing one. new_range.union(&self.ranges[idx]); self.ranges.remove(idx); } else if new_range.is_before(&self.ranges[idx]) && (idx == 0 || self.ranges[idx - 1].is_before(&new_range)) { // We are exactly after the current previous range and before the current // range, while not overlapping with none of them. // Or we are simply at the beginning. self.ranges.insert(idx, new_range); return Ok(()); } else { idx += 1; } } // Insert at the end. self.ranges.insert(idx, new_range); Ok(()) } } #[dom_struct] pub struct TimeRanges { reflector_: Reflector, #[ignore_malloc_size_of = "Rc"] ranges: Rc<DomRefCell<TimeRangesContainer>>, } //XXX(ferjm) We'll get warnings about unused methods until we use this // on the media element implementation. #[allow(dead_code)] impl TimeRanges { fn new_inherited(ranges: Rc<DomRefCell<TimeRangesContainer>>) -> TimeRanges { Self { reflector_: Reflector::new(), ranges, } } pub fn new( window: &Window, ranges: Rc<DomRefCell<TimeRangesContainer>>, ) -> DomRoot<TimeRanges> { reflect_dom_object( Box::new(TimeRanges::new_inherited(ranges)), window, TimeRangesBinding::Wrap, ) } } impl TimeRangesMethods for TimeRanges { // https://html.spec.whatwg.org/multipage/#dom-timeranges-length fn Length(&self) -> u32 { self.ranges.borrow().len() } // https://html.spec.whatwg.org/multipage/#dom-timeranges-start fn Start(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .start(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } // https://html.spec.whatwg.org/multipage/#dom-timeranges-end fn End(&self, index: u32) -> Fallible<Finite<f64>> { self.ranges .borrow() .end(index) .map(Finite::wrap) .map_err(|_| Error::IndexSize) } }
end
identifier_name
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { let msg = pubsub.get_message().unwrap(); handle_message(backend.clone(), msg).unwrap(); } }); } fn subscribe_to_redis(url: &str) -> redis::RedisResult<redis::PubSub>
fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>, msg: redis::Msg) -> redis::RedisResult<()> { let channel = msg.get_channel_name(); let payload: String = try!(msg.get_payload()); debug!("New message on Redis channel {}: '{}'", channel, payload); match channel { "backend_add" => { let mut backend = backend.lock().unwrap(); match backend.add(&payload) { Ok(_) => info!("Added new server {}", payload), _ => {} } } "backend_remove" => { let mut backend = backend.lock().unwrap(); match backend.remove(&payload) { Ok(_) => info!("Removed server {}", payload), _ => {} } } _ => info!("Cannot parse Redis message"), } Ok(()) }
{ let client = try!(redis::Client::open(url)); let mut pubsub: redis::PubSub = try!(client.get_pubsub()); try!(pubsub.subscribe("backend_add")); try!(pubsub.subscribe("backend_remove")); info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'"); Ok(pubsub) }
identifier_body
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { let msg = pubsub.get_message().unwrap(); handle_message(backend.clone(), msg).unwrap(); } }); } fn subscribe_to_redis(url: &str) -> redis::RedisResult<redis::PubSub> { let client = try!(redis::Client::open(url)); let mut pubsub: redis::PubSub = try!(client.get_pubsub()); try!(pubsub.subscribe("backend_add")); try!(pubsub.subscribe("backend_remove"));
msg: redis::Msg) -> redis::RedisResult<()> { let channel = msg.get_channel_name(); let payload: String = try!(msg.get_payload()); debug!("New message on Redis channel {}: '{}'", channel, payload); match channel { "backend_add" => { let mut backend = backend.lock().unwrap(); match backend.add(&payload) { Ok(_) => info!("Added new server {}", payload), _ => {} } } "backend_remove" => { let mut backend = backend.lock().unwrap(); match backend.remove(&payload) { Ok(_) => info!("Removed server {}", payload), _ => {} } } _ => info!("Cannot parse Redis message"), } Ok(()) }
info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'"); Ok(pubsub) } fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>,
random_line_split
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn
(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { let msg = pubsub.get_message().unwrap(); handle_message(backend.clone(), msg).unwrap(); } }); } fn subscribe_to_redis(url: &str) -> redis::RedisResult<redis::PubSub> { let client = try!(redis::Client::open(url)); let mut pubsub: redis::PubSub = try!(client.get_pubsub()); try!(pubsub.subscribe("backend_add")); try!(pubsub.subscribe("backend_remove")); info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'"); Ok(pubsub) } fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>, msg: redis::Msg) -> redis::RedisResult<()> { let channel = msg.get_channel_name(); let payload: String = try!(msg.get_payload()); debug!("New message on Redis channel {}: '{}'", channel, payload); match channel { "backend_add" => { let mut backend = backend.lock().unwrap(); match backend.add(&payload) { Ok(_) => info!("Added new server {}", payload), _ => {} } } "backend_remove" => { let mut backend = backend.lock().unwrap(); match backend.remove(&payload) { Ok(_) => info!("Removed server {}", payload), _ => {} } } _ => info!("Cannot parse Redis message"), } Ok(()) }
create_sync_thread
identifier_name
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { let msg = pubsub.get_message().unwrap(); handle_message(backend.clone(), msg).unwrap(); } }); } fn subscribe_to_redis(url: &str) -> redis::RedisResult<redis::PubSub> { let client = try!(redis::Client::open(url)); let mut pubsub: redis::PubSub = try!(client.get_pubsub()); try!(pubsub.subscribe("backend_add")); try!(pubsub.subscribe("backend_remove")); info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'"); Ok(pubsub) } fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>, msg: redis::Msg) -> redis::RedisResult<()> { let channel = msg.get_channel_name(); let payload: String = try!(msg.get_payload()); debug!("New message on Redis channel {}: '{}'", channel, payload); match channel { "backend_add" => { let mut backend = backend.lock().unwrap(); match backend.add(&payload) { Ok(_) => info!("Added new server {}", payload), _ =>
} } "backend_remove" => { let mut backend = backend.lock().unwrap(); match backend.remove(&payload) { Ok(_) => info!("Removed server {}", payload), _ => {} } } _ => info!("Cannot parse Redis message"), } Ok(()) }
{}
conditional_block
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Executed transaction. use hash::Address; use uint::Uint; use bytes::Bytes; /// Executed transaction. #[derive(Debug, PartialEq, Deserialize)] pub struct Transaction { /// Contract address. pub address: Address, /// Transaction sender. #[serde(rename="caller")] pub sender: Address, /// Contract code. pub code: Bytes, /// Input data. pub data: Bytes, /// Gas. pub gas: Uint, /// Gas price. #[serde(rename="gasPrice")] pub gas_price: Uint, /// Transaction origin. pub origin: Address, /// Sent value. pub value: Uint, } #[cfg(test)] mod tests { use serde_json; use vm::Transaction; #[test] fn
() { let s = r#"{ "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", "caller" : "cd1722f2947def4cf144679da39c4c32bdc35681", "code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055", "data" : "0x", "gas" : "0x0186a0", "gasPrice" : "0x5af3107a4000", "origin" : "cd1722f2947def4cf144679da39c4c32bdc35681", "value" : "0x0de0b6b3a7640000" }"#; let _deserialized: Transaction = serde_json::from_str(s).unwrap(); } }
transaction_deserialization
identifier_name
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity.
// 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/>. //! Executed transaction. use hash::Address; use uint::Uint; use bytes::Bytes; /// Executed transaction. #[derive(Debug, PartialEq, Deserialize)] pub struct Transaction { /// Contract address. pub address: Address, /// Transaction sender. #[serde(rename="caller")] pub sender: Address, /// Contract code. pub code: Bytes, /// Input data. pub data: Bytes, /// Gas. pub gas: Uint, /// Gas price. #[serde(rename="gasPrice")] pub gas_price: Uint, /// Transaction origin. pub origin: Address, /// Sent value. pub value: Uint, } #[cfg(test)] mod tests { use serde_json; use vm::Transaction; #[test] fn transaction_deserialization() { let s = r#"{ "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", "caller" : "cd1722f2947def4cf144679da39c4c32bdc35681", "code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055", "data" : "0x", "gas" : "0x0186a0", "gasPrice" : "0x5af3107a4000", "origin" : "cd1722f2947def4cf144679da39c4c32bdc35681", "value" : "0x0de0b6b3a7640000" }"#; let _deserialized: Transaction = serde_json::from_str(s).unwrap(); } }
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by
random_line_split
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread needs to be responsible for them because there's //! no guarantee that the responsible nodes will still exist in the future if the //! layout thread holds on to them during asynchronous operations. use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::globalscope::GlobalScope; use crate::dom::node::{document_from_node, Node}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Destination, RequestInit as FetchRequestInit}; use net_traits::{FetchMetadata, FetchResponseListener, FetchResponseMsg, NetworkError}; use net_traits::{ResourceFetchTiming, ResourceTimingType}; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; struct LayoutImageContext { id: PendingImageId, cache: Arc<dyn ImageCache>, resource_timing: ResourceFetchTiming, doc: Trusted<Document>, } impl FetchResponseListener for LayoutImageContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload)); } fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming { &mut self.resource_timing } fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for LayoutImageContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { ( InitiatorType::Other, self.resource_timing_global().get_url().clone(), ) } fn resource_timing_global(&self) -> DomRoot<GlobalScope>
} impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout( url: ServoUrl, node: &Node, id: PendingImageId, cache: Arc<dyn ImageCache>, ) { let document = document_from_node(node); let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), doc: Trusted::new(&document), })); let document = document_from_node(node); let (action_sender, action_receiver) = ipc::channel().unwrap(); let (task_source, canceller) = document .window() .task_manager() .networking_task_source_with_canceller(); let listener = NetworkListener { context, task_source, canceller: Some(canceller), }; ROUTER.add_route( action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); }), ); let request = FetchRequestInit { url: url, origin: document.origin().immutable().clone(), destination: Destination::Image, pipeline_id: Some(document.global().pipeline_id()), ..FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document .loader_mut() .fetch_async_background(request, action_sender); }
{ self.doc.root().global() }
identifier_body
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread needs to be responsible for them because there's //! no guarantee that the responsible nodes will still exist in the future if the //! layout thread holds on to them during asynchronous operations. use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::globalscope::GlobalScope; use crate::dom::node::{document_from_node, Node}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Destination, RequestInit as FetchRequestInit}; use net_traits::{FetchMetadata, FetchResponseListener, FetchResponseMsg, NetworkError}; use net_traits::{ResourceFetchTiming, ResourceTimingType}; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; struct LayoutImageContext { id: PendingImageId, cache: Arc<dyn ImageCache>, resource_timing: ResourceFetchTiming, doc: Trusted<Document>, } impl FetchResponseListener for LayoutImageContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload)); } fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming { &mut self.resource_timing } fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for LayoutImageContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { ( InitiatorType::Other, self.resource_timing_global().get_url().clone(), ) } fn resource_timing_global(&self) -> DomRoot<GlobalScope> { self.doc.root().global() } } impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout(
node: &Node, id: PendingImageId, cache: Arc<dyn ImageCache>, ) { let document = document_from_node(node); let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), doc: Trusted::new(&document), })); let document = document_from_node(node); let (action_sender, action_receiver) = ipc::channel().unwrap(); let (task_source, canceller) = document .window() .task_manager() .networking_task_source_with_canceller(); let listener = NetworkListener { context, task_source, canceller: Some(canceller), }; ROUTER.add_route( action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); }), ); let request = FetchRequestInit { url: url, origin: document.origin().immutable().clone(), destination: Destination::Image, pipeline_id: Some(document.global().pipeline_id()), ..FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document .loader_mut() .fetch_async_background(request, action_sender); }
url: ServoUrl,
random_line_split
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread needs to be responsible for them because there's //! no guarantee that the responsible nodes will still exist in the future if the //! layout thread holds on to them during asynchronous operations. use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::globalscope::GlobalScope; use crate::dom::node::{document_from_node, Node}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Destination, RequestInit as FetchRequestInit}; use net_traits::{FetchMetadata, FetchResponseListener, FetchResponseMsg, NetworkError}; use net_traits::{ResourceFetchTiming, ResourceTimingType}; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; struct LayoutImageContext { id: PendingImageId, cache: Arc<dyn ImageCache>, resource_timing: ResourceFetchTiming, doc: Trusted<Document>, } impl FetchResponseListener for LayoutImageContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn
(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload)); } fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming { &mut self.resource_timing } fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for LayoutImageContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { ( InitiatorType::Other, self.resource_timing_global().get_url().clone(), ) } fn resource_timing_global(&self) -> DomRoot<GlobalScope> { self.doc.root().global() } } impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout( url: ServoUrl, node: &Node, id: PendingImageId, cache: Arc<dyn ImageCache>, ) { let document = document_from_node(node); let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), doc: Trusted::new(&document), })); let document = document_from_node(node); let (action_sender, action_receiver) = ipc::channel().unwrap(); let (task_source, canceller) = document .window() .task_manager() .networking_task_source_with_canceller(); let listener = NetworkListener { context, task_source, canceller: Some(canceller), }; ROUTER.add_route( action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); }), ); let request = FetchRequestInit { url: url, origin: document.origin().immutable().clone(), destination: Destination::Image, pipeline_id: Some(document.global().pipeline_id()), ..FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document .loader_mut() .fetch_async_background(request, action_sender); }
process_response
identifier_name
tls.rs
#![allow(unused_variables)] #![allow(unused_imports)] /// Note: Fred must be compiled with the `enable-tls` feature for this to work. extern crate fred; extern crate tokio_core; extern crate futures; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use tokio_core::reactor::Core; use futures::Future; fn main()
let commands = client.on_connect().and_then(|client| { println!("Client connected."); client.select(0) }) .and_then(|client| { println!("Selected database."); client.info(None) }) .and_then(|(client, info)| { println!("Redis server info: {}", info); client.get("foo") }) .and_then(|(client, result)| { println!("Got foo: {:?}", result); client.set("foo", "bar", Some(Expiration::PX(1000)), Some(SetOptions::NX)) }) .and_then(|(client, result)| { println!("Set 'bar' at 'foo'? {}. Subscribing to 'baz'...", result); client.subscribe("baz") }) .and_then(|(client, result)| { println!("Subscribed to 'baz'. Now subscribed to {} channels. Now exiting...", result); client.quit() }); let (reason, client) = match core.run(connection.join(commands)) { Ok((r, c)) => (r, c), Err(e) => panic!("Connection closed abruptly: {}", e) }; println!("Connection closed gracefully with error: {:?}", reason); }
{ let config = RedisConfig::Centralized { // Note: this must match the hostname tied to the cert host: "foo.bar.com".into(), port: 6379, key: Some("key".into()), // if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless necessary tls: true }; // otherwise usage is the same as the non-tls client... let mut core = Core::new().unwrap(); let handle = core.handle(); println!("Connecting to {:?}...", config); let client = RedisClient::new(config, None); let connection = client.connect(&handle);
identifier_body
tls.rs
#![allow(unused_variables)] #![allow(unused_imports)] /// Note: Fred must be compiled with the `enable-tls` feature for this to work. extern crate fred; extern crate tokio_core; extern crate futures; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use tokio_core::reactor::Core; use futures::Future; fn
() { let config = RedisConfig::Centralized { // Note: this must match the hostname tied to the cert host: "foo.bar.com".into(), port: 6379, key: Some("key".into()), // if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless necessary tls: true }; // otherwise usage is the same as the non-tls client... let mut core = Core::new().unwrap(); let handle = core.handle(); println!("Connecting to {:?}...", config); let client = RedisClient::new(config, None); let connection = client.connect(&handle); let commands = client.on_connect().and_then(|client| { println!("Client connected."); client.select(0) }) .and_then(|client| { println!("Selected database."); client.info(None) }) .and_then(|(client, info)| { println!("Redis server info: {}", info); client.get("foo") }) .and_then(|(client, result)| { println!("Got foo: {:?}", result); client.set("foo", "bar", Some(Expiration::PX(1000)), Some(SetOptions::NX)) }) .and_then(|(client, result)| { println!("Set 'bar' at 'foo'? {}. Subscribing to 'baz'...", result); client.subscribe("baz") }) .and_then(|(client, result)| { println!("Subscribed to 'baz'. Now subscribed to {} channels. Now exiting...", result); client.quit() }); let (reason, client) = match core.run(connection.join(commands)) { Ok((r, c)) => (r, c), Err(e) => panic!("Connection closed abruptly: {}", e) }; println!("Connection closed gracefully with error: {:?}", reason); }
main
identifier_name
tls.rs
#![allow(unused_variables)] #![allow(unused_imports)] /// Note: Fred must be compiled with the `enable-tls` feature for this to work. extern crate fred; extern crate tokio_core; extern crate futures; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use tokio_core::reactor::Core; use futures::Future; fn main() { let config = RedisConfig::Centralized { // Note: this must match the hostname tied to the cert host: "foo.bar.com".into(), port: 6379, key: Some("key".into()), // if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless necessary tls: true }; // otherwise usage is the same as the non-tls client... let mut core = Core::new().unwrap(); let handle = core.handle(); println!("Connecting to {:?}...", config); let client = RedisClient::new(config, None); let connection = client.connect(&handle); let commands = client.on_connect().and_then(|client| { println!("Client connected."); client.select(0) }) .and_then(|client| { println!("Selected database."); client.info(None) }) .and_then(|(client, info)| { println!("Redis server info: {}", info); client.get("foo") }) .and_then(|(client, result)| { println!("Got foo: {:?}", result); client.set("foo", "bar", Some(Expiration::PX(1000)), Some(SetOptions::NX)) }) .and_then(|(client, result)| { println!("Set 'bar' at 'foo'? {}. Subscribing to 'baz'...", result); client.subscribe("baz") }) .and_then(|(client, result)| { println!("Subscribed to 'baz'. Now subscribed to {} channels. Now exiting...", result); client.quit()
let (reason, client) = match core.run(connection.join(commands)) { Ok((r, c)) => (r, c), Err(e) => panic!("Connection closed abruptly: {}", e) }; println!("Connection closed gracefully with error: {:?}", reason); }
});
random_line_split
addressbook_send.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. extern crate capnp; extern crate core;
pub mod addressbook_capnp { include!(concat!(env!("OUT_DIR"), "/addressbook_capnp.rs")); } use capnp::message::{Builder, HeapAllocator, TypedReader}; use std::sync::mpsc; use std::thread; pub mod addressbook { use addressbook_capnp::{address_book, person}; use capnp::message::{Builder, HeapAllocator, TypedReader}; pub fn build_address_book() -> TypedReader<Builder<HeapAllocator>, address_book::Owned> { let mut message = Builder::new_default(); { let address_book = message.init_root::<address_book::Builder>(); let mut people = address_book.init_people(2); { let mut alice = people.reborrow().get(0); alice.set_id(123); alice.set_name("Alice"); alice.set_email("[email protected]"); { let mut alice_phones = alice.reborrow().init_phones(1); alice_phones.reborrow().get(0).set_number("555-1212"); alice_phones.reborrow().get(0).set_type(person::phone_number::Type::Mobile); } alice.get_employment().set_school("MIT"); } { let mut bob = people.get(1); bob.set_id(456); bob.set_name("Bob"); bob.set_email("[email protected]"); { let mut bob_phones = bob.reborrow().init_phones(2); bob_phones.reborrow().get(0).set_number("555-4567"); bob_phones.reborrow().get(0).set_type(person::phone_number::Type::Home); bob_phones.reborrow().get(1).set_number("555-7654"); bob_phones.reborrow().get(1).set_type(person::phone_number::Type::Work); } bob.get_employment().set_unemployed(()); } } // There are two ways to get a TypedReader from our `message`: // // Option 1: Go through the full process manually // message.into_reader().into_typed() // // Option 2: Use the "Into" trait defined on the builder // message.into() // // Option 3: Use the "From" trait defined on the builder TypedReader::from(message) } } pub fn main() { let book = addressbook::build_address_book(); let (tx_book, rx_book) = mpsc::channel::<TypedReader<Builder<HeapAllocator>, addressbook_capnp::address_book::Owned>>(); let (tx_id, rx_id) = mpsc::channel::<u32>(); thread::spawn(move || { let addressbook_reader = rx_book.recv().unwrap(); let addressbook = addressbook_reader.get().unwrap(); let first_person = addressbook.get_people().unwrap().get(0); let first_id = first_person.get_id(); tx_id.send(first_id) }); tx_book.send(book).unwrap(); let first_id = rx_id.recv().unwrap(); assert_eq!(first_id, 123); }
random_line_split