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 |
---|---|---|---|---|
nvic.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Harris <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Interface to Nested Vector Interrupt Controller.
//!
//! NVIC memory location is 0xE000_E000.
// Link: http://infocenter.arm.com/help/topic/com.arm.doc.dui0552a/CIHIGCIF.html
#[inline(always)]
fn get_reg() -> &'static reg::NVIC {
unsafe { &*(0xE000_E000 as *mut reg::NVIC) }
}
/// Enable an interrupt
pub fn enable_irq(irqn: usize) {
get_reg().iser[irqn / 32].clear_iser(irqn % 32);
}
/// Disable an interrupt
pub fn disable_irq(irqn: usize) {
get_reg().icer[irqn / 32].clear_icer(irqn % 32);
}
/// Return whether the given interrupt is enabled
pub fn is_enabled(irqn: usize) -> bool {
get_reg().iser[irqn / 32].iser(irqn % 32)
}
/// Clear the pending flag for the given interrupt
pub fn clear_pending(irqn: usize) {
get_reg().icpr[irqn / 32].clear_icpr(irqn % 32);
}
/// Return whether the given interrupt is pending
pub fn is_pending(irqn: usize) -> bool {
get_reg().ispr[irqn / 32].ispr(irqn % 32)
}
/// Return whether the given interrupt is active
pub fn is_active(irqn: usize) -> bool {
get_reg().iabr[irqn / 32].iabr(irqn % 32)
}
/// Set the priority for the given interrupt
pub fn set_priority(irqn: usize, prio: u8) {
get_reg().ipr[irqn / 4].set_ipr(irqn % 4, prio as u32);
}
/// Return the priority for the given interrupt
pub fn get_priority(irqn: usize) -> u8 {
get_reg().ipr[irqn / 4].ipr(irqn % 4) as u8
}
mod reg {
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(NVIC = {
0x100 => reg32 iser[8] { //! Interrupt set enable register
0..31 => iser[32]: set_to_clear,
}
0x180 => reg32 icer[8] { //! Interrupt clear enable register
0..31 => icer[32]: set_to_clear,
}
0x200 => reg32 ispr[8] { //! Interrupt set pending register
0..31 => ispr[32]: set_to_clear,
}
0x280 => reg32 icpr[8] { //! Interrupt clear pending register
0..31 => icpr[32]: set_to_clear,
}
0x300 => reg32 iabr[8] { //! Interrupt active bit register
0..31 => iabr[32]: ro,
}
|
0..8 => stir,
}
});
}
|
0x400 => reg32 ipr[8] { //! Interrupt priority register
0..31 => ipr[4],
}
0xF00 => reg32 stir[8] { //! Software triggered interrupt register
|
random_line_split
|
issue-662-part-2.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[derive(Clone, Copy, Debug)]
pub struct RefPtr<T>(T);
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct nsMainThreadPtrHolder<T> {
pub a: T,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default for nsMainThreadPtrHolder<T> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
pub struct
|
<U> {
pub mPtr: RefPtr<nsMainThreadPtrHolder<U>>,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<U>>,
}
impl<U> Default for nsMainThreadPtrHandle<U> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
|
nsMainThreadPtrHandle
|
identifier_name
|
issue-662-part-2.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[derive(Clone, Copy, Debug)]
pub struct RefPtr<T>(T);
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct nsMainThreadPtrHolder<T> {
pub a: T,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default for nsMainThreadPtrHolder<T> {
fn default() -> Self
|
}
#[repr(C)]
pub struct nsMainThreadPtrHandle<U> {
pub mPtr: RefPtr<nsMainThreadPtrHolder<U>>,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<U>>,
}
impl<U> Default for nsMainThreadPtrHandle<U> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
|
{
unsafe { ::std::mem::zeroed() }
}
|
identifier_body
|
issue-662-part-2.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
|
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct nsMainThreadPtrHolder<T> {
pub a: T,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default for nsMainThreadPtrHolder<T> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
pub struct nsMainThreadPtrHandle<U> {
pub mPtr: RefPtr<nsMainThreadPtrHolder<U>>,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<U>>,
}
impl<U> Default for nsMainThreadPtrHandle<U> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
|
)]
#[derive(Clone, Copy, Debug)]
pub struct RefPtr<T>(T);
|
random_line_split
|
main.rs
|
// Mandelbrot set in rust
//
// This code shows how to calculate the set in serial and parallel.
// More parallel versions will be added in the future.
//
// Written by Willi Kappler, [email protected]
//
// License: MIT
//
//#![feature(plugin)]
//
//#![plugin(clippy)]
// External crates
extern crate time;
extern crate rayon;
// Internal crates
extern crate mandel_util;
extern crate mandel_method;
// External modules
use time::{now};
// Internal modules
use mandel_util::{parse_arguments, do_run, compiler_version};
use mandel_method::*;
fn
|
() {
// For example run with:
// cargo run --release -- --re1=-2.0 --re2=1.0 --img1=-1.5 --img2=1.5
// --max_iter=2048 --img_size=1024 --num_threads=2
//
// Or just using the default values:
// cargo run --release -- --num_threads=2
//
// Note that the image size must be a power of two
let mandel_config = parse_arguments();
let version = env!("CARGO_PKG_VERSION");
println!("mandel-rust version: {}", version);
println!("Number of repetitive runs: {}", mandel_config.num_of_runs);
println!("Rustc version: {}", compiler_version);
// Get current date and time once and pass it to the individual runs for the image filename.
let tm = now();
let tm = tm.strftime("%Y_%m_%d__%H_%M_%S").unwrap();
let time_now = format!("{}", &tm);
// vec! macro expects usize
let mut image: Vec<u32> = vec![0; (mandel_config.img_size * mandel_config.img_size) as usize];
do_run("serial", &serial, &mandel_config, &mut image, &time_now);
do_run("scoped_thread_pool", &scoped_thread_pool_, &mandel_config, &mut image, &time_now);
// Make sure this is only called once
match rayon::initialize(rayon::Configuration::new().set_num_threads(mandel_config.num_threads as usize)) {
Ok(_) => {
do_run("rayon_join", &rayon_join, &mandel_config, &mut image, &time_now);
do_run("rayon_par_iter", &rayon_par_iter, &mandel_config, &mut image, &time_now);
},
Err(e) => println!("Rayon error: set number of threads failed: {}", e)
}
do_run("rust_scoped_pool", &rust_scoped_pool, &mandel_config, &mut image, &time_now);
do_run("job_steal", &job_steal, &mandel_config, &mut image, &time_now);
do_run("job_steal_join", &job_steal_join, &mandel_config, &mut image, &time_now);
// do_run("kirk_crossbeam", &kirk_crossbeam, &mandel_config, &mut image, &time_now);
}
|
main
|
identifier_name
|
main.rs
|
// Mandelbrot set in rust
//
// This code shows how to calculate the set in serial and parallel.
// More parallel versions will be added in the future.
//
// Written by Willi Kappler, [email protected]
//
// License: MIT
//
//#![feature(plugin)]
//
//#![plugin(clippy)]
// External crates
extern crate time;
extern crate rayon;
// Internal crates
extern crate mandel_util;
extern crate mandel_method;
// External modules
use time::{now};
// Internal modules
use mandel_util::{parse_arguments, do_run, compiler_version};
use mandel_method::*;
fn main() {
// For example run with:
// cargo run --release -- --re1=-2.0 --re2=1.0 --img1=-1.5 --img2=1.5
// --max_iter=2048 --img_size=1024 --num_threads=2
//
// Or just using the default values:
// cargo run --release -- --num_threads=2
//
// Note that the image size must be a power of two
let mandel_config = parse_arguments();
let version = env!("CARGO_PKG_VERSION");
println!("mandel-rust version: {}", version);
println!("Number of repetitive runs: {}", mandel_config.num_of_runs);
println!("Rustc version: {}", compiler_version);
// Get current date and time once and pass it to the individual runs for the image filename.
let tm = now();
let tm = tm.strftime("%Y_%m_%d__%H_%M_%S").unwrap();
let time_now = format!("{}", &tm);
// vec! macro expects usize
let mut image: Vec<u32> = vec![0; (mandel_config.img_size * mandel_config.img_size) as usize];
do_run("serial", &serial, &mandel_config, &mut image, &time_now);
do_run("scoped_thread_pool", &scoped_thread_pool_, &mandel_config, &mut image, &time_now);
// Make sure this is only called once
match rayon::initialize(rayon::Configuration::new().set_num_threads(mandel_config.num_threads as usize)) {
Ok(_) =>
|
,
Err(e) => println!("Rayon error: set number of threads failed: {}", e)
}
do_run("rust_scoped_pool", &rust_scoped_pool, &mandel_config, &mut image, &time_now);
do_run("job_steal", &job_steal, &mandel_config, &mut image, &time_now);
do_run("job_steal_join", &job_steal_join, &mandel_config, &mut image, &time_now);
// do_run("kirk_crossbeam", &kirk_crossbeam, &mandel_config, &mut image, &time_now);
}
|
{
do_run("rayon_join", &rayon_join, &mandel_config, &mut image, &time_now);
do_run("rayon_par_iter", &rayon_par_iter, &mandel_config, &mut image, &time_now);
}
|
conditional_block
|
main.rs
|
// Mandelbrot set in rust
//
// This code shows how to calculate the set in serial and parallel.
// More parallel versions will be added in the future.
//
// Written by Willi Kappler, [email protected]
//
// License: MIT
//
//#![feature(plugin)]
//
//#![plugin(clippy)]
// External crates
extern crate time;
extern crate rayon;
// Internal crates
extern crate mandel_util;
extern crate mandel_method;
// External modules
use time::{now};
// Internal modules
use mandel_util::{parse_arguments, do_run, compiler_version};
use mandel_method::*;
fn main() {
// For example run with:
// cargo run --release -- --re1=-2.0 --re2=1.0 --img1=-1.5 --img2=1.5
// --max_iter=2048 --img_size=1024 --num_threads=2
//
// Or just using the default values:
// cargo run --release -- --num_threads=2
//
// Note that the image size must be a power of two
let mandel_config = parse_arguments();
let version = env!("CARGO_PKG_VERSION");
println!("mandel-rust version: {}", version);
println!("Number of repetitive runs: {}", mandel_config.num_of_runs);
println!("Rustc version: {}", compiler_version);
// Get current date and time once and pass it to the individual runs for the image filename.
let tm = now();
let tm = tm.strftime("%Y_%m_%d__%H_%M_%S").unwrap();
let time_now = format!("{}", &tm);
// vec! macro expects usize
let mut image: Vec<u32> = vec![0; (mandel_config.img_size * mandel_config.img_size) as usize];
do_run("serial", &serial, &mandel_config, &mut image, &time_now);
|
do_run("scoped_thread_pool", &scoped_thread_pool_, &mandel_config, &mut image, &time_now);
// Make sure this is only called once
match rayon::initialize(rayon::Configuration::new().set_num_threads(mandel_config.num_threads as usize)) {
Ok(_) => {
do_run("rayon_join", &rayon_join, &mandel_config, &mut image, &time_now);
do_run("rayon_par_iter", &rayon_par_iter, &mandel_config, &mut image, &time_now);
},
Err(e) => println!("Rayon error: set number of threads failed: {}", e)
}
do_run("rust_scoped_pool", &rust_scoped_pool, &mandel_config, &mut image, &time_now);
do_run("job_steal", &job_steal, &mandel_config, &mut image, &time_now);
do_run("job_steal_join", &job_steal_join, &mandel_config, &mut image, &time_now);
// do_run("kirk_crossbeam", &kirk_crossbeam, &mandel_config, &mut image, &time_now);
}
|
random_line_split
|
|
main.rs
|
// Mandelbrot set in rust
//
// This code shows how to calculate the set in serial and parallel.
// More parallel versions will be added in the future.
//
// Written by Willi Kappler, [email protected]
//
// License: MIT
//
//#![feature(plugin)]
//
//#![plugin(clippy)]
// External crates
extern crate time;
extern crate rayon;
// Internal crates
extern crate mandel_util;
extern crate mandel_method;
// External modules
use time::{now};
// Internal modules
use mandel_util::{parse_arguments, do_run, compiler_version};
use mandel_method::*;
fn main()
|
let tm = tm.strftime("%Y_%m_%d__%H_%M_%S").unwrap();
let time_now = format!("{}", &tm);
// vec! macro expects usize
let mut image: Vec<u32> = vec![0; (mandel_config.img_size * mandel_config.img_size) as usize];
do_run("serial", &serial, &mandel_config, &mut image, &time_now);
do_run("scoped_thread_pool", &scoped_thread_pool_, &mandel_config, &mut image, &time_now);
// Make sure this is only called once
match rayon::initialize(rayon::Configuration::new().set_num_threads(mandel_config.num_threads as usize)) {
Ok(_) => {
do_run("rayon_join", &rayon_join, &mandel_config, &mut image, &time_now);
do_run("rayon_par_iter", &rayon_par_iter, &mandel_config, &mut image, &time_now);
},
Err(e) => println!("Rayon error: set number of threads failed: {}", e)
}
do_run("rust_scoped_pool", &rust_scoped_pool, &mandel_config, &mut image, &time_now);
do_run("job_steal", &job_steal, &mandel_config, &mut image, &time_now);
do_run("job_steal_join", &job_steal_join, &mandel_config, &mut image, &time_now);
// do_run("kirk_crossbeam", &kirk_crossbeam, &mandel_config, &mut image, &time_now);
}
|
{
// For example run with:
// cargo run --release -- --re1=-2.0 --re2=1.0 --img1=-1.5 --img2=1.5
// --max_iter=2048 --img_size=1024 --num_threads=2
//
// Or just using the default values:
// cargo run --release -- --num_threads=2
//
// Note that the image size must be a power of two
let mandel_config = parse_arguments();
let version = env!("CARGO_PKG_VERSION");
println!("mandel-rust version: {}", version);
println!("Number of repetitive runs: {}", mandel_config.num_of_runs);
println!("Rustc version: {}", compiler_version);
// Get current date and time once and pass it to the individual runs for the image filename.
let tm = now();
|
identifier_body
|
lib.rs
|
// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_name="html5ever"]
#![crate_type="dylib"]
#![feature(macro_rules, phase, globs)]
#![deny(warnings)]
#![allow(unnecessary_parens)]
// Don't implicitly pull in things from std::*
// This helps us make a C-friendly library.
#![no_std]
extern crate alloc;
#[phase(plugin, link)]
extern crate core;
#[cfg(not(for_c))]
#[phase(plugin, link)]
extern crate std;
#[cfg(for_c)]
extern crate libc;
#[phase(plugin, link)]
extern crate collections;
#[cfg(not(for_c))]
#[phase(plugin, link)]
extern crate log;
#[phase(plugin, link)]
extern crate debug;
#[phase(plugin)]
extern crate phf_mac;
#[phase(plugin)]
extern crate string_cache_macros;
extern crate string_cache;
#[phase(plugin)]
extern crate html5ever_macros;
// Need #[start] for the test runner.
|
extern crate native;
extern crate phf;
extern crate time;
pub use tokenizer::Attribute;
pub use driver::{one_input, ParseOpts, parse_to, parse};
#[cfg(not(for_c))]
pub use serialize::serialize;
mod macros;
mod util {
#![macro_escape]
pub mod str;
pub mod smallcharset;
}
pub mod tokenizer;
pub mod tree_builder;
#[cfg(not(for_c))]
pub mod serialize;
/// Consumers of the parser API.
#[cfg(not(for_c))]
pub mod sink {
pub mod common;
pub mod rcdom;
pub mod owned_dom;
}
pub mod driver;
#[cfg(for_c)]
pub mod for_c {
pub mod common;
pub mod tokenizer;
}
/// A fake `std` module so that `deriving` and other macros will work.
/// See rust-lang/rust#16803.
#[cfg(for_c)]
mod std {
pub use core::{clone, cmp, default, fmt, option, str};
pub use collections::hash;
}
|
#[cfg(test)]
|
random_line_split
|
issue-13698.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:issue-13698.rs
// ignore-android
extern crate issue_13698;
pub struct Foo;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
|
impl Bar for Foo {}
|
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
|
random_line_split
|
issue-13698.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:issue-13698.rs
// ignore-android
extern crate issue_13698;
pub struct
|
;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {}
|
Foo
|
identifier_name
|
lib.rs
|
//! Data types that represent playing cards.
#![warn(bad_style, missing_docs,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(str_char)]
use std::fmt;
use std::str::FromStr;
use Suit::{Spade, Heart, Dia, Club};
/// Playing card's suite.
#[allow(missing_docs, unused_qualifications)] // FIXME rust-lang/rust#19102
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Suit {
Spade,
Heart,
Dia,
Club
}
impl fmt::Display for Suit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
&Spade => "S",
&Heart => "H",
&Dia => "D",
&Club => "C"
};
write!(f, "{}", s)
}
}
impl FromStr for Suit {
type Err = ();
fn from_str(s: &str) -> Result<Suit, ()> {
if s.len()!= 1 { return Err(()) }
return match s {
"S" => Ok(Spade),
"H" => Ok(Heart),
"D" => Ok(Dia),
"C" => Ok(Club),
_ => Err(())
};
}
}
/// Playing card that only contains suit cards.
#[allow(missing_docs)]
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub struct SuitCard {
pub num: u8,
pub suit: Suit
}
impl fmt::Display for SuitCard {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SuitCard { num: 1, suit: s } => write!(f, "A{}", s),
SuitCard { num: 10, suit: s } => write!(f, "T{}", s),
SuitCard { num: 11, suit: s } => write!(f, "J{}", s),
SuitCard { num: 12, suit: s } => write!(f, "Q{}", s),
SuitCard { num: 13, suit: s } => write!(f, "K{}", s),
SuitCard { num: n, suit: s } => write!(f, "{}{}", n, s)
}
}
}
impl FromStr for SuitCard {
type Err = ();
fn from_str(s: &str) -> Result<SuitCard, ()> {
if s.len()!= 2 { return Err(()) }
let (c0, c1) = s.slice_shift_char().unwrap();
let suit = FromStr::from_str(c1);
let num = match c0 {
'A' => Some(1),
'T' => Some(10),
'J' => Some(11),
'Q' => Some(12),
'K' => Some(13),
d => d.to_digit(10).map(|x| x as u8)
};
if let (Some(n), Ok(s)) = (num, suit) {
Ok(SuitCard { num: n, suit: s })
} else {
Err(())
}
}
}
/// Playing card that also contaiins jokers.
#[allow(missing_docs)]
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Card {
Suit(SuitCard),
BlackJoker,
WhiteJoker
}
|
match *self {
Card::BlackJoker => write!(f, "BJ"),
Card::WhiteJoker => write!(f, "WJ"),
Card::Suit(sc) => write!(f, "{}", sc),
}
}
}
impl FromStr for Card {
type Err = ();
fn from_str(s: &str) -> Result<Card, ()> {
match s {
"BJ" => Ok(Card::BlackJoker),
"WJ" => Ok(Card::WhiteJoker),
_ => FromStr::from_str(s).map(|sc| Card::Suit(sc))
}
}
}
impl Card {
/// Creates new `SuitCard`.
pub fn new(n: u8, s: Suit) -> Card {
Card::Suit(SuitCard { num: n, suit: s })
}
}
#[cfg(test)]
mod tests {
use super::{Suit, Card};
use super::Suit::{Spade, Heart, Dia, Club};
#[test]
fn show_suit() {
fn check_pair(s: String, suite: Suit) {
assert_eq!(s, format!("{}", suite));
assert_eq!(Ok(suite), s.parse());
}
check_pair("S".to_string(), Spade);
check_pair("H".to_string(), Heart);
check_pair("D".to_string(), Dia);
check_pair("C".to_string(), Club);
}
#[test]
fn show_card() {
fn check_pair(s: String, card: Card) {
assert_eq!(s, format!("{}", card));
assert_eq!(Ok(card), s.parse());
}
check_pair("BJ".to_string(), Card::BlackJoker);
check_pair("WJ".to_string(), Card::WhiteJoker);
check_pair("AH".to_string(), Card::new(1, Heart));
check_pair("2C".to_string(), Card::new(2, Club));
check_pair("9D".to_string(), Card::new(9, Dia));
check_pair("TS".to_string(), Card::new(10, Spade));
check_pair("JH".to_string(), Card::new(11, Heart));
check_pair("QC".to_string(), Card::new(12, Club));
check_pair("KD".to_string(), Card::new(13, Dia));
}
}
|
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
random_line_split
|
lib.rs
|
//! Data types that represent playing cards.
#![warn(bad_style, missing_docs,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(str_char)]
use std::fmt;
use std::str::FromStr;
use Suit::{Spade, Heart, Dia, Club};
/// Playing card's suite.
#[allow(missing_docs, unused_qualifications)] // FIXME rust-lang/rust#19102
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Suit {
Spade,
Heart,
Dia,
Club
}
impl fmt::Display for Suit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
&Spade => "S",
&Heart => "H",
&Dia => "D",
&Club => "C"
};
write!(f, "{}", s)
}
}
impl FromStr for Suit {
type Err = ();
fn from_str(s: &str) -> Result<Suit, ()> {
if s.len()!= 1 { return Err(()) }
return match s {
"S" => Ok(Spade),
"H" => Ok(Heart),
"D" => Ok(Dia),
"C" => Ok(Club),
_ => Err(())
};
}
}
/// Playing card that only contains suit cards.
#[allow(missing_docs)]
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub struct SuitCard {
pub num: u8,
pub suit: Suit
}
impl fmt::Display for SuitCard {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SuitCard { num: 1, suit: s } => write!(f, "A{}", s),
SuitCard { num: 10, suit: s } => write!(f, "T{}", s),
SuitCard { num: 11, suit: s } => write!(f, "J{}", s),
SuitCard { num: 12, suit: s } => write!(f, "Q{}", s),
SuitCard { num: 13, suit: s } => write!(f, "K{}", s),
SuitCard { num: n, suit: s } => write!(f, "{}{}", n, s)
}
}
}
impl FromStr for SuitCard {
type Err = ();
fn from_str(s: &str) -> Result<SuitCard, ()> {
if s.len()!= 2 { return Err(()) }
let (c0, c1) = s.slice_shift_char().unwrap();
let suit = FromStr::from_str(c1);
let num = match c0 {
'A' => Some(1),
'T' => Some(10),
'J' => Some(11),
'Q' => Some(12),
'K' => Some(13),
d => d.to_digit(10).map(|x| x as u8)
};
if let (Some(n), Ok(s)) = (num, suit) {
Ok(SuitCard { num: n, suit: s })
} else {
Err(())
}
}
}
/// Playing card that also contaiins jokers.
#[allow(missing_docs)]
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Card {
Suit(SuitCard),
BlackJoker,
WhiteJoker
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Card::BlackJoker => write!(f, "BJ"),
Card::WhiteJoker => write!(f, "WJ"),
Card::Suit(sc) => write!(f, "{}", sc),
}
}
}
impl FromStr for Card {
type Err = ();
fn from_str(s: &str) -> Result<Card, ()> {
match s {
"BJ" => Ok(Card::BlackJoker),
"WJ" => Ok(Card::WhiteJoker),
_ => FromStr::from_str(s).map(|sc| Card::Suit(sc))
}
}
}
impl Card {
/// Creates new `SuitCard`.
pub fn new(n: u8, s: Suit) -> Card {
Card::Suit(SuitCard { num: n, suit: s })
}
}
#[cfg(test)]
mod tests {
use super::{Suit, Card};
use super::Suit::{Spade, Heart, Dia, Club};
#[test]
fn show_suit() {
fn check_pair(s: String, suite: Suit)
|
check_pair("S".to_string(), Spade);
check_pair("H".to_string(), Heart);
check_pair("D".to_string(), Dia);
check_pair("C".to_string(), Club);
}
#[test]
fn show_card() {
fn check_pair(s: String, card: Card) {
assert_eq!(s, format!("{}", card));
assert_eq!(Ok(card), s.parse());
}
check_pair("BJ".to_string(), Card::BlackJoker);
check_pair("WJ".to_string(), Card::WhiteJoker);
check_pair("AH".to_string(), Card::new(1, Heart));
check_pair("2C".to_string(), Card::new(2, Club));
check_pair("9D".to_string(), Card::new(9, Dia));
check_pair("TS".to_string(), Card::new(10, Spade));
check_pair("JH".to_string(), Card::new(11, Heart));
check_pair("QC".to_string(), Card::new(12, Club));
check_pair("KD".to_string(), Card::new(13, Dia));
}
}
|
{
assert_eq!(s, format!("{}", suite));
assert_eq!(Ok(suite), s.parse());
}
|
identifier_body
|
lib.rs
|
//! Data types that represent playing cards.
#![warn(bad_style, missing_docs,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(str_char)]
use std::fmt;
use std::str::FromStr;
use Suit::{Spade, Heart, Dia, Club};
/// Playing card's suite.
#[allow(missing_docs, unused_qualifications)] // FIXME rust-lang/rust#19102
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Suit {
Spade,
Heart,
Dia,
Club
}
impl fmt::Display for Suit {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
&Spade => "S",
&Heart => "H",
&Dia => "D",
&Club => "C"
};
write!(f, "{}", s)
}
}
impl FromStr for Suit {
type Err = ();
fn from_str(s: &str) -> Result<Suit, ()> {
if s.len()!= 1 { return Err(()) }
return match s {
"S" => Ok(Spade),
"H" => Ok(Heart),
"D" => Ok(Dia),
"C" => Ok(Club),
_ => Err(())
};
}
}
/// Playing card that only contains suit cards.
#[allow(missing_docs)]
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub struct SuitCard {
pub num: u8,
pub suit: Suit
}
impl fmt::Display for SuitCard {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SuitCard { num: 1, suit: s } => write!(f, "A{}", s),
SuitCard { num: 10, suit: s } => write!(f, "T{}", s),
SuitCard { num: 11, suit: s } => write!(f, "J{}", s),
SuitCard { num: 12, suit: s } => write!(f, "Q{}", s),
SuitCard { num: 13, suit: s } => write!(f, "K{}", s),
SuitCard { num: n, suit: s } => write!(f, "{}{}", n, s)
}
}
}
impl FromStr for SuitCard {
type Err = ();
fn from_str(s: &str) -> Result<SuitCard, ()> {
if s.len()!= 2 { return Err(()) }
let (c0, c1) = s.slice_shift_char().unwrap();
let suit = FromStr::from_str(c1);
let num = match c0 {
'A' => Some(1),
'T' => Some(10),
'J' => Some(11),
'Q' => Some(12),
'K' => Some(13),
d => d.to_digit(10).map(|x| x as u8)
};
if let (Some(n), Ok(s)) = (num, suit) {
Ok(SuitCard { num: n, suit: s })
} else {
Err(())
}
}
}
/// Playing card that also contaiins jokers.
#[allow(missing_docs)]
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Card {
Suit(SuitCard),
BlackJoker,
WhiteJoker
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Card::BlackJoker => write!(f, "BJ"),
Card::WhiteJoker => write!(f, "WJ"),
Card::Suit(sc) => write!(f, "{}", sc),
}
}
}
impl FromStr for Card {
type Err = ();
fn from_str(s: &str) -> Result<Card, ()> {
match s {
"BJ" => Ok(Card::BlackJoker),
"WJ" => Ok(Card::WhiteJoker),
_ => FromStr::from_str(s).map(|sc| Card::Suit(sc))
}
}
}
impl Card {
/// Creates new `SuitCard`.
pub fn new(n: u8, s: Suit) -> Card {
Card::Suit(SuitCard { num: n, suit: s })
}
}
#[cfg(test)]
mod tests {
use super::{Suit, Card};
use super::Suit::{Spade, Heart, Dia, Club};
#[test]
fn show_suit() {
fn check_pair(s: String, suite: Suit) {
assert_eq!(s, format!("{}", suite));
assert_eq!(Ok(suite), s.parse());
}
check_pair("S".to_string(), Spade);
check_pair("H".to_string(), Heart);
check_pair("D".to_string(), Dia);
check_pair("C".to_string(), Club);
}
#[test]
fn show_card() {
fn check_pair(s: String, card: Card) {
assert_eq!(s, format!("{}", card));
assert_eq!(Ok(card), s.parse());
}
check_pair("BJ".to_string(), Card::BlackJoker);
check_pair("WJ".to_string(), Card::WhiteJoker);
check_pair("AH".to_string(), Card::new(1, Heart));
check_pair("2C".to_string(), Card::new(2, Club));
check_pair("9D".to_string(), Card::new(9, Dia));
check_pair("TS".to_string(), Card::new(10, Spade));
check_pair("JH".to_string(), Card::new(11, Heart));
check_pair("QC".to_string(), Card::new(12, Club));
check_pair("KD".to_string(), Card::new(13, Dia));
}
}
|
fmt
|
identifier_name
|
active.rs
|
//! Active (fully-registered) client connection handling
use irc;
use irc::driver::Client;
use irc::send::Sender;
use world::World;
/// An active client
pub struct Active {
world: World,
_out: Sender,
nick: String,
}
impl Active {
/// Creates a new `Active`
pub fn new(world: World, out: Sender, nick: String) -> Active {
Active { world: world, _out: out, nick: nick }
}
pub fn handle(self, m: irc::Message) -> irc::Op<Client> {
self.handle_easy(m).map(Client::Active)
}
fn handle_easy(mut self, m: irc::Message) -> irc::Op<Active> {
debug!(" -> {:?}", m);
match &m.verb[..] {
b"JOIN" => {
let chan = "#foo".to_string();
let op = self.world.join_user(chan, self.nick.clone());
irc::Op::crdb(op, self)
},
b"PART" => {
let chan = "#foo".to_string();
let op = self.world.part_user(chan, self.nick.clone());
irc::Op::crdb(op, self)
},
b"PRIVMSG" =>
|
,
_ => {
irc::Op::ok(self)
}
}
}
}
|
{
let chan = "#foo".to_string();
let message = "hello".to_string();
let op = self.world.message(chan, self.nick.clone(), message);
irc::Op::observe(op, self)
}
|
conditional_block
|
active.rs
|
//! Active (fully-registered) client connection handling
use irc;
use irc::driver::Client;
use irc::send::Sender;
use world::World;
/// An active client
pub struct Active {
world: World,
_out: Sender,
nick: String,
}
impl Active {
/// Creates a new `Active`
pub fn new(world: World, out: Sender, nick: String) -> Active {
Active { world: world, _out: out, nick: nick }
}
pub fn
|
(self, m: irc::Message) -> irc::Op<Client> {
self.handle_easy(m).map(Client::Active)
}
fn handle_easy(mut self, m: irc::Message) -> irc::Op<Active> {
debug!(" -> {:?}", m);
match &m.verb[..] {
b"JOIN" => {
let chan = "#foo".to_string();
let op = self.world.join_user(chan, self.nick.clone());
irc::Op::crdb(op, self)
},
b"PART" => {
let chan = "#foo".to_string();
let op = self.world.part_user(chan, self.nick.clone());
irc::Op::crdb(op, self)
},
b"PRIVMSG" => {
let chan = "#foo".to_string();
let message = "hello".to_string();
let op = self.world.message(chan, self.nick.clone(), message);
irc::Op::observe(op, self)
},
_ => {
irc::Op::ok(self)
}
}
}
}
|
handle
|
identifier_name
|
active.rs
|
//! Active (fully-registered) client connection handling
|
use irc::send::Sender;
use world::World;
/// An active client
pub struct Active {
world: World,
_out: Sender,
nick: String,
}
impl Active {
/// Creates a new `Active`
pub fn new(world: World, out: Sender, nick: String) -> Active {
Active { world: world, _out: out, nick: nick }
}
pub fn handle(self, m: irc::Message) -> irc::Op<Client> {
self.handle_easy(m).map(Client::Active)
}
fn handle_easy(mut self, m: irc::Message) -> irc::Op<Active> {
debug!(" -> {:?}", m);
match &m.verb[..] {
b"JOIN" => {
let chan = "#foo".to_string();
let op = self.world.join_user(chan, self.nick.clone());
irc::Op::crdb(op, self)
},
b"PART" => {
let chan = "#foo".to_string();
let op = self.world.part_user(chan, self.nick.clone());
irc::Op::crdb(op, self)
},
b"PRIVMSG" => {
let chan = "#foo".to_string();
let message = "hello".to_string();
let op = self.world.message(chan, self.nick.clone(), message);
irc::Op::observe(op, self)
},
_ => {
irc::Op::ok(self)
}
}
}
}
|
use irc;
use irc::driver::Client;
|
random_line_split
|
cursor.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use glutin::{Event, ElementState, MouseCursor};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn
|
() {
let window = glutin::WindowBuilder::new().with_gl_profile(glutin::GlProfile::Compatibility).build().unwrap();
window.set_title("A fantastic window!");
unsafe { window.make_current() };
let context = support::load(&window);
let cursors = [MouseCursor::Default, MouseCursor::Crosshair, MouseCursor::Hand, MouseCursor::Arrow, MouseCursor::Move, MouseCursor::Text, MouseCursor::Wait, MouseCursor::Help, MouseCursor::Progress, MouseCursor::NotAllowed, MouseCursor::ContextMenu, MouseCursor::NoneCursor, MouseCursor::Cell, MouseCursor::VerticalText, MouseCursor::Alias, MouseCursor::Copy, MouseCursor::NoDrop, MouseCursor::Grab, MouseCursor::Grabbing, MouseCursor::AllScroll, MouseCursor::ZoomIn, MouseCursor::ZoomOut, MouseCursor::EResize, MouseCursor::NResize, MouseCursor::NeResize, MouseCursor::NwResize, MouseCursor::SResize, MouseCursor::SeResize, MouseCursor::SwResize, MouseCursor::WResize, MouseCursor::EwResize, MouseCursor::NsResize, MouseCursor::NeswResize, MouseCursor::NwseResize, MouseCursor::ColResize, MouseCursor::RowResize];
let mut cursor_idx = 0;
for event in window.wait_events() {
match event {
Event::KeyboardInput(ElementState::Pressed, _, _) => {
println!("Setting cursor to \"{:?}\"", cursors[cursor_idx]);
window.set_cursor(cursors[cursor_idx]);
if cursor_idx < cursors.len() - 1 {
cursor_idx += 1;
} else {
cursor_idx = 0;
}
},
Event::Closed => break,
_ => (),
}
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
}
}
|
main
|
identifier_name
|
cursor.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use glutin::{Event, ElementState, MouseCursor};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main() {
let window = glutin::WindowBuilder::new().with_gl_profile(glutin::GlProfile::Compatibility).build().unwrap();
window.set_title("A fantastic window!");
unsafe { window.make_current() };
let context = support::load(&window);
let cursors = [MouseCursor::Default, MouseCursor::Crosshair, MouseCursor::Hand, MouseCursor::Arrow, MouseCursor::Move, MouseCursor::Text, MouseCursor::Wait, MouseCursor::Help, MouseCursor::Progress, MouseCursor::NotAllowed, MouseCursor::ContextMenu, MouseCursor::NoneCursor, MouseCursor::Cell, MouseCursor::VerticalText, MouseCursor::Alias, MouseCursor::Copy, MouseCursor::NoDrop, MouseCursor::Grab, MouseCursor::Grabbing, MouseCursor::AllScroll, MouseCursor::ZoomIn, MouseCursor::ZoomOut, MouseCursor::EResize, MouseCursor::NResize, MouseCursor::NeResize, MouseCursor::NwResize, MouseCursor::SResize, MouseCursor::SeResize, MouseCursor::SwResize, MouseCursor::WResize, MouseCursor::EwResize, MouseCursor::NsResize, MouseCursor::NeswResize, MouseCursor::NwseResize, MouseCursor::ColResize, MouseCursor::RowResize];
|
match event {
Event::KeyboardInput(ElementState::Pressed, _, _) => {
println!("Setting cursor to \"{:?}\"", cursors[cursor_idx]);
window.set_cursor(cursors[cursor_idx]);
if cursor_idx < cursors.len() - 1 {
cursor_idx += 1;
} else {
cursor_idx = 0;
}
},
Event::Closed => break,
_ => (),
}
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
}
}
|
let mut cursor_idx = 0;
for event in window.wait_events() {
|
random_line_split
|
cursor.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use glutin::{Event, ElementState, MouseCursor};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main()
|
},
Event::Closed => break,
_ => (),
}
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
}
}
|
{
let window = glutin::WindowBuilder::new().with_gl_profile(glutin::GlProfile::Compatibility).build().unwrap();
window.set_title("A fantastic window!");
unsafe { window.make_current() };
let context = support::load(&window);
let cursors = [MouseCursor::Default, MouseCursor::Crosshair, MouseCursor::Hand, MouseCursor::Arrow, MouseCursor::Move, MouseCursor::Text, MouseCursor::Wait, MouseCursor::Help, MouseCursor::Progress, MouseCursor::NotAllowed, MouseCursor::ContextMenu, MouseCursor::NoneCursor, MouseCursor::Cell, MouseCursor::VerticalText, MouseCursor::Alias, MouseCursor::Copy, MouseCursor::NoDrop, MouseCursor::Grab, MouseCursor::Grabbing, MouseCursor::AllScroll, MouseCursor::ZoomIn, MouseCursor::ZoomOut, MouseCursor::EResize, MouseCursor::NResize, MouseCursor::NeResize, MouseCursor::NwResize, MouseCursor::SResize, MouseCursor::SeResize, MouseCursor::SwResize, MouseCursor::WResize, MouseCursor::EwResize, MouseCursor::NsResize, MouseCursor::NeswResize, MouseCursor::NwseResize, MouseCursor::ColResize, MouseCursor::RowResize];
let mut cursor_idx = 0;
for event in window.wait_events() {
match event {
Event::KeyboardInput(ElementState::Pressed, _, _) => {
println!("Setting cursor to \"{:?}\"", cursors[cursor_idx]);
window.set_cursor(cursors[cursor_idx]);
if cursor_idx < cursors.len() - 1 {
cursor_idx += 1;
} else {
cursor_idx = 0;
}
|
identifier_body
|
webgluniformlocation.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::utils::{Reflector,reflect_dom_object};
#[dom_struct]
#[derive(HeapSizeOf)]
|
impl WebGLUniformLocation {
fn new_inherited(id: i32) -> WebGLUniformLocation {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
}
}
pub fn new(global: GlobalRef, id: i32) -> Root<WebGLUniformLocation> {
reflect_dom_object(box WebGLUniformLocation::new_inherited(id), global, WebGLUniformLocationBinding::Wrap)
}
}
pub trait WebGLUniformLocationHelpers {
fn id(self) -> i32;
}
impl<'a> WebGLUniformLocationHelpers for &'a WebGLUniformLocation {
fn id(self) -> i32 {
self.id
}
}
|
pub struct WebGLUniformLocation {
reflector_: Reflector,
id: i32,
}
|
random_line_split
|
webgluniformlocation.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::utils::{Reflector,reflect_dom_object};
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct WebGLUniformLocation {
reflector_: Reflector,
id: i32,
}
impl WebGLUniformLocation {
fn
|
(id: i32) -> WebGLUniformLocation {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
}
}
pub fn new(global: GlobalRef, id: i32) -> Root<WebGLUniformLocation> {
reflect_dom_object(box WebGLUniformLocation::new_inherited(id), global, WebGLUniformLocationBinding::Wrap)
}
}
pub trait WebGLUniformLocationHelpers {
fn id(self) -> i32;
}
impl<'a> WebGLUniformLocationHelpers for &'a WebGLUniformLocation {
fn id(self) -> i32 {
self.id
}
}
|
new_inherited
|
identifier_name
|
cssmediarule.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::cssconditionrule::CSSConditionRule;
use dom::cssrule::SpecificCSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::medialist::MediaList;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::media_queries::parse_media_query_list;
use style::stylesheets::MediaRule;
use style_traits::ToCss;
#[dom_struct]
pub struct CSSMediaRule {
cssrule: CSSConditionRule,
#[ignore_heap_size_of = "Arc"]
mediarule: Arc<RwLock<MediaRule>>,
medialist: MutNullableJS<MediaList>,
}
impl CSSMediaRule {
fn new_inherited(parent_stylesheet: &CSSStyleSheet, mediarule: Arc<RwLock<MediaRule>>)
-> CSSMediaRule {
let list = mediarule.read().rules.clone();
CSSMediaRule {
cssrule: CSSConditionRule::new_inherited(parent_stylesheet, list),
mediarule: mediarule,
medialist: MutNullableJS::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
mediarule: Arc<RwLock<MediaRule>>) -> Root<CSSMediaRule> {
reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule),
window,
CSSMediaRuleBinding::Wrap)
}
fn medialist(&self) -> Root<MediaList> {
self.medialist.or_init(|| MediaList::new(self.global().as_window(),
self.mediarule.read().media_queries.clone()))
}
/// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
pub fn get_condition_text(&self) -> DOMString {
let rule = self.mediarule.read();
let list = rule.media_queries.read();
list.to_css_string().into()
}
/// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
pub fn set_condition_text(&self, text: DOMString) {
let mut input = Parser::new(&text);
let new_medialist = parse_media_query_list(&mut input);
let rule = self.mediarule.read();
let mut list = rule.media_queries.write();
*list = new_medialist;
}
}
impl SpecificCSSRule for CSSMediaRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::MEDIA_RULE
}
fn get_css(&self) -> DOMString {
self.mediarule.read().to_css_string().into()
}
}
impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
fn
|
(&self) -> Root<MediaList> {
self.medialist()
}
}
|
Media
|
identifier_name
|
cssmediarule.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::cssconditionrule::CSSConditionRule;
use dom::cssrule::SpecificCSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::medialist::MediaList;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::media_queries::parse_media_query_list;
use style::stylesheets::MediaRule;
use style_traits::ToCss;
#[dom_struct]
pub struct CSSMediaRule {
cssrule: CSSConditionRule,
#[ignore_heap_size_of = "Arc"]
mediarule: Arc<RwLock<MediaRule>>,
medialist: MutNullableJS<MediaList>,
}
impl CSSMediaRule {
fn new_inherited(parent_stylesheet: &CSSStyleSheet, mediarule: Arc<RwLock<MediaRule>>)
-> CSSMediaRule {
let list = mediarule.read().rules.clone();
CSSMediaRule {
cssrule: CSSConditionRule::new_inherited(parent_stylesheet, list),
mediarule: mediarule,
medialist: MutNullableJS::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
mediarule: Arc<RwLock<MediaRule>>) -> Root<CSSMediaRule> {
reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule),
window,
CSSMediaRuleBinding::Wrap)
}
fn medialist(&self) -> Root<MediaList> {
self.medialist.or_init(|| MediaList::new(self.global().as_window(),
self.mediarule.read().media_queries.clone()))
}
/// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
pub fn get_condition_text(&self) -> DOMString {
let rule = self.mediarule.read();
let list = rule.media_queries.read();
list.to_css_string().into()
}
/// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
pub fn set_condition_text(&self, text: DOMString) {
let mut input = Parser::new(&text);
let new_medialist = parse_media_query_list(&mut input);
let rule = self.mediarule.read();
let mut list = rule.media_queries.write();
*list = new_medialist;
}
}
impl SpecificCSSRule for CSSMediaRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::MEDIA_RULE
}
fn get_css(&self) -> DOMString {
self.mediarule.read().to_css_string().into()
|
fn Media(&self) -> Root<MediaList> {
self.medialist()
}
}
|
}
}
impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
|
random_line_split
|
cssmediarule.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::cssconditionrule::CSSConditionRule;
use dom::cssrule::SpecificCSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::medialist::MediaList;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::media_queries::parse_media_query_list;
use style::stylesheets::MediaRule;
use style_traits::ToCss;
#[dom_struct]
pub struct CSSMediaRule {
cssrule: CSSConditionRule,
#[ignore_heap_size_of = "Arc"]
mediarule: Arc<RwLock<MediaRule>>,
medialist: MutNullableJS<MediaList>,
}
impl CSSMediaRule {
fn new_inherited(parent_stylesheet: &CSSStyleSheet, mediarule: Arc<RwLock<MediaRule>>)
-> CSSMediaRule {
let list = mediarule.read().rules.clone();
CSSMediaRule {
cssrule: CSSConditionRule::new_inherited(parent_stylesheet, list),
mediarule: mediarule,
medialist: MutNullableJS::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
mediarule: Arc<RwLock<MediaRule>>) -> Root<CSSMediaRule> {
reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule),
window,
CSSMediaRuleBinding::Wrap)
}
fn medialist(&self) -> Root<MediaList> {
self.medialist.or_init(|| MediaList::new(self.global().as_window(),
self.mediarule.read().media_queries.clone()))
}
/// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
pub fn get_condition_text(&self) -> DOMString {
let rule = self.mediarule.read();
let list = rule.media_queries.read();
list.to_css_string().into()
}
/// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
pub fn set_condition_text(&self, text: DOMString) {
let mut input = Parser::new(&text);
let new_medialist = parse_media_query_list(&mut input);
let rule = self.mediarule.read();
let mut list = rule.media_queries.write();
*list = new_medialist;
}
}
impl SpecificCSSRule for CSSMediaRule {
fn ty(&self) -> u16
|
fn get_css(&self) -> DOMString {
self.mediarule.read().to_css_string().into()
}
}
impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
fn Media(&self) -> Root<MediaList> {
self.medialist()
}
}
|
{
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::MEDIA_RULE
}
|
identifier_body
|
local_ptr.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.
//! Access to a single thread-local pointer.
//!
//! The runtime will use this for storing ~Task.
//!
//! XXX: Add runtime checks for usage of inconsistent pointer types.
//! and for overwriting an existing pointer.
#[allow(dead_code)];
use cast;
use ops::Drop;
use ptr::RawPtr;
#[cfg(windows)] // mingw-w32 doesn't like thread_local things
#[cfg(target_os = "android")] // see #10686
pub use self::native::*;
#[cfg(not(windows), not(target_os = "android"))]
pub use self::compiled::*;
/// Encapsulates a borrowed value. When this value goes out of scope, the
/// pointer is returned.
pub struct Borrowed<T> {
priv val: *(),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: ~T = cast::transmute(self.val);
put::<T>(val);
rtassert!(exists());
}
}
}
impl<T> Borrowed<T> {
pub fn get<'a>(&'a mut self) -> &'a mut T {
unsafe {
let val_ptr: &mut ~T = cast::transmute(&mut self.val);
let val_ptr: &'a mut T = *val_ptr;
val_ptr
}
}
}
/// Borrow the thread-local value from thread-local storage.
/// While the value is borrowed it is not available in TLS.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn borrow<T>() -> Borrowed<T> {
let val: *() = cast::transmute(take::<T>());
Borrowed {
val: val,
}
}
/// Compiled implementation of accessing the runtime local pointer. This is
/// implemented using LLVM's thread_local attribute which isn't necessarily
/// working on all platforms. This implementation is faster, however, so we use
/// it wherever possible.
#[cfg(not(windows), not(target_os = "android"))]
pub mod compiled {
use cast;
use option::{Option, Some, None};
use ptr::RawPtr;
#[cfg(not(test))] use libc::c_void;
#[cfg(test)]
pub use realstd::rt::shouldnt_be_public::RT_TLS_PTR;
#[cfg(not(test))]
#[thread_local]
pub static mut RT_TLS_PTR: *mut c_void = 0 as *mut c_void;
pub fn init() {}
pub unsafe fn cleanup() {}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: ~T)
|
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> ~T {
let ptr = RT_TLS_PTR;
rtassert!(!ptr.is_null());
let ptr: ~T = cast::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = cast::transmute(0);
ptr
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<~T> {
let ptr = RT_TLS_PTR;
if ptr.is_null() {
None
} else {
let ptr: ~T = cast::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = cast::transmute(0);
Some(ptr)
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> ~T {
cast::transmute(RT_TLS_PTR)
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
RT_TLS_PTR.is_not_null()
}
}
pub unsafe fn unsafe_borrow<T>() -> *mut T {
if RT_TLS_PTR.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
RT_TLS_PTR as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
if RT_TLS_PTR.is_null() {
None
} else {
Some(RT_TLS_PTR as *mut T)
}
}
}
/// Native implementation of having the runtime thread-local pointer. This
/// implementation uses the `thread_local_storage` module to provide a
/// thread-local value.
pub mod native {
use cast;
use libc::c_void;
use option::{Option, Some, None};
use ptr;
use ptr::RawPtr;
use tls = rt::thread_local_storage;
static mut RT_TLS_KEY: tls::Key = -1;
/// Initialize the TLS key. Other ops will fail if this isn't executed
/// first.
pub fn init() {
unsafe {
tls::create(&mut RT_TLS_KEY);
}
}
pub unsafe fn cleanup() {
rtassert!(RT_TLS_KEY!= -1);
tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: ~T) {
let key = tls_key();
let void_ptr: *mut c_void = cast::transmute(sched);
tls::set(key, void_ptr);
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> ~T {
let key = tls_key();
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: ~T = cast::transmute(void_ptr);
tls::set(key, ptr::mut_null());
return ptr;
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<~T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
None
} else {
let ptr: ~T = cast::transmute(void_ptr);
tls::set(key, ptr::mut_null());
Some(ptr)
}
}
None => None
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> ~T {
let key = tls_key();
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: ~T = cast::transmute(void_ptr);
return ptr;
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
match maybe_tls_key() {
Some(key) => tls::get(key).is_not_null(),
None => false
}
}
}
/// Borrow a mutable reference to the thread-local value
///
/// # Safety Note
///
/// Because this leaves the value in thread-local storage it is possible
/// For the Scheduler pointer to be aliased
pub unsafe fn unsafe_borrow<T>() -> *mut T {
let key = tls_key();
let void_ptr = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
void_ptr as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null() {
None
} else {
Some(void_ptr as *mut T)
}
}
None => None
}
}
#[inline]
fn tls_key() -> tls::Key {
match maybe_tls_key() {
Some(key) => key,
None => rtabort!("runtime tls key not initialized")
}
}
#[inline]
#[cfg(not(test))]
pub fn maybe_tls_key() -> Option<tls::Key> {
unsafe {
// NB: This is a little racy because, while the key is
// initalized under a mutex and it's assumed to be initalized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Threads that
// are not using the new Scheduler but still *want to check*
// whether they are running under a new Scheduler may see a 0
// value here that is in the process of being initialized in
// another thread. I think this is fine since the only action
// they could take if it was initialized would be to check the
// thread-local value and see that it's not set.
if RT_TLS_KEY!= -1 {
return Some(RT_TLS_KEY);
} else {
return None;
}
}
}
#[inline] #[cfg(test)]
pub fn maybe_tls_key() -> Option<tls::Key> {
use realstd;
unsafe {
cast::transmute(realstd::rt::shouldnt_be_public::maybe_tls_key())
}
}
}
|
{
RT_TLS_PTR = cast::transmute(sched)
}
|
identifier_body
|
local_ptr.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.
//! Access to a single thread-local pointer.
//!
//! The runtime will use this for storing ~Task.
//!
//! XXX: Add runtime checks for usage of inconsistent pointer types.
//! and for overwriting an existing pointer.
#[allow(dead_code)];
use cast;
use ops::Drop;
use ptr::RawPtr;
#[cfg(windows)] // mingw-w32 doesn't like thread_local things
#[cfg(target_os = "android")] // see #10686
pub use self::native::*;
#[cfg(not(windows), not(target_os = "android"))]
pub use self::compiled::*;
/// Encapsulates a borrowed value. When this value goes out of scope, the
/// pointer is returned.
pub struct Borrowed<T> {
priv val: *(),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: ~T = cast::transmute(self.val);
put::<T>(val);
rtassert!(exists());
}
}
}
impl<T> Borrowed<T> {
pub fn
|
<'a>(&'a mut self) -> &'a mut T {
unsafe {
let val_ptr: &mut ~T = cast::transmute(&mut self.val);
let val_ptr: &'a mut T = *val_ptr;
val_ptr
}
}
}
/// Borrow the thread-local value from thread-local storage.
/// While the value is borrowed it is not available in TLS.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn borrow<T>() -> Borrowed<T> {
let val: *() = cast::transmute(take::<T>());
Borrowed {
val: val,
}
}
/// Compiled implementation of accessing the runtime local pointer. This is
/// implemented using LLVM's thread_local attribute which isn't necessarily
/// working on all platforms. This implementation is faster, however, so we use
/// it wherever possible.
#[cfg(not(windows), not(target_os = "android"))]
pub mod compiled {
use cast;
use option::{Option, Some, None};
use ptr::RawPtr;
#[cfg(not(test))] use libc::c_void;
#[cfg(test)]
pub use realstd::rt::shouldnt_be_public::RT_TLS_PTR;
#[cfg(not(test))]
#[thread_local]
pub static mut RT_TLS_PTR: *mut c_void = 0 as *mut c_void;
pub fn init() {}
pub unsafe fn cleanup() {}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: ~T) {
RT_TLS_PTR = cast::transmute(sched)
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> ~T {
let ptr = RT_TLS_PTR;
rtassert!(!ptr.is_null());
let ptr: ~T = cast::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = cast::transmute(0);
ptr
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<~T> {
let ptr = RT_TLS_PTR;
if ptr.is_null() {
None
} else {
let ptr: ~T = cast::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = cast::transmute(0);
Some(ptr)
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> ~T {
cast::transmute(RT_TLS_PTR)
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
RT_TLS_PTR.is_not_null()
}
}
pub unsafe fn unsafe_borrow<T>() -> *mut T {
if RT_TLS_PTR.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
RT_TLS_PTR as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
if RT_TLS_PTR.is_null() {
None
} else {
Some(RT_TLS_PTR as *mut T)
}
}
}
/// Native implementation of having the runtime thread-local pointer. This
/// implementation uses the `thread_local_storage` module to provide a
/// thread-local value.
pub mod native {
use cast;
use libc::c_void;
use option::{Option, Some, None};
use ptr;
use ptr::RawPtr;
use tls = rt::thread_local_storage;
static mut RT_TLS_KEY: tls::Key = -1;
/// Initialize the TLS key. Other ops will fail if this isn't executed
/// first.
pub fn init() {
unsafe {
tls::create(&mut RT_TLS_KEY);
}
}
pub unsafe fn cleanup() {
rtassert!(RT_TLS_KEY!= -1);
tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: ~T) {
let key = tls_key();
let void_ptr: *mut c_void = cast::transmute(sched);
tls::set(key, void_ptr);
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> ~T {
let key = tls_key();
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: ~T = cast::transmute(void_ptr);
tls::set(key, ptr::mut_null());
return ptr;
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<~T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
None
} else {
let ptr: ~T = cast::transmute(void_ptr);
tls::set(key, ptr::mut_null());
Some(ptr)
}
}
None => None
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> ~T {
let key = tls_key();
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: ~T = cast::transmute(void_ptr);
return ptr;
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
match maybe_tls_key() {
Some(key) => tls::get(key).is_not_null(),
None => false
}
}
}
/// Borrow a mutable reference to the thread-local value
///
/// # Safety Note
///
/// Because this leaves the value in thread-local storage it is possible
/// For the Scheduler pointer to be aliased
pub unsafe fn unsafe_borrow<T>() -> *mut T {
let key = tls_key();
let void_ptr = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
void_ptr as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null() {
None
} else {
Some(void_ptr as *mut T)
}
}
None => None
}
}
#[inline]
fn tls_key() -> tls::Key {
match maybe_tls_key() {
Some(key) => key,
None => rtabort!("runtime tls key not initialized")
}
}
#[inline]
#[cfg(not(test))]
pub fn maybe_tls_key() -> Option<tls::Key> {
unsafe {
// NB: This is a little racy because, while the key is
// initalized under a mutex and it's assumed to be initalized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Threads that
// are not using the new Scheduler but still *want to check*
// whether they are running under a new Scheduler may see a 0
// value here that is in the process of being initialized in
// another thread. I think this is fine since the only action
// they could take if it was initialized would be to check the
// thread-local value and see that it's not set.
if RT_TLS_KEY!= -1 {
return Some(RT_TLS_KEY);
} else {
return None;
}
}
}
#[inline] #[cfg(test)]
pub fn maybe_tls_key() -> Option<tls::Key> {
use realstd;
unsafe {
cast::transmute(realstd::rt::shouldnt_be_public::maybe_tls_key())
}
}
}
|
get
|
identifier_name
|
local_ptr.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.
//! Access to a single thread-local pointer.
//!
//! The runtime will use this for storing ~Task.
//!
//! XXX: Add runtime checks for usage of inconsistent pointer types.
//! and for overwriting an existing pointer.
#[allow(dead_code)];
use cast;
use ops::Drop;
use ptr::RawPtr;
#[cfg(windows)] // mingw-w32 doesn't like thread_local things
#[cfg(target_os = "android")] // see #10686
pub use self::native::*;
#[cfg(not(windows), not(target_os = "android"))]
pub use self::compiled::*;
/// Encapsulates a borrowed value. When this value goes out of scope, the
/// pointer is returned.
pub struct Borrowed<T> {
priv val: *(),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: ~T = cast::transmute(self.val);
put::<T>(val);
rtassert!(exists());
}
}
}
impl<T> Borrowed<T> {
pub fn get<'a>(&'a mut self) -> &'a mut T {
unsafe {
let val_ptr: &mut ~T = cast::transmute(&mut self.val);
let val_ptr: &'a mut T = *val_ptr;
val_ptr
}
}
}
/// Borrow the thread-local value from thread-local storage.
/// While the value is borrowed it is not available in TLS.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn borrow<T>() -> Borrowed<T> {
let val: *() = cast::transmute(take::<T>());
Borrowed {
val: val,
}
}
/// Compiled implementation of accessing the runtime local pointer. This is
/// implemented using LLVM's thread_local attribute which isn't necessarily
/// working on all platforms. This implementation is faster, however, so we use
/// it wherever possible.
#[cfg(not(windows), not(target_os = "android"))]
pub mod compiled {
use cast;
use option::{Option, Some, None};
use ptr::RawPtr;
#[cfg(not(test))] use libc::c_void;
#[cfg(test)]
pub use realstd::rt::shouldnt_be_public::RT_TLS_PTR;
#[cfg(not(test))]
#[thread_local]
pub static mut RT_TLS_PTR: *mut c_void = 0 as *mut c_void;
pub fn init() {}
pub unsafe fn cleanup() {}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: ~T) {
RT_TLS_PTR = cast::transmute(sched)
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> ~T {
let ptr = RT_TLS_PTR;
rtassert!(!ptr.is_null());
let ptr: ~T = cast::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = cast::transmute(0);
ptr
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<~T> {
let ptr = RT_TLS_PTR;
if ptr.is_null() {
None
} else {
let ptr: ~T = cast::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = cast::transmute(0);
Some(ptr)
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> ~T {
cast::transmute(RT_TLS_PTR)
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
RT_TLS_PTR.is_not_null()
}
}
pub unsafe fn unsafe_borrow<T>() -> *mut T {
if RT_TLS_PTR.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
RT_TLS_PTR as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
if RT_TLS_PTR.is_null() {
None
|
} else {
Some(RT_TLS_PTR as *mut T)
}
}
}
/// Native implementation of having the runtime thread-local pointer. This
/// implementation uses the `thread_local_storage` module to provide a
/// thread-local value.
pub mod native {
use cast;
use libc::c_void;
use option::{Option, Some, None};
use ptr;
use ptr::RawPtr;
use tls = rt::thread_local_storage;
static mut RT_TLS_KEY: tls::Key = -1;
/// Initialize the TLS key. Other ops will fail if this isn't executed
/// first.
pub fn init() {
unsafe {
tls::create(&mut RT_TLS_KEY);
}
}
pub unsafe fn cleanup() {
rtassert!(RT_TLS_KEY!= -1);
tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: ~T) {
let key = tls_key();
let void_ptr: *mut c_void = cast::transmute(sched);
tls::set(key, void_ptr);
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> ~T {
let key = tls_key();
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: ~T = cast::transmute(void_ptr);
tls::set(key, ptr::mut_null());
return ptr;
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<~T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
None
} else {
let ptr: ~T = cast::transmute(void_ptr);
tls::set(key, ptr::mut_null());
Some(ptr)
}
}
None => None
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> ~T {
let key = tls_key();
let void_ptr: *mut c_void = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: ~T = cast::transmute(void_ptr);
return ptr;
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
match maybe_tls_key() {
Some(key) => tls::get(key).is_not_null(),
None => false
}
}
}
/// Borrow a mutable reference to the thread-local value
///
/// # Safety Note
///
/// Because this leaves the value in thread-local storage it is possible
/// For the Scheduler pointer to be aliased
pub unsafe fn unsafe_borrow<T>() -> *mut T {
let key = tls_key();
let void_ptr = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
void_ptr as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null() {
None
} else {
Some(void_ptr as *mut T)
}
}
None => None
}
}
#[inline]
fn tls_key() -> tls::Key {
match maybe_tls_key() {
Some(key) => key,
None => rtabort!("runtime tls key not initialized")
}
}
#[inline]
#[cfg(not(test))]
pub fn maybe_tls_key() -> Option<tls::Key> {
unsafe {
// NB: This is a little racy because, while the key is
// initalized under a mutex and it's assumed to be initalized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Threads that
// are not using the new Scheduler but still *want to check*
// whether they are running under a new Scheduler may see a 0
// value here that is in the process of being initialized in
// another thread. I think this is fine since the only action
// they could take if it was initialized would be to check the
// thread-local value and see that it's not set.
if RT_TLS_KEY!= -1 {
return Some(RT_TLS_KEY);
} else {
return None;
}
}
}
#[inline] #[cfg(test)]
pub fn maybe_tls_key() -> Option<tls::Key> {
use realstd;
unsafe {
cast::transmute(realstd::rt::shouldnt_be_public::maybe_tls_key())
}
}
}
|
random_line_split
|
|
click_object.rs
|
extern crate gtk;
use gtk::{ScrolledWindow,ContainerExt,Box,Orientation,Entry,EntryExt,Frame};
use std::vec::Vec;
pub trait Attachable{
fn attach<F:ContainerExt>(&self,parent: &F);
}
pub struct Control {}
impl Control {
pub fn play(&self){
println!("Play")
}
pub fn rew(&self){
println!("Rewind")
}
pub fn ff(&self)
|
}
impl Clone for Control{
fn clone(&self)->Self{
return Control{}
}
}
impl Copy for Control {}
pub struct LabelFrame {
label_box:Box,
labels:Vec<Label>
}
impl LabelFrame{
pub fn new(labels:Vec<Label>)->LabelFrame{
let label_box=Box::new(Orientation::Vertical,0);
//Add labels here
for label in &labels{
label.attach(&label_box)
}
LabelFrame{label_box: label_box,labels:labels}
}
}
impl Attachable for LabelFrame{
fn attach<F:ContainerExt>(&self,parent: &F){
let scroll=ScrolledWindow::new(None,None);
scroll.add(&self.label_box);
parent.add(&scroll);
}
}
pub struct Label{
key:String,
value:Entry
}
impl Label{
pub fn new(label:&str)->Label{
let k = String::from(label);
let v = Entry::new();
v.set_text("0");
Label{key:k,value:v}
}
}
impl Attachable for Label{
fn attach<F:ContainerExt>(&self,parent: &F){
let f=Frame::new(Some(self.key.as_str()));
f.add(&self.value);
parent.add(&f);
}
}
|
{
println!("Fast Forward")
}
|
identifier_body
|
click_object.rs
|
extern crate gtk;
use gtk::{ScrolledWindow,ContainerExt,Box,Orientation,Entry,EntryExt,Frame};
use std::vec::Vec;
pub trait Attachable{
fn attach<F:ContainerExt>(&self,parent: &F);
}
pub struct Control {}
impl Control {
pub fn play(&self){
println!("Play")
}
pub fn rew(&self){
println!("Rewind")
}
pub fn ff(&self){
println!("Fast Forward")
}
}
impl Clone for Control{
fn clone(&self)->Self{
return Control{}
}
}
impl Copy for Control {}
pub struct LabelFrame {
label_box:Box,
labels:Vec<Label>
}
impl LabelFrame{
pub fn new(labels:Vec<Label>)->LabelFrame{
let label_box=Box::new(Orientation::Vertical,0);
//Add labels here
for label in &labels{
label.attach(&label_box)
}
LabelFrame{label_box: label_box,labels:labels}
}
}
impl Attachable for LabelFrame{
fn attach<F:ContainerExt>(&self,parent: &F){
let scroll=ScrolledWindow::new(None,None);
scroll.add(&self.label_box);
parent.add(&scroll);
}
}
pub struct Label{
key:String,
value:Entry
}
impl Label{
pub fn new(label:&str)->Label{
let k = String::from(label);
let v = Entry::new();
v.set_text("0");
Label{key:k,value:v}
}
}
impl Attachable for Label{
fn attach<F:ContainerExt>(&self,parent: &F){
let f=Frame::new(Some(self.key.as_str()));
f.add(&self.value);
parent.add(&f);
}
|
}
|
random_line_split
|
|
click_object.rs
|
extern crate gtk;
use gtk::{ScrolledWindow,ContainerExt,Box,Orientation,Entry,EntryExt,Frame};
use std::vec::Vec;
pub trait Attachable{
fn attach<F:ContainerExt>(&self,parent: &F);
}
pub struct Control {}
impl Control {
pub fn play(&self){
println!("Play")
}
pub fn rew(&self){
println!("Rewind")
}
pub fn ff(&self){
println!("Fast Forward")
}
}
impl Clone for Control{
fn clone(&self)->Self{
return Control{}
}
}
impl Copy for Control {}
pub struct LabelFrame {
label_box:Box,
labels:Vec<Label>
}
impl LabelFrame{
pub fn
|
(labels:Vec<Label>)->LabelFrame{
let label_box=Box::new(Orientation::Vertical,0);
//Add labels here
for label in &labels{
label.attach(&label_box)
}
LabelFrame{label_box: label_box,labels:labels}
}
}
impl Attachable for LabelFrame{
fn attach<F:ContainerExt>(&self,parent: &F){
let scroll=ScrolledWindow::new(None,None);
scroll.add(&self.label_box);
parent.add(&scroll);
}
}
pub struct Label{
key:String,
value:Entry
}
impl Label{
pub fn new(label:&str)->Label{
let k = String::from(label);
let v = Entry::new();
v.set_text("0");
Label{key:k,value:v}
}
}
impl Attachable for Label{
fn attach<F:ContainerExt>(&self,parent: &F){
let f=Frame::new(Some(self.key.as_str()));
f.add(&self.value);
parent.add(&f);
}
}
|
new
|
identifier_name
|
rewrite.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// A generic trait to abstract the rewriting of an element (of the AST).
use syntax::codemap::{CodeMap, Span};
use syntax::parse::ParseSess;
use Shape;
use config::Config;
pub trait Rewrite {
/// Rewrite self into shape.
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String>;
}
#[derive(Clone)]
pub struct
|
<'a> {
pub parse_session: &'a ParseSess,
pub codemap: &'a CodeMap,
pub config: &'a Config,
}
impl<'a> RewriteContext<'a> {
pub fn snippet(&self, span: Span) -> String {
self.codemap.span_to_snippet(span).unwrap()
}
}
|
RewriteContext
|
identifier_name
|
rewrite.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// A generic trait to abstract the rewriting of an element (of the AST).
use syntax::codemap::{CodeMap, Span};
use syntax::parse::ParseSess;
use Shape;
use config::Config;
pub trait Rewrite {
/// Rewrite self into shape.
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String>;
}
#[derive(Clone)]
pub struct RewriteContext<'a> {
pub parse_session: &'a ParseSess,
pub codemap: &'a CodeMap,
pub config: &'a Config,
}
impl<'a> RewriteContext<'a> {
pub fn snippet(&self, span: Span) -> String {
self.codemap.span_to_snippet(span).unwrap()
}
}
|
// http://rust-lang.org/COPYRIGHT.
//
|
random_line_split
|
windows.rs
|
use std::ffi::OsStr;
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
pub trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
pub trait OsStrExt2 {
fn starts_with(&self, s: &[u8]) -> bool;
fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
fn split_at(&self, i: usize) -> (&OsStr, &OsStr);
fn trim_left_matches(&self, b: u8) -> &OsStr;
fn len_(&self) -> usize;
fn contains_byte(&self, b: u8) -> bool;
fn is_empty_(&self) -> bool;
fn split(&self, b: u8) -> OsSplit;
}
impl OsStrExt3 for OsStr {
// TODO JB: fix this allow
#[allow(clippy::transmute_ptr_to_ptr)]
fn from_bytes(b: &[u8]) -> &Self {
use std::mem;
unsafe { mem::transmute(b) }
}
fn as_bytes(&self) -> &[u8] { self.to_str().map(str::as_bytes).expect(INVALID_UTF8) }
}
impl OsStrExt2 for OsStr {
fn starts_with(&self, s: &[u8]) -> bool { self.as_bytes().starts_with(s) }
fn is_empty_(&self) -> bool { self.as_bytes().is_empty() }
fn contains_byte(&self, byte: u8) -> bool {
for b in self.as_bytes() {
if b == &byte {
return true;
}
}
false
}
fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) {
for (i, b) in self.as_bytes().iter().enumerate() {
if b == &byte {
return (&OsStr::from_bytes(&self.as_bytes()[..i]),
&OsStr::from_bytes(&self.as_bytes()[i + 1..]));
}
}
(&*self, &OsStr::from_bytes(&self.as_bytes()[self.len_()..self.len_()]))
}
fn trim_left_matches(&self, byte: u8) -> &OsStr {
for (i, b) in self.as_bytes().iter().enumerate() {
if b!= &byte {
return &OsStr::from_bytes(&self.as_bytes()[i..]);
}
}
&*self
}
fn split_at(&self, i: usize) -> (&OsStr, &OsStr) {
(&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i..]))
}
fn len_(&self) -> usize { self.as_bytes().len() }
fn split(&self, b: u8) -> OsSplit {
OsSplit { sep: b,
val: self.as_bytes(),
pos: 0, }
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct OsSplit<'a> {
sep: u8,
val: &'a [u8],
pos: usize,
}
impl<'a> Iterator for OsSplit<'a> {
type Item = &'a OsStr;
fn next(&mut self) -> Option<&'a OsStr> {
if self.pos == self.val.len() {
return None;
}
let start = self.pos;
for b in &self.val[start..] {
self.pos += 1;
if *b == self.sep {
return Some(&OsStr::from_bytes(&self.val[start..self.pos - 1]));
}
}
Some(&OsStr::from_bytes(&self.val[start..]))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let mut count = 0;
for b in &self.val[self.pos..] {
if *b == self.sep {
count += 1;
}
}
if count > 0 {
return (count, Some(count));
}
(0, None)
}
}
impl<'a> DoubleEndedIterator for OsSplit<'a> {
fn next_back(&mut self) -> Option<&'a OsStr> {
if self.pos == 0 {
return None;
}
let start = self.pos;
for b in self.val[..self.pos].iter().rev() {
self.pos -= 1;
if *b == self.sep
|
}
Some(&OsStr::from_bytes(&self.val[..start]))
}
}
|
{
return Some(&OsStr::from_bytes(&self.val[self.pos + 1..start]));
}
|
conditional_block
|
windows.rs
|
use std::ffi::OsStr;
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
pub trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
pub trait OsStrExt2 {
fn starts_with(&self, s: &[u8]) -> bool;
fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
fn split_at(&self, i: usize) -> (&OsStr, &OsStr);
fn trim_left_matches(&self, b: u8) -> &OsStr;
fn len_(&self) -> usize;
fn contains_byte(&self, b: u8) -> bool;
fn is_empty_(&self) -> bool;
fn split(&self, b: u8) -> OsSplit;
}
impl OsStrExt3 for OsStr {
// TODO JB: fix this allow
#[allow(clippy::transmute_ptr_to_ptr)]
fn
|
(b: &[u8]) -> &Self {
use std::mem;
unsafe { mem::transmute(b) }
}
fn as_bytes(&self) -> &[u8] { self.to_str().map(str::as_bytes).expect(INVALID_UTF8) }
}
impl OsStrExt2 for OsStr {
fn starts_with(&self, s: &[u8]) -> bool { self.as_bytes().starts_with(s) }
fn is_empty_(&self) -> bool { self.as_bytes().is_empty() }
fn contains_byte(&self, byte: u8) -> bool {
for b in self.as_bytes() {
if b == &byte {
return true;
}
}
false
}
fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) {
for (i, b) in self.as_bytes().iter().enumerate() {
if b == &byte {
return (&OsStr::from_bytes(&self.as_bytes()[..i]),
&OsStr::from_bytes(&self.as_bytes()[i + 1..]));
}
}
(&*self, &OsStr::from_bytes(&self.as_bytes()[self.len_()..self.len_()]))
}
fn trim_left_matches(&self, byte: u8) -> &OsStr {
for (i, b) in self.as_bytes().iter().enumerate() {
if b!= &byte {
return &OsStr::from_bytes(&self.as_bytes()[i..]);
}
}
&*self
}
fn split_at(&self, i: usize) -> (&OsStr, &OsStr) {
(&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i..]))
}
fn len_(&self) -> usize { self.as_bytes().len() }
fn split(&self, b: u8) -> OsSplit {
OsSplit { sep: b,
val: self.as_bytes(),
pos: 0, }
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct OsSplit<'a> {
sep: u8,
val: &'a [u8],
pos: usize,
}
impl<'a> Iterator for OsSplit<'a> {
type Item = &'a OsStr;
fn next(&mut self) -> Option<&'a OsStr> {
if self.pos == self.val.len() {
return None;
}
let start = self.pos;
for b in &self.val[start..] {
self.pos += 1;
if *b == self.sep {
return Some(&OsStr::from_bytes(&self.val[start..self.pos - 1]));
}
}
Some(&OsStr::from_bytes(&self.val[start..]))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let mut count = 0;
for b in &self.val[self.pos..] {
if *b == self.sep {
count += 1;
}
}
if count > 0 {
return (count, Some(count));
}
(0, None)
}
}
impl<'a> DoubleEndedIterator for OsSplit<'a> {
fn next_back(&mut self) -> Option<&'a OsStr> {
if self.pos == 0 {
return None;
}
let start = self.pos;
for b in self.val[..self.pos].iter().rev() {
self.pos -= 1;
if *b == self.sep {
return Some(&OsStr::from_bytes(&self.val[self.pos + 1..start]));
}
}
Some(&OsStr::from_bytes(&self.val[..start]))
}
}
|
from_bytes
|
identifier_name
|
windows.rs
|
use std::ffi::OsStr;
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
pub trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
pub trait OsStrExt2 {
fn starts_with(&self, s: &[u8]) -> bool;
fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
fn split_at(&self, i: usize) -> (&OsStr, &OsStr);
|
fn split(&self, b: u8) -> OsSplit;
}
impl OsStrExt3 for OsStr {
// TODO JB: fix this allow
#[allow(clippy::transmute_ptr_to_ptr)]
fn from_bytes(b: &[u8]) -> &Self {
use std::mem;
unsafe { mem::transmute(b) }
}
fn as_bytes(&self) -> &[u8] { self.to_str().map(str::as_bytes).expect(INVALID_UTF8) }
}
impl OsStrExt2 for OsStr {
fn starts_with(&self, s: &[u8]) -> bool { self.as_bytes().starts_with(s) }
fn is_empty_(&self) -> bool { self.as_bytes().is_empty() }
fn contains_byte(&self, byte: u8) -> bool {
for b in self.as_bytes() {
if b == &byte {
return true;
}
}
false
}
fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) {
for (i, b) in self.as_bytes().iter().enumerate() {
if b == &byte {
return (&OsStr::from_bytes(&self.as_bytes()[..i]),
&OsStr::from_bytes(&self.as_bytes()[i + 1..]));
}
}
(&*self, &OsStr::from_bytes(&self.as_bytes()[self.len_()..self.len_()]))
}
fn trim_left_matches(&self, byte: u8) -> &OsStr {
for (i, b) in self.as_bytes().iter().enumerate() {
if b!= &byte {
return &OsStr::from_bytes(&self.as_bytes()[i..]);
}
}
&*self
}
fn split_at(&self, i: usize) -> (&OsStr, &OsStr) {
(&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i..]))
}
fn len_(&self) -> usize { self.as_bytes().len() }
fn split(&self, b: u8) -> OsSplit {
OsSplit { sep: b,
val: self.as_bytes(),
pos: 0, }
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct OsSplit<'a> {
sep: u8,
val: &'a [u8],
pos: usize,
}
impl<'a> Iterator for OsSplit<'a> {
type Item = &'a OsStr;
fn next(&mut self) -> Option<&'a OsStr> {
if self.pos == self.val.len() {
return None;
}
let start = self.pos;
for b in &self.val[start..] {
self.pos += 1;
if *b == self.sep {
return Some(&OsStr::from_bytes(&self.val[start..self.pos - 1]));
}
}
Some(&OsStr::from_bytes(&self.val[start..]))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let mut count = 0;
for b in &self.val[self.pos..] {
if *b == self.sep {
count += 1;
}
}
if count > 0 {
return (count, Some(count));
}
(0, None)
}
}
impl<'a> DoubleEndedIterator for OsSplit<'a> {
fn next_back(&mut self) -> Option<&'a OsStr> {
if self.pos == 0 {
return None;
}
let start = self.pos;
for b in self.val[..self.pos].iter().rev() {
self.pos -= 1;
if *b == self.sep {
return Some(&OsStr::from_bytes(&self.val[self.pos + 1..start]));
}
}
Some(&OsStr::from_bytes(&self.val[..start]))
}
}
|
fn trim_left_matches(&self, b: u8) -> &OsStr;
fn len_(&self) -> usize;
fn contains_byte(&self, b: u8) -> bool;
fn is_empty_(&self) -> bool;
|
random_line_split
|
windows.rs
|
use std::ffi::OsStr;
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
pub trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
pub trait OsStrExt2 {
fn starts_with(&self, s: &[u8]) -> bool;
fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
fn split_at(&self, i: usize) -> (&OsStr, &OsStr);
fn trim_left_matches(&self, b: u8) -> &OsStr;
fn len_(&self) -> usize;
fn contains_byte(&self, b: u8) -> bool;
fn is_empty_(&self) -> bool;
fn split(&self, b: u8) -> OsSplit;
}
impl OsStrExt3 for OsStr {
// TODO JB: fix this allow
#[allow(clippy::transmute_ptr_to_ptr)]
fn from_bytes(b: &[u8]) -> &Self {
use std::mem;
unsafe { mem::transmute(b) }
}
fn as_bytes(&self) -> &[u8] { self.to_str().map(str::as_bytes).expect(INVALID_UTF8) }
}
impl OsStrExt2 for OsStr {
fn starts_with(&self, s: &[u8]) -> bool { self.as_bytes().starts_with(s) }
fn is_empty_(&self) -> bool { self.as_bytes().is_empty() }
fn contains_byte(&self, byte: u8) -> bool {
for b in self.as_bytes() {
if b == &byte {
return true;
}
}
false
}
fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) {
for (i, b) in self.as_bytes().iter().enumerate() {
if b == &byte {
return (&OsStr::from_bytes(&self.as_bytes()[..i]),
&OsStr::from_bytes(&self.as_bytes()[i + 1..]));
}
}
(&*self, &OsStr::from_bytes(&self.as_bytes()[self.len_()..self.len_()]))
}
fn trim_left_matches(&self, byte: u8) -> &OsStr {
for (i, b) in self.as_bytes().iter().enumerate() {
if b!= &byte {
return &OsStr::from_bytes(&self.as_bytes()[i..]);
}
}
&*self
}
fn split_at(&self, i: usize) -> (&OsStr, &OsStr)
|
fn len_(&self) -> usize { self.as_bytes().len() }
fn split(&self, b: u8) -> OsSplit {
OsSplit { sep: b,
val: self.as_bytes(),
pos: 0, }
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct OsSplit<'a> {
sep: u8,
val: &'a [u8],
pos: usize,
}
impl<'a> Iterator for OsSplit<'a> {
type Item = &'a OsStr;
fn next(&mut self) -> Option<&'a OsStr> {
if self.pos == self.val.len() {
return None;
}
let start = self.pos;
for b in &self.val[start..] {
self.pos += 1;
if *b == self.sep {
return Some(&OsStr::from_bytes(&self.val[start..self.pos - 1]));
}
}
Some(&OsStr::from_bytes(&self.val[start..]))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let mut count = 0;
for b in &self.val[self.pos..] {
if *b == self.sep {
count += 1;
}
}
if count > 0 {
return (count, Some(count));
}
(0, None)
}
}
impl<'a> DoubleEndedIterator for OsSplit<'a> {
fn next_back(&mut self) -> Option<&'a OsStr> {
if self.pos == 0 {
return None;
}
let start = self.pos;
for b in self.val[..self.pos].iter().rev() {
self.pos -= 1;
if *b == self.sep {
return Some(&OsStr::from_bytes(&self.val[self.pos + 1..start]));
}
}
Some(&OsStr::from_bytes(&self.val[..start]))
}
}
|
{
(&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i..]))
}
|
identifier_body
|
strconv.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A simple integer-to-string conversion code with statically sized buffers.
use core::mem::uninitialized;
|
let mut rbuf : [u8; 32] = unsafe { uninitialized() };
let mut myval : u32 = val;
let mut idx: isize = 0;
if myval == 0 {
buf[0] = '0' as u8;
return;
}
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as usize] = digit;
idx += 1;
}
idx -= 1;
let mut ridx = 0;
while idx >= 0 {
let charcode : u8 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'][rbuf[idx as usize] as usize] as u8;
buf[ridx] = charcode;
idx -= 1;
ridx += 1;
}
}
|
/// Convert an integer to a string.
pub fn itoa(val: u32, buf : &mut [u8], base: u32) {
|
random_line_split
|
strconv.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A simple integer-to-string conversion code with statically sized buffers.
use core::mem::uninitialized;
/// Convert an integer to a string.
pub fn itoa(val: u32, buf : &mut [u8], base: u32)
|
let mut ridx = 0;
while idx >= 0 {
let charcode : u8 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'][rbuf[idx as usize] as usize] as u8;
buf[ridx] = charcode;
idx -= 1;
ridx += 1;
}
}
|
{
let mut rbuf : [u8; 32] = unsafe { uninitialized() };
let mut myval : u32 = val;
let mut idx: isize = 0;
if myval == 0 {
buf[0] = '0' as u8;
return;
}
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as usize] = digit;
idx += 1;
}
idx -= 1;
|
identifier_body
|
strconv.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A simple integer-to-string conversion code with statically sized buffers.
use core::mem::uninitialized;
/// Convert an integer to a string.
pub fn itoa(val: u32, buf : &mut [u8], base: u32) {
let mut rbuf : [u8; 32] = unsafe { uninitialized() };
let mut myval : u32 = val;
let mut idx: isize = 0;
if myval == 0
|
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as usize] = digit;
idx += 1;
}
idx -= 1;
let mut ridx = 0;
while idx >= 0 {
let charcode : u8 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'][rbuf[idx as usize] as usize] as u8;
buf[ridx] = charcode;
idx -= 1;
ridx += 1;
}
}
|
{
buf[0] = '0' as u8;
return;
}
|
conditional_block
|
strconv.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A simple integer-to-string conversion code with statically sized buffers.
use core::mem::uninitialized;
/// Convert an integer to a string.
pub fn
|
(val: u32, buf : &mut [u8], base: u32) {
let mut rbuf : [u8; 32] = unsafe { uninitialized() };
let mut myval : u32 = val;
let mut idx: isize = 0;
if myval == 0 {
buf[0] = '0' as u8;
return;
}
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as usize] = digit;
idx += 1;
}
idx -= 1;
let mut ridx = 0;
while idx >= 0 {
let charcode : u8 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'][rbuf[idx as usize] as usize] as u8;
buf[ridx] = charcode;
idx -= 1;
ridx += 1;
}
}
|
itoa
|
identifier_name
|
generic-struct-style-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print union on
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print case1
// check:$1 = {{Case1, a = 0, b = 31868, c = 31868, d = 31868, e = 31868}, {Case1, a = 0, b = 2088533116, c = 2088533116}, {Case1, a = 0, b = 8970181431921507452}}
// debugger:print case2
// check:$2 = {{Case2, a = 0, b = 4369, c = 4369, d = 4369, e = 4369}, {Case2, a = 0, b = 286331153, c = 286331153}, {Case2, a = 0, b = 1229782938247303441}}
// debugger:print case3
// check:$3 = {{Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {Case3, a = 0, b = 1499027801, c = 1499027801}, {Case3, a = 0, b = 6438275382588823897}}
// debugger:print univariant
// check:$4 = {a = -1}
#[feature(struct_variant)];
// NOTE: This is a copy of the non-generic test case. The `Txx` type parameters have to be
// substituted with something of size `xx` bits and the same alignment as an integer type of the
// same size.
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular<T16, T32, T64> {
Case1 { a: T64, b: T16, c: T16, d: T16, e: T16},
Case2 { a: T64, b: T32, c: T32},
Case3 { a: T64, b: T64 }
}
enum Univariant<T> {
TheOnlyCase { a: T }
}
fn main()
|
// 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3: Regular<u16, i32, u64> = Case3 { a: 0, b: 6438275382588823897 };
let univariant = TheOnlyCase { a: -1 };
zzz();
}
fn zzz() {()}
|
{
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let case1: Regular<u16, u32, i64> = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 };
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let case2: Regular<i16, u32, i64> = Case2 { a: 0, b: 286331153, c: 286331153 };
// 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
// 0b01011001010110010101100101011001 = 1499027801
|
identifier_body
|
generic-struct-style-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print union on
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print case1
// check:$1 = {{Case1, a = 0, b = 31868, c = 31868, d = 31868, e = 31868}, {Case1, a = 0, b = 2088533116, c = 2088533116}, {Case1, a = 0, b = 8970181431921507452}}
// debugger:print case2
// check:$2 = {{Case2, a = 0, b = 4369, c = 4369, d = 4369, e = 4369}, {Case2, a = 0, b = 286331153, c = 286331153}, {Case2, a = 0, b = 1229782938247303441}}
// debugger:print case3
// check:$3 = {{Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {Case3, a = 0, b = 1499027801, c = 1499027801}, {Case3, a = 0, b = 6438275382588823897}}
// debugger:print univariant
// check:$4 = {a = -1}
|
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular<T16, T32, T64> {
Case1 { a: T64, b: T16, c: T16, d: T16, e: T16},
Case2 { a: T64, b: T32, c: T32},
Case3 { a: T64, b: T64 }
}
enum Univariant<T> {
TheOnlyCase { a: T }
}
fn main() {
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let case1: Regular<u16, u32, i64> = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 };
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let case2: Regular<i16, u32, i64> = Case2 { a: 0, b: 286331153, c: 286331153 };
// 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
// 0b01011001010110010101100101011001 = 1499027801
// 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3: Regular<u16, i32, u64> = Case3 { a: 0, b: 6438275382588823897 };
let univariant = TheOnlyCase { a: -1 };
zzz();
}
fn zzz() {()}
|
#[feature(struct_variant)];
// NOTE: This is a copy of the non-generic test case. The `Txx` type parameters have to be
// substituted with something of size `xx` bits and the same alignment as an integer type of the
// same size.
|
random_line_split
|
generic-struct-style-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print union on
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print case1
// check:$1 = {{Case1, a = 0, b = 31868, c = 31868, d = 31868, e = 31868}, {Case1, a = 0, b = 2088533116, c = 2088533116}, {Case1, a = 0, b = 8970181431921507452}}
// debugger:print case2
// check:$2 = {{Case2, a = 0, b = 4369, c = 4369, d = 4369, e = 4369}, {Case2, a = 0, b = 286331153, c = 286331153}, {Case2, a = 0, b = 1229782938247303441}}
// debugger:print case3
// check:$3 = {{Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {Case3, a = 0, b = 1499027801, c = 1499027801}, {Case3, a = 0, b = 6438275382588823897}}
// debugger:print univariant
// check:$4 = {a = -1}
#[feature(struct_variant)];
// NOTE: This is a copy of the non-generic test case. The `Txx` type parameters have to be
// substituted with something of size `xx` bits and the same alignment as an integer type of the
// same size.
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular<T16, T32, T64> {
Case1 { a: T64, b: T16, c: T16, d: T16, e: T16},
Case2 { a: T64, b: T32, c: T32},
Case3 { a: T64, b: T64 }
}
enum Univariant<T> {
TheOnlyCase { a: T }
}
fn main() {
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let case1: Regular<u16, u32, i64> = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 };
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let case2: Regular<i16, u32, i64> = Case2 { a: 0, b: 286331153, c: 286331153 };
// 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
// 0b01011001010110010101100101011001 = 1499027801
// 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3: Regular<u16, i32, u64> = Case3 { a: 0, b: 6438275382588823897 };
let univariant = TheOnlyCase { a: -1 };
zzz();
}
fn
|
() {()}
|
zzz
|
identifier_name
|
variance-use-invariant-struct-1.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test various uses of structs with distint variances to make sure
// they permit lifetimes to be approximated as expected.
struct SomeStruct<T>(*mut T);
fn foo<'min,'max>(v: SomeStruct<&'max ()>)
-> SomeStruct<&'min ()>
where'max :'min
{
v //~ ERROR mismatched types
}
fn bar<'min,'max>(v: SomeStruct<&'min ()>)
-> SomeStruct<&'max ()>
where'max :'min
{
v //~ ERROR mismatched types
}
fn main()
|
{ }
|
identifier_body
|
|
variance-use-invariant-struct-1.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test various uses of structs with distint variances to make sure
// they permit lifetimes to be approximated as expected.
struct SomeStruct<T>(*mut T);
fn foo<'min,'max>(v: SomeStruct<&'max ()>)
-> SomeStruct<&'min ()>
where'max :'min
{
v //~ ERROR mismatched types
}
fn
|
<'min,'max>(v: SomeStruct<&'min ()>)
-> SomeStruct<&'max ()>
where'max :'min
{
v //~ ERROR mismatched types
}
fn main() { }
|
bar
|
identifier_name
|
variance-use-invariant-struct-1.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test various uses of structs with distint variances to make sure
// they permit lifetimes to be approximated as expected.
struct SomeStruct<T>(*mut T);
fn foo<'min,'max>(v: SomeStruct<&'max ()>)
-> SomeStruct<&'min ()>
where'max :'min
{
v //~ ERROR mismatched types
}
fn bar<'min,'max>(v: SomeStruct<&'min ()>)
-> SomeStruct<&'max ()>
where'max :'min
{
v //~ ERROR mismatched types
}
|
fn main() { }
|
random_line_split
|
|
navigator.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::utils::{WrapperCache, BindingObject, CacheableWrapper};
use dom::bindings::utils::{DOMString, ErrorResult, str, null_string};
use dom::bindings::codegen::NavigatorBinding;
use script_task::{page_from_context};
use js::jsapi::{JSContext, JSObject};
use std::cast;
pub struct Navigator {
wrapper: WrapperCache
}
impl Navigator {
pub fn new() -> @mut Navigator {
@mut Navigator {
wrapper: WrapperCache::new()
}
}
pub fn DoNotTrack(&self) -> DOMString {
str(~"unspecified")
}
pub fn Vendor(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn VendorSub(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn Product(&self) -> DOMString {
str(~"Gecko") // This is supposed to be constant, see webidl.
}
pub fn ProductSub(&self) -> DOMString {
null_string
}
pub fn CookieEnabled(&self) -> bool {
false
}
pub fn GetBuildID(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn JavaEnabled(&self, _rv: &mut ErrorResult) -> bool {
false
}
pub fn TaintEnabled(&self) -> bool {
false
}
pub fn AppName(&self) -> DOMString {
str(~"Netscape") // Like Gecko/Webkit
}
pub fn GetAppCodeName(&self, _rv: &mut ErrorResult) -> DOMString
|
pub fn GetAppVersion(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetPlatform(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetUserAgent(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetLanguage(&self) -> DOMString {
null_string
}
pub fn OnLine(&self) -> bool {
true
}
}
impl CacheableWrapper for Navigator {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
NavigatorBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for Navigator {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
let page = page_from_context(cx);
unsafe {
Some((*page).frame.get_ref().window as @mut CacheableWrapper)
}
}
}
|
{
str(~"Mozilla") // Like Gecko/Webkit
}
|
identifier_body
|
navigator.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::utils::{WrapperCache, BindingObject, CacheableWrapper};
use dom::bindings::utils::{DOMString, ErrorResult, str, null_string};
use dom::bindings::codegen::NavigatorBinding;
use script_task::{page_from_context};
use js::jsapi::{JSContext, JSObject};
use std::cast;
pub struct Navigator {
wrapper: WrapperCache
|
impl Navigator {
pub fn new() -> @mut Navigator {
@mut Navigator {
wrapper: WrapperCache::new()
}
}
pub fn DoNotTrack(&self) -> DOMString {
str(~"unspecified")
}
pub fn Vendor(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn VendorSub(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn Product(&self) -> DOMString {
str(~"Gecko") // This is supposed to be constant, see webidl.
}
pub fn ProductSub(&self) -> DOMString {
null_string
}
pub fn CookieEnabled(&self) -> bool {
false
}
pub fn GetBuildID(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn JavaEnabled(&self, _rv: &mut ErrorResult) -> bool {
false
}
pub fn TaintEnabled(&self) -> bool {
false
}
pub fn AppName(&self) -> DOMString {
str(~"Netscape") // Like Gecko/Webkit
}
pub fn GetAppCodeName(&self, _rv: &mut ErrorResult) -> DOMString {
str(~"Mozilla") // Like Gecko/Webkit
}
pub fn GetAppVersion(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetPlatform(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetUserAgent(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetLanguage(&self) -> DOMString {
null_string
}
pub fn OnLine(&self) -> bool {
true
}
}
impl CacheableWrapper for Navigator {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
NavigatorBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for Navigator {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
let page = page_from_context(cx);
unsafe {
Some((*page).frame.get_ref().window as @mut CacheableWrapper)
}
}
}
|
}
|
random_line_split
|
navigator.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::utils::{WrapperCache, BindingObject, CacheableWrapper};
use dom::bindings::utils::{DOMString, ErrorResult, str, null_string};
use dom::bindings::codegen::NavigatorBinding;
use script_task::{page_from_context};
use js::jsapi::{JSContext, JSObject};
use std::cast;
pub struct Navigator {
wrapper: WrapperCache
}
impl Navigator {
pub fn
|
() -> @mut Navigator {
@mut Navigator {
wrapper: WrapperCache::new()
}
}
pub fn DoNotTrack(&self) -> DOMString {
str(~"unspecified")
}
pub fn Vendor(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn VendorSub(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn Product(&self) -> DOMString {
str(~"Gecko") // This is supposed to be constant, see webidl.
}
pub fn ProductSub(&self) -> DOMString {
null_string
}
pub fn CookieEnabled(&self) -> bool {
false
}
pub fn GetBuildID(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn JavaEnabled(&self, _rv: &mut ErrorResult) -> bool {
false
}
pub fn TaintEnabled(&self) -> bool {
false
}
pub fn AppName(&self) -> DOMString {
str(~"Netscape") // Like Gecko/Webkit
}
pub fn GetAppCodeName(&self, _rv: &mut ErrorResult) -> DOMString {
str(~"Mozilla") // Like Gecko/Webkit
}
pub fn GetAppVersion(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetPlatform(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetUserAgent(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetLanguage(&self) -> DOMString {
null_string
}
pub fn OnLine(&self) -> bool {
true
}
}
impl CacheableWrapper for Navigator {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
NavigatorBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for Navigator {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
let page = page_from_context(cx);
unsafe {
Some((*page).frame.get_ref().window as @mut CacheableWrapper)
}
}
}
|
new
|
identifier_name
|
packet_handler.rs
|
extern crate netfilter_queue as nfq;
use std::ptr::null;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{CopyMode, Verdict, PacketHandler, QueueHandle};
use nfq::message::Message;
use nfq::error::Error;
fn main() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok().unwrap();
let mut queue = handle.queue(0, Decider).ok().unwrap();
let _ = queue.set_mode(CopyMode::Metadata).unwrap();
println!("Listening for packets...");
handle.start(4096);
println!("...finished.");
}
struct Decider;
impl PacketHandler for Decider {
#[allow(non_snake_case)]
fn handle(&mut self, hq: QueueHandle, message: Result<&Message, &Error>) -> i32
|
}
|
{
match message {
Ok(m) => {
let _ = Verdict::set_verdict(hq, m.header.id(), Verdict::Accept, 0, null());
},
Err(_) => ()
}
0
}
|
identifier_body
|
packet_handler.rs
|
extern crate netfilter_queue as nfq;
use std::ptr::null;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{CopyMode, Verdict, PacketHandler, QueueHandle};
use nfq::message::Message;
use nfq::error::Error;
fn
|
() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok().unwrap();
let mut queue = handle.queue(0, Decider).ok().unwrap();
let _ = queue.set_mode(CopyMode::Metadata).unwrap();
println!("Listening for packets...");
handle.start(4096);
println!("...finished.");
}
struct Decider;
impl PacketHandler for Decider {
#[allow(non_snake_case)]
fn handle(&mut self, hq: QueueHandle, message: Result<&Message, &Error>) -> i32 {
match message {
Ok(m) => {
let _ = Verdict::set_verdict(hq, m.header.id(), Verdict::Accept, 0, null());
},
Err(_) => ()
}
0
}
}
|
main
|
identifier_name
|
packet_handler.rs
|
extern crate netfilter_queue as nfq;
use std::ptr::null;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{CopyMode, Verdict, PacketHandler, QueueHandle};
use nfq::message::Message;
use nfq::error::Error;
fn main() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok().unwrap();
let mut queue = handle.queue(0, Decider).ok().unwrap();
let _ = queue.set_mode(CopyMode::Metadata).unwrap();
println!("Listening for packets...");
|
handle.start(4096);
println!("...finished.");
}
struct Decider;
impl PacketHandler for Decider {
#[allow(non_snake_case)]
fn handle(&mut self, hq: QueueHandle, message: Result<&Message, &Error>) -> i32 {
match message {
Ok(m) => {
let _ = Verdict::set_verdict(hq, m.header.id(), Verdict::Accept, 0, null());
},
Err(_) => ()
}
0
}
}
|
random_line_split
|
|
posix.rs
|
use {TryRead, TryWrite};
use io::{self, PipeReader, PipeWriter};
use std::mem;
use std::os::unix::io::{Fd, AsRawFd};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
writer: PipeWriter,
}
impl Awakener {
pub fn new() -> io::Result<Awakener> {
let (rd, wr) = try!(io::pipe());
Ok(Awakener {
reader: rd,
writer: wr
})
}
pub fn as_raw_fd(&self) -> Fd {
self.reader.as_raw_fd()
}
pub fn wakeup(&self) -> io::Result<()> {
// A hack, but such is life. PipeWriter is backed by a single FD, which
// is thread safe.
unsafe {
let wr: &mut PipeWriter = mem::transmute(&self.writer);
wr.write_slice(b"0x01").map(|_| ())
}
}
pub fn cleanup(&self) {
let mut buf = [0; 128];
loop {
// Also a bit hackish. It would be possible to split up the read /
// write sides of the awakener, but that would be a more
// significant refactor. A transmute here is safe.
unsafe {
|
// Consume data until all bytes are purged
match rd.read_slice(&mut buf) {
Ok(Some(i)) if i > 0 => {},
_ => return,
}
}
}
}
}
|
let rd: &mut PipeReader = mem::transmute(&self.reader);
|
random_line_split
|
posix.rs
|
use {TryRead, TryWrite};
use io::{self, PipeReader, PipeWriter};
use std::mem;
use std::os::unix::io::{Fd, AsRawFd};
/*
*
* ===== Awakener =====
*
*/
pub struct
|
{
reader: PipeReader,
writer: PipeWriter,
}
impl Awakener {
pub fn new() -> io::Result<Awakener> {
let (rd, wr) = try!(io::pipe());
Ok(Awakener {
reader: rd,
writer: wr
})
}
pub fn as_raw_fd(&self) -> Fd {
self.reader.as_raw_fd()
}
pub fn wakeup(&self) -> io::Result<()> {
// A hack, but such is life. PipeWriter is backed by a single FD, which
// is thread safe.
unsafe {
let wr: &mut PipeWriter = mem::transmute(&self.writer);
wr.write_slice(b"0x01").map(|_| ())
}
}
pub fn cleanup(&self) {
let mut buf = [0; 128];
loop {
// Also a bit hackish. It would be possible to split up the read /
// write sides of the awakener, but that would be a more
// significant refactor. A transmute here is safe.
unsafe {
let rd: &mut PipeReader = mem::transmute(&self.reader);
// Consume data until all bytes are purged
match rd.read_slice(&mut buf) {
Ok(Some(i)) if i > 0 => {},
_ => return,
}
}
}
}
}
|
Awakener
|
identifier_name
|
posix.rs
|
use {TryRead, TryWrite};
use io::{self, PipeReader, PipeWriter};
use std::mem;
use std::os::unix::io::{Fd, AsRawFd};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
writer: PipeWriter,
}
impl Awakener {
pub fn new() -> io::Result<Awakener> {
let (rd, wr) = try!(io::pipe());
Ok(Awakener {
reader: rd,
writer: wr
})
}
pub fn as_raw_fd(&self) -> Fd {
self.reader.as_raw_fd()
}
pub fn wakeup(&self) -> io::Result<()> {
// A hack, but such is life. PipeWriter is backed by a single FD, which
// is thread safe.
unsafe {
let wr: &mut PipeWriter = mem::transmute(&self.writer);
wr.write_slice(b"0x01").map(|_| ())
}
}
pub fn cleanup(&self)
|
}
|
{
let mut buf = [0; 128];
loop {
// Also a bit hackish. It would be possible to split up the read /
// write sides of the awakener, but that would be a more
// significant refactor. A transmute here is safe.
unsafe {
let rd: &mut PipeReader = mem::transmute(&self.reader);
// Consume data until all bytes are purged
match rd.read_slice(&mut buf) {
Ok(Some(i)) if i > 0 => {},
_ => return,
}
}
}
}
|
identifier_body
|
ws.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! WebSockets server tests.
use std::sync::Arc;
use devtools::http_client;
use jsonrpc_core::MetaIoHandler;
use rand;
use ws;
use v1::{extractors, informant};
use tests::helpers::{GuardedAuthCodes, Server};
/// Setup a mock signer for tests
pub fn serve() -> (Server<ws::Server>, usize, GuardedAuthCodes) {
let port = 35000 + rand::random::<usize>() % 10000;
let address = format!("127.0.0.1:{}", port).parse().unwrap();
let io = MetaIoHandler::default();
let authcodes = GuardedAuthCodes::new();
let stats = Arc::new(informant::RpcStats::default());
let res = Server::new(|remote| ::start_ws(
&address,
io,
remote,
ws::DomainsValidation::Disabled,
ws::DomainsValidation::Disabled,
extractors::WsExtractor::new(Some(&authcodes.path)),
extractors::WsExtractor::new(Some(&authcodes.path)),
|
extractors::WsStats::new(stats),
).unwrap());
(res, port, authcodes)
}
/// Test a single request to running server
pub fn request(server: Server<ws::Server>, request: &str) -> http_client::Response {
http_client::request(server.server.addr(), request)
}
#[cfg(test)]
mod testing {
use std::time;
use hash::keccak;
use devtools::http_client;
use super::{serve, request};
#[test]
fn should_not_redirect_to_parity_host() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: close\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 200 Ok".to_owned());
}
#[test]
fn should_block_if_authorization_is_incorrect() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: wrong\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 403 Forbidden".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_allow_if_authorization_is_correct() {
// given
let (server, port, mut authcodes) = serve();
let code = authcodes.generate_new().unwrap().replace("-", "");
authcodes.to_file(&authcodes.path).unwrap();
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: {:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
// then
assert_eq!(response.status, "HTTP/1.1 101 Switching Protocols".to_owned());
}
#[test]
fn should_allow_initial_connection_but_only_once() {
// given
let (server, port, authcodes) = serve();
let code = "initial";
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
assert!(authcodes.is_empty());
// when
let response1 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
let response2 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
// then
assert_eq!(response1.status, "HTTP/1.1 101 Switching Protocols".to_owned());
assert_eq!(response2.status, "HTTP/1.1 403 Forbidden".to_owned());
http_client::assert_security_headers_present(&response2.headers, None);
}
}
|
random_line_split
|
|
ws.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! WebSockets server tests.
use std::sync::Arc;
use devtools::http_client;
use jsonrpc_core::MetaIoHandler;
use rand;
use ws;
use v1::{extractors, informant};
use tests::helpers::{GuardedAuthCodes, Server};
/// Setup a mock signer for tests
pub fn serve() -> (Server<ws::Server>, usize, GuardedAuthCodes) {
let port = 35000 + rand::random::<usize>() % 10000;
let address = format!("127.0.0.1:{}", port).parse().unwrap();
let io = MetaIoHandler::default();
let authcodes = GuardedAuthCodes::new();
let stats = Arc::new(informant::RpcStats::default());
let res = Server::new(|remote| ::start_ws(
&address,
io,
remote,
ws::DomainsValidation::Disabled,
ws::DomainsValidation::Disabled,
extractors::WsExtractor::new(Some(&authcodes.path)),
extractors::WsExtractor::new(Some(&authcodes.path)),
extractors::WsStats::new(stats),
).unwrap());
(res, port, authcodes)
}
/// Test a single request to running server
pub fn request(server: Server<ws::Server>, request: &str) -> http_client::Response {
http_client::request(server.server.addr(), request)
}
#[cfg(test)]
mod testing {
use std::time;
use hash::keccak;
use devtools::http_client;
use super::{serve, request};
#[test]
fn should_not_redirect_to_parity_host() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: close\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 200 Ok".to_owned());
}
#[test]
fn should_block_if_authorization_is_incorrect() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: wrong\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 403 Forbidden".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_allow_if_authorization_is_correct() {
// given
let (server, port, mut authcodes) = serve();
let code = authcodes.generate_new().unwrap().replace("-", "");
authcodes.to_file(&authcodes.path).unwrap();
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: {:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
// then
assert_eq!(response.status, "HTTP/1.1 101 Switching Protocols".to_owned());
}
#[test]
fn
|
() {
// given
let (server, port, authcodes) = serve();
let code = "initial";
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
assert!(authcodes.is_empty());
// when
let response1 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
let response2 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
// then
assert_eq!(response1.status, "HTTP/1.1 101 Switching Protocols".to_owned());
assert_eq!(response2.status, "HTTP/1.1 403 Forbidden".to_owned());
http_client::assert_security_headers_present(&response2.headers, None);
}
}
|
should_allow_initial_connection_but_only_once
|
identifier_name
|
ws.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! WebSockets server tests.
use std::sync::Arc;
use devtools::http_client;
use jsonrpc_core::MetaIoHandler;
use rand;
use ws;
use v1::{extractors, informant};
use tests::helpers::{GuardedAuthCodes, Server};
/// Setup a mock signer for tests
pub fn serve() -> (Server<ws::Server>, usize, GuardedAuthCodes) {
let port = 35000 + rand::random::<usize>() % 10000;
let address = format!("127.0.0.1:{}", port).parse().unwrap();
let io = MetaIoHandler::default();
let authcodes = GuardedAuthCodes::new();
let stats = Arc::new(informant::RpcStats::default());
let res = Server::new(|remote| ::start_ws(
&address,
io,
remote,
ws::DomainsValidation::Disabled,
ws::DomainsValidation::Disabled,
extractors::WsExtractor::new(Some(&authcodes.path)),
extractors::WsExtractor::new(Some(&authcodes.path)),
extractors::WsStats::new(stats),
).unwrap());
(res, port, authcodes)
}
/// Test a single request to running server
pub fn request(server: Server<ws::Server>, request: &str) -> http_client::Response {
http_client::request(server.server.addr(), request)
}
#[cfg(test)]
mod testing {
use std::time;
use hash::keccak;
use devtools::http_client;
use super::{serve, request};
#[test]
fn should_not_redirect_to_parity_host()
|
#[test]
fn should_block_if_authorization_is_incorrect() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: wrong\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 403 Forbidden".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_allow_if_authorization_is_correct() {
// given
let (server, port, mut authcodes) = serve();
let code = authcodes.generate_new().unwrap().replace("-", "");
authcodes.to_file(&authcodes.path).unwrap();
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: {:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
// then
assert_eq!(response.status, "HTTP/1.1 101 Switching Protocols".to_owned());
}
#[test]
fn should_allow_initial_connection_but_only_once() {
// given
let (server, port, authcodes) = serve();
let code = "initial";
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
assert!(authcodes.is_empty());
// when
let response1 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
let response2 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
keccak(format!("{}:{}", code, timestamp)),
timestamp,
)
);
// then
assert_eq!(response1.status, "HTTP/1.1 101 Switching Protocols".to_owned());
assert_eq!(response2.status, "HTTP/1.1 403 Forbidden".to_owned());
http_client::assert_security_headers_present(&response2.headers, None);
}
}
|
{
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: close\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 200 Ok".to_owned());
}
|
identifier_body
|
unresolved_type_param.rs
|
// Provoke an unresolved type error (T).
// Error message should pinpoint the type parameter T as needing to be bound
// (rather than give a general error message)
// edition:2018
async fn bar<T>() -> () {}
async fn foo() {
bar().await;
//~^ ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE in this expansion of desugaring of `await`
//~| NOTE in this expansion of desugaring of `await`
//~| NOTE in this expansion of desugaring of `await`
}
fn
|
() {}
|
main
|
identifier_name
|
unresolved_type_param.rs
|
// Provoke an unresolved type error (T).
// Error message should pinpoint the type parameter T as needing to be bound
// (rather than give a general error message)
// edition:2018
|
//~^ ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE in this expansion of desugaring of `await`
//~| NOTE in this expansion of desugaring of `await`
//~| NOTE in this expansion of desugaring of `await`
}
fn main() {}
|
async fn bar<T>() -> () {}
async fn foo() {
bar().await;
|
random_line_split
|
unresolved_type_param.rs
|
// Provoke an unresolved type error (T).
// Error message should pinpoint the type parameter T as needing to be bound
// (rather than give a general error message)
// edition:2018
async fn bar<T>() -> () {}
async fn foo()
|
fn main() {}
|
{
bar().await;
//~^ ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE the type is part of the `async fn` body because of this `await`
//~| NOTE in this expansion of desugaring of `await`
//~| NOTE in this expansion of desugaring of `await`
//~| NOTE in this expansion of desugaring of `await`
}
|
identifier_body
|
to_str.rs
|
use ::ffi;
use ::libc::c_char;
use std::ffi::CStr;
// To-string converters
// See http://www.libnfc.org/api/group__string-converter.html
|
pub fn modulation_type(pnd: ffi::nfc_modulation_type) -> &'static str {
unsafe {
let modulation_type = CStr::from_ptr(ffi::str_nfc_modulation_type(pnd)).to_str().unwrap();
modulation_type
}
}
/// Converts nfc_baud_rate value to string
pub fn baud_rate(baud_rate: ffi::nfc_baud_rate) -> &'static str {
unsafe {
let baud_rate = CStr::from_ptr(ffi::str_nfc_baud_rate(baud_rate)).to_str().unwrap();
baud_rate
}
}
/// Returns the number of characters printed
pub fn target(buf: *mut *mut c_char, pnt: *mut ffi::nfc_target, verbose: u8) -> i32 {
unsafe { ffi::str_nfc_target(buf, pnt, verbose) }
}
|
/// Converts nfc_modulation_type value to string
|
random_line_split
|
to_str.rs
|
use ::ffi;
use ::libc::c_char;
use std::ffi::CStr;
// To-string converters
// See http://www.libnfc.org/api/group__string-converter.html
/// Converts nfc_modulation_type value to string
pub fn modulation_type(pnd: ffi::nfc_modulation_type) -> &'static str {
unsafe {
let modulation_type = CStr::from_ptr(ffi::str_nfc_modulation_type(pnd)).to_str().unwrap();
modulation_type
}
}
/// Converts nfc_baud_rate value to string
pub fn baud_rate(baud_rate: ffi::nfc_baud_rate) -> &'static str
|
/// Returns the number of characters printed
pub fn target(buf: *mut *mut c_char, pnt: *mut ffi::nfc_target, verbose: u8) -> i32 {
unsafe { ffi::str_nfc_target(buf, pnt, verbose) }
}
|
{
unsafe {
let baud_rate = CStr::from_ptr(ffi::str_nfc_baud_rate(baud_rate)).to_str().unwrap();
baud_rate
}
}
|
identifier_body
|
to_str.rs
|
use ::ffi;
use ::libc::c_char;
use std::ffi::CStr;
// To-string converters
// See http://www.libnfc.org/api/group__string-converter.html
/// Converts nfc_modulation_type value to string
pub fn modulation_type(pnd: ffi::nfc_modulation_type) -> &'static str {
unsafe {
let modulation_type = CStr::from_ptr(ffi::str_nfc_modulation_type(pnd)).to_str().unwrap();
modulation_type
}
}
/// Converts nfc_baud_rate value to string
pub fn
|
(baud_rate: ffi::nfc_baud_rate) -> &'static str {
unsafe {
let baud_rate = CStr::from_ptr(ffi::str_nfc_baud_rate(baud_rate)).to_str().unwrap();
baud_rate
}
}
/// Returns the number of characters printed
pub fn target(buf: *mut *mut c_char, pnt: *mut ffi::nfc_target, verbose: u8) -> i32 {
unsafe { ffi::str_nfc_target(buf, pnt, verbose) }
}
|
baud_rate
|
identifier_name
|
name.rs
|
use std;
/// Represents a name.
#[derive(Clone,Debug)]
pub enum Name
{
/// The value is unnamed.
Unnamed,
/// The value has a name.
Named(String),
}
impl Name
{
/// Create an unspecified name.
pub fn unnamed() -> Name {
Name::Unnamed
}
|
Name::Named(name.into())
}
pub fn is_named(&self) -> bool {
match *self {
Name::Unnamed => false,
Name::Named(..) => true,
}
}
}
impl Into<String> for Name
{
fn into(self) -> String {
match self {
Name::Unnamed => unimplemented!(),
Name::Named(s) => s,
}
}
}
impl std::fmt::Display for Name
{
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
match *self {
Name::Unnamed => "unnamed".fmt(fmt), // FIXME: we need to have a global accumulator
Name::Named(ref val) => val.fmt(fmt),
}
}
}
impl std::cmp::PartialEq for Name
{
fn eq(&self, other: &Name) -> bool {
match (self,other) {
(&Name::Named(ref n1),
&Name::Named(ref n2)) => n1 == n2,
_ => false, // unnamed values are always unique
}
}
}
impl std::cmp::Eq for Name { }
|
pub fn named<S>(name: S) -> Name
where S: Into<String> {
|
random_line_split
|
name.rs
|
use std;
/// Represents a name.
#[derive(Clone,Debug)]
pub enum Name
{
/// The value is unnamed.
Unnamed,
/// The value has a name.
Named(String),
}
impl Name
{
/// Create an unspecified name.
pub fn unnamed() -> Name {
Name::Unnamed
}
pub fn named<S>(name: S) -> Name
where S: Into<String> {
Name::Named(name.into())
}
pub fn is_named(&self) -> bool {
match *self {
Name::Unnamed => false,
Name::Named(..) => true,
}
}
}
impl Into<String> for Name
{
fn into(self) -> String {
match self {
Name::Unnamed => unimplemented!(),
Name::Named(s) => s,
}
}
}
impl std::fmt::Display for Name
{
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
match *self {
Name::Unnamed => "unnamed".fmt(fmt), // FIXME: we need to have a global accumulator
Name::Named(ref val) => val.fmt(fmt),
}
}
}
impl std::cmp::PartialEq for Name
{
fn
|
(&self, other: &Name) -> bool {
match (self,other) {
(&Name::Named(ref n1),
&Name::Named(ref n2)) => n1 == n2,
_ => false, // unnamed values are always unique
}
}
}
impl std::cmp::Eq for Name { }
|
eq
|
identifier_name
|
name.rs
|
use std;
/// Represents a name.
#[derive(Clone,Debug)]
pub enum Name
{
/// The value is unnamed.
Unnamed,
/// The value has a name.
Named(String),
}
impl Name
{
/// Create an unspecified name.
pub fn unnamed() -> Name {
Name::Unnamed
}
pub fn named<S>(name: S) -> Name
where S: Into<String> {
Name::Named(name.into())
}
pub fn is_named(&self) -> bool {
match *self {
Name::Unnamed => false,
Name::Named(..) => true,
}
}
}
impl Into<String> for Name
{
fn into(self) -> String {
match self {
Name::Unnamed => unimplemented!(),
Name::Named(s) => s,
}
}
}
impl std::fmt::Display for Name
{
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
match *self {
Name::Unnamed => "unnamed".fmt(fmt), // FIXME: we need to have a global accumulator
Name::Named(ref val) => val.fmt(fmt),
}
}
}
impl std::cmp::PartialEq for Name
{
fn eq(&self, other: &Name) -> bool
|
}
impl std::cmp::Eq for Name { }
|
{
match (self,other) {
(&Name::Named(ref n1),
&Name::Named(ref n2)) => n1 == n2,
_ => false, // unnamed values are always unique
}
}
|
identifier_body
|
traits.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Disk-backed `HashDB` implementation.
use {Bytes, H256, UtilError};
use hashdb::*;
use kvdb::{self, DBTransaction};
use std::sync::Arc;
/// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually
/// exclusive actions.
pub trait JournalDB: HashDB {
/// Return a copy of ourself, in a box.
fn boxed_clone(&self) -> Box<JournalDB>;
/// Returns heap memory size used
fn mem_used(&self) -> usize;
/// Returns the size of journalled state in memory.
/// This function has a considerable speed requirement --
/// it must be fast enough to call several times per block imported.
fn journal_size(&self) -> usize {
0
}
/// Check if this database has any commits
fn is_empty(&self) -> bool;
/// Get the earliest era in the DB. None if there isn't yet any data in there.
fn earliest_era(&self) -> Option<u64> {
None
}
/// Get the latest era in the DB. None if there isn't yet any data in there.
fn latest_era(&self) -> Option<u64>;
/// Journal recent database operations as being associated with a given era and id.
// TODO: give the overlay to this function so journaldbs don't manage the overlays themeselves.
fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError>;
/// Mark a given block as canonical, indicating that competing blocks' states may be pruned out.
fn mark_canonical(&mut self, batch: &mut DBTransaction, era: u64, id: &H256) -> Result<u32, UtilError>;
/// Commit all queued insert and delete operations without affecting any journalling -- this requires that all insertions
/// and deletions are indeed canonical and will likely lead to an invalid database if that assumption is violated.
///
/// Any keys or values inserted or deleted must be completely independent of those affected
/// by any previous `commit` operations. Essentially, this means that `inject` can be used
/// either to restore a state to a fresh database, or to insert data which may only be journalled
/// from this point onwards.
fn inject(&mut self, batch: &mut DBTransaction) -> Result<u32, UtilError>;
/// State data query
fn state(&self, _id: &H256) -> Option<Bytes>;
/// Whether this database is pruned.
fn is_pruned(&self) -> bool {
true
}
/// Get backing database.
fn backing(&self) -> &Arc<kvdb::KeyValueDB>;
/// Clear internal strucutres. This should called after changes have been written
/// to the backing strage
fn flush(&self) {}
/// Consolidate all the insertions and deletions in the given memory overlay.
fn consolidate(&mut self, overlay: ::memorydb::MemoryDB);
/// Commit all changes in a single batch
#[cfg(test)]
fn commit_batch(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let mut ops = self.journal_under(&mut batch, now, id)?;
if let Some((end_era, canon_id)) = end {
ops += self.mark_canonical(&mut batch, end_era, &canon_id)?;
}
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into);
self.flush();
result
}
/// Inject all changes in a single batch.
#[cfg(test)]
fn
|
(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let res = self.inject(&mut batch)?;
self.backing().write(batch).map(|_| res).map_err(Into::into)
}
}
|
inject_batch
|
identifier_name
|
traits.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Disk-backed `HashDB` implementation.
use {Bytes, H256, UtilError};
use hashdb::*;
use kvdb::{self, DBTransaction};
use std::sync::Arc;
/// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually
/// exclusive actions.
pub trait JournalDB: HashDB {
/// Return a copy of ourself, in a box.
fn boxed_clone(&self) -> Box<JournalDB>;
/// Returns heap memory size used
fn mem_used(&self) -> usize;
/// Returns the size of journalled state in memory.
/// This function has a considerable speed requirement --
/// it must be fast enough to call several times per block imported.
fn journal_size(&self) -> usize {
0
}
/// Check if this database has any commits
fn is_empty(&self) -> bool;
/// Get the earliest era in the DB. None if there isn't yet any data in there.
fn earliest_era(&self) -> Option<u64>
|
/// Get the latest era in the DB. None if there isn't yet any data in there.
fn latest_era(&self) -> Option<u64>;
/// Journal recent database operations as being associated with a given era and id.
// TODO: give the overlay to this function so journaldbs don't manage the overlays themeselves.
fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError>;
/// Mark a given block as canonical, indicating that competing blocks' states may be pruned out.
fn mark_canonical(&mut self, batch: &mut DBTransaction, era: u64, id: &H256) -> Result<u32, UtilError>;
/// Commit all queued insert and delete operations without affecting any journalling -- this requires that all insertions
/// and deletions are indeed canonical and will likely lead to an invalid database if that assumption is violated.
///
/// Any keys or values inserted or deleted must be completely independent of those affected
/// by any previous `commit` operations. Essentially, this means that `inject` can be used
/// either to restore a state to a fresh database, or to insert data which may only be journalled
/// from this point onwards.
fn inject(&mut self, batch: &mut DBTransaction) -> Result<u32, UtilError>;
/// State data query
fn state(&self, _id: &H256) -> Option<Bytes>;
/// Whether this database is pruned.
fn is_pruned(&self) -> bool {
true
}
/// Get backing database.
fn backing(&self) -> &Arc<kvdb::KeyValueDB>;
/// Clear internal strucutres. This should called after changes have been written
/// to the backing strage
fn flush(&self) {}
/// Consolidate all the insertions and deletions in the given memory overlay.
fn consolidate(&mut self, overlay: ::memorydb::MemoryDB);
/// Commit all changes in a single batch
#[cfg(test)]
fn commit_batch(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let mut ops = self.journal_under(&mut batch, now, id)?;
if let Some((end_era, canon_id)) = end {
ops += self.mark_canonical(&mut batch, end_era, &canon_id)?;
}
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into);
self.flush();
result
}
/// Inject all changes in a single batch.
#[cfg(test)]
fn inject_batch(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let res = self.inject(&mut batch)?;
self.backing().write(batch).map(|_| res).map_err(Into::into)
}
}
|
{
None
}
|
identifier_body
|
traits.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Disk-backed `HashDB` implementation.
use {Bytes, H256, UtilError};
use hashdb::*;
use kvdb::{self, DBTransaction};
use std::sync::Arc;
/// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually
/// exclusive actions.
pub trait JournalDB: HashDB {
/// Return a copy of ourself, in a box.
fn boxed_clone(&self) -> Box<JournalDB>;
/// Returns heap memory size used
fn mem_used(&self) -> usize;
/// Returns the size of journalled state in memory.
/// This function has a considerable speed requirement --
/// it must be fast enough to call several times per block imported.
fn journal_size(&self) -> usize {
0
}
/// Check if this database has any commits
fn is_empty(&self) -> bool;
/// Get the earliest era in the DB. None if there isn't yet any data in there.
fn earliest_era(&self) -> Option<u64> {
None
}
/// Get the latest era in the DB. None if there isn't yet any data in there.
fn latest_era(&self) -> Option<u64>;
/// Journal recent database operations as being associated with a given era and id.
// TODO: give the overlay to this function so journaldbs don't manage the overlays themeselves.
fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError>;
/// Mark a given block as canonical, indicating that competing blocks' states may be pruned out.
fn mark_canonical(&mut self, batch: &mut DBTransaction, era: u64, id: &H256) -> Result<u32, UtilError>;
/// Commit all queued insert and delete operations without affecting any journalling -- this requires that all insertions
/// and deletions are indeed canonical and will likely lead to an invalid database if that assumption is violated.
///
/// Any keys or values inserted or deleted must be completely independent of those affected
/// by any previous `commit` operations. Essentially, this means that `inject` can be used
/// either to restore a state to a fresh database, or to insert data which may only be journalled
/// from this point onwards.
fn inject(&mut self, batch: &mut DBTransaction) -> Result<u32, UtilError>;
/// State data query
fn state(&self, _id: &H256) -> Option<Bytes>;
/// Whether this database is pruned.
fn is_pruned(&self) -> bool {
true
}
/// Get backing database.
fn backing(&self) -> &Arc<kvdb::KeyValueDB>;
/// Clear internal strucutres. This should called after changes have been written
/// to the backing strage
fn flush(&self) {}
/// Consolidate all the insertions and deletions in the given memory overlay.
fn consolidate(&mut self, overlay: ::memorydb::MemoryDB);
/// Commit all changes in a single batch
#[cfg(test)]
fn commit_batch(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let mut ops = self.journal_under(&mut batch, now, id)?;
if let Some((end_era, canon_id)) = end
|
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into);
self.flush();
result
}
/// Inject all changes in a single batch.
#[cfg(test)]
fn inject_batch(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let res = self.inject(&mut batch)?;
self.backing().write(batch).map(|_| res).map_err(Into::into)
}
}
|
{
ops += self.mark_canonical(&mut batch, end_era, &canon_id)?;
}
|
conditional_block
|
traits.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Disk-backed `HashDB` implementation.
use {Bytes, H256, UtilError};
use hashdb::*;
use kvdb::{self, DBTransaction};
use std::sync::Arc;
/// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually
/// exclusive actions.
pub trait JournalDB: HashDB {
/// Return a copy of ourself, in a box.
fn boxed_clone(&self) -> Box<JournalDB>;
/// Returns heap memory size used
fn mem_used(&self) -> usize;
/// Returns the size of journalled state in memory.
/// This function has a considerable speed requirement --
/// it must be fast enough to call several times per block imported.
fn journal_size(&self) -> usize {
0
}
/// Check if this database has any commits
fn is_empty(&self) -> bool;
/// Get the earliest era in the DB. None if there isn't yet any data in there.
fn earliest_era(&self) -> Option<u64> {
None
}
/// Get the latest era in the DB. None if there isn't yet any data in there.
fn latest_era(&self) -> Option<u64>;
/// Journal recent database operations as being associated with a given era and id.
// TODO: give the overlay to this function so journaldbs don't manage the overlays themeselves.
fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError>;
/// Mark a given block as canonical, indicating that competing blocks' states may be pruned out.
fn mark_canonical(&mut self, batch: &mut DBTransaction, era: u64, id: &H256) -> Result<u32, UtilError>;
/// Commit all queued insert and delete operations without affecting any journalling -- this requires that all insertions
/// and deletions are indeed canonical and will likely lead to an invalid database if that assumption is violated.
///
/// Any keys or values inserted or deleted must be completely independent of those affected
/// by any previous `commit` operations. Essentially, this means that `inject` can be used
/// either to restore a state to a fresh database, or to insert data which may only be journalled
/// from this point onwards.
fn inject(&mut self, batch: &mut DBTransaction) -> Result<u32, UtilError>;
/// State data query
fn state(&self, _id: &H256) -> Option<Bytes>;
/// Whether this database is pruned.
fn is_pruned(&self) -> bool {
true
}
/// Get backing database.
fn backing(&self) -> &Arc<kvdb::KeyValueDB>;
/// Clear internal strucutres. This should called after changes have been written
/// to the backing strage
fn flush(&self) {}
/// Consolidate all the insertions and deletions in the given memory overlay.
fn consolidate(&mut self, overlay: ::memorydb::MemoryDB);
/// Commit all changes in a single batch
#[cfg(test)]
fn commit_batch(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let mut ops = self.journal_under(&mut batch, now, id)?;
if let Some((end_era, canon_id)) = end {
ops += self.mark_canonical(&mut batch, end_era, &canon_id)?;
}
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into);
self.flush();
result
}
/// Inject all changes in a single batch.
|
let res = self.inject(&mut batch)?;
self.backing().write(batch).map(|_| res).map_err(Into::into)
}
}
|
#[cfg(test)]
fn inject_batch(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
|
random_line_split
|
workqueue.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use task::spawn_named;
use task_state;
use libc::funcs::posix88::unistd::usleep;
use rand::{Rng, weak_rng, XorShiftRng};
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData:'static, WorkData:'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static> {
Finished,
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {}
static SPIN_COUNT: u32 = 128;
static SPINS_UNTIL_BACKOFF: u32 = 100;
static BACKOFF_INCREMENT_IN_US: u32 = 5;
impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
};
let mut back_off_sleep = 0 as u32;
// We're off!
//
// FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug.
loop {
// FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue
// cross-crate.
let mut work_unit = unsafe {
mem::uninitialized()
};
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
let mut should_continue = true;
loop {
let victim = (self.rng.next_u32() as usize) % self.other_deques.len();
match self.other_deques[victim].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF_INCREMENT_IN_US;
}
if i == SPIN_COUNT {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => {
should_continue = false;
break
}
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
i = 0
} else {
i += 1
}
}
if!should_continue {
break
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
queue_data: queue_data,
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::SeqCst) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: *const QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::SeqCst));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data<'b>(&'b self) -> &'b QueueData {
unsafe {
mem::transmute(self.queue_data)
}
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
/// Arbitrary user data.
pub data: QueueData,
}
impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(task_name: &'static str,
state: task_state::TaskState,
thread_count: usize,
user_data: QueueData) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let pool = BufferPool::new();
let (worker, thief) = pool.deque();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for i in 0..thread_count {
for j in 0..thread_count {
if i!= j {
threads[i].other_deques.push(infos[j].thief.clone())
}
}
assert!(threads[i].other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", task_name, i+1, thread_count),
move || {
task_state::initialize(state | task_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
data: user_data,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>)
|
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in self.workers.iter_mut() {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
&self.data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
pub fn shutdown(&mut self) {
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
|
{
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
|
identifier_body
|
workqueue.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use task::spawn_named;
use task_state;
use libc::funcs::posix88::unistd::usleep;
use rand::{Rng, weak_rng, XorShiftRng};
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData:'static, WorkData:'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static> {
Finished,
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {}
static SPIN_COUNT: u32 = 128;
static SPINS_UNTIL_BACKOFF: u32 = 100;
static BACKOFF_INCREMENT_IN_US: u32 = 5;
impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
};
let mut back_off_sleep = 0 as u32;
// We're off!
//
// FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug.
loop {
// FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue
// cross-crate.
let mut work_unit = unsafe {
mem::uninitialized()
};
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
let mut should_continue = true;
loop {
let victim = (self.rng.next_u32() as usize) % self.other_deques.len();
match self.other_deques[victim].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF_INCREMENT_IN_US;
}
if i == SPIN_COUNT {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => {
should_continue = false;
break
}
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
i = 0
} else {
i += 1
}
}
if!should_continue {
break
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
queue_data: queue_data,
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::SeqCst) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: *const QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::SeqCst));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data<'b>(&'b self) -> &'b QueueData {
unsafe {
mem::transmute(self.queue_data)
}
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
/// Arbitrary user data.
pub data: QueueData,
}
impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(task_name: &'static str,
state: task_state::TaskState,
thread_count: usize,
user_data: QueueData) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let pool = BufferPool::new();
let (worker, thief) = pool.deque();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for i in 0..thread_count {
for j in 0..thread_count {
if i!= j {
threads[i].other_deques.push(infos[j].thief.clone())
}
}
assert!(threads[i].other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", task_name, i+1, thread_count),
move || {
task_state::initialize(state | task_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
data: user_data,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None =>
|
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in self.workers.iter_mut() {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
&self.data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
pub fn shutdown(&mut self) {
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
|
{
panic!("tried to push a block but we don't have the deque?!")
}
|
conditional_block
|
workqueue.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use task::spawn_named;
use task_state;
use libc::funcs::posix88::unistd::usleep;
use rand::{Rng, weak_rng, XorShiftRng};
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum
|
<QueueData:'static, WorkData:'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static> {
Finished,
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {}
static SPIN_COUNT: u32 = 128;
static SPINS_UNTIL_BACKOFF: u32 = 100;
static BACKOFF_INCREMENT_IN_US: u32 = 5;
impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
};
let mut back_off_sleep = 0 as u32;
// We're off!
//
// FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug.
loop {
// FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue
// cross-crate.
let mut work_unit = unsafe {
mem::uninitialized()
};
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
let mut should_continue = true;
loop {
let victim = (self.rng.next_u32() as usize) % self.other_deques.len();
match self.other_deques[victim].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF_INCREMENT_IN_US;
}
if i == SPIN_COUNT {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => {
should_continue = false;
break
}
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
i = 0
} else {
i += 1
}
}
if!should_continue {
break
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
queue_data: queue_data,
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::SeqCst) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: *const QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::SeqCst));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data<'b>(&'b self) -> &'b QueueData {
unsafe {
mem::transmute(self.queue_data)
}
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
/// Arbitrary user data.
pub data: QueueData,
}
impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(task_name: &'static str,
state: task_state::TaskState,
thread_count: usize,
user_data: QueueData) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let pool = BufferPool::new();
let (worker, thief) = pool.deque();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for i in 0..thread_count {
for j in 0..thread_count {
if i!= j {
threads[i].other_deques.push(infos[j].thief.clone())
}
}
assert!(threads[i].other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", task_name, i+1, thread_count),
move || {
task_state::initialize(state | task_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
data: user_data,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in self.workers.iter_mut() {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
&self.data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
pub fn shutdown(&mut self) {
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
|
WorkerMsg
|
identifier_name
|
workqueue.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use task::spawn_named;
use task_state;
use libc::funcs::posix88::unistd::usleep;
use rand::{Rng, weak_rng, XorShiftRng};
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData:'static, WorkData:'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static> {
Finished,
|
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {}
static SPIN_COUNT: u32 = 128;
static SPINS_UNTIL_BACKOFF: u32 = 100;
static BACKOFF_INCREMENT_IN_US: u32 = 5;
impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
};
let mut back_off_sleep = 0 as u32;
// We're off!
//
// FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug.
loop {
// FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue
// cross-crate.
let mut work_unit = unsafe {
mem::uninitialized()
};
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
let mut should_continue = true;
loop {
let victim = (self.rng.next_u32() as usize) % self.other_deques.len();
match self.other_deques[victim].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF_INCREMENT_IN_US;
}
if i == SPIN_COUNT {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => {
should_continue = false;
break
}
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
i = 0
} else {
i += 1
}
}
if!should_continue {
break
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
queue_data: queue_data,
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::SeqCst) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: *const QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::SeqCst));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data<'b>(&'b self) -> &'b QueueData {
unsafe {
mem::transmute(self.queue_data)
}
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
/// Arbitrary user data.
pub data: QueueData,
}
impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(task_name: &'static str,
state: task_state::TaskState,
thread_count: usize,
user_data: QueueData) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let pool = BufferPool::new();
let (worker, thief) = pool.deque();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for i in 0..thread_count {
for j in 0..thread_count {
if i!= j {
threads[i].other_deques.push(infos[j].thief.clone())
}
}
assert!(threads[i].other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", task_name, i+1, thread_count),
move || {
task_state::initialize(state | task_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
data: user_data,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in self.workers.iter_mut() {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
&self.data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
pub fn shutdown(&mut self) {
for worker in self.workers.iter() {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
|
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData: 'static, WorkData: 'static> Send for SupervisorMsg<QueueData, WorkData> {}
|
random_line_split
|
ioport.rs
|
// Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Genesis 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 Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Genesis. If not, see <http://www.gnu.org/licenses/>.
pub unsafe fn out<T>(port: u16, val: T) {
asm!("out $0, $1"
: // no output
: "{al}" (val), "{dx}" (port)
: // no clobber
: "volatile");
}
pub unsafe fn inb(port: u16) -> u8 {
let val: u8;
asm!("in $1, $0"
: "={al}" (val)
: "{dx}" (port)
: // no clobber
: "volatile");
val
|
}
|
random_line_split
|
|
ioport.rs
|
// Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Genesis 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 Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Genesis. If not, see <http://www.gnu.org/licenses/>.
pub unsafe fn
|
<T>(port: u16, val: T) {
asm!("out $0, $1"
: // no output
: "{al}" (val), "{dx}" (port)
: // no clobber
: "volatile");
}
pub unsafe fn inb(port: u16) -> u8 {
let val: u8;
asm!("in $1, $0"
: "={al}" (val)
: "{dx}" (port)
: // no clobber
: "volatile");
val
}
|
out
|
identifier_name
|
ioport.rs
|
// Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Genesis 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 Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Genesis. If not, see <http://www.gnu.org/licenses/>.
pub unsafe fn out<T>(port: u16, val: T) {
asm!("out $0, $1"
: // no output
: "{al}" (val), "{dx}" (port)
: // no clobber
: "volatile");
}
pub unsafe fn inb(port: u16) -> u8
|
{
let val: u8;
asm!("in $1, $0"
: "={al}" (val)
: "{dx}" (port)
: // no clobber
: "volatile");
val
}
|
identifier_body
|
|
vocabs.rs
|
extern crate rand;
use bahasa::bimap::Bimap;
pub struct Vocabs<'a> {
vocabs: Bimap<&'a str, &'a str>,
vocab_vector: Vec<&'a str>,
}
impl<'b> Vocabs<'b> {
pub fn new<'c> () -> Vocabs<'c> {
Vocabs { vocabs: Bimap::new(), vocab_vector: vec![] }
}
pub fn insert(&mut self, first: &'static str, second: &'static str) {
self.vocabs.insert(first, second);
self.vocab_vector.push(first);
}
pub fn get<'a>(&'a self, string: &'a str) -> Option<&&str> {
self.vocabs.get(&string)
}
pub fn get_random(&self) -> &str {
let r = rand::random::<f64>();
|
let index = (r * self.vocab_vector.len() as f64) as usize;
self.vocab_vector[index]
}
}
|
random_line_split
|
|
vocabs.rs
|
extern crate rand;
use bahasa::bimap::Bimap;
pub struct Vocabs<'a> {
vocabs: Bimap<&'a str, &'a str>,
vocab_vector: Vec<&'a str>,
}
impl<'b> Vocabs<'b> {
pub fn new<'c> () -> Vocabs<'c>
|
pub fn insert(&mut self, first: &'static str, second: &'static str) {
self.vocabs.insert(first, second);
self.vocab_vector.push(first);
}
pub fn get<'a>(&'a self, string: &'a str) -> Option<&&str> {
self.vocabs.get(&string)
}
pub fn get_random(&self) -> &str {
let r = rand::random::<f64>();
let index = (r * self.vocab_vector.len() as f64) as usize;
self.vocab_vector[index]
}
}
|
{
Vocabs { vocabs: Bimap::new(), vocab_vector: vec![] }
}
|
identifier_body
|
vocabs.rs
|
extern crate rand;
use bahasa::bimap::Bimap;
pub struct Vocabs<'a> {
vocabs: Bimap<&'a str, &'a str>,
vocab_vector: Vec<&'a str>,
}
impl<'b> Vocabs<'b> {
pub fn new<'c> () -> Vocabs<'c> {
Vocabs { vocabs: Bimap::new(), vocab_vector: vec![] }
}
pub fn insert(&mut self, first: &'static str, second: &'static str) {
self.vocabs.insert(first, second);
self.vocab_vector.push(first);
}
pub fn
|
<'a>(&'a self, string: &'a str) -> Option<&&str> {
self.vocabs.get(&string)
}
pub fn get_random(&self) -> &str {
let r = rand::random::<f64>();
let index = (r * self.vocab_vector.len() as f64) as usize;
self.vocab_vector[index]
}
}
|
get
|
identifier_name
|
monitor.rs
|
//! Asynchronous server and topology discovery and monitoring using isMaster results.
use {Client, Result};
use Error::{self, ArgumentError, OperationError};
use bson::{self, Bson, oid};
use chrono::{DateTime, UTC};
use coll::options::FindOptions;
use command_type::CommandType;
use connstring::{self, Host};
use cursor::Cursor;
use pool::ConnectionPool;
use wire_protocol::flags::OpQueryFlags;
use std::collections::BTreeMap;
use std::sync::{Arc, Condvar, Mutex, RwLock};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use time;
use super::server::{ServerDescription, ServerType};
use super::{DEFAULT_HEARTBEAT_FREQUENCY_MS, TopologyDescription};
const DEFAULT_MAX_BSON_OBJECT_SIZE: i64 = 16 * 1024 * 1024;
const DEFAULT_MAX_MESSAGE_SIZE_BYTES: i64 = 48000000;
/// The result of an isMaster operation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IsMasterResult {
pub ok: bool,
pub is_master: bool,
pub max_bson_object_size: i64,
pub max_message_size_bytes: i64,
pub local_time: Option<DateTime<UTC>>,
pub min_wire_version: i64,
pub max_wire_version: i64,
/// Shard-specific. mongos instances will add this field to the
/// isMaster reply, and it will contain the value "isdbgrid".
pub msg: String,
// Replica Set specific
pub is_replica_set: bool,
pub is_secondary: bool,
pub me: Option<Host>,
pub hosts: Vec<Host>,
pub passives: Vec<Host>,
pub arbiters: Vec<Host>,
pub arbiter_only: bool,
pub tags: BTreeMap<String, String>,
pub set_name: String,
pub election_id: Option<oid::ObjectId>,
pub primary: Option<Host>,
pub hidden: bool,
}
/// Monitors and updates server and topology information.
pub struct Monitor {
// Host being monitored.
host: Host,
// Connection pool for the host.
server_pool: Arc<ConnectionPool>,
// Topology description to update.
top_description: Arc<RwLock<TopologyDescription>>,
// Server description to update.
server_description: Arc<RwLock<ServerDescription>>,
// Client reference.
client: Client,
// Owned, single-threaded pool.
personal_pool: Arc<ConnectionPool>,
// Owned copy of the topology's heartbeat frequency.
heartbeat_frequency_ms: AtomicUsize,
// Used for condvar functionality.
dummy_lock: Mutex<()>,
// To allow servers to request an immediate update, this
// condvar can be notified to wake up the monitor.
condvar: Condvar,
/// While true, the monitor will check server connection health
/// at the topology's heartbeat frequency rate.
pub running: Arc<AtomicBool>,
}
impl IsMasterResult {
/// Parses an isMaster response document from the server.
pub fn new(doc: bson::Document) -> Result<IsMasterResult> {
let ok = match doc.get("ok") {
Some(&Bson::I32(v)) => if v == 0 { false } else { true },
Some(&Bson::I64(v)) => if v == 0 { false } else { true },
Some(&Bson::FloatingPoint(v)) => if v == 0.0 { false } else { true },
_ => return Err(ArgumentError("result does not contain `ok`.".to_owned())),
};
let mut result = IsMasterResult {
ok: ok,
is_master: false,
max_bson_object_size: DEFAULT_MAX_BSON_OBJECT_SIZE,
max_message_size_bytes: DEFAULT_MAX_MESSAGE_SIZE_BYTES,
local_time: None,
min_wire_version: -1,
max_wire_version: -1,
msg: String::new(),
is_secondary: false,
is_replica_set: false,
me: None,
hosts: Vec::new(),
passives: Vec::new(),
arbiters: Vec::new(),
arbiter_only: false,
tags: BTreeMap::new(),
set_name: String::new(),
election_id: None,
primary: None,
hidden: false,
};
if let Some(&Bson::Boolean(b)) = doc.get("ismaster") {
result.is_master = b;
}
if let Some(&Bson::UtcDatetime(ref datetime)) = doc.get("localTime") {
result.local_time = Some(datetime.clone());
}
if let Some(&Bson::I64(v)) = doc.get("minWireVersion") {
result.min_wire_version = v;
}
if let Some(&Bson::I64(v)) = doc.get("maxWireVersion") {
result.max_wire_version = v;
}
if let Some(&Bson::String(ref s)) = doc.get("msg") {
result.msg = s.to_owned();
}
if let Some(&Bson::Boolean(ref b)) = doc.get("secondary") {
result.is_secondary = *b;
}
if let Some(&Bson::Boolean(ref b)) = doc.get("isreplicaset") {
result.is_replica_set = *b;
}
if let Some(&Bson::String(ref s)) = doc.get("setName") {
result.set_name = s.to_owned();
}
if let Some(&Bson::String(ref s)) = doc.get("me") {
result.me = Some(try!(connstring::parse_host(s)));
}
if let Some(&Bson::Array(ref arr)) = doc.get("hosts") {
result.hosts = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::Array(ref arr)) = doc.get("passives") {
result.passives = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::Array(ref arr)) = doc.get("arbiters") {
result.arbiters = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::String(ref s)) = doc.get("primary") {
result.primary = Some(try!(connstring::parse_host(s)));
}
if let Some(&Bson::Boolean(ref b)) = doc.get("arbiterOnly") {
result.arbiter_only = *b;
}
if let Some(&Bson::Boolean(ref h)) = doc.get("hidden") {
result.hidden = *h;
}
if let Some(&Bson::Document(ref doc)) = doc.get("tags") {
for (k, v) in doc.into_iter() {
if let &Bson::String(ref tag) = v {
result.tags.insert(k.to_owned(), tag.to_owned());
}
}
}
match doc.get("electionId") {
Some(&Bson::ObjectId(ref id)) => result.election_id = Some(id.clone()),
Some(&Bson::Document(ref doc)) => if let Some(&Bson::String(ref s)) = doc.get("$oid") {
result.election_id = Some(try!(oid::ObjectId::with_string(s)));
},
_ => (),
}
Ok(result)
}
}
impl Monitor {
/// Returns a new monitor connected to the server.
pub fn new(client: Client, host: Host, pool: Arc<ConnectionPool>,
top_description: Arc<RwLock<TopologyDescription>>,
server_description: Arc<RwLock<ServerDescription>>) -> Monitor {
Monitor {
client: client,
host: host.clone(),
server_pool: pool,
personal_pool: Arc::new(ConnectionPool::with_size(host, 1)),
top_description: top_description,
server_description: server_description,
heartbeat_frequency_ms: AtomicUsize::new(DEFAULT_HEARTBEAT_FREQUENCY_MS as usize),
dummy_lock: Mutex::new(()),
condvar: Condvar::new(),
running: Arc::new(AtomicBool::new(false)),
}
}
// Set server description error field.
fn set_err(&self, err: Error) {
let mut server_description = self.server_description.write().unwrap();
server_description.set_err(err);
self.update_top_description(server_description.clone());
}
/// Returns an isMaster server response using an owned monitor socket.
pub fn is_master(&self) -> Result<(Cursor, i64)> {
let options = FindOptions::new().with_limit(1);
let flags = OpQueryFlags::with_find_options(&options);
let mut filter = bson::Document::new();
filter.insert("isMaster".to_owned(), Bson::I32(1));
let stream = try!(self.personal_pool.acquire_stream());
let time_start = time::get_time();
let cursor = try!(Cursor::query_with_stream(
stream, self.client.clone(), "local.$cmd".to_owned(), 1,
flags, options.skip as i32, 1, filter.clone(), options.projection.clone(),
CommandType::IsMaster, false, None));
let time_end = time::get_time();
let sec_start_ms: i64 = time_start.sec * 1000;
let start_ms = sec_start_ms + time_start.nsec as i64 / 1000000;
let sec_end_ms: i64 = time_end.sec * 1000;
let end_ms = sec_end_ms + time_end.nsec as i64 / 1000000;
let round_trip_time = end_ms - start_ms;
Ok((cursor, round_trip_time))
}
pub fn request_update(&self) {
self.condvar.notify_one();
}
// Updates the server description associated with this monitor using an isMaster server response.
fn update_server_description(&self, doc: bson::Document,
round_trip_time: i64) -> Result<ServerDescription> {
|
let ismaster_result = IsMasterResult::new(doc);
let mut server_description = self.server_description.write().unwrap();
match ismaster_result {
Ok(ismaster) => server_description.update(ismaster, round_trip_time),
Err(err) => {
server_description.set_err(err);
return Err(OperationError("Failed to parse ismaster result.".to_owned()))
},
}
Ok(server_description.clone())
}
// Updates the topology description associated with this monitor using a new server description.
fn update_top_description(&self, description: ServerDescription) {
let mut top_description = self.top_description.write().unwrap();
top_description.update(self.host.clone(), description, self.client.clone(),
self.top_description.clone());
}
// Updates server and topology descriptions using a successful isMaster cursor result.
fn update_with_is_master_cursor(&self, cursor: &mut Cursor, round_trip_time: i64) {
match cursor.next() {
Some(Ok(doc)) => {
if let Ok(description) = self.update_server_description(doc, round_trip_time) {
self.update_top_description(description);
}
},
Some(Err(err)) => {
self.set_err(err);
},
None => {
self.set_err(OperationError("ismaster returned no response.".to_owned()));
}
}
}
/// Execute isMaster and update the server and topology.
fn execute_update(&self) {
match self.is_master() {
Ok((mut cursor, rtt)) => self.update_with_is_master_cursor(&mut cursor, rtt),
Err(err) => {
// Refresh all connections
self.server_pool.clear();
self.personal_pool.clear();
let stype = self.server_description.read().unwrap().server_type;
if stype == ServerType::Unknown {
self.set_err(err);
} else {
// Retry once
match self.is_master() {
Ok((mut cursor, rtt)) => self.update_with_is_master_cursor(&mut cursor, rtt),
Err(err) => self.set_err(err),
}
}
}
}
}
/// Starts server monitoring.
pub fn run(&self) {
if self.running.load(Ordering::SeqCst) {
return;
}
self.running.store(true, Ordering::SeqCst);
let mut guard = self.dummy_lock.lock().unwrap();
loop {
if!self.running.load(Ordering::SeqCst) {
break;
}
self.execute_update();
if let Ok(description) = self.top_description.read() {
self.heartbeat_frequency_ms.store(description.heartbeat_frequency_ms as usize,
Ordering::SeqCst);
}
let frequency = self.heartbeat_frequency_ms.load(Ordering::SeqCst) as u32;
guard = self.condvar.wait_timeout_ms(guard, frequency).unwrap().0;
}
}
}
|
random_line_split
|
|
monitor.rs
|
//! Asynchronous server and topology discovery and monitoring using isMaster results.
use {Client, Result};
use Error::{self, ArgumentError, OperationError};
use bson::{self, Bson, oid};
use chrono::{DateTime, UTC};
use coll::options::FindOptions;
use command_type::CommandType;
use connstring::{self, Host};
use cursor::Cursor;
use pool::ConnectionPool;
use wire_protocol::flags::OpQueryFlags;
use std::collections::BTreeMap;
use std::sync::{Arc, Condvar, Mutex, RwLock};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use time;
use super::server::{ServerDescription, ServerType};
use super::{DEFAULT_HEARTBEAT_FREQUENCY_MS, TopologyDescription};
const DEFAULT_MAX_BSON_OBJECT_SIZE: i64 = 16 * 1024 * 1024;
const DEFAULT_MAX_MESSAGE_SIZE_BYTES: i64 = 48000000;
/// The result of an isMaster operation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IsMasterResult {
pub ok: bool,
pub is_master: bool,
pub max_bson_object_size: i64,
pub max_message_size_bytes: i64,
pub local_time: Option<DateTime<UTC>>,
pub min_wire_version: i64,
pub max_wire_version: i64,
/// Shard-specific. mongos instances will add this field to the
/// isMaster reply, and it will contain the value "isdbgrid".
pub msg: String,
// Replica Set specific
pub is_replica_set: bool,
pub is_secondary: bool,
pub me: Option<Host>,
pub hosts: Vec<Host>,
pub passives: Vec<Host>,
pub arbiters: Vec<Host>,
pub arbiter_only: bool,
pub tags: BTreeMap<String, String>,
pub set_name: String,
pub election_id: Option<oid::ObjectId>,
pub primary: Option<Host>,
pub hidden: bool,
}
/// Monitors and updates server and topology information.
pub struct Monitor {
// Host being monitored.
host: Host,
// Connection pool for the host.
server_pool: Arc<ConnectionPool>,
// Topology description to update.
top_description: Arc<RwLock<TopologyDescription>>,
// Server description to update.
server_description: Arc<RwLock<ServerDescription>>,
// Client reference.
client: Client,
// Owned, single-threaded pool.
personal_pool: Arc<ConnectionPool>,
// Owned copy of the topology's heartbeat frequency.
heartbeat_frequency_ms: AtomicUsize,
// Used for condvar functionality.
dummy_lock: Mutex<()>,
// To allow servers to request an immediate update, this
// condvar can be notified to wake up the monitor.
condvar: Condvar,
/// While true, the monitor will check server connection health
/// at the topology's heartbeat frequency rate.
pub running: Arc<AtomicBool>,
}
impl IsMasterResult {
/// Parses an isMaster response document from the server.
pub fn new(doc: bson::Document) -> Result<IsMasterResult> {
let ok = match doc.get("ok") {
Some(&Bson::I32(v)) => if v == 0 { false } else { true },
Some(&Bson::I64(v)) => if v == 0 { false } else { true },
Some(&Bson::FloatingPoint(v)) => if v == 0.0 { false } else { true },
_ => return Err(ArgumentError("result does not contain `ok`.".to_owned())),
};
let mut result = IsMasterResult {
ok: ok,
is_master: false,
max_bson_object_size: DEFAULT_MAX_BSON_OBJECT_SIZE,
max_message_size_bytes: DEFAULT_MAX_MESSAGE_SIZE_BYTES,
local_time: None,
min_wire_version: -1,
max_wire_version: -1,
msg: String::new(),
is_secondary: false,
is_replica_set: false,
me: None,
hosts: Vec::new(),
passives: Vec::new(),
arbiters: Vec::new(),
arbiter_only: false,
tags: BTreeMap::new(),
set_name: String::new(),
election_id: None,
primary: None,
hidden: false,
};
if let Some(&Bson::Boolean(b)) = doc.get("ismaster") {
result.is_master = b;
}
if let Some(&Bson::UtcDatetime(ref datetime)) = doc.get("localTime") {
result.local_time = Some(datetime.clone());
}
if let Some(&Bson::I64(v)) = doc.get("minWireVersion") {
result.min_wire_version = v;
}
if let Some(&Bson::I64(v)) = doc.get("maxWireVersion") {
result.max_wire_version = v;
}
if let Some(&Bson::String(ref s)) = doc.get("msg") {
result.msg = s.to_owned();
}
if let Some(&Bson::Boolean(ref b)) = doc.get("secondary") {
result.is_secondary = *b;
}
if let Some(&Bson::Boolean(ref b)) = doc.get("isreplicaset") {
result.is_replica_set = *b;
}
if let Some(&Bson::String(ref s)) = doc.get("setName") {
result.set_name = s.to_owned();
}
if let Some(&Bson::String(ref s)) = doc.get("me") {
result.me = Some(try!(connstring::parse_host(s)));
}
if let Some(&Bson::Array(ref arr)) = doc.get("hosts") {
result.hosts = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::Array(ref arr)) = doc.get("passives") {
result.passives = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::Array(ref arr)) = doc.get("arbiters") {
result.arbiters = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::String(ref s)) = doc.get("primary") {
result.primary = Some(try!(connstring::parse_host(s)));
}
if let Some(&Bson::Boolean(ref b)) = doc.get("arbiterOnly") {
result.arbiter_only = *b;
}
if let Some(&Bson::Boolean(ref h)) = doc.get("hidden") {
result.hidden = *h;
}
if let Some(&Bson::Document(ref doc)) = doc.get("tags") {
for (k, v) in doc.into_iter() {
if let &Bson::String(ref tag) = v {
result.tags.insert(k.to_owned(), tag.to_owned());
}
}
}
match doc.get("electionId") {
Some(&Bson::ObjectId(ref id)) => result.election_id = Some(id.clone()),
Some(&Bson::Document(ref doc)) => if let Some(&Bson::String(ref s)) = doc.get("$oid") {
result.election_id = Some(try!(oid::ObjectId::with_string(s)));
},
_ => (),
}
Ok(result)
}
}
impl Monitor {
/// Returns a new monitor connected to the server.
pub fn new(client: Client, host: Host, pool: Arc<ConnectionPool>,
top_description: Arc<RwLock<TopologyDescription>>,
server_description: Arc<RwLock<ServerDescription>>) -> Monitor {
Monitor {
client: client,
host: host.clone(),
server_pool: pool,
personal_pool: Arc::new(ConnectionPool::with_size(host, 1)),
top_description: top_description,
server_description: server_description,
heartbeat_frequency_ms: AtomicUsize::new(DEFAULT_HEARTBEAT_FREQUENCY_MS as usize),
dummy_lock: Mutex::new(()),
condvar: Condvar::new(),
running: Arc::new(AtomicBool::new(false)),
}
}
// Set server description error field.
fn set_err(&self, err: Error) {
let mut server_description = self.server_description.write().unwrap();
server_description.set_err(err);
self.update_top_description(server_description.clone());
}
/// Returns an isMaster server response using an owned monitor socket.
pub fn is_master(&self) -> Result<(Cursor, i64)> {
let options = FindOptions::new().with_limit(1);
let flags = OpQueryFlags::with_find_options(&options);
let mut filter = bson::Document::new();
filter.insert("isMaster".to_owned(), Bson::I32(1));
let stream = try!(self.personal_pool.acquire_stream());
let time_start = time::get_time();
let cursor = try!(Cursor::query_with_stream(
stream, self.client.clone(), "local.$cmd".to_owned(), 1,
flags, options.skip as i32, 1, filter.clone(), options.projection.clone(),
CommandType::IsMaster, false, None));
let time_end = time::get_time();
let sec_start_ms: i64 = time_start.sec * 1000;
let start_ms = sec_start_ms + time_start.nsec as i64 / 1000000;
let sec_end_ms: i64 = time_end.sec * 1000;
let end_ms = sec_end_ms + time_end.nsec as i64 / 1000000;
let round_trip_time = end_ms - start_ms;
Ok((cursor, round_trip_time))
}
pub fn request_update(&self)
|
// Updates the server description associated with this monitor using an isMaster server response.
fn update_server_description(&self, doc: bson::Document,
round_trip_time: i64) -> Result<ServerDescription> {
let ismaster_result = IsMasterResult::new(doc);
let mut server_description = self.server_description.write().unwrap();
match ismaster_result {
Ok(ismaster) => server_description.update(ismaster, round_trip_time),
Err(err) => {
server_description.set_err(err);
return Err(OperationError("Failed to parse ismaster result.".to_owned()))
},
}
Ok(server_description.clone())
}
// Updates the topology description associated with this monitor using a new server description.
fn update_top_description(&self, description: ServerDescription) {
let mut top_description = self.top_description.write().unwrap();
top_description.update(self.host.clone(), description, self.client.clone(),
self.top_description.clone());
}
// Updates server and topology descriptions using a successful isMaster cursor result.
fn update_with_is_master_cursor(&self, cursor: &mut Cursor, round_trip_time: i64) {
match cursor.next() {
Some(Ok(doc)) => {
if let Ok(description) = self.update_server_description(doc, round_trip_time) {
self.update_top_description(description);
}
},
Some(Err(err)) => {
self.set_err(err);
},
None => {
self.set_err(OperationError("ismaster returned no response.".to_owned()));
}
}
}
/// Execute isMaster and update the server and topology.
fn execute_update(&self) {
match self.is_master() {
Ok((mut cursor, rtt)) => self.update_with_is_master_cursor(&mut cursor, rtt),
Err(err) => {
// Refresh all connections
self.server_pool.clear();
self.personal_pool.clear();
let stype = self.server_description.read().unwrap().server_type;
if stype == ServerType::Unknown {
self.set_err(err);
} else {
// Retry once
match self.is_master() {
Ok((mut cursor, rtt)) => self.update_with_is_master_cursor(&mut cursor, rtt),
Err(err) => self.set_err(err),
}
}
}
}
}
/// Starts server monitoring.
pub fn run(&self) {
if self.running.load(Ordering::SeqCst) {
return;
}
self.running.store(true, Ordering::SeqCst);
let mut guard = self.dummy_lock.lock().unwrap();
loop {
if!self.running.load(Ordering::SeqCst) {
break;
}
self.execute_update();
if let Ok(description) = self.top_description.read() {
self.heartbeat_frequency_ms.store(description.heartbeat_frequency_ms as usize,
Ordering::SeqCst);
}
let frequency = self.heartbeat_frequency_ms.load(Ordering::SeqCst) as u32;
guard = self.condvar.wait_timeout_ms(guard, frequency).unwrap().0;
}
}
}
|
{
self.condvar.notify_one();
}
|
identifier_body
|
monitor.rs
|
//! Asynchronous server and topology discovery and monitoring using isMaster results.
use {Client, Result};
use Error::{self, ArgumentError, OperationError};
use bson::{self, Bson, oid};
use chrono::{DateTime, UTC};
use coll::options::FindOptions;
use command_type::CommandType;
use connstring::{self, Host};
use cursor::Cursor;
use pool::ConnectionPool;
use wire_protocol::flags::OpQueryFlags;
use std::collections::BTreeMap;
use std::sync::{Arc, Condvar, Mutex, RwLock};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use time;
use super::server::{ServerDescription, ServerType};
use super::{DEFAULT_HEARTBEAT_FREQUENCY_MS, TopologyDescription};
const DEFAULT_MAX_BSON_OBJECT_SIZE: i64 = 16 * 1024 * 1024;
const DEFAULT_MAX_MESSAGE_SIZE_BYTES: i64 = 48000000;
/// The result of an isMaster operation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IsMasterResult {
pub ok: bool,
pub is_master: bool,
pub max_bson_object_size: i64,
pub max_message_size_bytes: i64,
pub local_time: Option<DateTime<UTC>>,
pub min_wire_version: i64,
pub max_wire_version: i64,
/// Shard-specific. mongos instances will add this field to the
/// isMaster reply, and it will contain the value "isdbgrid".
pub msg: String,
// Replica Set specific
pub is_replica_set: bool,
pub is_secondary: bool,
pub me: Option<Host>,
pub hosts: Vec<Host>,
pub passives: Vec<Host>,
pub arbiters: Vec<Host>,
pub arbiter_only: bool,
pub tags: BTreeMap<String, String>,
pub set_name: String,
pub election_id: Option<oid::ObjectId>,
pub primary: Option<Host>,
pub hidden: bool,
}
/// Monitors and updates server and topology information.
pub struct Monitor {
// Host being monitored.
host: Host,
// Connection pool for the host.
server_pool: Arc<ConnectionPool>,
// Topology description to update.
top_description: Arc<RwLock<TopologyDescription>>,
// Server description to update.
server_description: Arc<RwLock<ServerDescription>>,
// Client reference.
client: Client,
// Owned, single-threaded pool.
personal_pool: Arc<ConnectionPool>,
// Owned copy of the topology's heartbeat frequency.
heartbeat_frequency_ms: AtomicUsize,
// Used for condvar functionality.
dummy_lock: Mutex<()>,
// To allow servers to request an immediate update, this
// condvar can be notified to wake up the monitor.
condvar: Condvar,
/// While true, the monitor will check server connection health
/// at the topology's heartbeat frequency rate.
pub running: Arc<AtomicBool>,
}
impl IsMasterResult {
/// Parses an isMaster response document from the server.
pub fn new(doc: bson::Document) -> Result<IsMasterResult> {
let ok = match doc.get("ok") {
Some(&Bson::I32(v)) => if v == 0 { false } else { true },
Some(&Bson::I64(v)) => if v == 0 { false } else { true },
Some(&Bson::FloatingPoint(v)) => if v == 0.0 { false } else { true },
_ => return Err(ArgumentError("result does not contain `ok`.".to_owned())),
};
let mut result = IsMasterResult {
ok: ok,
is_master: false,
max_bson_object_size: DEFAULT_MAX_BSON_OBJECT_SIZE,
max_message_size_bytes: DEFAULT_MAX_MESSAGE_SIZE_BYTES,
local_time: None,
min_wire_version: -1,
max_wire_version: -1,
msg: String::new(),
is_secondary: false,
is_replica_set: false,
me: None,
hosts: Vec::new(),
passives: Vec::new(),
arbiters: Vec::new(),
arbiter_only: false,
tags: BTreeMap::new(),
set_name: String::new(),
election_id: None,
primary: None,
hidden: false,
};
if let Some(&Bson::Boolean(b)) = doc.get("ismaster") {
result.is_master = b;
}
if let Some(&Bson::UtcDatetime(ref datetime)) = doc.get("localTime") {
result.local_time = Some(datetime.clone());
}
if let Some(&Bson::I64(v)) = doc.get("minWireVersion") {
result.min_wire_version = v;
}
if let Some(&Bson::I64(v)) = doc.get("maxWireVersion") {
result.max_wire_version = v;
}
if let Some(&Bson::String(ref s)) = doc.get("msg") {
result.msg = s.to_owned();
}
if let Some(&Bson::Boolean(ref b)) = doc.get("secondary") {
result.is_secondary = *b;
}
if let Some(&Bson::Boolean(ref b)) = doc.get("isreplicaset") {
result.is_replica_set = *b;
}
if let Some(&Bson::String(ref s)) = doc.get("setName") {
result.set_name = s.to_owned();
}
if let Some(&Bson::String(ref s)) = doc.get("me") {
result.me = Some(try!(connstring::parse_host(s)));
}
if let Some(&Bson::Array(ref arr)) = doc.get("hosts") {
result.hosts = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::Array(ref arr)) = doc.get("passives") {
result.passives = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::Array(ref arr)) = doc.get("arbiters") {
result.arbiters = arr.iter().filter_map(|bson| match bson {
&Bson::String(ref s) => connstring::parse_host(s).ok(),
_ => None,
}).collect();
}
if let Some(&Bson::String(ref s)) = doc.get("primary") {
result.primary = Some(try!(connstring::parse_host(s)));
}
if let Some(&Bson::Boolean(ref b)) = doc.get("arbiterOnly") {
result.arbiter_only = *b;
}
if let Some(&Bson::Boolean(ref h)) = doc.get("hidden") {
result.hidden = *h;
}
if let Some(&Bson::Document(ref doc)) = doc.get("tags") {
for (k, v) in doc.into_iter() {
if let &Bson::String(ref tag) = v {
result.tags.insert(k.to_owned(), tag.to_owned());
}
}
}
match doc.get("electionId") {
Some(&Bson::ObjectId(ref id)) => result.election_id = Some(id.clone()),
Some(&Bson::Document(ref doc)) => if let Some(&Bson::String(ref s)) = doc.get("$oid") {
result.election_id = Some(try!(oid::ObjectId::with_string(s)));
},
_ => (),
}
Ok(result)
}
}
impl Monitor {
/// Returns a new monitor connected to the server.
pub fn new(client: Client, host: Host, pool: Arc<ConnectionPool>,
top_description: Arc<RwLock<TopologyDescription>>,
server_description: Arc<RwLock<ServerDescription>>) -> Monitor {
Monitor {
client: client,
host: host.clone(),
server_pool: pool,
personal_pool: Arc::new(ConnectionPool::with_size(host, 1)),
top_description: top_description,
server_description: server_description,
heartbeat_frequency_ms: AtomicUsize::new(DEFAULT_HEARTBEAT_FREQUENCY_MS as usize),
dummy_lock: Mutex::new(()),
condvar: Condvar::new(),
running: Arc::new(AtomicBool::new(false)),
}
}
// Set server description error field.
fn set_err(&self, err: Error) {
let mut server_description = self.server_description.write().unwrap();
server_description.set_err(err);
self.update_top_description(server_description.clone());
}
/// Returns an isMaster server response using an owned monitor socket.
pub fn is_master(&self) -> Result<(Cursor, i64)> {
let options = FindOptions::new().with_limit(1);
let flags = OpQueryFlags::with_find_options(&options);
let mut filter = bson::Document::new();
filter.insert("isMaster".to_owned(), Bson::I32(1));
let stream = try!(self.personal_pool.acquire_stream());
let time_start = time::get_time();
let cursor = try!(Cursor::query_with_stream(
stream, self.client.clone(), "local.$cmd".to_owned(), 1,
flags, options.skip as i32, 1, filter.clone(), options.projection.clone(),
CommandType::IsMaster, false, None));
let time_end = time::get_time();
let sec_start_ms: i64 = time_start.sec * 1000;
let start_ms = sec_start_ms + time_start.nsec as i64 / 1000000;
let sec_end_ms: i64 = time_end.sec * 1000;
let end_ms = sec_end_ms + time_end.nsec as i64 / 1000000;
let round_trip_time = end_ms - start_ms;
Ok((cursor, round_trip_time))
}
pub fn request_update(&self) {
self.condvar.notify_one();
}
// Updates the server description associated with this monitor using an isMaster server response.
fn update_server_description(&self, doc: bson::Document,
round_trip_time: i64) -> Result<ServerDescription> {
let ismaster_result = IsMasterResult::new(doc);
let mut server_description = self.server_description.write().unwrap();
match ismaster_result {
Ok(ismaster) => server_description.update(ismaster, round_trip_time),
Err(err) => {
server_description.set_err(err);
return Err(OperationError("Failed to parse ismaster result.".to_owned()))
},
}
Ok(server_description.clone())
}
// Updates the topology description associated with this monitor using a new server description.
fn update_top_description(&self, description: ServerDescription) {
let mut top_description = self.top_description.write().unwrap();
top_description.update(self.host.clone(), description, self.client.clone(),
self.top_description.clone());
}
// Updates server and topology descriptions using a successful isMaster cursor result.
fn update_with_is_master_cursor(&self, cursor: &mut Cursor, round_trip_time: i64) {
match cursor.next() {
Some(Ok(doc)) => {
if let Ok(description) = self.update_server_description(doc, round_trip_time) {
self.update_top_description(description);
}
},
Some(Err(err)) => {
self.set_err(err);
},
None => {
self.set_err(OperationError("ismaster returned no response.".to_owned()));
}
}
}
/// Execute isMaster and update the server and topology.
fn
|
(&self) {
match self.is_master() {
Ok((mut cursor, rtt)) => self.update_with_is_master_cursor(&mut cursor, rtt),
Err(err) => {
// Refresh all connections
self.server_pool.clear();
self.personal_pool.clear();
let stype = self.server_description.read().unwrap().server_type;
if stype == ServerType::Unknown {
self.set_err(err);
} else {
// Retry once
match self.is_master() {
Ok((mut cursor, rtt)) => self.update_with_is_master_cursor(&mut cursor, rtt),
Err(err) => self.set_err(err),
}
}
}
}
}
/// Starts server monitoring.
pub fn run(&self) {
if self.running.load(Ordering::SeqCst) {
return;
}
self.running.store(true, Ordering::SeqCst);
let mut guard = self.dummy_lock.lock().unwrap();
loop {
if!self.running.load(Ordering::SeqCst) {
break;
}
self.execute_update();
if let Ok(description) = self.top_description.read() {
self.heartbeat_frequency_ms.store(description.heartbeat_frequency_ms as usize,
Ordering::SeqCst);
}
let frequency = self.heartbeat_frequency_ms.load(Ordering::SeqCst) as u32;
guard = self.condvar.wait_timeout_ms(guard, frequency).unwrap().0;
}
}
}
|
execute_update
|
identifier_name
|
test.rs
|
i),
ignore: is_ignored(&*i),
should_panic: should_panic(&*i)
};
self.cx.testfns.push(test);
self.tests.push(i.ident);
// debug!("have {} test/bench functions",
// cx.testfns.len());
// Make all tests public so we can call them from outside
// the module (note that the tests are re-exported and must
// be made public themselves to avoid privacy errors).
i.map(|mut i| {
i.vis = ast::Public;
i
})
}
}
} else {
i
};
// We don't want to recurse into anything other than mods, since
// mods or tests inside of functions will break things
let res = match i.node {
ast::ItemMod(..) => fold::noop_fold_item(i, self),
_ => SmallVector::one(i),
};
if ident.name!= token::special_idents::invalid.name {
self.cx.path.pop();
}
res
}
fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod {
let tests = mem::replace(&mut self.tests, Vec::new());
let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
let mut mod_folded = fold::noop_fold_mod(m, self);
let tests = mem::replace(&mut self.tests, tests);
let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
if!tests.is_empty() ||!tested_submods.is_empty() {
let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods);
mod_folded.items.push(it);
if!self.cx.path.is_empty() {
self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
} else {
debug!("pushing nothing, sym: {:?}", sym);
self.cx.toplevel_reexport = Some(sym);
}
}
mod_folded
}
}
struct EntryPointCleaner {
// Current depth in the ast
depth: usize,
}
impl fold::Folder for EntryPointCleaner {
fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
self.depth += 1;
let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
self.depth -= 1;
// Remove any #[main] or #[start] from the AST so it doesn't
// clash with the one we're going to add, but mark it as
// #[allow(dead_code)] to avoid printing warnings.
let folded = match entry::entry_point_type(&*folded, self.depth) {
EntryPointType::MainNamed |
EntryPointType::MainAttr |
EntryPointType::Start =>
folded.map(|ast::Item {id, ident, attrs, node, vis, span}| {
let allow_str = InternedString::new("allow");
let dead_code_str = InternedString::new("dead_code");
let allow_dead_code_item =
attr::mk_list_item(allow_str,
vec![attr::mk_word_item(dead_code_str)]);
let allow_dead_code = attr::mk_attr_outer(attr::mk_attr_id(),
allow_dead_code_item);
ast::Item {
id: id,
ident: ident,
attrs: attrs.into_iter()
.filter(|attr| {
!attr.check_name("main") &&!attr.check_name("start")
})
.chain(iter::once(allow_dead_code))
.collect(),
node: node,
vis: vis,
span: span
}
}),
EntryPointType::None |
EntryPointType::OtherMain => folded,
};
SmallVector::one(folded)
}
}
fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>,
tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) {
let super_ = token::str_to_ident("super");
let items = tests.into_iter().map(|r| {
cx.ext_cx.item_use_simple(DUMMY_SP, ast::Public,
cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
}).chain(tested_submods.into_iter().map(|(r, sym)| {
let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Public, r, path)
}));
let reexport_mod = ast::Mod {
inner: DUMMY_SP,
items: items.collect(),
};
let sym = token::gensym_ident("__test_reexports");
let it = P(ast::Item {
ident: sym.clone(),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: ast::ItemMod(reexport_mod),
vis: ast::Public,
span: DUMMY_SP,
});
(it, sym)
}
fn generate_test_harness(sess: &ParseSess,
reexport_test_harness_main: Option<InternedString>,
krate: ast::Crate,
cfg: &ast::CrateConfig,
sd: &diagnostic::SpanHandler) -> ast::Crate {
// Remove the entry points
let mut cleaner = EntryPointCleaner { depth: 0 };
let krate = cleaner.fold_crate(krate);
let mut feature_gated_cfgs = vec![];
let mut cx: TestCtxt = TestCtxt {
sess: sess,
span_diagnostic: sd,
ext_cx: ExtCtxt::new(sess, cfg.clone(),
ExpansionConfig::default("test".to_string()),
&mut feature_gated_cfgs),
path: Vec::new(),
testfns: Vec::new(),
reexport_test_harness_main: reexport_test_harness_main,
is_test_crate: is_test_crate(&krate),
config: krate.config.clone(),
toplevel_reexport: None,
};
cx.ext_cx.crate_root = Some("std");
cx.ext_cx.bt_push(ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
format: MacroAttribute(intern("test")),
span: None,
allow_internal_unstable: false,
}
});
let mut fold = TestHarnessGenerator {
cx: cx,
tests: Vec::new(),
tested_submods: Vec::new(),
};
let res = fold.fold_crate(krate);
fold.cx.ext_cx.bt_pop();
return res;
}
fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
// When not compiling with --test we should not compile the
// #[test] functions
config::strip_items(krate, |attrs| {
!attr::contains_name(&attrs[..], "test") &&
!attr::contains_name(&attrs[..], "bench")
})
}
/// Craft a span that will be ignored by the stability lint's
/// call to codemap's is_internal check.
/// The expanded code calls some unstable functions in the test crate.
fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
let info = ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
format: MacroAttribute(intern("test")),
span: None,
allow_internal_unstable: true,
}
};
let expn_id = cx.sess.codemap().record_expansion(info);
let mut sp = sp;
sp.expn_id = expn_id;
return sp;
}
#[derive(PartialEq)]
enum HasTestSignature {
Yes,
No,
NotEvenAFunction,
}
fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
let has_test_attr = attr::contains_name(&i.attrs, "test");
fn has_test_signature(i: &ast::Item) -> HasTestSignature {
match &i.node {
&ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
let no_output = match decl.output {
ast::DefaultReturn(..) => true,
ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
_ => false
};
if decl.inputs.is_empty()
&& no_output
&&!generics.is_parameterized() {
Yes
} else {
No
}
}
_ => NotEvenAFunction,
}
}
if has_test_attr {
let diag = cx.span_diagnostic;
match has_test_signature(i) {
Yes => {},
No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
NotEvenAFunction => diag.span_err(i.span,
"only functions may be used as tests"),
}
}
return has_test_attr && has_test_signature(i) == Yes;
}
fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
let has_bench_attr = attr::contains_name(&i.attrs, "bench");
fn has_test_signature(i: &ast::Item) -> bool {
match i.node {
ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
let input_cnt = decl.inputs.len();
let no_output = match decl.output {
ast::DefaultReturn(..) => true,
ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
_ => false
};
let tparm_cnt = generics.ty_params.len();
// NB: inadequate check, but we're running
// well before resolve, can't get too deep.
input_cnt == 1
&& no_output && tparm_cnt == 0
}
_ => false
}
}
if has_bench_attr &&!has_test_signature(i) {
let diag = cx.span_diagnostic;
diag.span_err(i.span, "functions used as benches must have signature \
`fn(&mut Bencher) -> ()`");
}
return has_bench_attr && has_test_signature(i);
}
fn is_ignored(i: &ast::Item) -> bool {
i.attrs.iter().any(|attr| attr.check_name("ignore"))
}
fn should_panic(i: &ast::Item) -> ShouldPanic {
match i.attrs.iter().find(|attr| attr.check_name("should_panic")) {
Some(attr) => {
let msg = attr.meta_item_list()
.and_then(|list| list.iter().find(|mi| mi.check_name("expected")))
.and_then(|mi| mi.value_str());
ShouldPanic::Yes(msg)
}
None => ShouldPanic::No,
}
}
/*
We're going to be building a module that looks more or less like:
mod __test {
extern crate test (name = "test", vers = "...");
fn main() {
test::test_main_static(&::os::args()[], tests)
}
static tests : &'static [test::TestDescAndFn] = &[
... the list of tests in the crate...
];
}
*/
fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
let id_test = token::str_to_ident("test");
let (vi, vis, ident) = if cx.is_test_crate {
(ast::ItemUse(
P(nospan(ast::ViewPathSimple(id_test,
path_node(vec!(id_test)))))),
ast::Public, token::special_idents::invalid)
} else {
(ast::ItemExternCrate(None), ast::Inherited, id_test)
};
P(ast::Item {
id: ast::DUMMY_NODE_ID,
ident: ident,
node: vi,
attrs: vec![],
vis: vis,
span: DUMMY_SP
})
}
fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
// Writing this out by hand with 'ignored_span':
// pub fn main() {
// #![main]
// use std::slice::AsSlice;
// test::test_main_static(::std::os::args().as_slice(), TESTS);
// }
let sp = ignored_span(cx, DUMMY_SP);
let ecx = &cx.ext_cx;
// test::test_main_static
let test_main_path = ecx.path(sp, vec![token::str_to_ident("test"),
token::str_to_ident("test_main_static")]);
// test::test_main_static(...)
let test_main_path_expr = ecx.expr_path(test_main_path);
let tests_ident_expr = ecx.expr_ident(sp, token::str_to_ident("TESTS"));
let call_test_main = ecx.expr_call(sp, test_main_path_expr,
vec![tests_ident_expr]);
let call_test_main = ecx.stmt_expr(call_test_main);
// #![main]
let main_meta = ecx.meta_word(sp, token::intern_and_get_ident("main"));
let main_attr = ecx.attribute(sp, main_meta);
// pub fn main() {... }
let main_ret_ty = ecx.ty(sp, ast::TyTup(vec![]));
let main_body = ecx.block_all(sp, vec![call_test_main], None);
let main = ast::ItemFn(ecx.fn_decl(vec![], main_ret_ty),
ast::Unsafety::Normal,
ast::Constness::NotConst,
::abi::Rust, empty_generics(), main_body);
let main = P(ast::Item {
ident: token::str_to_ident("main"),
attrs: vec![main_attr],
id: ast::DUMMY_NODE_ID,
node: main,
vis: ast::Public,
span: sp
});
return main;
}
fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
// Link to test crate
let import = mk_std(cx);
// A constant vector of test descriptors.
let tests = mk_tests(cx);
// The synthesized main function which will call the console test runner
// with our list of tests
let mainfn = mk_main(cx);
let testmod = ast::Mod {
inner: DUMMY_SP,
items: vec![import, mainfn, tests],
};
let item_ = ast::ItemMod(testmod);
let mod_ident = token::gensym_ident("__test");
let item = P(ast::Item {
id: ast::DUMMY_NODE_ID,
ident: mod_ident,
attrs: vec![],
node: item_,
vis: ast::Public,
span: DUMMY_SP,
});
let reexport = cx.reexport_test_harness_main.as_ref().map(|s| {
// building `use <ident> = __test::main`
let reexport_ident = token::str_to_ident(&s);
let use_path =
nospan(ast::ViewPathSimple(reexport_ident,
path_node(vec![mod_ident, token::str_to_ident("main")])));
P(ast::Item {
id: ast::DUMMY_NODE_ID,
ident: token::special_idents::invalid,
attrs: vec![],
node: ast::ItemUse(P(use_path)),
vis: ast::Inherited,
span: DUMMY_SP
})
});
debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&*item));
(item, reexport)
}
fn nospan<T>(t: T) -> codemap::Spanned<T> {
codemap::Spanned { node: t, span: DUMMY_SP }
}
fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
ast::Path {
span: DUMMY_SP,
global: false,
segments: ids.into_iter().map(|identifier| ast::PathSegment {
identifier: identifier,
parameters: ast::PathParameters::none(),
}).collect()
}
}
fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
// The vector of test_descs for this crate
let test_descs = mk_test_descs(cx);
// FIXME #15962: should be using quote_item, but that stringifies
// __test_reexports, causing it to be reinterned, losing the
// gensym information.
let sp = DUMMY_SP;
let ecx = &cx.ext_cx;
let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"),
ecx.ident_of("test"),
ecx.ident_of("TestDescAndFn")]));
let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name);
// &'static [self::test::TestDescAndFn]
let static_type = ecx.ty_rptr(sp,
ecx.ty(sp, ast::TyVec(struct_type)),
Some(static_lt),
ast::MutImmutable);
// static TESTS: $static_type = &[...];
ecx.item_const(sp,
ecx.ident_of("TESTS"),
static_type,
test_descs)
}
fn
|
is_test_crate
|
identifier_name
|
|
test.rs
|
Generator<'a> {
cx: TestCtxt<'a>,
tests: Vec<ast::Ident>,
// submodule name, gensym'd identifier for re-exports
tested_submods: Vec<(ast::Ident, ast::Ident)>,
}
impl<'a> fold::Folder for TestHarnessGenerator<'a> {
fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
let mut folded = fold::noop_fold_crate(c, self);
// Add a special __test module to the crate that will contain code
// generated for the test harness
let (mod_, reexport) = mk_test_module(&mut self.cx);
match reexport {
Some(re) => folded.module.items.push(re),
None => {}
}
folded.module.items.push(mod_);
folded
}
fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>>
|
ignore: is_ignored(&*i),
should_panic: should_panic(&*i)
};
self.cx.testfns.push(test);
self.tests.push(i.ident);
// debug!("have {} test/bench functions",
// cx.testfns.len());
// Make all tests public so we can call them from outside
// the module (note that the tests are re-exported and must
// be made public themselves to avoid privacy errors).
i.map(|mut i| {
i.vis = ast::Public;
i
})
}
}
} else {
i
};
// We don't want to recurse into anything other than mods, since
// mods or tests inside of functions will break things
let res = match i.node {
ast::ItemMod(..) => fold::noop_fold_item(i, self),
_ => SmallVector::one(i),
};
if ident.name!= token::special_idents::invalid.name {
self.cx.path.pop();
}
res
}
fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod {
let tests = mem::replace(&mut self.tests, Vec::new());
let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
let mut mod_folded = fold::noop_fold_mod(m, self);
let tests = mem::replace(&mut self.tests, tests);
let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
if!tests.is_empty() ||!tested_submods.is_empty() {
let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods);
mod_folded.items.push(it);
if!self.cx.path.is_empty() {
self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
} else {
debug!("pushing nothing, sym: {:?}", sym);
self.cx.toplevel_reexport = Some(sym);
}
}
mod_folded
}
}
struct EntryPointCleaner {
// Current depth in the ast
depth: usize,
}
impl fold::Folder for EntryPointCleaner {
fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
self.depth += 1;
let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
self.depth -= 1;
// Remove any #[main] or #[start] from the AST so it doesn't
// clash with the one we're going to add, but mark it as
// #[allow(dead_code)] to avoid printing warnings.
let folded = match entry::entry_point_type(&*folded, self.depth) {
EntryPointType::MainNamed |
EntryPointType::MainAttr |
EntryPointType::Start =>
folded.map(|ast::Item {id, ident, attrs, node, vis, span}| {
let allow_str = InternedString::new("allow");
let dead_code_str = InternedString::new("dead_code");
let allow_dead_code_item =
attr::mk_list_item(allow_str,
vec![attr::mk_word_item(dead_code_str)]);
let allow_dead_code = attr::mk_attr_outer(attr::mk_attr_id(),
allow_dead_code_item);
ast::Item {
id: id,
ident: ident,
attrs: attrs.into_iter()
.filter(|attr| {
!attr.check_name("main") &&!attr.check_name("start")
})
.chain(iter::once(allow_dead_code))
.collect(),
node: node,
vis: vis,
span: span
}
}),
EntryPointType::None |
EntryPointType::OtherMain => folded,
};
SmallVector::one(folded)
}
}
fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>,
tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) {
let super_ = token::str_to_ident("super");
let items = tests.into_iter().map(|r| {
cx.ext_cx.item_use_simple(DUMMY_SP, ast::Public,
cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
}).chain(tested_submods.into_iter().map(|(r, sym)| {
let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Public, r, path)
}));
let reexport_mod = ast::Mod {
inner: DUMMY_SP,
items: items.collect(),
};
let sym = token::gensym_ident("__test_reexports");
let it = P(ast::Item {
ident: sym.clone(),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: ast::ItemMod(reexport_mod),
vis: ast::Public,
span: DUMMY_SP,
});
(it, sym)
}
fn generate_test_harness(sess: &ParseSess,
reexport_test_harness_main: Option<InternedString>,
krate: ast::Crate,
cfg: &ast::CrateConfig,
sd: &diagnostic::SpanHandler) -> ast::Crate {
// Remove the entry points
let mut cleaner = EntryPointCleaner { depth: 0 };
let krate = cleaner.fold_crate(krate);
let mut feature_gated_cfgs = vec![];
let mut cx: TestCtxt = TestCtxt {
sess: sess,
span_diagnostic: sd,
ext_cx: ExtCtxt::new(sess, cfg.clone(),
ExpansionConfig::default("test".to_string()),
&mut feature_gated_cfgs),
path: Vec::new(),
testfns: Vec::new(),
reexport_test_harness_main: reexport_test_harness_main,
is_test_crate: is_test_crate(&krate),
config: krate.config.clone(),
toplevel_reexport: None,
};
cx.ext_cx.crate_root = Some("std");
cx.ext_cx.bt_push(ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
format: MacroAttribute(intern("test")),
span: None,
allow_internal_unstable: false,
}
});
let mut fold = TestHarnessGenerator {
cx: cx,
tests: Vec::new(),
tested_submods: Vec::new(),
};
let res = fold.fold_crate(krate);
fold.cx.ext_cx.bt_pop();
return res;
}
fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
// When not compiling with --test we should not compile the
// #[test] functions
config::strip_items(krate, |attrs| {
!attr::contains_name(&attrs[..], "test") &&
!attr::contains_name(&attrs[..], "bench")
})
}
/// Craft a span that will be ignored by the stability lint's
/// call to codemap's is_internal check.
/// The expanded code calls some unstable functions in the test crate.
fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
let info = ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
format: MacroAttribute(intern("test")),
span: None,
allow_internal_unstable: true,
}
};
let expn_id = cx.sess.codemap().record_expansion(info);
let mut sp = sp;
sp.expn_id = expn_id;
return sp;
}
#[derive(PartialEq)]
enum HasTestSignature {
Yes,
No,
NotEvenAFunction,
}
fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
let has_test_attr = attr::contains_name(&i.attrs, "test");
fn has_test_signature(i: &ast::Item) -> HasTestSignature {
match &i.node {
&ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
let no_output = match decl.output {
ast::DefaultReturn(..) => true,
ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
_ => false
};
if decl.inputs.is_empty()
&& no_output
&&!generics.is_parameterized() {
Yes
} else {
No
}
}
_ => NotEvenAFunction,
}
}
if has_test_attr {
let diag = cx.span_diagnostic;
match has_test_signature(i) {
Yes => {},
No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
NotEvenAFunction => diag.span_err(i.span,
"only functions may be used as tests"),
}
}
return has_test_attr && has_test_signature(i) == Yes;
}
fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
let has_bench_attr = attr::contains_name(&i.attrs, "bench");
fn has_test_signature(i: &ast::Item) -> bool {
match i.node {
ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
let input_cnt = decl.inputs.len();
let no_output = match decl.output {
ast::DefaultReturn(..) => true,
ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
_ => false
};
let tparm_cnt = generics.ty_params.len();
// NB: inadequate check, but we're running
// well before resolve, can't get too deep.
input_cnt == 1
&& no_output && tparm_cnt == 0
}
_ => false
}
}
if has_bench_attr &&!has_test_signature(i) {
let diag = cx.span_diagnostic;
diag.span_err(i.span, "functions used as benches must have signature \
`fn(&mut Bencher) -> ()`");
}
return has_bench_attr && has_test_signature(i);
}
fn is_ignored(i: &ast::Item) -> bool {
i.attrs.iter().any(|attr| attr.check_name("ignore"))
}
fn should_panic(i: &ast::Item) -> ShouldPanic {
match i.attrs.iter().find(|attr| attr.check_name("should_panic")) {
Some(attr) => {
let msg = attr.meta_item_list()
.and_then(|list| list.iter().find(|mi| mi.check_name("expected")))
.and_then(|mi| mi.value_str());
ShouldPanic::Yes(msg)
}
None => ShouldPanic::No,
}
}
/*
We're going to be building a module that looks more or less like:
mod __test {
extern crate test (name = "test", vers = "...");
fn main() {
test::test_main_static(&::os::args()[], tests)
}
static tests : &'static [test::TestDescAndFn] = &[
... the list of tests in the crate...
];
}
*/
fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
let id_test = token::str_to_ident("test");
let (vi, vis, ident) = if cx.is_test_crate {
(ast::ItemUse(
P(nospan(ast::ViewPathSimple(id_test,
path_node(vec!(id_test)))))),
ast::Public, token::special_idents::invalid)
} else {
(ast::ItemExternCrate(None), ast::Inherited, id_test)
};
P(ast::Item {
id: ast::DUMMY_NODE_ID,
ident: ident,
node: vi,
attrs: vec![],
vis: vis,
span: DUMMY_SP
})
}
fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
// Writing this out by hand with 'ignored_span':
// pub fn main() {
// #![main]
// use std::slice::AsSlice;
// test::test_main_static(::std::os::args().as_slice(), TESTS);
// }
let sp = ignored_span(cx, DUMMY_SP);
let ecx = &cx.ext_cx;
// test::test_main_static
let test_main_path = ecx.path(sp, vec![token::str_to_ident("test"),
token::str_to_ident("test_main_static")]);
// test::test_main_static(...)
let test_main_path_expr = ecx.expr_path(test_main_path);
let tests_ident_expr = ecx.expr_ident(sp, token::str_to_ident("TESTS"));
let call_test_main = ecx.expr_call(sp, test_main_path_expr,
vec![tests_ident_expr]);
let call_test_main = ecx.stmt_expr(call_test_main);
// #![main]
let main_meta = ecx.meta_word(sp, token::intern_and_get_ident("main"));
let main_attr = ecx.attribute(sp, main_meta);
// pub fn main() {... }
let main_ret_ty = ecx.ty(sp, ast::TyTup(vec![]));
let main_body = ecx.block_all(sp, vec![call_test_main], None);
let main = ast::ItemFn(ecx.fn_decl(vec![], main_ret_ty),
ast::Unsafety::Normal,
ast::Constness::NotConst,
::abi::Rust, empty_generics(), main_body);
let main = P(ast::Item {
ident: token::str_to_ident("main"),
attrs: vec![main_attr],
id: ast::DUMMY_NODE_ID,
node: main,
vis: ast::Public,
span: sp
});
return main;
}
fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
// Link to test crate
let import = mk_std(cx);
// A constant vector of test descriptors.
let tests = mk_tests(cx);
// The synthesized main function which will call the console test runner
// with our list of tests
let mainfn = mk_main(cx);
let testmod = ast::Mod {
inner: DUMMY_SP,
items: vec![import, mainfn, tests],
};
let item_ = ast::ItemMod(testmod);
let mod_ident = token::gensym_ident("__test");
let item = P(ast::Item {
id: ast::DUMMY_NODE_ID,
ident: mod_ident,
attrs: vec![],
node: item_,
vis: ast::Public,
span: DUMMY_SP,
});
let reexport = cx.reexport_test_harness_main.as_ref().map(|s| {
// building `use <ident> = __test::main`
let reexport_ident = token::str_to_ident(&s);
let use_path =
nospan(ast::ViewPathSimple(reexport_ident,
path_node(vec![mod_ident, token::str_to_ident("main")])));
P(ast::Item {
id: ast::DUMMY_NODE_ID,
ident: token::special_idents::invalid,
attrs: vec![],
node: ast::ItemUse(P(use_path)),
vis: ast::Inherited,
span: DUMMY_SP
})
});
debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&*item));
|
{
let ident = i.ident;
if ident.name != token::special_idents::invalid.name {
self.cx.path.push(ident);
}
debug!("current path: {}",
ast_util::path_name_i(&self.cx.path));
let i = if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) {
match i.node {
ast::ItemFn(_, ast::Unsafety::Unsafe, _, _, _, _) => {
let diag = self.cx.span_diagnostic;
panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests"));
}
_ => {
debug!("this is a test function");
let test = Test {
span: i.span,
path: self.cx.path.clone(),
bench: is_bench_fn(&self.cx, &*i),
|
identifier_body
|
test.rs
|
testfns: Vec<Test>,
reexport_test_harness_main: Option<InternedString>,
is_test_crate: bool,
config: ast::CrateConfig,
// top-level re-export submodule, filled out after folding is finished
toplevel_reexport: Option<ast::Ident>,
}
// Traverse the crate, collecting all the test functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: &ParseSess,
cfg: &ast::CrateConfig,
krate: ast::Crate,
span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
// We generate the test harness when building in the 'test'
// configuration, either with the '--test' or '--cfg test'
// command line options.
let should_test = attr::contains_name(&krate.config, "test");
// Check for #[reexport_test_harness_main = "some_name"] which
// creates a `use some_name = __test::main;`. This needs to be
// unconditional, so that the attribute is still marked as used in
// non-test builds.
let reexport_test_harness_main =
attr::first_attr_value_str_by_name(&krate.attrs,
"reexport_test_harness_main");
if should_test {
generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic)
} else {
strip_test_functions(krate)
}
}
struct TestHarnessGenerator<'a> {
cx: TestCtxt<'a>,
tests: Vec<ast::Ident>,
// submodule name, gensym'd identifier for re-exports
tested_submods: Vec<(ast::Ident, ast::Ident)>,
}
impl<'a> fold::Folder for TestHarnessGenerator<'a> {
fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
let mut folded = fold::noop_fold_crate(c, self);
// Add a special __test module to the crate that will contain code
// generated for the test harness
let (mod_, reexport) = mk_test_module(&mut self.cx);
match reexport {
Some(re) => folded.module.items.push(re),
None => {}
}
folded.module.items.push(mod_);
folded
}
fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
let ident = i.ident;
if ident.name!= token::special_idents::invalid.name {
self.cx.path.push(ident);
}
debug!("current path: {}",
ast_util::path_name_i(&self.cx.path));
let i = if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) {
match i.node {
ast::ItemFn(_, ast::Unsafety::Unsafe, _, _, _, _) => {
let diag = self.cx.span_diagnostic;
panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests"));
}
_ => {
debug!("this is a test function");
let test = Test {
span: i.span,
path: self.cx.path.clone(),
bench: is_bench_fn(&self.cx, &*i),
ignore: is_ignored(&*i),
should_panic: should_panic(&*i)
};
self.cx.testfns.push(test);
self.tests.push(i.ident);
// debug!("have {} test/bench functions",
// cx.testfns.len());
// Make all tests public so we can call them from outside
// the module (note that the tests are re-exported and must
// be made public themselves to avoid privacy errors).
i.map(|mut i| {
i.vis = ast::Public;
i
})
}
}
} else {
i
};
// We don't want to recurse into anything other than mods, since
// mods or tests inside of functions will break things
let res = match i.node {
ast::ItemMod(..) => fold::noop_fold_item(i, self),
_ => SmallVector::one(i),
};
if ident.name!= token::special_idents::invalid.name {
self.cx.path.pop();
}
res
}
fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod {
let tests = mem::replace(&mut self.tests, Vec::new());
let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
let mut mod_folded = fold::noop_fold_mod(m, self);
let tests = mem::replace(&mut self.tests, tests);
let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
if!tests.is_empty() ||!tested_submods.is_empty() {
let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods);
mod_folded.items.push(it);
if!self.cx.path.is_empty() {
self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
} else {
debug!("pushing nothing, sym: {:?}", sym);
self.cx.toplevel_reexport = Some(sym);
}
}
mod_folded
}
}
struct EntryPointCleaner {
// Current depth in the ast
depth: usize,
}
impl fold::Folder for EntryPointCleaner {
fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
self.depth += 1;
let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
self.depth -= 1;
// Remove any #[main] or #[start] from the AST so it doesn't
// clash with the one we're going to add, but mark it as
// #[allow(dead_code)] to avoid printing warnings.
let folded = match entry::entry_point_type(&*folded, self.depth) {
EntryPointType::MainNamed |
EntryPointType::MainAttr |
EntryPointType::Start =>
folded.map(|ast::Item {id, ident, attrs, node, vis, span}| {
let allow_str = InternedString::new("allow");
let dead_code_str = InternedString::new("dead_code");
let allow_dead_code_item =
attr::mk_list_item(allow_str,
vec![attr::mk_word_item(dead_code_str)]);
let allow_dead_code = attr::mk_attr_outer(attr::mk_attr_id(),
allow_dead_code_item);
ast::Item {
id: id,
ident: ident,
attrs: attrs.into_iter()
.filter(|attr| {
!attr.check_name("main") &&!attr.check_name("start")
})
.chain(iter::once(allow_dead_code))
.collect(),
node: node,
vis: vis,
span: span
}
}),
EntryPointType::None |
EntryPointType::OtherMain => folded,
};
SmallVector::one(folded)
}
}
fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>,
tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) {
let super_ = token::str_to_ident("super");
let items = tests.into_iter().map(|r| {
cx.ext_cx.item_use_simple(DUMMY_SP, ast::Public,
cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
}).chain(tested_submods.into_iter().map(|(r, sym)| {
let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Public, r, path)
}));
let reexport_mod = ast::Mod {
inner: DUMMY_SP,
items: items.collect(),
};
let sym = token::gensym_ident("__test_reexports");
let it = P(ast::Item {
ident: sym.clone(),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: ast::ItemMod(reexport_mod),
vis: ast::Public,
span: DUMMY_SP,
});
(it, sym)
}
fn generate_test_harness(sess: &ParseSess,
reexport_test_harness_main: Option<InternedString>,
krate: ast::Crate,
cfg: &ast::CrateConfig,
sd: &diagnostic::SpanHandler) -> ast::Crate {
// Remove the entry points
let mut cleaner = EntryPointCleaner { depth: 0 };
let krate = cleaner.fold_crate(krate);
let mut feature_gated_cfgs = vec![];
let mut cx: TestCtxt = TestCtxt {
sess: sess,
span_diagnostic: sd,
ext_cx: ExtCtxt::new(sess, cfg.clone(),
ExpansionConfig::default("test".to_string()),
&mut feature_gated_cfgs),
path: Vec::new(),
testfns: Vec::new(),
reexport_test_harness_main: reexport_test_harness_main,
is_test_crate: is_test_crate(&krate),
config: krate.config.clone(),
toplevel_reexport: None,
};
cx.ext_cx.crate_root = Some("std");
cx.ext_cx.bt_push(ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
format: MacroAttribute(intern("test")),
span: None,
allow_internal_unstable: false,
}
});
let mut fold = TestHarnessGenerator {
cx: cx,
tests: Vec::new(),
tested_submods: Vec::new(),
};
let res = fold.fold_crate(krate);
fold.cx.ext_cx.bt_pop();
return res;
}
fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
// When not compiling with --test we should not compile the
// #[test] functions
config::strip_items(krate, |attrs| {
!attr::contains_name(&attrs[..], "test") &&
!attr::contains_name(&attrs[..], "bench")
})
}
/// Craft a span that will be ignored by the stability lint's
/// call to codemap's is_internal check.
/// The expanded code calls some unstable functions in the test crate.
fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
let info = ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
format: MacroAttribute(intern("test")),
span: None,
allow_internal_unstable: true,
}
};
let expn_id = cx.sess.codemap().record_expansion(info);
let mut sp = sp;
sp.expn_id = expn_id;
return sp;
}
#[derive(PartialEq)]
enum HasTestSignature {
Yes,
No,
NotEvenAFunction,
}
fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
let has_test_attr = attr::contains_name(&i.attrs, "test");
fn has_test_signature(i: &ast::Item) -> HasTestSignature {
match &i.node {
&ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
let no_output = match decl.output {
ast::DefaultReturn(..) => true,
ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
_ => false
};
if decl.inputs.is_empty()
&& no_output
&&!generics.is_parameterized() {
Yes
} else {
No
}
}
_ => NotEvenAFunction,
}
}
if has_test_attr {
let diag = cx.span_diagnostic;
match has_test_signature(i) {
Yes => {},
No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
NotEvenAFunction => diag.span_err(i.span,
"only functions may be used as tests"),
}
}
return has_test_attr && has_test_signature(i) == Yes;
}
fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
let has_bench_attr = attr::contains_name(&i.attrs, "bench");
fn has_test_signature(i: &ast::Item) -> bool {
match i.node {
ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
let input_cnt = decl.inputs.len();
let no_output = match decl.output {
ast::DefaultReturn(..) => true,
ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
_ => false
};
let tparm_cnt = generics.ty_params.len();
// NB: inadequate check, but we're running
// well before resolve, can't get too deep.
input_cnt == 1
&& no_output && tparm_cnt == 0
}
_ => false
}
}
if has_bench_attr &&!has_test_signature(i) {
let diag = cx.span_diagnostic;
diag.span_err(i.span, "functions used as benches must have signature \
`fn(&mut Bencher) -> ()`");
}
return has_bench_attr && has_test_signature(i);
}
fn is_ignored(i: &ast::Item) -> bool {
i.attrs.iter().any(|attr| attr.check_name("ignore"))
}
fn should_panic(i: &ast::Item) -> ShouldPanic {
match i.attrs.iter().find(|attr| attr.check_name("should_panic")) {
Some(attr) => {
let msg = attr.meta_item_list()
.and_then(|list| list.iter().find(|mi| mi.check_name("expected")))
.and_then(|mi| mi.value_str());
ShouldPanic::Yes(msg)
}
None => ShouldPanic::No,
}
}
/*
We're going to be building a module that looks more or less like:
mod __test {
extern crate test (name = "test", vers = "...");
fn main() {
test::test_main_static(&::os::args()[], tests)
}
static tests : &'static [test::TestDescAndFn] = &[
... the list of tests in the crate...
];
}
*/
fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
let id_test = token::str_to_ident("test");
let (vi, vis, ident) = if cx.is_test_crate {
(ast::ItemUse(
P(nospan(ast::ViewPathSimple(id_test,
path_node(vec!(id_test)))))),
ast::Public, token::special_idents::invalid)
} else {
(ast::ItemExternCrate(None), ast::Inherited, id_test)
};
P(ast::Item {
id: ast::DUMMY_NODE_ID,
ident: ident,
node: vi,
attrs: vec![],
vis: vis,
span: DUMMY_SP
})
}
fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
// Writing this out by hand with 'ignored_span':
// pub fn main() {
// #![main]
// use std::slice::AsSlice;
// test::test_main_static(::std::os::args().as_slice(), TESTS);
// }
let sp = ignored_span(cx, DUMMY_SP);
let ecx = &cx.ext_cx;
// test::test_main_static
let test_main_path = ecx.path(sp, vec![token::str_to_ident("test"),
token::str_to_ident("test_main_static")]);
// test::test_main_static(...)
let test_main_path_expr = ecx.expr_path(test_main_path);
let tests_ident_expr = ecx.expr_ident(sp, token::str_to_ident("TESTS"));
let call_test_main = ecx.expr_call(sp, test_main_path_expr,
vec![tests_ident_expr]);
let call_test_main = ecx.stmt_expr(call_test_main);
// #![main]
let main_meta = ecx.meta_word(sp, token::intern_and_get_ident("main"));
let main_attr = ecx.attribute(sp, main_meta);
// pub fn main() {... }
let main_ret_ty = ecx.ty(sp, ast::TyTup(vec![]));
let main_body = ecx.block_all(sp, vec![call_test_main], None);
let main = ast::ItemFn(ecx.fn_decl(vec![], main_ret_ty),
ast::Unsafety::Normal,
ast::Constness::NotConst,
::abi::Rust, empty_generics(), main_body);
let main = P(ast::Item {
ident: token::str_to_ident("main"),
attrs: vec![main_attr],
id: ast::DUMMY_NODE_ID,
node: main,
vis: ast::Public,
span: sp
});
return main;
}
fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>,
|
sess: &'a ParseSess,
span_diagnostic: &'a diagnostic::SpanHandler,
path: Vec<ast::Ident>,
ext_cx: ExtCtxt<'a>,
|
random_line_split
|
|
issue-54462-mutable-noalias-correctness.rs
|
row * 1 + col * 3
}
fn main() {
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3)] {
for k in 0..4 {
let (x, rest) = mat.split_at_mut(linidx(i, k) + 1);
let a = x.last_mut().unwrap();
let b = rest.get_mut(linidx(j, k) - linidx(i, k) - 1).unwrap();
::std::mem::swap(a, b);
}
}
}
}
assert_eq!([9.0, 5.0, 1.0, 10.0, 6.0, 2.0, 11.0, 7.0, 3.0, 12.0, 8.0, 4.0], mat);
}
|
// run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn linidx(row: usize, col: usize) -> usize {
|
random_line_split
|
|
issue-54462-mutable-noalias-correctness.rs
|
// run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn linidx(row: usize, col: usize) -> usize {
row * 1 + col * 3
}
fn main()
|
{
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3)] {
for k in 0..4 {
let (x, rest) = mat.split_at_mut(linidx(i, k) + 1);
let a = x.last_mut().unwrap();
let b = rest.get_mut(linidx(j, k) - linidx(i, k) - 1).unwrap();
::std::mem::swap(a, b);
}
}
}
}
assert_eq!([9.0, 5.0, 1.0, 10.0, 6.0, 2.0, 11.0, 7.0, 3.0, 12.0, 8.0, 4.0], mat);
}
|
identifier_body
|
|
issue-54462-mutable-noalias-correctness.rs
|
// run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn
|
(row: usize, col: usize) -> usize {
row * 1 + col * 3
}
fn main() {
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3)] {
for k in 0..4 {
let (x, rest) = mat.split_at_mut(linidx(i, k) + 1);
let a = x.last_mut().unwrap();
let b = rest.get_mut(linidx(j, k) - linidx(i, k) - 1).unwrap();
::std::mem::swap(a, b);
}
}
}
}
assert_eq!([9.0, 5.0, 1.0, 10.0, 6.0, 2.0, 11.0, 7.0, 3.0, 12.0, 8.0, 4.0], mat);
}
|
linidx
|
identifier_name
|
issue-54462-mutable-noalias-correctness.rs
|
// run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn linidx(row: usize, col: usize) -> usize {
row * 1 + col * 3
}
fn main() {
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3)]
|
}
}
assert_eq!([9.0, 5.0, 1.0, 10.0, 6.0, 2.0, 11.0, 7.0, 3.0, 12.0, 8.0, 4.0], mat);
}
|
{
for k in 0..4 {
let (x, rest) = mat.split_at_mut(linidx(i, k) + 1);
let a = x.last_mut().unwrap();
let b = rest.get_mut(linidx(j, k) - linidx(i, k) - 1).unwrap();
::std::mem::swap(a, b);
}
}
|
conditional_block
|
udpsink.rs
|
// Copyright (C) 2019 Mathieu Duponchelle <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use std::thread;
use glib::prelude::*;
fn init() {
use std::sync::Once;
static INIT: Once = Once::new();
INIT.call_once(|| {
gst::init().unwrap();
gstthreadshare::plugin_register_static().expect("gstthreadshare udpsrc test");
});
}
#[test]
fn test_client_management() {
init();
let h = gst_check::Harness::new("ts-udpsink");
let udpsink = h.get_element().unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
udpsink.emit("add", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
/* Adding a client twice is not supported */
udpsink.emit("add", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
udpsink.emit("remove", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
/* Removing a non-existing client should not be a problem */
udpsink.emit("remove", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
/* Removing the default client is possible */
udpsink.emit("remove", &[&"127.0.0.1", &5004i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "");
/* The client properties is writable too */
udpsink
.set_property("clients", &"127.0.0.1:5004,192.168.1.1:57")
.unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
udpsink.emit("clear", &[]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "");
}
#[test]
fn test_chain() {
init();
let mut h = gst_check::Harness::new("ts-udpsink");
h.set_src_caps_str(&"foo/bar");
{
let udpsink = h.get_element().unwrap();
udpsink.set_property("clients", &"127.0.0.1:5005").unwrap();
}
thread::spawn(move || {
use std::net;
|
thread::sleep(time::Duration::from_millis(50));
let socket = net::UdpSocket::bind("127.0.0.1:5005").unwrap();
let mut buf = [0; 5];
let (amt, _) = socket.recv_from(&mut buf).unwrap();
assert!(amt == 4);
assert!(buf == [42, 43, 44, 45, 0]);
});
let buf = gst::Buffer::from_slice(&[42, 43, 44, 45]);
assert!(h.push(buf) == Ok(gst::FlowSuccess::Ok));
}
|
use std::time;
|
random_line_split
|
udpsink.rs
|
// Copyright (C) 2019 Mathieu Duponchelle <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use std::thread;
use glib::prelude::*;
fn init() {
use std::sync::Once;
static INIT: Once = Once::new();
INIT.call_once(|| {
gst::init().unwrap();
gstthreadshare::plugin_register_static().expect("gstthreadshare udpsrc test");
});
}
#[test]
fn
|
() {
init();
let h = gst_check::Harness::new("ts-udpsink");
let udpsink = h.get_element().unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
udpsink.emit("add", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
/* Adding a client twice is not supported */
udpsink.emit("add", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
udpsink.emit("remove", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
/* Removing a non-existing client should not be a problem */
udpsink.emit("remove", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
/* Removing the default client is possible */
udpsink.emit("remove", &[&"127.0.0.1", &5004i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "");
/* The client properties is writable too */
udpsink
.set_property("clients", &"127.0.0.1:5004,192.168.1.1:57")
.unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
udpsink.emit("clear", &[]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "");
}
#[test]
fn test_chain() {
init();
let mut h = gst_check::Harness::new("ts-udpsink");
h.set_src_caps_str(&"foo/bar");
{
let udpsink = h.get_element().unwrap();
udpsink.set_property("clients", &"127.0.0.1:5005").unwrap();
}
thread::spawn(move || {
use std::net;
use std::time;
thread::sleep(time::Duration::from_millis(50));
let socket = net::UdpSocket::bind("127.0.0.1:5005").unwrap();
let mut buf = [0; 5];
let (amt, _) = socket.recv_from(&mut buf).unwrap();
assert!(amt == 4);
assert!(buf == [42, 43, 44, 45, 0]);
});
let buf = gst::Buffer::from_slice(&[42, 43, 44, 45]);
assert!(h.push(buf) == Ok(gst::FlowSuccess::Ok));
}
|
test_client_management
|
identifier_name
|
udpsink.rs
|
// Copyright (C) 2019 Mathieu Duponchelle <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use std::thread;
use glib::prelude::*;
fn init() {
use std::sync::Once;
static INIT: Once = Once::new();
INIT.call_once(|| {
gst::init().unwrap();
gstthreadshare::plugin_register_static().expect("gstthreadshare udpsrc test");
});
}
#[test]
fn test_client_management()
|
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
/* Adding a client twice is not supported */
udpsink.emit("add", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
udpsink.emit("remove", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
/* Removing a non-existing client should not be a problem */
udpsink.emit("remove", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
/* Removing the default client is possible */
udpsink.emit("remove", &[&"127.0.0.1", &5004i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "");
/* The client properties is writable too */
udpsink
.set_property("clients", &"127.0.0.1:5004,192.168.1.1:57")
.unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004,192.168.1.1:57");
udpsink.emit("clear", &[]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "");
}
#[test]
fn test_chain() {
init();
let mut h = gst_check::Harness::new("ts-udpsink");
h.set_src_caps_str(&"foo/bar");
{
let udpsink = h.get_element().unwrap();
udpsink.set_property("clients", &"127.0.0.1:5005").unwrap();
}
thread::spawn(move || {
use std::net;
use std::time;
thread::sleep(time::Duration::from_millis(50));
let socket = net::UdpSocket::bind("127.0.0.1:5005").unwrap();
let mut buf = [0; 5];
let (amt, _) = socket.recv_from(&mut buf).unwrap();
assert!(amt == 4);
assert!(buf == [42, 43, 44, 45, 0]);
});
let buf = gst::Buffer::from_slice(&[42, 43, 44, 45]);
assert!(h.push(buf) == Ok(gst::FlowSuccess::Ok));
}
|
{
init();
let h = gst_check::Harness::new("ts-udpsink");
let udpsink = h.get_element().unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
.unwrap()
.unwrap();
assert_eq!(clients, "127.0.0.1:5004");
udpsink.emit("add", &[&"192.168.1.1", &57i32]).unwrap();
let clients = udpsink
.get_property("clients")
.unwrap()
.get::<String>()
|
identifier_body
|
mod.rs
|
//! An asynchronous stub resolver.
//!
//! A resolver is the component in the DNS that answers queries. A stub
//! resolver does so by simply relaying queries to a different resolver
//! chosen from a predefined set. This is how pretty much all user
//! applications use DNS.
//!
//! This module implements a modern, asynchronous stub resolver built on
//! top of [futures] and [tokio].
//!
//! The module provides ways to create a *resolver* that knows how to
//! process DNS *queries*. A query asks for all the resource records
//! associated with a given triple of a domain name, resource record type,
//! and class (known as a *question*). It is a future resolving to a DNS
//! message with a successful response or an error. Queries can be combined
//! into *lookups* that use the returned resource records to answer more
//! specific enquiries such as all the IP addresses associated with a given
//! host name. The module provides a rich set of common lookups in the
//! [lookup] sub-module.
//!
//! The following gives an introduction into using the resolver. For an
//! introduction into the internal design, please have a look at the [intro]
//! sub-module.
//!
//!
//! # Creating a Resolver
//!
//! The resolver is represented by the [`Resolver`] type. When creating a
//! value of this type, you create all the parts of an actual resolver
//! according to a resolver configuration. Since these parts are handling
//! actual network traffic, the resolver needs a handle to a Tokio reactor
//! into which these parts will be spawned as futures.
//!
//! For the resolver configuration, there’s [`ResolvConf`]. While you can
//! create a value of this type by hand, the more common way is to use your
//! system’s resolver configuration. [`ResolvConf`] implements the `Default`
//! trait doing exactly that by reading `/etc/resolv.conf`.
//!
//! > That probably won’t work on Windows, but, sadly, I have no idea how to
//! > retrieve the resolver configuration there. Some help here would be
//! > very much appreciated.
//!
//! Since using the system configuration is the most common case by far,
//! [`Resolver`]’s `new()` function does just that. So, the easiest way to
//! get a resolver is just this:
//!
//! ```rust,no_run
//! # extern crate domain;
//! # extern crate tokio_core;
//! use domain::resolv::Resolver;
//! use tokio_core::reactor::Core;
//!
//! # fn main() {
//! let core = Core::new().unwrap();
//! let resolv = Resolver::new(&core.handle());
//! # }
//! ```
//!
//! If you do have a configuration, you can use the `from_conf()` function
//! instead.
//!
//!
//! # Using the Resolver: Queries
//!
//! As was mentioned above, the [`Resolver`] doesn’t actually contain the
//! networking parts necessary to answer queries. Instead, it only knows how
//! to contact those parts. Because of this, you can clone the resolver,
//! even pass it to other threads.
//!
//! The main purpose of the resolver, though, is to start queries. This is
//! done through [`Resolver::query()`]. It takes something that can be
//! turned into a question and returns a future that will resolve into
//! either a [`MessageBuf`] with the response to the query or an [`Error`].
//! Conveniently, a triple of a domain name, a resource record type, and a
//! class is something than can be turned into a question, so you don’t need
//! to build the question from hand. (You will have to convert a string into
//! a domain name from hand since that may fail.)
//!
//! As an example, let’s find out the IPv6 addresses for `www.rust-lang.org`:
//!
//! ```rust,no_run
//! extern crate domain;
//! extern crate futures;
//! extern crate tokio_core;
//!
//! use std::str::FromStr;
//! use domain::bits::DNameBuf;
//! use domain::iana::{Class, Rtype};
//! use domain::rdata::Aaaa;
//! use domain::resolv::Resolver;
//! use futures::Future;
//! use tokio_core::reactor::Core;
//!
//! fn main() {
//! let mut core = Core::new().unwrap();
//! let resolv = Resolver::new(&core.handle());
//!
//! let name = DNameBuf::from_str("www.rust-lang.org.").unwrap();
//! let addrs = resolv.query((name, Rtype::Aaaa, Class::In));
//! let response = core.run(addrs).unwrap();
//! for record in response.answer().unwrap().limit_to::<Aaaa>() {
//! println!("{}", record.unwrap());
//! }
//! }
//! ```
//!
//! Note the final dot at `"www.rust-lang.org."` making it an absolute domain
//! name. Queries don’t know how to deal with relative names and will error
//! out if given one.
//!
//!
//! # Complex Queries: Lookups
//!
//! Most of the times when you are using DNS you aren’t really interested in a
//! bunch of resource records. You want an answer to a more concrete
//! question. For instance, if you want to know the IP addresses for a
//! host name, you don’t really care that you have to make a query for the
//! `A` records and one for `AAAA` records for that host name. You want the
//! addresses.
//!
//! This is what lookups do. They are functions that take a [`Resolver`]
//! and some additional information and turn that into a future of some
//! specific result.
//!
//! Using [`lookup_host()`], the process of looking up the IP addresses
//! becomes much easier. To update above’s example:
//!
//! ```rust,no_run
//! extern crate domain;
//! extern crate futures;
//! extern crate tokio_core;
//!
//! use std::str::FromStr;
//! use domain::bits::DNameBuf;
//! use domain::resolv::Resolver;
//! use domain::resolv::lookup::lookup_host;
//! use futures::Future;
//! use tokio_core::reactor::Core;
//!
//! fn main() {
//! let mut core = Core::new().unwrap();
//! let resolv = Resolver::new(&core.handle());
//!
//! let name = DNameBuf::from_str("www.rust-lang.org").unwrap();
//! let addrs = lookup_host(resolv, name);
//! let response = core.run(addrs).unwrap();
//! for addr in response.iter() {
//! println!("{}", addr);
//! }
//! }
//! ```
//!
//! No more fiddeling with record types and classes and the result can now
//! iterate over IP addresses. And we get both IPv4 and IPv6 addresses to
//! boot.
|
//!
//! Furthermore, we now can use a relative host name. It will be turned into
//! an absolute name according to the rules set down by the configuration we
//! used when creating the resolver.
//!
//! As an aside, the lookup functions are named after the thing they look
//! up not their result following the example of the standard library. So,
//! when you look for the addresses for the host, you have to use
//! [`lookup_host()`], not [`lookup_addr()`].
//!
//! Have a look at the [lookup] module for all the lookup functions
//! currently available.
//!
//!
//! # The Run Shortcut
//!
//! If you only want to do a DNS lookup and don’t otherwise use tokio, there
//! is a shortcut through the [`Resolver::run()`] associated function. It
//! takes a closure from a [`Resolver`] to a future and waits while
//! driving the future to completing. In other words, it takes away all the
//! boiler plate from above:
//!
//! ```rust,no_run
//! extern crate domain;
//!
//! use std::str::FromStr;
//! use domain::bits::DNameBuf;
//! use domain::resolv::Resolver;
//! use domain::resolv::lookup::lookup_host;
//!
//! fn main() {
//! let response = Resolver::run(|resolv| {
//! let name = DNameBuf::from_str("www.rust-lang.org").unwrap();
//! lookup_host(resolv, name)
//! });
//! for addr in response.unwrap().iter() {
//! println!("{}", addr);
//! }
//! }
//! ```
//!
//!
//! [futures]: https://github.com/alexcrichton/futures-rs
//! [tokio]: https://tokio.rs/
//! [intro]: intro/index.html
//! [lookup]: lookup/index.html
//! [`Error`]: error/enum.Error.html
//! [`MessageBuf`]:../bits/message/struct.MessageBuf.html
//! [`ResolvConf`]: conf/struct.ResolvConf.html
//! [`Resolver`]: struct.Resolver.html
//! [`Resolver::start()`]: struct.Resolver.html#method.start
//! [`Resolver::run()`]: struct.Resolver.html#method.run
//! [`Resolver::query()`]: struct.Resolver.html#method.query
//! [`lookup_addr()`]: lookup/fn.lookup_addr.html
//! [`lookup_host()`]: lookup/fn.lookup_host.html
//------------ Re-exports ----------------------------------------------------
pub use self::conf::ResolvConf;
pub use self::public::{Query, Resolver};
//------------ Public Modules ------------------------------------------------
pub mod conf;
pub mod error;
pub mod lookup;
//------------ Meta-modules for Documentation --------------------------------
pub mod intro;
//------------ Private Modules -----------------------------------------------
mod channel;
mod public;
mod request;
mod tcp;
mod transport;
mod udp;
|
random_line_split
|
|
outfile.rs
|
use std::fs::File;
use std::path::Path;
use std::io::Write;
pub struct
|
{
filename: String,
file: Option<File>,
}
impl FileIo {
pub fn new(name: String) -> FileIo {
FileIo {
filename: name.clone(),
file: match File::create(&Path::new(&*name)) {
Ok(f) => Some(f),
Err(e) => if name == "" {
None
} else {
panic!("Could not open file: {}", e);
}
},
}
}
pub fn write(&mut self, message: &str) -> bool {
if self.filename == "" {
println!("{}", message);
true
} else {
match self.file.as_mut().unwrap().write(message.as_bytes()) {
Ok(_) => true,
Err(e) => {
println!("Cannot write: {}", e);
false
},
}
}
}
}
|
FileIo
|
identifier_name
|
outfile.rs
|
use std::fs::File;
use std::path::Path;
use std::io::Write;
pub struct FileIo {
filename: String,
file: Option<File>,
}
impl FileIo {
pub fn new(name: String) -> FileIo {
FileIo {
filename: name.clone(),
file: match File::create(&Path::new(&*name)) {
Ok(f) => Some(f),
Err(e) => if name == "" {
None
} else
|
},
}
}
pub fn write(&mut self, message: &str) -> bool {
if self.filename == "" {
println!("{}", message);
true
} else {
match self.file.as_mut().unwrap().write(message.as_bytes()) {
Ok(_) => true,
Err(e) => {
println!("Cannot write: {}", e);
false
},
}
}
}
}
|
{
panic!("Could not open file: {}", e);
}
|
conditional_block
|
outfile.rs
|
use std::fs::File;
use std::path::Path;
use std::io::Write;
pub struct FileIo {
filename: String,
|
impl FileIo {
pub fn new(name: String) -> FileIo {
FileIo {
filename: name.clone(),
file: match File::create(&Path::new(&*name)) {
Ok(f) => Some(f),
Err(e) => if name == "" {
None
} else {
panic!("Could not open file: {}", e);
}
},
}
}
pub fn write(&mut self, message: &str) -> bool {
if self.filename == "" {
println!("{}", message);
true
} else {
match self.file.as_mut().unwrap().write(message.as_bytes()) {
Ok(_) => true,
Err(e) => {
println!("Cannot write: {}", e);
false
},
}
}
}
}
|
file: Option<File>,
}
|
random_line_split
|
outfile.rs
|
use std::fs::File;
use std::path::Path;
use std::io::Write;
pub struct FileIo {
filename: String,
file: Option<File>,
}
impl FileIo {
pub fn new(name: String) -> FileIo
|
pub fn write(&mut self, message: &str) -> bool {
if self.filename == "" {
println!("{}", message);
true
} else {
match self.file.as_mut().unwrap().write(message.as_bytes()) {
Ok(_) => true,
Err(e) => {
println!("Cannot write: {}", e);
false
},
}
}
}
}
|
{
FileIo {
filename: name.clone(),
file: match File::create(&Path::new(&*name)) {
Ok(f) => Some(f),
Err(e) => if name == "" {
None
} else {
panic!("Could not open file: {}", e);
}
},
}
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.