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
challenge19_20.rs
use crate::errors::*; use crate::set1::break_multibyte_xor_for_keysize; use aes::random_block; use std::path::PathBuf; use aes::{Aes128, MODE}; use serialize::from_base64_lines; pub enum Exercise { _19, _20, } struct
{ key: Vec<u8>, exercise: Exercise, } impl Encrypter { pub fn new(exercise: Exercise) -> Self { Encrypter { key: random_block(), exercise, } } pub fn get_ciphertexts(&self) -> Result<Vec<Vec<u8>>> { let mut input_file_path = PathBuf::from("data"); let input_file_name = match self.exercise { Exercise::_19 => "19.txt", Exercise::_20 => "20.txt", }; input_file_path.push(input_file_name); let cleartexts = from_base64_lines(input_file_path.as_path())?; cleartexts .iter() .map(|c| { c.encrypt(&self.key, None, MODE::CTR) .map_err(|err| err.into()) }) .collect::<Result<Vec<Vec<u8>>>>() } pub fn verify_solution(&self, candidate_key: &[u8], size: usize) -> Result<()> { // TODO: The first entry of the recovered key is wrong because the distribution of first letters // of sentences is very different from the overall distribution of letters in a text. compare_eq( &vec![0; size].encrypt(&self.key, None, MODE::CTR)?[1..], &candidate_key[1..], ) } } pub fn run(exercise: Exercise) -> Result<()> { let encrypter = Encrypter::new(exercise); let ciphertexts = encrypter.get_ciphertexts()?; let size = ciphertexts.iter().map(|c| c.len()).min().unwrap(); // unwrap is ok let ciphertext: Vec<u8> = ciphertexts .iter() .flat_map(|ciphertext| &ciphertext[..size]) .cloned() .collect(); let key = break_multibyte_xor_for_keysize(&ciphertext, size); encrypter.verify_solution(&key, size) }
Encrypter
identifier_name
challenge19_20.rs
use crate::errors::*; use crate::set1::break_multibyte_xor_for_keysize; use aes::random_block; use std::path::PathBuf; use aes::{Aes128, MODE}; use serialize::from_base64_lines;
pub enum Exercise { _19, _20, } struct Encrypter { key: Vec<u8>, exercise: Exercise, } impl Encrypter { pub fn new(exercise: Exercise) -> Self { Encrypter { key: random_block(), exercise, } } pub fn get_ciphertexts(&self) -> Result<Vec<Vec<u8>>> { let mut input_file_path = PathBuf::from("data"); let input_file_name = match self.exercise { Exercise::_19 => "19.txt", Exercise::_20 => "20.txt", }; input_file_path.push(input_file_name); let cleartexts = from_base64_lines(input_file_path.as_path())?; cleartexts .iter() .map(|c| { c.encrypt(&self.key, None, MODE::CTR) .map_err(|err| err.into()) }) .collect::<Result<Vec<Vec<u8>>>>() } pub fn verify_solution(&self, candidate_key: &[u8], size: usize) -> Result<()> { // TODO: The first entry of the recovered key is wrong because the distribution of first letters // of sentences is very different from the overall distribution of letters in a text. compare_eq( &vec![0; size].encrypt(&self.key, None, MODE::CTR)?[1..], &candidate_key[1..], ) } } pub fn run(exercise: Exercise) -> Result<()> { let encrypter = Encrypter::new(exercise); let ciphertexts = encrypter.get_ciphertexts()?; let size = ciphertexts.iter().map(|c| c.len()).min().unwrap(); // unwrap is ok let ciphertext: Vec<u8> = ciphertexts .iter() .flat_map(|ciphertext| &ciphertext[..size]) .cloned() .collect(); let key = break_multibyte_xor_for_keysize(&ciphertext, size); encrypter.verify_solution(&key, size) }
random_line_split
challenge19_20.rs
use crate::errors::*; use crate::set1::break_multibyte_xor_for_keysize; use aes::random_block; use std::path::PathBuf; use aes::{Aes128, MODE}; use serialize::from_base64_lines; pub enum Exercise { _19, _20, } struct Encrypter { key: Vec<u8>, exercise: Exercise, } impl Encrypter { pub fn new(exercise: Exercise) -> Self { Encrypter { key: random_block(), exercise, } } pub fn get_ciphertexts(&self) -> Result<Vec<Vec<u8>>> { let mut input_file_path = PathBuf::from("data"); let input_file_name = match self.exercise { Exercise::_19 => "19.txt", Exercise::_20 => "20.txt", }; input_file_path.push(input_file_name); let cleartexts = from_base64_lines(input_file_path.as_path())?; cleartexts .iter() .map(|c| { c.encrypt(&self.key, None, MODE::CTR) .map_err(|err| err.into()) }) .collect::<Result<Vec<Vec<u8>>>>() } pub fn verify_solution(&self, candidate_key: &[u8], size: usize) -> Result<()> { // TODO: The first entry of the recovered key is wrong because the distribution of first letters // of sentences is very different from the overall distribution of letters in a text. compare_eq( &vec![0; size].encrypt(&self.key, None, MODE::CTR)?[1..], &candidate_key[1..], ) } } pub fn run(exercise: Exercise) -> Result<()>
{ let encrypter = Encrypter::new(exercise); let ciphertexts = encrypter.get_ciphertexts()?; let size = ciphertexts.iter().map(|c| c.len()).min().unwrap(); // unwrap is ok let ciphertext: Vec<u8> = ciphertexts .iter() .flat_map(|ciphertext| &ciphertext[..size]) .cloned() .collect(); let key = break_multibyte_xor_for_keysize(&ciphertext, size); encrypter.verify_solution(&key, size) }
identifier_body
helpers.rs
// Example of a module shared among test code. /*BEGIN*/pub fn helper() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)] /*BEGIN*/pub fn unused() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used
// ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)]
// ^^^^^^^^^^^^^^^NOTE(>=1.22.0,<1.24.0-beta) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used
random_line_split
helpers.rs
// Example of a module shared among test code. /*BEGIN*/pub fn helper()
/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)] /*BEGIN*/pub fn unused() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0,<1.24.0-beta) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)]
{ // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0) #[warn(dead_code)] }
identifier_body
helpers.rs
// Example of a module shared among test code. /*BEGIN*/pub fn helper() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)] /*BEGIN*/pub fn
() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0,<1.24.0-beta) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)]
unused
identifier_name
match-arm-statics.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(struct_variant)] struct NewBool(bool); enum Direction { North, East, South, West } struct Foo { bar: Option<Direction>, baz: NewBool } enum EnumWithStructVariants { Variant1(bool), Variant2 { dir: Direction } } const TRUE_TRUE: (bool, bool) = (true, true); const NONE: Option<Direction> = None; const EAST: Direction = Direction::East; const NEW_FALSE: NewBool = NewBool(false); const STATIC_FOO: Foo = Foo { bar: Some(Direction::South), baz: NEW_FALSE }; const VARIANT2_NORTH: EnumWithStructVariants = EnumWithStructVariants::Variant2 { dir: Direction::North }; pub mod glfw { pub struct InputState(uint); pub const RELEASE : InputState = InputState(0); pub const PRESS : InputState = InputState(1); pub const REPEAT : InputState = InputState(2); } fn issue_6533() { use glfw; fn action_to_str(state: glfw::InputState) -> &'static str { use glfw::{RELEASE, PRESS, REPEAT}; match state { RELEASE => { "Released" } PRESS => { "Pressed" } REPEAT =>
_ => { "Unknown" } } } assert_eq!(action_to_str(glfw::RELEASE), "Released"); assert_eq!(action_to_str(glfw::PRESS), "Pressed"); assert_eq!(action_to_str(glfw::REPEAT), "Repeated"); } fn issue_13626() { const VAL: [u8,..1] = [0]; match [1] { VAL => unreachable!(), _ => () } } fn issue_14576() { type Foo = (i32, i32); const ON: Foo = (1, 1); const OFF: Foo = (0, 0); match (1, 1) { OFF => unreachable!(), ON => (), _ => unreachable!() } enum C { D = 3, E = 4 } const F : C = C::D; assert_eq!(match C::D { F => 1i, _ => 2, }, 1); } fn issue_13731() { enum A { AA(()) } const B: A = A::AA(()); match A::AA(()) { B => () } } fn issue_15393() { #![allow(dead_code)] struct Flags { bits: uint } const FOO: Flags = Flags { bits: 0x01 }; const BAR: Flags = Flags { bits: 0x02 }; match (Flags { bits: 0x02 }) { FOO => unreachable!(), BAR => (), _ => unreachable!() } } fn main() { assert_eq!(match (true, false) { TRUE_TRUE => 1i, (false, false) => 2, (false, true) => 3, (true, false) => 4 }, 4); assert_eq!(match Some(Some(Direction::North)) { Some(NONE) => 1i, Some(Some(Direction::North)) => 2, Some(Some(EAST)) => 3, Some(Some(Direction::South)) => 4, Some(Some(Direction::West)) => 5, None => 6 }, 2); assert_eq!(match (Foo { bar: Some(Direction::West), baz: NewBool(true) }) { Foo { bar: None, baz: NewBool(true) } => 1i, Foo { bar: NONE, baz: NEW_FALSE } => 2, STATIC_FOO => 3, Foo { bar: _, baz: NEW_FALSE } => 4, Foo { bar: Some(Direction::West), baz: NewBool(true) } => 5, Foo { bar: Some(Direction::South), baz: NewBool(true) } => 6, Foo { bar: Some(EAST),.. } => 7, Foo { bar: Some(Direction::North), baz: NewBool(true) } => 8 }, 5); assert_eq!(match (EnumWithStructVariants::Variant2 { dir: Direction::North }) { EnumWithStructVariants::Variant1(true) => 1i, EnumWithStructVariants::Variant1(false) => 2, EnumWithStructVariants::Variant2 { dir: Direction::West } => 3, VARIANT2_NORTH => 4, EnumWithStructVariants::Variant2 { dir: Direction::South } => 5, EnumWithStructVariants::Variant2 { dir: Direction::East } => 6 }, 4); issue_6533(); issue_13626(); issue_13731(); issue_14576(); issue_15393(); }
{ "Repeated" }
conditional_block
match-arm-statics.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(struct_variant)] struct NewBool(bool); enum Direction { North, East, South, West } struct Foo { bar: Option<Direction>, baz: NewBool } enum EnumWithStructVariants { Variant1(bool), Variant2 { dir: Direction } } const TRUE_TRUE: (bool, bool) = (true, true); const NONE: Option<Direction> = None; const EAST: Direction = Direction::East; const NEW_FALSE: NewBool = NewBool(false); const STATIC_FOO: Foo = Foo { bar: Some(Direction::South), baz: NEW_FALSE }; const VARIANT2_NORTH: EnumWithStructVariants = EnumWithStructVariants::Variant2 { dir: Direction::North }; pub mod glfw { pub struct InputState(uint); pub const RELEASE : InputState = InputState(0); pub const PRESS : InputState = InputState(1); pub const REPEAT : InputState = InputState(2); } fn issue_6533() { use glfw; fn action_to_str(state: glfw::InputState) -> &'static str { use glfw::{RELEASE, PRESS, REPEAT}; match state { RELEASE => { "Released" } PRESS => { "Pressed" } REPEAT => { "Repeated" } _ => { "Unknown" } } } assert_eq!(action_to_str(glfw::RELEASE), "Released"); assert_eq!(action_to_str(glfw::PRESS), "Pressed"); assert_eq!(action_to_str(glfw::REPEAT), "Repeated"); } fn issue_13626() { const VAL: [u8,..1] = [0]; match [1] { VAL => unreachable!(), _ => () } } fn issue_14576() { type Foo = (i32, i32); const ON: Foo = (1, 1); const OFF: Foo = (0, 0); match (1, 1) { OFF => unreachable!(), ON => (), _ => unreachable!() }
assert_eq!(match C::D { F => 1i, _ => 2, }, 1); } fn issue_13731() { enum A { AA(()) } const B: A = A::AA(()); match A::AA(()) { B => () } } fn issue_15393() { #![allow(dead_code)] struct Flags { bits: uint } const FOO: Flags = Flags { bits: 0x01 }; const BAR: Flags = Flags { bits: 0x02 }; match (Flags { bits: 0x02 }) { FOO => unreachable!(), BAR => (), _ => unreachable!() } } fn main() { assert_eq!(match (true, false) { TRUE_TRUE => 1i, (false, false) => 2, (false, true) => 3, (true, false) => 4 }, 4); assert_eq!(match Some(Some(Direction::North)) { Some(NONE) => 1i, Some(Some(Direction::North)) => 2, Some(Some(EAST)) => 3, Some(Some(Direction::South)) => 4, Some(Some(Direction::West)) => 5, None => 6 }, 2); assert_eq!(match (Foo { bar: Some(Direction::West), baz: NewBool(true) }) { Foo { bar: None, baz: NewBool(true) } => 1i, Foo { bar: NONE, baz: NEW_FALSE } => 2, STATIC_FOO => 3, Foo { bar: _, baz: NEW_FALSE } => 4, Foo { bar: Some(Direction::West), baz: NewBool(true) } => 5, Foo { bar: Some(Direction::South), baz: NewBool(true) } => 6, Foo { bar: Some(EAST),.. } => 7, Foo { bar: Some(Direction::North), baz: NewBool(true) } => 8 }, 5); assert_eq!(match (EnumWithStructVariants::Variant2 { dir: Direction::North }) { EnumWithStructVariants::Variant1(true) => 1i, EnumWithStructVariants::Variant1(false) => 2, EnumWithStructVariants::Variant2 { dir: Direction::West } => 3, VARIANT2_NORTH => 4, EnumWithStructVariants::Variant2 { dir: Direction::South } => 5, EnumWithStructVariants::Variant2 { dir: Direction::East } => 6 }, 4); issue_6533(); issue_13626(); issue_13731(); issue_14576(); issue_15393(); }
enum C { D = 3, E = 4 } const F : C = C::D;
random_line_split
match-arm-statics.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(struct_variant)] struct NewBool(bool); enum Direction { North, East, South, West } struct Foo { bar: Option<Direction>, baz: NewBool } enum
{ Variant1(bool), Variant2 { dir: Direction } } const TRUE_TRUE: (bool, bool) = (true, true); const NONE: Option<Direction> = None; const EAST: Direction = Direction::East; const NEW_FALSE: NewBool = NewBool(false); const STATIC_FOO: Foo = Foo { bar: Some(Direction::South), baz: NEW_FALSE }; const VARIANT2_NORTH: EnumWithStructVariants = EnumWithStructVariants::Variant2 { dir: Direction::North }; pub mod glfw { pub struct InputState(uint); pub const RELEASE : InputState = InputState(0); pub const PRESS : InputState = InputState(1); pub const REPEAT : InputState = InputState(2); } fn issue_6533() { use glfw; fn action_to_str(state: glfw::InputState) -> &'static str { use glfw::{RELEASE, PRESS, REPEAT}; match state { RELEASE => { "Released" } PRESS => { "Pressed" } REPEAT => { "Repeated" } _ => { "Unknown" } } } assert_eq!(action_to_str(glfw::RELEASE), "Released"); assert_eq!(action_to_str(glfw::PRESS), "Pressed"); assert_eq!(action_to_str(glfw::REPEAT), "Repeated"); } fn issue_13626() { const VAL: [u8,..1] = [0]; match [1] { VAL => unreachable!(), _ => () } } fn issue_14576() { type Foo = (i32, i32); const ON: Foo = (1, 1); const OFF: Foo = (0, 0); match (1, 1) { OFF => unreachable!(), ON => (), _ => unreachable!() } enum C { D = 3, E = 4 } const F : C = C::D; assert_eq!(match C::D { F => 1i, _ => 2, }, 1); } fn issue_13731() { enum A { AA(()) } const B: A = A::AA(()); match A::AA(()) { B => () } } fn issue_15393() { #![allow(dead_code)] struct Flags { bits: uint } const FOO: Flags = Flags { bits: 0x01 }; const BAR: Flags = Flags { bits: 0x02 }; match (Flags { bits: 0x02 }) { FOO => unreachable!(), BAR => (), _ => unreachable!() } } fn main() { assert_eq!(match (true, false) { TRUE_TRUE => 1i, (false, false) => 2, (false, true) => 3, (true, false) => 4 }, 4); assert_eq!(match Some(Some(Direction::North)) { Some(NONE) => 1i, Some(Some(Direction::North)) => 2, Some(Some(EAST)) => 3, Some(Some(Direction::South)) => 4, Some(Some(Direction::West)) => 5, None => 6 }, 2); assert_eq!(match (Foo { bar: Some(Direction::West), baz: NewBool(true) }) { Foo { bar: None, baz: NewBool(true) } => 1i, Foo { bar: NONE, baz: NEW_FALSE } => 2, STATIC_FOO => 3, Foo { bar: _, baz: NEW_FALSE } => 4, Foo { bar: Some(Direction::West), baz: NewBool(true) } => 5, Foo { bar: Some(Direction::South), baz: NewBool(true) } => 6, Foo { bar: Some(EAST),.. } => 7, Foo { bar: Some(Direction::North), baz: NewBool(true) } => 8 }, 5); assert_eq!(match (EnumWithStructVariants::Variant2 { dir: Direction::North }) { EnumWithStructVariants::Variant1(true) => 1i, EnumWithStructVariants::Variant1(false) => 2, EnumWithStructVariants::Variant2 { dir: Direction::West } => 3, VARIANT2_NORTH => 4, EnumWithStructVariants::Variant2 { dir: Direction::South } => 5, EnumWithStructVariants::Variant2 { dir: Direction::East } => 6 }, 4); issue_6533(); issue_13626(); issue_13731(); issue_14576(); issue_15393(); }
EnumWithStructVariants
identifier_name
animation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS transitions and animations. use clock_ticks; use flow::{self, Flow}; use gfx::display_list::OpaqueNode; use incremental::{self, RestyleDamage}; use layout_task::{LayoutTask, LayoutTaskData}; use msg::constellation_msg::{AnimationState, Msg, PipelineId}; use script::layout_interface::Animation; use script_traits::ConstellationControlMsg; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::Arc; use std::sync::mpsc::Sender; use style::animation::{GetMod, PropertyAnimation}; use style::properties::ComputedValues; /// Inserts transitions into the queue of running animations as applicable for the given style /// difference. This is called from the layout worker threads. pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>, node: OpaqueNode, old_style: &ComputedValues, new_style: &mut ComputedValues) { for i in 0..new_style.get_animation().transition_property.0.len() { // Create any property animations, if applicable. let property_animations = PropertyAnimation::from_transition(i, old_style, new_style); for property_animation in property_animations { // Set the property to the initial value. property_animation.update(new_style, 0.0); // Kick off the animation. let now = clock_ticks::precise_time_s(); let animation_style = new_style.get_animation(); let start_time = now + (animation_style.transition_delay.0.get_mod(i).seconds() as f64); new_animations_sender.send(Animation { node: node.id(), property_animation: property_animation, start_time: start_time, end_time: start_time + (animation_style.transition_duration.0.get_mod(i).seconds() as f64), }).unwrap() } } } /// Processes any new animations that were discovered after style recalculation. /// Also expire any old animations that have completed. pub fn update_animation_state(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) { let mut new_running_animations = Vec::new(); while let Ok(animation) = rw_data.new_animations_receiver.try_recv() { new_running_animations.push(animation) } let mut running_animations_hash = (*rw_data.running_animations).clone(); // Expire old running animations. let now = clock_ticks::precise_time_s(); let mut keys_to_remove = Vec::new(); for (key, running_animations) in &mut running_animations_hash { running_animations.retain(|running_animation| { now < running_animation.end_time }); if running_animations.len() == 0 { keys_to_remove.push(*key); } } for key in keys_to_remove { running_animations_hash.remove(&key).unwrap(); } // Add new running animations. for new_running_animation in new_running_animations { match running_animations_hash.entry(OpaqueNode(new_running_animation.node)) { Entry::Vacant(entry) => { entry.insert(vec![new_running_animation]); } Entry::Occupied(mut entry) => entry.get_mut().push(new_running_animation), } } rw_data.running_animations = Arc::new(running_animations_hash); let animation_state; if rw_data.running_animations.is_empty() { animation_state = AnimationState::NoAnimationsPresent; } else { animation_state = AnimationState::AnimationsPresent; } rw_data.constellation_chan .0 .send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state)) .unwrap(); } /// Recalculates style for a set of animations. This does *not* run with the DOM lock held. pub fn recalc_style_for_animations(flow: &mut Flow, animations: &HashMap<OpaqueNode, Vec<Animation>>) { let mut damage = RestyleDamage::empty(); flow.mutate_fragments(&mut |fragment| { if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) { for animation in *animations { let now = clock_ticks::precise_time_s(); let mut progress = (now - animation.start_time) / animation.duration(); if progress > 1.0 { progress = 1.0 } if progress <= 0.0 { continue } let mut new_style = fragment.style.clone(); animation.property_animation.update(&mut *Arc::make_mut(&mut new_style), progress); damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style)); fragment.style = new_style } } }); let base = flow::mut_base(flow); base.restyle_damage.insert(damage); for kid in base.children.iter_mut() { recalc_style_for_animations(kid, animations) } } /// Handles animation updates. pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData)
{ layout_task.tick_animations(rw_data); layout_task.script_chan .send(ConstellationControlMsg::TickAllAnimations(layout_task.id)) .unwrap(); }
identifier_body
animation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS transitions and animations. use clock_ticks; use flow::{self, Flow}; use gfx::display_list::OpaqueNode; use incremental::{self, RestyleDamage}; use layout_task::{LayoutTask, LayoutTaskData}; use msg::constellation_msg::{AnimationState, Msg, PipelineId}; use script::layout_interface::Animation; use script_traits::ConstellationControlMsg; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::Arc; use std::sync::mpsc::Sender; use style::animation::{GetMod, PropertyAnimation}; use style::properties::ComputedValues; /// Inserts transitions into the queue of running animations as applicable for the given style /// difference. This is called from the layout worker threads. pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>, node: OpaqueNode, old_style: &ComputedValues, new_style: &mut ComputedValues) { for i in 0..new_style.get_animation().transition_property.0.len() { // Create any property animations, if applicable. let property_animations = PropertyAnimation::from_transition(i, old_style, new_style); for property_animation in property_animations { // Set the property to the initial value. property_animation.update(new_style, 0.0); // Kick off the animation. let now = clock_ticks::precise_time_s(); let animation_style = new_style.get_animation(); let start_time = now + (animation_style.transition_delay.0.get_mod(i).seconds() as f64); new_animations_sender.send(Animation { node: node.id(), property_animation: property_animation, start_time: start_time, end_time: start_time + (animation_style.transition_duration.0.get_mod(i).seconds() as f64), }).unwrap() } } } /// Processes any new animations that were discovered after style recalculation. /// Also expire any old animations that have completed. pub fn update_animation_state(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) { let mut new_running_animations = Vec::new(); while let Ok(animation) = rw_data.new_animations_receiver.try_recv() { new_running_animations.push(animation) } let mut running_animations_hash = (*rw_data.running_animations).clone(); // Expire old running animations. let now = clock_ticks::precise_time_s(); let mut keys_to_remove = Vec::new(); for (key, running_animations) in &mut running_animations_hash { running_animations.retain(|running_animation| { now < running_animation.end_time }); if running_animations.len() == 0 { keys_to_remove.push(*key); } } for key in keys_to_remove { running_animations_hash.remove(&key).unwrap(); } // Add new running animations. for new_running_animation in new_running_animations { match running_animations_hash.entry(OpaqueNode(new_running_animation.node)) { Entry::Vacant(entry) => { entry.insert(vec![new_running_animation]); } Entry::Occupied(mut entry) => entry.get_mut().push(new_running_animation), } } rw_data.running_animations = Arc::new(running_animations_hash); let animation_state; if rw_data.running_animations.is_empty() { animation_state = AnimationState::NoAnimationsPresent; } else { animation_state = AnimationState::AnimationsPresent; } rw_data.constellation_chan .0 .send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state)) .unwrap(); } /// Recalculates style for a set of animations. This does *not* run with the DOM lock held. pub fn recalc_style_for_animations(flow: &mut Flow, animations: &HashMap<OpaqueNode, Vec<Animation>>) { let mut damage = RestyleDamage::empty(); flow.mutate_fragments(&mut |fragment| { if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) { for animation in *animations { let now = clock_ticks::precise_time_s(); let mut progress = (now - animation.start_time) / animation.duration(); if progress > 1.0 { progress = 1.0 } if progress <= 0.0 { continue } let mut new_style = fragment.style.clone(); animation.property_animation.update(&mut *Arc::make_mut(&mut new_style), progress); damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style)); fragment.style = new_style } } }); let base = flow::mut_base(flow); base.restyle_damage.insert(damage); for kid in base.children.iter_mut() { recalc_style_for_animations(kid, animations) } } /// Handles animation updates. pub fn
(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) { layout_task.tick_animations(rw_data); layout_task.script_chan .send(ConstellationControlMsg::TickAllAnimations(layout_task.id)) .unwrap(); }
tick_all_animations
identifier_name
animation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS transitions and animations.
use incremental::{self, RestyleDamage}; use layout_task::{LayoutTask, LayoutTaskData}; use msg::constellation_msg::{AnimationState, Msg, PipelineId}; use script::layout_interface::Animation; use script_traits::ConstellationControlMsg; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::Arc; use std::sync::mpsc::Sender; use style::animation::{GetMod, PropertyAnimation}; use style::properties::ComputedValues; /// Inserts transitions into the queue of running animations as applicable for the given style /// difference. This is called from the layout worker threads. pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>, node: OpaqueNode, old_style: &ComputedValues, new_style: &mut ComputedValues) { for i in 0..new_style.get_animation().transition_property.0.len() { // Create any property animations, if applicable. let property_animations = PropertyAnimation::from_transition(i, old_style, new_style); for property_animation in property_animations { // Set the property to the initial value. property_animation.update(new_style, 0.0); // Kick off the animation. let now = clock_ticks::precise_time_s(); let animation_style = new_style.get_animation(); let start_time = now + (animation_style.transition_delay.0.get_mod(i).seconds() as f64); new_animations_sender.send(Animation { node: node.id(), property_animation: property_animation, start_time: start_time, end_time: start_time + (animation_style.transition_duration.0.get_mod(i).seconds() as f64), }).unwrap() } } } /// Processes any new animations that were discovered after style recalculation. /// Also expire any old animations that have completed. pub fn update_animation_state(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) { let mut new_running_animations = Vec::new(); while let Ok(animation) = rw_data.new_animations_receiver.try_recv() { new_running_animations.push(animation) } let mut running_animations_hash = (*rw_data.running_animations).clone(); // Expire old running animations. let now = clock_ticks::precise_time_s(); let mut keys_to_remove = Vec::new(); for (key, running_animations) in &mut running_animations_hash { running_animations.retain(|running_animation| { now < running_animation.end_time }); if running_animations.len() == 0 { keys_to_remove.push(*key); } } for key in keys_to_remove { running_animations_hash.remove(&key).unwrap(); } // Add new running animations. for new_running_animation in new_running_animations { match running_animations_hash.entry(OpaqueNode(new_running_animation.node)) { Entry::Vacant(entry) => { entry.insert(vec![new_running_animation]); } Entry::Occupied(mut entry) => entry.get_mut().push(new_running_animation), } } rw_data.running_animations = Arc::new(running_animations_hash); let animation_state; if rw_data.running_animations.is_empty() { animation_state = AnimationState::NoAnimationsPresent; } else { animation_state = AnimationState::AnimationsPresent; } rw_data.constellation_chan .0 .send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state)) .unwrap(); } /// Recalculates style for a set of animations. This does *not* run with the DOM lock held. pub fn recalc_style_for_animations(flow: &mut Flow, animations: &HashMap<OpaqueNode, Vec<Animation>>) { let mut damage = RestyleDamage::empty(); flow.mutate_fragments(&mut |fragment| { if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) { for animation in *animations { let now = clock_ticks::precise_time_s(); let mut progress = (now - animation.start_time) / animation.duration(); if progress > 1.0 { progress = 1.0 } if progress <= 0.0 { continue } let mut new_style = fragment.style.clone(); animation.property_animation.update(&mut *Arc::make_mut(&mut new_style), progress); damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style)); fragment.style = new_style } } }); let base = flow::mut_base(flow); base.restyle_damage.insert(damage); for kid in base.children.iter_mut() { recalc_style_for_animations(kid, animations) } } /// Handles animation updates. pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) { layout_task.tick_animations(rw_data); layout_task.script_chan .send(ConstellationControlMsg::TickAllAnimations(layout_task.id)) .unwrap(); }
use clock_ticks; use flow::{self, Flow}; use gfx::display_list::OpaqueNode;
random_line_split
cache_padded.rs
use std::marker; use std::cell::UnsafeCell; use std::mem; use std::ptr; use std::ops::{Deref, DerefMut}; // For now, treat this as an arch-independent constant. const CACHE_LINE: usize = 32; #[repr(simd)] struct Padding(u64, u64, u64, u64); /// Pad `T` to the length of a cacheline. /// /// Sometimes concurrent programming requires a piece of data to be padded out /// to the size of a cacheline to avoid "false sharing": cachelines being /// invalidated due to unrelated concurrent activity. Use the `CachePadded` type /// when you want to *avoid* cache locality. /// /// At the moment, cache lines are assumed to be 32 * sizeof(usize) on all /// architectures. /// /// **Warning**: the wrapped data is never dropped; move out using `ptr::read` /// if you need to run dtors. pub struct CachePadded<T> { data: UnsafeCell<[usize; CACHE_LINE]>, _marker: ([Padding; 0], marker::PhantomData<T>), } unsafe impl<T: Send> Send for CachePadded<T> {} unsafe impl<T: Sync> Sync for CachePadded<T> {} /// Types for which mem::zeroed() is safe. /// /// If a type `T: ZerosValid`, then a sequence of zeros the size of `T` must be /// a valid member of the type `T`. pub unsafe trait ZerosValid {} unsafe impl ZerosValid for.. {} macro_rules! zeros_valid { ($( $T:ty )*) => ($( unsafe impl ZerosValid for $T {} )*)} zeros_valid!(u8 u16 u32 u64 usize); zeros_valid!(i8 i16 i32 i64 isize); unsafe impl ZerosValid for ::std::sync::atomic::AtomicUsize {} unsafe impl<T> ZerosValid for ::std::sync::atomic::AtomicPtr<T> {} impl<T: ZerosValid> CachePadded<T> { /// A const fn equivalent to mem::zeroed(). pub const fn zeroed() -> CachePadded<T> { CachePadded { data: UnsafeCell::new(([0; CACHE_LINE])), _marker: ([], marker::PhantomData), } } } #[inline] /// Assert that the size and alignment of `T` are consistent with `CachePadded<T>`. fn assert_valid<T>() { assert!(mem::size_of::<T>() <= mem::size_of::<CachePadded<T>>()); assert!(mem::align_of::<T>() <= mem::align_of::<CachePadded<T>>()); } impl<T> CachePadded<T> { /// Wrap `t` with cacheline padding. /// /// **Warning**: the wrapped data is never dropped; move out using /// `ptr:read` if you need to run dtors. pub fn new(t: T) -> CachePadded<T> { assert_valid::<T>(); let ret = CachePadded { data: UnsafeCell::new(([0; CACHE_LINE])), _marker: ([], marker::PhantomData), }; unsafe { let p: *mut T = mem::transmute(&ret.data); ptr::write(p, t); } ret } } impl<T> Deref for CachePadded<T> { type Target = T; fn
(&self) -> &T { assert_valid::<T>(); unsafe { mem::transmute(&self.data) } } } impl<T> DerefMut for CachePadded<T> { fn deref_mut(&mut self) -> &mut T { assert_valid::<T>(); unsafe { mem::transmute(&mut self.data) } } } // FIXME: support Drop by pulling out a version usable for statics /* impl<T> Drop for CachePadded<T> { fn drop(&mut self) { assert_valid::<T>(); let p: *mut T = mem::transmute(&self.data); mem::drop(ptr::read(p)); } } */ #[cfg(test)] mod test { use super::*; #[test] fn cache_padded_store_u64() { let x: CachePadded<u64> = unsafe { CachePadded::new(17) }; assert_eq!(*x, 17); } #[test] fn cache_padded_store_pair() { let x: CachePadded<(u64, u64)> = unsafe { CachePadded::new((17, 37)) }; assert_eq!(x.0, 17); assert_eq!(x.1, 37); } }
deref
identifier_name
cache_padded.rs
use std::marker; use std::cell::UnsafeCell; use std::mem; use std::ptr; use std::ops::{Deref, DerefMut}; // For now, treat this as an arch-independent constant. const CACHE_LINE: usize = 32; #[repr(simd)] struct Padding(u64, u64, u64, u64); /// Pad `T` to the length of a cacheline. /// /// Sometimes concurrent programming requires a piece of data to be padded out /// to the size of a cacheline to avoid "false sharing": cachelines being /// invalidated due to unrelated concurrent activity. Use the `CachePadded` type /// when you want to *avoid* cache locality.
/// architectures. /// /// **Warning**: the wrapped data is never dropped; move out using `ptr::read` /// if you need to run dtors. pub struct CachePadded<T> { data: UnsafeCell<[usize; CACHE_LINE]>, _marker: ([Padding; 0], marker::PhantomData<T>), } unsafe impl<T: Send> Send for CachePadded<T> {} unsafe impl<T: Sync> Sync for CachePadded<T> {} /// Types for which mem::zeroed() is safe. /// /// If a type `T: ZerosValid`, then a sequence of zeros the size of `T` must be /// a valid member of the type `T`. pub unsafe trait ZerosValid {} unsafe impl ZerosValid for.. {} macro_rules! zeros_valid { ($( $T:ty )*) => ($( unsafe impl ZerosValid for $T {} )*)} zeros_valid!(u8 u16 u32 u64 usize); zeros_valid!(i8 i16 i32 i64 isize); unsafe impl ZerosValid for ::std::sync::atomic::AtomicUsize {} unsafe impl<T> ZerosValid for ::std::sync::atomic::AtomicPtr<T> {} impl<T: ZerosValid> CachePadded<T> { /// A const fn equivalent to mem::zeroed(). pub const fn zeroed() -> CachePadded<T> { CachePadded { data: UnsafeCell::new(([0; CACHE_LINE])), _marker: ([], marker::PhantomData), } } } #[inline] /// Assert that the size and alignment of `T` are consistent with `CachePadded<T>`. fn assert_valid<T>() { assert!(mem::size_of::<T>() <= mem::size_of::<CachePadded<T>>()); assert!(mem::align_of::<T>() <= mem::align_of::<CachePadded<T>>()); } impl<T> CachePadded<T> { /// Wrap `t` with cacheline padding. /// /// **Warning**: the wrapped data is never dropped; move out using /// `ptr:read` if you need to run dtors. pub fn new(t: T) -> CachePadded<T> { assert_valid::<T>(); let ret = CachePadded { data: UnsafeCell::new(([0; CACHE_LINE])), _marker: ([], marker::PhantomData), }; unsafe { let p: *mut T = mem::transmute(&ret.data); ptr::write(p, t); } ret } } impl<T> Deref for CachePadded<T> { type Target = T; fn deref(&self) -> &T { assert_valid::<T>(); unsafe { mem::transmute(&self.data) } } } impl<T> DerefMut for CachePadded<T> { fn deref_mut(&mut self) -> &mut T { assert_valid::<T>(); unsafe { mem::transmute(&mut self.data) } } } // FIXME: support Drop by pulling out a version usable for statics /* impl<T> Drop for CachePadded<T> { fn drop(&mut self) { assert_valid::<T>(); let p: *mut T = mem::transmute(&self.data); mem::drop(ptr::read(p)); } } */ #[cfg(test)] mod test { use super::*; #[test] fn cache_padded_store_u64() { let x: CachePadded<u64> = unsafe { CachePadded::new(17) }; assert_eq!(*x, 17); } #[test] fn cache_padded_store_pair() { let x: CachePadded<(u64, u64)> = unsafe { CachePadded::new((17, 37)) }; assert_eq!(x.0, 17); assert_eq!(x.1, 37); } }
/// /// At the moment, cache lines are assumed to be 32 * sizeof(usize) on all
random_line_split
highlighter.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ use std::cell::RefMut; use unicode_width::UnicodeWidthStr; use ncurses::*; use core::line::Line; use ui::printer::Viewport; use ui::content::State as ContentState; use ui::rendered_line::RenderedLineCollection; #[derive(PartialEq)] pub enum Highlight { VisibleOrLast, Next, Previous, Current, } pub struct LineHighlighter<'a> { line: &'a Line, window: WINDOW, container_width: i32, color_pair_id: i16, } impl<'a> LineHighlighter<'a> { pub fn new(window: WINDOW, line: &'a Line, container_width: i32, color_pair_id: i16) -> LineHighlighter<'a> { LineHighlighter { line: line, window: window, container_width: container_width, color_pair_id: color_pair_id, } } pub fn print(&self, text: &str, accumulated_height: i32, line_height: i32) -> Vec<usize> { let mut locations = vec![]; let matches = &self.line.matches_for(text); for &(offset_x, value) in matches { let location = self.handle_match(offset_x as i32, accumulated_height, value); locations.push(location); } wmove(self.window, accumulated_height + line_height, 0); locations } pub fn print_single_match(&self, text: &str, index: usize, offset_y: i32) { let (offset_x, value) = self.line.matches_for(text)[index]; self.handle_match(offset_x as i32, offset_y, value); } fn handle_match(&self, mut offset_x: i32, mut offset_y: i32, value: &str) -> usize { let initial_offset_y = offset_y; offset_x = self.line.content_without_ansi.split_at(offset_x as usize).0.width() as i32; offset_y += offset_x / self.container_width; offset_x %= self.container_width; wattron(self.window, COLOR_PAIR(self.color_pair_id)); mvwprintw(self.window, offset_y, offset_x, value); wattroff(self.window, COLOR_PAIR(self.color_pair_id)); (offset_y - initial_offset_y) as usize } } pub struct State<'a> { state: RefMut<'a, ContentState>, rendered_lines: &'a RenderedLineCollection, viewport: Viewport, } impl<'a> State<'a> { pub fn new(state: RefMut<'a, ContentState>, rendered_lines: &'a RenderedLineCollection, viewport: Viewport) -> State<'a> { State { state: state, rendered_lines: rendered_lines, viewport: viewport, } } pub fn update(&mut self, highlight: &Highlight) { match *highlight { Highlight::VisibleOrLast | Highlight::Current => self.handle_visible_or_last(), Highlight::Next => self.handle_next(), Highlight::Previous => self.handle_previous(), } } fn handle_visible_or_last(&mut self) { let matched_line = self.rendered_lines .viewport_match(&self.viewport) .unwrap_or(self.rendered_lines.last_match()); self.state.highlighted_line = self.rendered_lines.len() - matched_line.line - 1; self.state.highlighted_match = matched_line.match_index; } fn handle_next(&mut self) { let rendered_line = &self.rendered_lines[self.state.highlighted_line]; if self.state.highlighted_match < rendered_line.match_count() - 1 { self.state.highlighted_match += 1; } else { let matched_line_opt = self.rendered_lines .next_match(self.state.highlighted_line); if let Some(matched_line) = matched_line_opt { self.state.highlighted_line = matched_line.line; self.state.highlighted_match = 0; } } } fn handle_previous(&mut self) { if self.state.highlighted_match > 0 { self.state.highlighted_match -= 1; } else if self.state.highlighted_line > 0 { let matched_line_opt = self.rendered_lines .previous_match(self.state.highlighted_line); if let Some(matched_line) = matched_line_opt
} } }
{ self.state.highlighted_line = matched_line.line; self.state.highlighted_match = matched_line.match_index; }
conditional_block
highlighter.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ use std::cell::RefMut; use unicode_width::UnicodeWidthStr; use ncurses::*; use core::line::Line; use ui::printer::Viewport; use ui::content::State as ContentState; use ui::rendered_line::RenderedLineCollection; #[derive(PartialEq)] pub enum
{ VisibleOrLast, Next, Previous, Current, } pub struct LineHighlighter<'a> { line: &'a Line, window: WINDOW, container_width: i32, color_pair_id: i16, } impl<'a> LineHighlighter<'a> { pub fn new(window: WINDOW, line: &'a Line, container_width: i32, color_pair_id: i16) -> LineHighlighter<'a> { LineHighlighter { line: line, window: window, container_width: container_width, color_pair_id: color_pair_id, } } pub fn print(&self, text: &str, accumulated_height: i32, line_height: i32) -> Vec<usize> { let mut locations = vec![]; let matches = &self.line.matches_for(text); for &(offset_x, value) in matches { let location = self.handle_match(offset_x as i32, accumulated_height, value); locations.push(location); } wmove(self.window, accumulated_height + line_height, 0); locations } pub fn print_single_match(&self, text: &str, index: usize, offset_y: i32) { let (offset_x, value) = self.line.matches_for(text)[index]; self.handle_match(offset_x as i32, offset_y, value); } fn handle_match(&self, mut offset_x: i32, mut offset_y: i32, value: &str) -> usize { let initial_offset_y = offset_y; offset_x = self.line.content_without_ansi.split_at(offset_x as usize).0.width() as i32; offset_y += offset_x / self.container_width; offset_x %= self.container_width; wattron(self.window, COLOR_PAIR(self.color_pair_id)); mvwprintw(self.window, offset_y, offset_x, value); wattroff(self.window, COLOR_PAIR(self.color_pair_id)); (offset_y - initial_offset_y) as usize } } pub struct State<'a> { state: RefMut<'a, ContentState>, rendered_lines: &'a RenderedLineCollection, viewport: Viewport, } impl<'a> State<'a> { pub fn new(state: RefMut<'a, ContentState>, rendered_lines: &'a RenderedLineCollection, viewport: Viewport) -> State<'a> { State { state: state, rendered_lines: rendered_lines, viewport: viewport, } } pub fn update(&mut self, highlight: &Highlight) { match *highlight { Highlight::VisibleOrLast | Highlight::Current => self.handle_visible_or_last(), Highlight::Next => self.handle_next(), Highlight::Previous => self.handle_previous(), } } fn handle_visible_or_last(&mut self) { let matched_line = self.rendered_lines .viewport_match(&self.viewport) .unwrap_or(self.rendered_lines.last_match()); self.state.highlighted_line = self.rendered_lines.len() - matched_line.line - 1; self.state.highlighted_match = matched_line.match_index; } fn handle_next(&mut self) { let rendered_line = &self.rendered_lines[self.state.highlighted_line]; if self.state.highlighted_match < rendered_line.match_count() - 1 { self.state.highlighted_match += 1; } else { let matched_line_opt = self.rendered_lines .next_match(self.state.highlighted_line); if let Some(matched_line) = matched_line_opt { self.state.highlighted_line = matched_line.line; self.state.highlighted_match = 0; } } } fn handle_previous(&mut self) { if self.state.highlighted_match > 0 { self.state.highlighted_match -= 1; } else if self.state.highlighted_line > 0 { let matched_line_opt = self.rendered_lines .previous_match(self.state.highlighted_line); if let Some(matched_line) = matched_line_opt { self.state.highlighted_line = matched_line.line; self.state.highlighted_match = matched_line.match_index; } } } }
Highlight
identifier_name
highlighter.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ use std::cell::RefMut; use unicode_width::UnicodeWidthStr;
use ui::rendered_line::RenderedLineCollection; #[derive(PartialEq)] pub enum Highlight { VisibleOrLast, Next, Previous, Current, } pub struct LineHighlighter<'a> { line: &'a Line, window: WINDOW, container_width: i32, color_pair_id: i16, } impl<'a> LineHighlighter<'a> { pub fn new(window: WINDOW, line: &'a Line, container_width: i32, color_pair_id: i16) -> LineHighlighter<'a> { LineHighlighter { line: line, window: window, container_width: container_width, color_pair_id: color_pair_id, } } pub fn print(&self, text: &str, accumulated_height: i32, line_height: i32) -> Vec<usize> { let mut locations = vec![]; let matches = &self.line.matches_for(text); for &(offset_x, value) in matches { let location = self.handle_match(offset_x as i32, accumulated_height, value); locations.push(location); } wmove(self.window, accumulated_height + line_height, 0); locations } pub fn print_single_match(&self, text: &str, index: usize, offset_y: i32) { let (offset_x, value) = self.line.matches_for(text)[index]; self.handle_match(offset_x as i32, offset_y, value); } fn handle_match(&self, mut offset_x: i32, mut offset_y: i32, value: &str) -> usize { let initial_offset_y = offset_y; offset_x = self.line.content_without_ansi.split_at(offset_x as usize).0.width() as i32; offset_y += offset_x / self.container_width; offset_x %= self.container_width; wattron(self.window, COLOR_PAIR(self.color_pair_id)); mvwprintw(self.window, offset_y, offset_x, value); wattroff(self.window, COLOR_PAIR(self.color_pair_id)); (offset_y - initial_offset_y) as usize } } pub struct State<'a> { state: RefMut<'a, ContentState>, rendered_lines: &'a RenderedLineCollection, viewport: Viewport, } impl<'a> State<'a> { pub fn new(state: RefMut<'a, ContentState>, rendered_lines: &'a RenderedLineCollection, viewport: Viewport) -> State<'a> { State { state: state, rendered_lines: rendered_lines, viewport: viewport, } } pub fn update(&mut self, highlight: &Highlight) { match *highlight { Highlight::VisibleOrLast | Highlight::Current => self.handle_visible_or_last(), Highlight::Next => self.handle_next(), Highlight::Previous => self.handle_previous(), } } fn handle_visible_or_last(&mut self) { let matched_line = self.rendered_lines .viewport_match(&self.viewport) .unwrap_or(self.rendered_lines.last_match()); self.state.highlighted_line = self.rendered_lines.len() - matched_line.line - 1; self.state.highlighted_match = matched_line.match_index; } fn handle_next(&mut self) { let rendered_line = &self.rendered_lines[self.state.highlighted_line]; if self.state.highlighted_match < rendered_line.match_count() - 1 { self.state.highlighted_match += 1; } else { let matched_line_opt = self.rendered_lines .next_match(self.state.highlighted_line); if let Some(matched_line) = matched_line_opt { self.state.highlighted_line = matched_line.line; self.state.highlighted_match = 0; } } } fn handle_previous(&mut self) { if self.state.highlighted_match > 0 { self.state.highlighted_match -= 1; } else if self.state.highlighted_line > 0 { let matched_line_opt = self.rendered_lines .previous_match(self.state.highlighted_line); if let Some(matched_line) = matched_line_opt { self.state.highlighted_line = matched_line.line; self.state.highlighted_match = matched_line.match_index; } } } }
use ncurses::*; use core::line::Line; use ui::printer::Viewport; use ui::content::State as ContentState;
random_line_split
process.rs
// This file is part of the uutils coreutils package. // // (c) Maciej Dziardziel <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE file // that was distributed with this source code. // spell-checker:ignore (vars) cvar exitstatus // spell-checker:ignore (sys/unix) WIFSIGNALED //! Set of functions to manage IDs use libc::{gid_t, pid_t, uid_t}; use std::fmt; use std::io; use std::process::Child; use std::process::ExitStatus as StdExitStatus; use std::thread; use std::time::{Duration, Instant}; // SAFETY: These functions always succeed and return simple integers. /// `geteuid()` returns the effective user ID of the calling process. pub fn geteuid() -> uid_t { unsafe { libc::geteuid() } } /// `getegid()` returns the effective group ID of the calling process. pub fn getegid() -> gid_t { unsafe { libc::getegid() } } /// `getgid()` returns the real group ID of the calling process. pub fn getgid() -> gid_t { unsafe { libc::getgid() } } /// `getuid()` returns the real user ID of the calling process. pub fn getuid() -> uid_t { unsafe { libc::getuid() } } // This is basically sys::unix::process::ExitStatus #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum ExitStatus { Code(i32), Signal(i32), } #[allow(clippy::trivially_copy_pass_by_ref)] impl ExitStatus { fn from_std_status(status: StdExitStatus) -> Self { #[cfg(unix)] { use std::os::unix::process::ExitStatusExt; if let Some(signal) = status.signal() { return Self::Signal(signal); } } // NOTE: this should never fail as we check if the program exited through a signal above Self::Code(status.code().unwrap()) } pub fn success(&self) -> bool { match *self { ExitStatus::Code(code) => code == 0, _ => false, } } pub fn code(&self) -> Option<i32> { match *self { ExitStatus::Code(code) => Some(code), _ => None, } } pub fn signal(&self) -> Option<i32> { match *self { ExitStatus::Signal(code) => Some(code), _ => None, } } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ExitStatus::Code(code) => write!(f, "exit code: {}", code), ExitStatus::Signal(code) => write!(f, "exit code: {}", code), } } } /// Missing methods for Child objects pub trait ChildExt { /// Send a signal to a Child process. /// /// Caller beware: if the process already exited then you may accidentally /// send the signal to an unrelated process that recycled the PID. fn send_signal(&mut self, signal: usize) -> io::Result<()>; /// Wait for a process to finish or return after the specified duration. /// A `timeout` of zero disables the timeout. fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>>; } impl ChildExt for Child { fn send_signal(&mut self, signal: usize) -> io::Result<()> { if unsafe { libc::kill(self.id() as pid_t, signal as i32) }!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>> { if timeout == Duration::from_micros(0) { return self .wait() .map(|status| Some(ExitStatus::from_std_status(status))); } //.try_wait() doesn't drop stdin, so we do it manually drop(self.stdin.take()); let start = Instant::now(); loop { if let Some(status) = self.try_wait()?
if start.elapsed() >= timeout { break; } // XXX: this is kinda gross, but it's cleaner than starting a thread just to wait // (which was the previous solution). We might want to use a different duration // here as well thread::sleep(Duration::from_millis(100)); } Ok(None) } }
{ return Ok(Some(ExitStatus::from_std_status(status))); }
conditional_block
process.rs
// This file is part of the uutils coreutils package. // // (c) Maciej Dziardziel <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE file // that was distributed with this source code. // spell-checker:ignore (vars) cvar exitstatus // spell-checker:ignore (sys/unix) WIFSIGNALED //! Set of functions to manage IDs use libc::{gid_t, pid_t, uid_t}; use std::fmt; use std::io; use std::process::Child; use std::process::ExitStatus as StdExitStatus; use std::thread; use std::time::{Duration, Instant}; // SAFETY: These functions always succeed and return simple integers. /// `geteuid()` returns the effective user ID of the calling process. pub fn geteuid() -> uid_t { unsafe { libc::geteuid() } } /// `getegid()` returns the effective group ID of the calling process. pub fn getegid() -> gid_t { unsafe { libc::getegid() } } /// `getgid()` returns the real group ID of the calling process. pub fn getgid() -> gid_t { unsafe { libc::getgid() } } /// `getuid()` returns the real user ID of the calling process. pub fn getuid() -> uid_t { unsafe { libc::getuid() } } // This is basically sys::unix::process::ExitStatus #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum ExitStatus { Code(i32), Signal(i32), } #[allow(clippy::trivially_copy_pass_by_ref)] impl ExitStatus { fn from_std_status(status: StdExitStatus) -> Self { #[cfg(unix)] { use std::os::unix::process::ExitStatusExt; if let Some(signal) = status.signal() { return Self::Signal(signal); } } // NOTE: this should never fail as we check if the program exited through a signal above Self::Code(status.code().unwrap()) } pub fn success(&self) -> bool { match *self { ExitStatus::Code(code) => code == 0, _ => false, } } pub fn code(&self) -> Option<i32>
pub fn signal(&self) -> Option<i32> { match *self { ExitStatus::Signal(code) => Some(code), _ => None, } } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ExitStatus::Code(code) => write!(f, "exit code: {}", code), ExitStatus::Signal(code) => write!(f, "exit code: {}", code), } } } /// Missing methods for Child objects pub trait ChildExt { /// Send a signal to a Child process. /// /// Caller beware: if the process already exited then you may accidentally /// send the signal to an unrelated process that recycled the PID. fn send_signal(&mut self, signal: usize) -> io::Result<()>; /// Wait for a process to finish or return after the specified duration. /// A `timeout` of zero disables the timeout. fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>>; } impl ChildExt for Child { fn send_signal(&mut self, signal: usize) -> io::Result<()> { if unsafe { libc::kill(self.id() as pid_t, signal as i32) }!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>> { if timeout == Duration::from_micros(0) { return self .wait() .map(|status| Some(ExitStatus::from_std_status(status))); } //.try_wait() doesn't drop stdin, so we do it manually drop(self.stdin.take()); let start = Instant::now(); loop { if let Some(status) = self.try_wait()? { return Ok(Some(ExitStatus::from_std_status(status))); } if start.elapsed() >= timeout { break; } // XXX: this is kinda gross, but it's cleaner than starting a thread just to wait // (which was the previous solution). We might want to use a different duration // here as well thread::sleep(Duration::from_millis(100)); } Ok(None) } }
{ match *self { ExitStatus::Code(code) => Some(code), _ => None, } }
identifier_body
process.rs
// This file is part of the uutils coreutils package. // // (c) Maciej Dziardziel <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE file // that was distributed with this source code. // spell-checker:ignore (vars) cvar exitstatus // spell-checker:ignore (sys/unix) WIFSIGNALED //! Set of functions to manage IDs use libc::{gid_t, pid_t, uid_t}; use std::fmt; use std::io; use std::process::Child; use std::process::ExitStatus as StdExitStatus; use std::thread; use std::time::{Duration, Instant}; // SAFETY: These functions always succeed and return simple integers. /// `geteuid()` returns the effective user ID of the calling process. pub fn geteuid() -> uid_t { unsafe { libc::geteuid() } } /// `getegid()` returns the effective group ID of the calling process. pub fn
() -> gid_t { unsafe { libc::getegid() } } /// `getgid()` returns the real group ID of the calling process. pub fn getgid() -> gid_t { unsafe { libc::getgid() } } /// `getuid()` returns the real user ID of the calling process. pub fn getuid() -> uid_t { unsafe { libc::getuid() } } // This is basically sys::unix::process::ExitStatus #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum ExitStatus { Code(i32), Signal(i32), } #[allow(clippy::trivially_copy_pass_by_ref)] impl ExitStatus { fn from_std_status(status: StdExitStatus) -> Self { #[cfg(unix)] { use std::os::unix::process::ExitStatusExt; if let Some(signal) = status.signal() { return Self::Signal(signal); } } // NOTE: this should never fail as we check if the program exited through a signal above Self::Code(status.code().unwrap()) } pub fn success(&self) -> bool { match *self { ExitStatus::Code(code) => code == 0, _ => false, } } pub fn code(&self) -> Option<i32> { match *self { ExitStatus::Code(code) => Some(code), _ => None, } } pub fn signal(&self) -> Option<i32> { match *self { ExitStatus::Signal(code) => Some(code), _ => None, } } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ExitStatus::Code(code) => write!(f, "exit code: {}", code), ExitStatus::Signal(code) => write!(f, "exit code: {}", code), } } } /// Missing methods for Child objects pub trait ChildExt { /// Send a signal to a Child process. /// /// Caller beware: if the process already exited then you may accidentally /// send the signal to an unrelated process that recycled the PID. fn send_signal(&mut self, signal: usize) -> io::Result<()>; /// Wait for a process to finish or return after the specified duration. /// A `timeout` of zero disables the timeout. fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>>; } impl ChildExt for Child { fn send_signal(&mut self, signal: usize) -> io::Result<()> { if unsafe { libc::kill(self.id() as pid_t, signal as i32) }!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>> { if timeout == Duration::from_micros(0) { return self .wait() .map(|status| Some(ExitStatus::from_std_status(status))); } //.try_wait() doesn't drop stdin, so we do it manually drop(self.stdin.take()); let start = Instant::now(); loop { if let Some(status) = self.try_wait()? { return Ok(Some(ExitStatus::from_std_status(status))); } if start.elapsed() >= timeout { break; } // XXX: this is kinda gross, but it's cleaner than starting a thread just to wait // (which was the previous solution). We might want to use a different duration // here as well thread::sleep(Duration::from_millis(100)); } Ok(None) } }
getegid
identifier_name
process.rs
// This file is part of the uutils coreutils package. // // (c) Maciej Dziardziel <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE file // that was distributed with this source code. // spell-checker:ignore (vars) cvar exitstatus // spell-checker:ignore (sys/unix) WIFSIGNALED //! Set of functions to manage IDs use libc::{gid_t, pid_t, uid_t}; use std::fmt; use std::io; use std::process::Child; use std::process::ExitStatus as StdExitStatus; use std::thread; use std::time::{Duration, Instant}; // SAFETY: These functions always succeed and return simple integers. /// `geteuid()` returns the effective user ID of the calling process. pub fn geteuid() -> uid_t { unsafe { libc::geteuid() } } /// `getegid()` returns the effective group ID of the calling process. pub fn getegid() -> gid_t { unsafe { libc::getegid() } } /// `getgid()` returns the real group ID of the calling process. pub fn getgid() -> gid_t { unsafe { libc::getgid() } } /// `getuid()` returns the real user ID of the calling process. pub fn getuid() -> uid_t {
} // This is basically sys::unix::process::ExitStatus #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum ExitStatus { Code(i32), Signal(i32), } #[allow(clippy::trivially_copy_pass_by_ref)] impl ExitStatus { fn from_std_status(status: StdExitStatus) -> Self { #[cfg(unix)] { use std::os::unix::process::ExitStatusExt; if let Some(signal) = status.signal() { return Self::Signal(signal); } } // NOTE: this should never fail as we check if the program exited through a signal above Self::Code(status.code().unwrap()) } pub fn success(&self) -> bool { match *self { ExitStatus::Code(code) => code == 0, _ => false, } } pub fn code(&self) -> Option<i32> { match *self { ExitStatus::Code(code) => Some(code), _ => None, } } pub fn signal(&self) -> Option<i32> { match *self { ExitStatus::Signal(code) => Some(code), _ => None, } } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ExitStatus::Code(code) => write!(f, "exit code: {}", code), ExitStatus::Signal(code) => write!(f, "exit code: {}", code), } } } /// Missing methods for Child objects pub trait ChildExt { /// Send a signal to a Child process. /// /// Caller beware: if the process already exited then you may accidentally /// send the signal to an unrelated process that recycled the PID. fn send_signal(&mut self, signal: usize) -> io::Result<()>; /// Wait for a process to finish or return after the specified duration. /// A `timeout` of zero disables the timeout. fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>>; } impl ChildExt for Child { fn send_signal(&mut self, signal: usize) -> io::Result<()> { if unsafe { libc::kill(self.id() as pid_t, signal as i32) }!= 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } fn wait_or_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>> { if timeout == Duration::from_micros(0) { return self .wait() .map(|status| Some(ExitStatus::from_std_status(status))); } //.try_wait() doesn't drop stdin, so we do it manually drop(self.stdin.take()); let start = Instant::now(); loop { if let Some(status) = self.try_wait()? { return Ok(Some(ExitStatus::from_std_status(status))); } if start.elapsed() >= timeout { break; } // XXX: this is kinda gross, but it's cleaner than starting a thread just to wait // (which was the previous solution). We might want to use a different duration // here as well thread::sleep(Duration::from_millis(100)); } Ok(None) } }
unsafe { libc::getuid() }
random_line_split
webglshader.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 angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, HeapSizeOf, JSTraceable, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32, source: DOMRefCell<Option<DOMString>>, info_log: DOMRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>, compilation_status: Cell<ShaderCompilationStatus>, #[ignore_heap_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DOMRefCell::new(None), info_log: DOMRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<Root<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> Root<WebGLShader> { reflect_dom_object(box WebGLShader::new_inherited(renderer, id, shader_type), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) =>
, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } } pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool { self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> { let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() } /// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn set_source(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn successfully_compiled(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
{ debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }
conditional_block
webglshader.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 angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, HeapSizeOf, JSTraceable, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32,
compilation_status: Cell<ShaderCompilationStatus>, #[ignore_heap_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DOMRefCell::new(None), info_log: DOMRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<Root<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> Root<WebGLShader> { reflect_dom_object(box WebGLShader::new_inherited(renderer, id, shader_type), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) => { debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } } pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool { self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> { let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() } /// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn set_source(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn successfully_compiled(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
source: DOMRefCell<Option<DOMString>>, info_log: DOMRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>,
random_line_split
webglshader.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 angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, HeapSizeOf, JSTraceable, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32, source: DOMRefCell<Option<DOMString>>, info_log: DOMRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>, compilation_status: Cell<ShaderCompilationStatus>, #[ignore_heap_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DOMRefCell::new(None), info_log: DOMRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<Root<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> Root<WebGLShader> { reflect_dom_object(box WebGLShader::new_inherited(renderer, id, shader_type), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) => { debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } } pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool { self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> { let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() } /// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn set_source(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn
(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
successfully_compiled
identifier_name
webglshader.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 angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, HeapSizeOf, JSTraceable, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32, source: DOMRefCell<Option<DOMString>>, info_log: DOMRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>, compilation_status: Cell<ShaderCompilationStatus>, #[ignore_heap_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DOMRefCell::new(None), info_log: DOMRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<Root<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> Root<WebGLShader> { reflect_dom_object(box WebGLShader::new_inherited(renderer, id, shader_type), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) => { debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self)
pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool { self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> { let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() } /// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn set_source(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn successfully_compiled(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
{ if !self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } }
identifier_body
verify_project.rs
use crate::command_prelude::*; use std::collections::HashMap; use std::process; use cargo::print_json; pub fn cli() -> App { subcommand("verify-project") .about("Check correctness of crate manifest") .arg(opt("quiet", "No output printed to stdout").short("q")) .arg_manifest_path() } pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { fn fail(reason: &str, value: &str) ->!
if let Err(e) = args.workspace(config) { fail("invalid", &e.to_string()) } let mut h = HashMap::new(); h.insert("success".to_string(), "true".to_string()); print_json(&h); Ok(()) }
{ let mut h = HashMap::new(); h.insert(reason.to_string(), value.to_string()); print_json(&h); process::exit(1) }
identifier_body
verify_project.rs
use crate::command_prelude::*; use std::collections::HashMap; use std::process; use cargo::print_json; pub fn
() -> App { subcommand("verify-project") .about("Check correctness of crate manifest") .arg(opt("quiet", "No output printed to stdout").short("q")) .arg_manifest_path() } pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { fn fail(reason: &str, value: &str) ->! { let mut h = HashMap::new(); h.insert(reason.to_string(), value.to_string()); print_json(&h); process::exit(1) } if let Err(e) = args.workspace(config) { fail("invalid", &e.to_string()) } let mut h = HashMap::new(); h.insert("success".to_string(), "true".to_string()); print_json(&h); Ok(()) }
cli
identifier_name
verify_project.rs
use crate::command_prelude::*; use std::collections::HashMap; use std::process; use cargo::print_json; pub fn cli() -> App { subcommand("verify-project") .about("Check correctness of crate manifest") .arg(opt("quiet", "No output printed to stdout").short("q")) .arg_manifest_path() } pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { fn fail(reason: &str, value: &str) ->! {
process::exit(1) } if let Err(e) = args.workspace(config) { fail("invalid", &e.to_string()) } let mut h = HashMap::new(); h.insert("success".to_string(), "true".to_string()); print_json(&h); Ok(()) }
let mut h = HashMap::new(); h.insert(reason.to_string(), value.to_string()); print_json(&h);
random_line_split
verify_project.rs
use crate::command_prelude::*; use std::collections::HashMap; use std::process; use cargo::print_json; pub fn cli() -> App { subcommand("verify-project") .about("Check correctness of crate manifest") .arg(opt("quiet", "No output printed to stdout").short("q")) .arg_manifest_path() } pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { fn fail(reason: &str, value: &str) ->! { let mut h = HashMap::new(); h.insert(reason.to_string(), value.to_string()); print_json(&h); process::exit(1) } if let Err(e) = args.workspace(config)
let mut h = HashMap::new(); h.insert("success".to_string(), "true".to_string()); print_json(&h); Ok(()) }
{ fail("invalid", &e.to_string()) }
conditional_block
voxtree.rs
use voxel::vox::Vox; /// voxel tree for fast traversal of content #[derive(Clone)] pub struct Voxtree<T>{ pub bitset:u64, pub content:Option<T>, pub children:Vec<Voxtree<T>>, } impl <T> Voxtree<T>{ pub fn new()->Self{ Voxtree{bitset:0u64, content: None, children:Vec::new()} } /// ///Traverse the tree and get the node at this location /// /// pub fn get_content(&self, location:&Vec<u64>)->&Option<T>{ let voxtree = self.get_tree(location); &voxtree.content } pub fn set_content(&mut self, location:&Vec<u64>, content:&mut Option<T>){ let mut stack = Vec::new(); stack.push(self); for i in 0..location.len() { let mut top:&mut Voxtree<T> = match stack.pop(){ Some(x) => x, None => panic!("Oh no's, stack in empty!"), }; top.set_path(location[i]); let node = top.get_as_mut(location[i]); stack.push(node); } let last_node = match stack.pop(){ Some(x) => x, None => panic!("stack in empty!"), }; let last = location.len() - 1; last_node.set_path(location[last]); last_node.set_leaf(location[last], content); } pub fn set_leaf(&mut self, location:u64, content:&mut Option<T>){ self.bitset = self.bitset | location; self.content = content.take(); } } impl <T> Vox for Voxtree<T>{ fn bitset(&self)->u64{ self.bitset } fn children(&self, index:usize)->&Self{ &self.children[index] } fn mut_children(&mut self, index:usize)->&mut Self{ &mut self.children[index] } fn num_children(&self)->usize{ self.children.len() } fn new_children(&mut self){ self.children.push(Voxtree::new()); } fn or_bitset(&mut self, location:u64)
fn drain(&mut self){ drop(self); } }
{ self.bitset = self.bitset | location; }
identifier_body
voxtree.rs
use voxel::vox::Vox; /// voxel tree for fast traversal of content #[derive(Clone)] pub struct Voxtree<T>{ pub bitset:u64, pub content:Option<T>, pub children:Vec<Voxtree<T>>, } impl <T> Voxtree<T>{ pub fn new()->Self{ Voxtree{bitset:0u64, content: None, children:Vec::new()} } /// ///Traverse the tree and get the node at this location /// /// pub fn get_content(&self, location:&Vec<u64>)->&Option<T>{ let voxtree = self.get_tree(location); &voxtree.content } pub fn set_content(&mut self, location:&Vec<u64>, content:&mut Option<T>){ let mut stack = Vec::new(); stack.push(self); for i in 0..location.len() { let mut top:&mut Voxtree<T> = match stack.pop(){ Some(x) => x, None => panic!("Oh no's, stack in empty!"), }; top.set_path(location[i]); let node = top.get_as_mut(location[i]); stack.push(node); } let last_node = match stack.pop(){ Some(x) => x, None => panic!("stack in empty!"), }; let last = location.len() - 1; last_node.set_path(location[last]); last_node.set_leaf(location[last], content); } pub fn set_leaf(&mut self, location:u64, content:&mut Option<T>){ self.bitset = self.bitset | location; self.content = content.take(); } } impl <T> Vox for Voxtree<T>{ fn bitset(&self)->u64{ self.bitset } fn children(&self, index:usize)->&Self{ &self.children[index] } fn mut_children(&mut self, index:usize)->&mut Self{ &mut self.children[index] } fn num_children(&self)->usize{ self.children.len() } fn new_children(&mut self){ self.children.push(Voxtree::new()); } fn
(&mut self, location:u64){ self.bitset = self.bitset | location; } fn drain(&mut self){ drop(self); } }
or_bitset
identifier_name
voxtree.rs
use voxel::vox::Vox; /// voxel tree for fast traversal of content #[derive(Clone)] pub struct Voxtree<T>{ pub bitset:u64, pub content:Option<T>, pub children:Vec<Voxtree<T>>, } impl <T> Voxtree<T>{ pub fn new()->Self{ Voxtree{bitset:0u64, content: None, children:Vec::new()} }
///Traverse the tree and get the node at this location /// /// pub fn get_content(&self, location:&Vec<u64>)->&Option<T>{ let voxtree = self.get_tree(location); &voxtree.content } pub fn set_content(&mut self, location:&Vec<u64>, content:&mut Option<T>){ let mut stack = Vec::new(); stack.push(self); for i in 0..location.len() { let mut top:&mut Voxtree<T> = match stack.pop(){ Some(x) => x, None => panic!("Oh no's, stack in empty!"), }; top.set_path(location[i]); let node = top.get_as_mut(location[i]); stack.push(node); } let last_node = match stack.pop(){ Some(x) => x, None => panic!("stack in empty!"), }; let last = location.len() - 1; last_node.set_path(location[last]); last_node.set_leaf(location[last], content); } pub fn set_leaf(&mut self, location:u64, content:&mut Option<T>){ self.bitset = self.bitset | location; self.content = content.take(); } } impl <T> Vox for Voxtree<T>{ fn bitset(&self)->u64{ self.bitset } fn children(&self, index:usize)->&Self{ &self.children[index] } fn mut_children(&mut self, index:usize)->&mut Self{ &mut self.children[index] } fn num_children(&self)->usize{ self.children.len() } fn new_children(&mut self){ self.children.push(Voxtree::new()); } fn or_bitset(&mut self, location:u64){ self.bitset = self.bitset | location; } fn drain(&mut self){ drop(self); } }
///
random_line_split
logging-separate-lines.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
// ignore-android // ignore-win32 // exec-env:RUST_LOG=debug #![feature(phase)] #[phase(plugin, link)] extern crate log; use std::io::Command; use std::os; use std::str; fn main() { let args = os::args(); let args = args.as_slice(); if args.len() > 1 && args[1].as_slice() == "child" { debug!("foo"); debug!("bar"); return } let p = Command::new(args[0].as_slice()) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p.status.success()); let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines(); assert!(lines.next().unwrap().contains("foo")); assert!(lines.next().unwrap().contains("bar")); }
random_line_split
logging-separate-lines.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android // ignore-win32 // exec-env:RUST_LOG=debug #![feature(phase)] #[phase(plugin, link)] extern crate log; use std::io::Command; use std::os; use std::str; fn main() { let args = os::args(); let args = args.as_slice(); if args.len() > 1 && args[1].as_slice() == "child"
let p = Command::new(args[0].as_slice()) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p.status.success()); let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines(); assert!(lines.next().unwrap().contains("foo")); assert!(lines.next().unwrap().contains("bar")); }
{ debug!("foo"); debug!("bar"); return }
conditional_block
logging-separate-lines.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android // ignore-win32 // exec-env:RUST_LOG=debug #![feature(phase)] #[phase(plugin, link)] extern crate log; use std::io::Command; use std::os; use std::str; fn
() { let args = os::args(); let args = args.as_slice(); if args.len() > 1 && args[1].as_slice() == "child" { debug!("foo"); debug!("bar"); return } let p = Command::new(args[0].as_slice()) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p.status.success()); let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines(); assert!(lines.next().unwrap().contains("foo")); assert!(lines.next().unwrap().contains("bar")); }
main
identifier_name
logging-separate-lines.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android // ignore-win32 // exec-env:RUST_LOG=debug #![feature(phase)] #[phase(plugin, link)] extern crate log; use std::io::Command; use std::os; use std::str; fn main()
{ let args = os::args(); let args = args.as_slice(); if args.len() > 1 && args[1].as_slice() == "child" { debug!("foo"); debug!("bar"); return } let p = Command::new(args[0].as_slice()) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p.status.success()); let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines(); assert!(lines.next().unwrap().contains("foo")); assert!(lines.next().unwrap().contains("bar")); }
identifier_body
day_4.rs
pub use tdd_kata::string_calc_kata::iter_2::day_4::evaluate; pub use expectest::prelude::be_ok; describe! string_calculator { it "should evaluate integer number" { expect!(evaluate("54357632471")).to(be_ok().value(54357632471.0)); } it "shoould evaluate float number" { expect!(evaluate("4325546.1235454")).to(be_ok().value(4325546.1235454)); } it "should add two numbers" { expect!(evaluate("32543.456+3254.231")).to(be_ok().value(35797.687)); } it "should sub two numbers" { expect!(evaluate("3248.546-123.567")).to(be_ok().value(3124.979)); } it "should mul two numbers" { expect!(evaluate("32254.546×15.5")).to(be_ok().value(499945.463)); } it "should div two numbers" { expect!(evaluate("32543÷546.4")).to(be_ok().value(59.55893118594437)); } it "should evaluate numbers of operations" {
expect!(evaluate("3245+45.55+567.876-658561.54÷154+4325×25+3534")).to(be_ok().value(111241.05236363637)); } }
random_line_split
atbash-cipher.rs
extern crate atbash_cipher as cipher; #[test] fn test_encode_yes() { assert_eq!("bvh", cipher::encode("yes")); } #[test] #[ignore] fn test_encode_no() { assert_eq!("ml", cipher::encode("no")); } #[test] #[ignore] fn test_encode_omg() { assert_eq!("lnt", cipher::encode("OMG")); } #[test] #[ignore] fn test_encode_spaces() { assert_eq!("lnt", cipher::encode("O M G")); } #[test] #[ignore] fn test_encode_mindblowingly() { assert_eq!("nrmwy oldrm tob", cipher::encode("mindblowingly")); } #[test] #[ignore] fn test_encode_numbers()
#[test] #[ignore] fn test_encode_deep_thought() { assert_eq!("gifgs rhurx grlm", cipher::encode("Truth is fiction.")); } #[test] #[ignore] fn test_encode_all_the_letters() { assert_eq!("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt", cipher::encode("The quick brown fox jumps over the lazy dog.")); } #[test] #[ignore] fn test_encode_ignores_non_ascii() { assert_eq!("mlmzh xrrrt mlivw", cipher::encode("non ascii éignored")); } #[test] #[ignore] fn test_decode_exercism() { assert_eq!("exercism", cipher::decode("vcvix rhn")); } #[test] #[ignore] fn test_decode_a_sentence() { assert_eq!("anobstacleisoftenasteppingstone", cipher::decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")); } #[test] #[ignore] fn test_decode_numbers() { assert_eq!("testing123testing", cipher::decode("gvhgr mt123 gvhgr mt")); } #[test] #[ignore] fn test_decode_all_the_letters() { assert_eq!("thequickbrownfoxjumpsoverthelazydog", cipher::decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")); }
{ assert_eq!("gvhgr mt123 gvhgr mt", cipher::encode("Testing,1 2 3, testing.")); }
identifier_body
atbash-cipher.rs
extern crate atbash_cipher as cipher; #[test] fn test_encode_yes() { assert_eq!("bvh", cipher::encode("yes")); } #[test] #[ignore] fn test_encode_no() { assert_eq!("ml", cipher::encode("no")); } #[test] #[ignore] fn test_encode_omg() { assert_eq!("lnt", cipher::encode("OMG")); } #[test] #[ignore] fn test_encode_spaces() { assert_eq!("lnt", cipher::encode("O M G")); } #[test] #[ignore] fn test_encode_mindblowingly() { assert_eq!("nrmwy oldrm tob", cipher::encode("mindblowingly")); } #[test] #[ignore] fn test_encode_numbers() { assert_eq!("gvhgr mt123 gvhgr mt", cipher::encode("Testing,1 2 3, testing.")); }
assert_eq!("gifgs rhurx grlm", cipher::encode("Truth is fiction.")); } #[test] #[ignore] fn test_encode_all_the_letters() { assert_eq!("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt", cipher::encode("The quick brown fox jumps over the lazy dog.")); } #[test] #[ignore] fn test_encode_ignores_non_ascii() { assert_eq!("mlmzh xrrrt mlivw", cipher::encode("non ascii éignored")); } #[test] #[ignore] fn test_decode_exercism() { assert_eq!("exercism", cipher::decode("vcvix rhn")); } #[test] #[ignore] fn test_decode_a_sentence() { assert_eq!("anobstacleisoftenasteppingstone", cipher::decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")); } #[test] #[ignore] fn test_decode_numbers() { assert_eq!("testing123testing", cipher::decode("gvhgr mt123 gvhgr mt")); } #[test] #[ignore] fn test_decode_all_the_letters() { assert_eq!("thequickbrownfoxjumpsoverthelazydog", cipher::decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")); }
#[test] #[ignore] fn test_encode_deep_thought() {
random_line_split
atbash-cipher.rs
extern crate atbash_cipher as cipher; #[test] fn test_encode_yes() { assert_eq!("bvh", cipher::encode("yes")); } #[test] #[ignore] fn test_encode_no() { assert_eq!("ml", cipher::encode("no")); } #[test] #[ignore] fn test_encode_omg() { assert_eq!("lnt", cipher::encode("OMG")); } #[test] #[ignore] fn test_encode_spaces() { assert_eq!("lnt", cipher::encode("O M G")); } #[test] #[ignore] fn
() { assert_eq!("nrmwy oldrm tob", cipher::encode("mindblowingly")); } #[test] #[ignore] fn test_encode_numbers() { assert_eq!("gvhgr mt123 gvhgr mt", cipher::encode("Testing,1 2 3, testing.")); } #[test] #[ignore] fn test_encode_deep_thought() { assert_eq!("gifgs rhurx grlm", cipher::encode("Truth is fiction.")); } #[test] #[ignore] fn test_encode_all_the_letters() { assert_eq!("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt", cipher::encode("The quick brown fox jumps over the lazy dog.")); } #[test] #[ignore] fn test_encode_ignores_non_ascii() { assert_eq!("mlmzh xrrrt mlivw", cipher::encode("non ascii éignored")); } #[test] #[ignore] fn test_decode_exercism() { assert_eq!("exercism", cipher::decode("vcvix rhn")); } #[test] #[ignore] fn test_decode_a_sentence() { assert_eq!("anobstacleisoftenasteppingstone", cipher::decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")); } #[test] #[ignore] fn test_decode_numbers() { assert_eq!("testing123testing", cipher::decode("gvhgr mt123 gvhgr mt")); } #[test] #[ignore] fn test_decode_all_the_letters() { assert_eq!("thequickbrownfoxjumpsoverthelazydog", cipher::decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")); }
test_encode_mindblowingly
identifier_name
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![recursion_limit="256"] #![deny( dead_code, non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] #[macro_use] extern crate log; extern crate toml; extern crate toml_query;
#[macro_use] extern crate libimagstore; extern crate libimagerror; extern crate libimagentryedit; module_entry_path_mod!("notes"); pub mod error; pub mod note; pub mod notestore; pub mod notestoreid; pub mod iter;
#[macro_use] extern crate error_chain; extern crate libimagrt;
random_line_split
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(BarrierState::new(threshold)), } } fn wait(&self) -> bool { let ret; match self.state.lock() { Err(e) => panic!(format!("Locking failed: {}", e)), Ok(mut state) => { if!state.valid { panic!("Waiting on invalid Barrier"); } let current_cycle = state.cycle; state.counter -= 1; if state.counter <= 0 { state.cycle =!state.cycle; state.counter = self.threshold; self.open.notify_all(); ret = true; } else { while current_cycle == state.cycle { state = self.open.wait(state).unwrap(); } ret = false; } }, } ret } } struct BarrierState { counter: usize, cycle: bool, valid: bool, } impl BarrierState { fn new(counter: usize) -> Self { BarrierState { counter: counter, cycle: true, valid: true, } } } const ARRAY_SIZE: usize = 6; const THREADS: usize = 5; const OUTLOOPS: usize = 10; const INLOOPS: usize = 1000; struct ThreadContext { array: Mutex<ThreadArray>, barrier: Arc<Barrier>, } impl ThreadContext { fn new(increment: u32, barrier: Arc<Barrier>) -> Self
} struct ThreadArray { data: [u32; ARRAY_SIZE], increment: u32, } impl ThreadArray { fn new(increment: u32) -> Self { let mut array = ThreadArray { data: [0; ARRAY_SIZE], increment: increment, }; for i in 0..array.data.len() { array.data[i] = (i + 1) as u32; } array } } fn main() { let mut handles = Vec::with_capacity(THREADS); let barrier = Arc::new(Barrier::new(THREADS)); let mut contexts = Vec::with_capacity(THREADS); for i in 0..THREADS { contexts.push(ThreadContext::new(i as u32, barrier.clone())); } let contexts = Arc::new(contexts); for i in 0..contexts.len() { let thread_contexts = contexts.clone(); handles.push(thread::spawn(move || { thread_routine(thread_contexts, i as usize); })); } for handle in handles { handle.join().unwrap(); } for p in contexts.iter().enumerate() { let thread_num = p.0; let ctx = p.1; match ctx.array.lock() { Err(_) => panic!(format!("Failed to lock data mutex to print results")), Ok(array) => { print!("{}", format!("{:02}: ({}) ", thread_num, array.increment)); for i in 0..array.data.len() { print!("{}", format!("{:10} ", array.data[i])); } print!("\n"); }, } } } fn thread_routine(contexts: Arc<Vec<ThreadContext>>, thread_num: usize) { let my_ctx = &contexts[thread_num]; for _ in 0..OUTLOOPS { my_ctx.barrier.wait(); match my_ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex in inner loop: {}", e)), Ok(mut array) => { for _ in 0..INLOOPS { for counter in 0..array.data.len() { array.data[counter] += array.increment; } } }, } if my_ctx.barrier.wait() { for ctx in contexts.iter() { match ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex to increment: {}", e)), Ok(mut array) => { array.increment += 1; }, } } } } }
{ ThreadContext { array: Mutex::new(ThreadArray::new(increment)), barrier: barrier, } }
identifier_body
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(BarrierState::new(threshold)), } } fn wait(&self) -> bool { let ret; match self.state.lock() { Err(e) => panic!(format!("Locking failed: {}", e)), Ok(mut state) => { if!state.valid { panic!("Waiting on invalid Barrier"); } let current_cycle = state.cycle; state.counter -= 1; if state.counter <= 0
else { while current_cycle == state.cycle { state = self.open.wait(state).unwrap(); } ret = false; } }, } ret } } struct BarrierState { counter: usize, cycle: bool, valid: bool, } impl BarrierState { fn new(counter: usize) -> Self { BarrierState { counter: counter, cycle: true, valid: true, } } } const ARRAY_SIZE: usize = 6; const THREADS: usize = 5; const OUTLOOPS: usize = 10; const INLOOPS: usize = 1000; struct ThreadContext { array: Mutex<ThreadArray>, barrier: Arc<Barrier>, } impl ThreadContext { fn new(increment: u32, barrier: Arc<Barrier>) -> Self { ThreadContext { array: Mutex::new(ThreadArray::new(increment)), barrier: barrier, } } } struct ThreadArray { data: [u32; ARRAY_SIZE], increment: u32, } impl ThreadArray { fn new(increment: u32) -> Self { let mut array = ThreadArray { data: [0; ARRAY_SIZE], increment: increment, }; for i in 0..array.data.len() { array.data[i] = (i + 1) as u32; } array } } fn main() { let mut handles = Vec::with_capacity(THREADS); let barrier = Arc::new(Barrier::new(THREADS)); let mut contexts = Vec::with_capacity(THREADS); for i in 0..THREADS { contexts.push(ThreadContext::new(i as u32, barrier.clone())); } let contexts = Arc::new(contexts); for i in 0..contexts.len() { let thread_contexts = contexts.clone(); handles.push(thread::spawn(move || { thread_routine(thread_contexts, i as usize); })); } for handle in handles { handle.join().unwrap(); } for p in contexts.iter().enumerate() { let thread_num = p.0; let ctx = p.1; match ctx.array.lock() { Err(_) => panic!(format!("Failed to lock data mutex to print results")), Ok(array) => { print!("{}", format!("{:02}: ({}) ", thread_num, array.increment)); for i in 0..array.data.len() { print!("{}", format!("{:10} ", array.data[i])); } print!("\n"); }, } } } fn thread_routine(contexts: Arc<Vec<ThreadContext>>, thread_num: usize) { let my_ctx = &contexts[thread_num]; for _ in 0..OUTLOOPS { my_ctx.barrier.wait(); match my_ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex in inner loop: {}", e)), Ok(mut array) => { for _ in 0..INLOOPS { for counter in 0..array.data.len() { array.data[counter] += array.increment; } } }, } if my_ctx.barrier.wait() { for ctx in contexts.iter() { match ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex to increment: {}", e)), Ok(mut array) => { array.increment += 1; }, } } } } }
{ state.cycle = !state.cycle; state.counter = self.threshold; self.open.notify_all(); ret = true; }
conditional_block
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(BarrierState::new(threshold)), } } fn wait(&self) -> bool { let ret; match self.state.lock() { Err(e) => panic!(format!("Locking failed: {}", e)), Ok(mut state) => { if!state.valid { panic!("Waiting on invalid Barrier"); } let current_cycle = state.cycle; state.counter -= 1; if state.counter <= 0 { state.cycle =!state.cycle; state.counter = self.threshold; self.open.notify_all(); ret = true; } else { while current_cycle == state.cycle { state = self.open.wait(state).unwrap(); } ret = false; } }, } ret } } struct BarrierState { counter: usize, cycle: bool, valid: bool, } impl BarrierState { fn
(counter: usize) -> Self { BarrierState { counter: counter, cycle: true, valid: true, } } } const ARRAY_SIZE: usize = 6; const THREADS: usize = 5; const OUTLOOPS: usize = 10; const INLOOPS: usize = 1000; struct ThreadContext { array: Mutex<ThreadArray>, barrier: Arc<Barrier>, } impl ThreadContext { fn new(increment: u32, barrier: Arc<Barrier>) -> Self { ThreadContext { array: Mutex::new(ThreadArray::new(increment)), barrier: barrier, } } } struct ThreadArray { data: [u32; ARRAY_SIZE], increment: u32, } impl ThreadArray { fn new(increment: u32) -> Self { let mut array = ThreadArray { data: [0; ARRAY_SIZE], increment: increment, }; for i in 0..array.data.len() { array.data[i] = (i + 1) as u32; } array } } fn main() { let mut handles = Vec::with_capacity(THREADS); let barrier = Arc::new(Barrier::new(THREADS)); let mut contexts = Vec::with_capacity(THREADS); for i in 0..THREADS { contexts.push(ThreadContext::new(i as u32, barrier.clone())); } let contexts = Arc::new(contexts); for i in 0..contexts.len() { let thread_contexts = contexts.clone(); handles.push(thread::spawn(move || { thread_routine(thread_contexts, i as usize); })); } for handle in handles { handle.join().unwrap(); } for p in contexts.iter().enumerate() { let thread_num = p.0; let ctx = p.1; match ctx.array.lock() { Err(_) => panic!(format!("Failed to lock data mutex to print results")), Ok(array) => { print!("{}", format!("{:02}: ({}) ", thread_num, array.increment)); for i in 0..array.data.len() { print!("{}", format!("{:10} ", array.data[i])); } print!("\n"); }, } } } fn thread_routine(contexts: Arc<Vec<ThreadContext>>, thread_num: usize) { let my_ctx = &contexts[thread_num]; for _ in 0..OUTLOOPS { my_ctx.barrier.wait(); match my_ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex in inner loop: {}", e)), Ok(mut array) => { for _ in 0..INLOOPS { for counter in 0..array.data.len() { array.data[counter] += array.increment; } } }, } if my_ctx.barrier.wait() { for ctx in contexts.iter() { match ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex to increment: {}", e)), Ok(mut array) => { array.increment += 1; }, } } } } }
new
identifier_name
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(BarrierState::new(threshold)), } } fn wait(&self) -> bool { let ret; match self.state.lock() { Err(e) => panic!(format!("Locking failed: {}", e)), Ok(mut state) => { if!state.valid { panic!("Waiting on invalid Barrier"); } let current_cycle = state.cycle; state.counter -= 1; if state.counter <= 0 { state.cycle =!state.cycle; state.counter = self.threshold; self.open.notify_all(); ret = true; } else { while current_cycle == state.cycle { state = self.open.wait(state).unwrap(); } ret = false; } }, } ret } } struct BarrierState { counter: usize, cycle: bool, valid: bool, } impl BarrierState { fn new(counter: usize) -> Self { BarrierState { counter: counter, cycle: true, valid: true, } } } const ARRAY_SIZE: usize = 6; const THREADS: usize = 5; const OUTLOOPS: usize = 10; const INLOOPS: usize = 1000; struct ThreadContext { array: Mutex<ThreadArray>, barrier: Arc<Barrier>, } impl ThreadContext { fn new(increment: u32, barrier: Arc<Barrier>) -> Self { ThreadContext { array: Mutex::new(ThreadArray::new(increment)), barrier: barrier, } } } struct ThreadArray { data: [u32; ARRAY_SIZE], increment: u32,
impl ThreadArray { fn new(increment: u32) -> Self { let mut array = ThreadArray { data: [0; ARRAY_SIZE], increment: increment, }; for i in 0..array.data.len() { array.data[i] = (i + 1) as u32; } array } } fn main() { let mut handles = Vec::with_capacity(THREADS); let barrier = Arc::new(Barrier::new(THREADS)); let mut contexts = Vec::with_capacity(THREADS); for i in 0..THREADS { contexts.push(ThreadContext::new(i as u32, barrier.clone())); } let contexts = Arc::new(contexts); for i in 0..contexts.len() { let thread_contexts = contexts.clone(); handles.push(thread::spawn(move || { thread_routine(thread_contexts, i as usize); })); } for handle in handles { handle.join().unwrap(); } for p in contexts.iter().enumerate() { let thread_num = p.0; let ctx = p.1; match ctx.array.lock() { Err(_) => panic!(format!("Failed to lock data mutex to print results")), Ok(array) => { print!("{}", format!("{:02}: ({}) ", thread_num, array.increment)); for i in 0..array.data.len() { print!("{}", format!("{:10} ", array.data[i])); } print!("\n"); }, } } } fn thread_routine(contexts: Arc<Vec<ThreadContext>>, thread_num: usize) { let my_ctx = &contexts[thread_num]; for _ in 0..OUTLOOPS { my_ctx.barrier.wait(); match my_ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex in inner loop: {}", e)), Ok(mut array) => { for _ in 0..INLOOPS { for counter in 0..array.data.len() { array.data[counter] += array.increment; } } }, } if my_ctx.barrier.wait() { for ctx in contexts.iter() { match ctx.array.lock() { Err(e) => panic!(format!("Unable to lock mutex to increment: {}", e)), Ok(mut array) => { array.increment += 1; }, } } } } }
}
random_line_split
wait.rs
use libc::{self, c_int}; use {Errno, Result}; use unistd::Pid; use sys::signal::Signal; libc_bitflags!( pub struct WaitPidFlag: c_int { WNOHANG; WUNTRACED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WEXITED; WCONTINUED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WSTOPPED; /// Don't reap, just poll status. #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WNOWAIT; /// Don't wait on children of other threads in this group #[cfg(any(target_os = "android", target_os = "linux"))] __WNOTHREAD; /// Wait on all children, regardless of type #[cfg(any(target_os = "android", target_os = "linux"))] __WALL; #[cfg(any(target_os = "android", target_os = "linux"))] __WCLONE; } ); /// Possible return values from `wait()` or `waitpid()`. /// /// Each status (other than `StillAlive`) describes a state transition /// in a child process `Pid`, such as the process exiting or stopping, /// plus additional data about the transition if any. /// /// Note that there are two Linux-specific enum variants, `PtraceEvent` /// and `PtraceSyscall`. Portable code should avoid exhaustively /// matching on `WaitStatus`. #[derive(Eq, PartialEq, Clone, Copy, Debug)] pub enum WaitStatus { /// The process exited normally (as with `exit()` or returning from /// `main`) with the given exit code. This case matches the C macro /// `WIFEXITED(status)`; the second field is `WEXITSTATUS(status)`. Exited(Pid, i32), /// The process was killed by the given signal. The third field /// indicates whether the signal generated a core dump. This case /// matches the C macro `WIFSIGNALED(status)`; the last two fields /// correspond to `WTERMSIG(status)` and `WCOREDUMP(status)`. Signaled(Pid, Signal, bool), /// The process is alive, but was stopped by the given signal. This /// is only reported if `WaitPidFlag::WUNTRACED` was passed. This /// case matches the C macro `WIFSTOPPED(status)`; the second field /// is `WSTOPSIG(status)`. Stopped(Pid, Signal), /// The traced process was stopped by a `PTRACE_EVENT_*` event. See /// [`nix::sys::ptrace`] and [`ptrace`(2)] for more information. All /// currently-defined events use `SIGTRAP` as the signal; the third /// field is the `PTRACE_EVENT_*` value of the event. /// /// [`nix::sys::ptrace`]:../ptrace/index.html /// [`ptrace`(2)]: http://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] PtraceEvent(Pid, Signal, c_int), /// The traced process was stopped by execution of a system call, /// and `PTRACE_O_TRACESYSGOOD` is in effect. See [`ptrace`(2)] for /// more information. /// /// [`ptrace`(2)]: http://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] PtraceSyscall(Pid), /// The process was previously stopped but has resumed execution /// after receiving a `SIGCONT` signal. This is only reported if /// `WaitPidFlag::WCONTINUED` was passed. This case matches the C /// macro `WIFCONTINUED(status)`. Continued(Pid), /// There are currently no state changes to report in any awaited /// child process. This is only returned if `WaitPidFlag::WNOHANG` /// was used (otherwise `wait()` or `waitpid()` would block until /// there was something to report). StillAlive, } impl WaitStatus { /// Extracts the PID from the WaitStatus unless it equals StillAlive. pub fn pid(&self) -> Option<Pid> { use self::WaitStatus::*; match *self { Exited(p, _) => Some(p), Signaled(p, _, _) => Some(p), Stopped(p, _) => Some(p), Continued(p) => Some(p), StillAlive => None, #[cfg(any(target_os = "linux", target_os = "android"))] PtraceEvent(p, _, _) => Some(p), #[cfg(any(target_os = "linux", target_os = "android"))] PtraceSyscall(p) => Some(p), } } } fn exited(status: i32) -> bool { unsafe { libc::WIFEXITED(status) } } fn exit_status(status: i32) -> i32 { unsafe { libc::WEXITSTATUS(status) } } fn signaled(status: i32) -> bool { unsafe { libc::WIFSIGNALED(status) } } fn term_signal(status: i32) -> Signal { Signal::from_c_int(unsafe { libc::WTERMSIG(status) }).unwrap() } fn dumped_core(status: i32) -> bool { unsafe { libc::WCOREDUMP(status) } } fn stopped(status: i32) -> bool { unsafe { libc::WIFSTOPPED(status) } } fn stop_signal(status: i32) -> Signal { Signal::from_c_int(unsafe { libc::WSTOPSIG(status) }).unwrap() } fn syscall_stop(status: i32) -> bool { // From ptrace(2), setting PTRACE_O_TRACESYSGOOD has the effect // of delivering SIGTRAP | 0x80 as the signal number for syscall // stops. This allows easily distinguishing syscall stops from // genuine SIGTRAP signals. unsafe { libc::WSTOPSIG(status) == libc::SIGTRAP | 0x80 } } fn stop_additional(status: i32) -> c_int { (status >> 16) as c_int } fn continued(status: i32) -> bool { unsafe { libc::WIFCONTINUED(status) } } fn decode(pid: Pid, status: i32) -> WaitStatus
WaitStatus::Stopped(pid, stop_signal(status)) } } } decode_stopped(pid, status) } else { assert!(continued(status)); WaitStatus::Continued(pid) } } pub fn waitpid<P: Into<Option<Pid>>>(pid: P, options: Option<WaitPidFlag>) -> Result<WaitStatus> { use self::WaitStatus::*; let mut status: i32 = 0; let option_bits = match options { Some(bits) => bits.bits(), None => 0, }; let res = unsafe { libc::waitpid( pid.into().unwrap_or(Pid::from_raw(-1)).into(), &mut status as *mut c_int, option_bits, ) }; Ok(match try!(Errno::result(res)) { 0 => StillAlive, res => decode(Pid::from_raw(res), status), }) } pub fn wait() -> Result<WaitStatus> { waitpid(None, None) }
{ if exited(status) { WaitStatus::Exited(pid, exit_status(status)) } else if signaled(status) { WaitStatus::Signaled(pid, term_signal(status), dumped_core(status)) } else if stopped(status) { cfg_if! { if #[cfg(any(target_os = "linux", target_os = "android"))] { fn decode_stopped(pid: Pid, status: i32) -> WaitStatus { let status_additional = stop_additional(status); if syscall_stop(status) { WaitStatus::PtraceSyscall(pid) } else if status_additional == 0 { WaitStatus::Stopped(pid, stop_signal(status)) } else { WaitStatus::PtraceEvent(pid, stop_signal(status), stop_additional(status)) } } } else { fn decode_stopped(pid: Pid, status: i32) -> WaitStatus {
identifier_body
wait.rs
use libc::{self, c_int}; use {Errno, Result}; use unistd::Pid; use sys::signal::Signal; libc_bitflags!( pub struct WaitPidFlag: c_int { WNOHANG; WUNTRACED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WEXITED; WCONTINUED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WSTOPPED; /// Don't reap, just poll status. #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WNOWAIT; /// Don't wait on children of other threads in this group #[cfg(any(target_os = "android", target_os = "linux"))] __WNOTHREAD; /// Wait on all children, regardless of type #[cfg(any(target_os = "android", target_os = "linux"))] __WALL; #[cfg(any(target_os = "android", target_os = "linux"))] __WCLONE; } ); /// Possible return values from `wait()` or `waitpid()`. /// /// Each status (other than `StillAlive`) describes a state transition /// in a child process `Pid`, such as the process exiting or stopping, /// plus additional data about the transition if any. /// /// Note that there are two Linux-specific enum variants, `PtraceEvent` /// and `PtraceSyscall`. Portable code should avoid exhaustively /// matching on `WaitStatus`. #[derive(Eq, PartialEq, Clone, Copy, Debug)] pub enum WaitStatus { /// The process exited normally (as with `exit()` or returning from /// `main`) with the given exit code. This case matches the C macro /// `WIFEXITED(status)`; the second field is `WEXITSTATUS(status)`. Exited(Pid, i32), /// The process was killed by the given signal. The third field /// indicates whether the signal generated a core dump. This case /// matches the C macro `WIFSIGNALED(status)`; the last two fields /// correspond to `WTERMSIG(status)` and `WCOREDUMP(status)`. Signaled(Pid, Signal, bool), /// The process is alive, but was stopped by the given signal. This /// is only reported if `WaitPidFlag::WUNTRACED` was passed. This /// case matches the C macro `WIFSTOPPED(status)`; the second field /// is `WSTOPSIG(status)`. Stopped(Pid, Signal), /// The traced process was stopped by a `PTRACE_EVENT_*` event. See /// [`nix::sys::ptrace`] and [`ptrace`(2)] for more information. All /// currently-defined events use `SIGTRAP` as the signal; the third /// field is the `PTRACE_EVENT_*` value of the event. /// /// [`nix::sys::ptrace`]:../ptrace/index.html /// [`ptrace`(2)]: http://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] PtraceEvent(Pid, Signal, c_int), /// The traced process was stopped by execution of a system call, /// and `PTRACE_O_TRACESYSGOOD` is in effect. See [`ptrace`(2)] for /// more information. /// /// [`ptrace`(2)]: http://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] PtraceSyscall(Pid), /// The process was previously stopped but has resumed execution /// after receiving a `SIGCONT` signal. This is only reported if /// `WaitPidFlag::WCONTINUED` was passed. This case matches the C /// macro `WIFCONTINUED(status)`. Continued(Pid), /// There are currently no state changes to report in any awaited /// child process. This is only returned if `WaitPidFlag::WNOHANG` /// was used (otherwise `wait()` or `waitpid()` would block until /// there was something to report). StillAlive, } impl WaitStatus { /// Extracts the PID from the WaitStatus unless it equals StillAlive. pub fn pid(&self) -> Option<Pid> { use self::WaitStatus::*; match *self { Exited(p, _) => Some(p), Signaled(p, _, _) => Some(p), Stopped(p, _) => Some(p), Continued(p) => Some(p), StillAlive => None, #[cfg(any(target_os = "linux", target_os = "android"))] PtraceEvent(p, _, _) => Some(p), #[cfg(any(target_os = "linux", target_os = "android"))] PtraceSyscall(p) => Some(p), } } } fn exited(status: i32) -> bool { unsafe { libc::WIFEXITED(status) } } fn exit_status(status: i32) -> i32 { unsafe { libc::WEXITSTATUS(status) } } fn signaled(status: i32) -> bool { unsafe { libc::WIFSIGNALED(status) } } fn term_signal(status: i32) -> Signal { Signal::from_c_int(unsafe { libc::WTERMSIG(status) }).unwrap() } fn
(status: i32) -> bool { unsafe { libc::WCOREDUMP(status) } } fn stopped(status: i32) -> bool { unsafe { libc::WIFSTOPPED(status) } } fn stop_signal(status: i32) -> Signal { Signal::from_c_int(unsafe { libc::WSTOPSIG(status) }).unwrap() } fn syscall_stop(status: i32) -> bool { // From ptrace(2), setting PTRACE_O_TRACESYSGOOD has the effect // of delivering SIGTRAP | 0x80 as the signal number for syscall // stops. This allows easily distinguishing syscall stops from // genuine SIGTRAP signals. unsafe { libc::WSTOPSIG(status) == libc::SIGTRAP | 0x80 } } fn stop_additional(status: i32) -> c_int { (status >> 16) as c_int } fn continued(status: i32) -> bool { unsafe { libc::WIFCONTINUED(status) } } fn decode(pid: Pid, status: i32) -> WaitStatus { if exited(status) { WaitStatus::Exited(pid, exit_status(status)) } else if signaled(status) { WaitStatus::Signaled(pid, term_signal(status), dumped_core(status)) } else if stopped(status) { cfg_if! { if #[cfg(any(target_os = "linux", target_os = "android"))] { fn decode_stopped(pid: Pid, status: i32) -> WaitStatus { let status_additional = stop_additional(status); if syscall_stop(status) { WaitStatus::PtraceSyscall(pid) } else if status_additional == 0 { WaitStatus::Stopped(pid, stop_signal(status)) } else { WaitStatus::PtraceEvent(pid, stop_signal(status), stop_additional(status)) } } } else { fn decode_stopped(pid: Pid, status: i32) -> WaitStatus { WaitStatus::Stopped(pid, stop_signal(status)) } } } decode_stopped(pid, status) } else { assert!(continued(status)); WaitStatus::Continued(pid) } } pub fn waitpid<P: Into<Option<Pid>>>(pid: P, options: Option<WaitPidFlag>) -> Result<WaitStatus> { use self::WaitStatus::*; let mut status: i32 = 0; let option_bits = match options { Some(bits) => bits.bits(), None => 0, }; let res = unsafe { libc::waitpid( pid.into().unwrap_or(Pid::from_raw(-1)).into(), &mut status as *mut c_int, option_bits, ) }; Ok(match try!(Errno::result(res)) { 0 => StillAlive, res => decode(Pid::from_raw(res), status), }) } pub fn wait() -> Result<WaitStatus> { waitpid(None, None) }
dumped_core
identifier_name
wait.rs
use libc::{self, c_int}; use {Errno, Result}; use unistd::Pid; use sys::signal::Signal; libc_bitflags!( pub struct WaitPidFlag: c_int { WNOHANG; WUNTRACED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WEXITED; WCONTINUED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WSTOPPED; /// Don't reap, just poll status. #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd"))] WNOWAIT; /// Don't wait on children of other threads in this group #[cfg(any(target_os = "android", target_os = "linux"))] __WNOTHREAD; /// Wait on all children, regardless of type #[cfg(any(target_os = "android", target_os = "linux"))] __WALL; #[cfg(any(target_os = "android", target_os = "linux"))] __WCLONE; } ); /// Possible return values from `wait()` or `waitpid()`. /// /// Each status (other than `StillAlive`) describes a state transition /// in a child process `Pid`, such as the process exiting or stopping, /// plus additional data about the transition if any. /// /// Note that there are two Linux-specific enum variants, `PtraceEvent` /// and `PtraceSyscall`. Portable code should avoid exhaustively /// matching on `WaitStatus`. #[derive(Eq, PartialEq, Clone, Copy, Debug)] pub enum WaitStatus { /// The process exited normally (as with `exit()` or returning from /// `main`) with the given exit code. This case matches the C macro /// `WIFEXITED(status)`; the second field is `WEXITSTATUS(status)`. Exited(Pid, i32), /// The process was killed by the given signal. The third field /// indicates whether the signal generated a core dump. This case /// matches the C macro `WIFSIGNALED(status)`; the last two fields /// correspond to `WTERMSIG(status)` and `WCOREDUMP(status)`. Signaled(Pid, Signal, bool), /// The process is alive, but was stopped by the given signal. This /// is only reported if `WaitPidFlag::WUNTRACED` was passed. This /// case matches the C macro `WIFSTOPPED(status)`; the second field /// is `WSTOPSIG(status)`. Stopped(Pid, Signal), /// The traced process was stopped by a `PTRACE_EVENT_*` event. See /// [`nix::sys::ptrace`] and [`ptrace`(2)] for more information. All /// currently-defined events use `SIGTRAP` as the signal; the third /// field is the `PTRACE_EVENT_*` value of the event. /// /// [`nix::sys::ptrace`]:../ptrace/index.html /// [`ptrace`(2)]: http://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] PtraceEvent(Pid, Signal, c_int), /// The traced process was stopped by execution of a system call, /// and `PTRACE_O_TRACESYSGOOD` is in effect. See [`ptrace`(2)] for /// more information. /// /// [`ptrace`(2)]: http://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] PtraceSyscall(Pid), /// The process was previously stopped but has resumed execution /// after receiving a `SIGCONT` signal. This is only reported if /// `WaitPidFlag::WCONTINUED` was passed. This case matches the C /// macro `WIFCONTINUED(status)`. Continued(Pid), /// There are currently no state changes to report in any awaited /// child process. This is only returned if `WaitPidFlag::WNOHANG` /// was used (otherwise `wait()` or `waitpid()` would block until /// there was something to report). StillAlive, } impl WaitStatus { /// Extracts the PID from the WaitStatus unless it equals StillAlive. pub fn pid(&self) -> Option<Pid> { use self::WaitStatus::*; match *self { Exited(p, _) => Some(p), Signaled(p, _, _) => Some(p), Stopped(p, _) => Some(p), Continued(p) => Some(p), StillAlive => None, #[cfg(any(target_os = "linux", target_os = "android"))] PtraceEvent(p, _, _) => Some(p), #[cfg(any(target_os = "linux", target_os = "android"))] PtraceSyscall(p) => Some(p), } } } fn exited(status: i32) -> bool { unsafe { libc::WIFEXITED(status) } } fn exit_status(status: i32) -> i32 { unsafe { libc::WEXITSTATUS(status) } } fn signaled(status: i32) -> bool { unsafe { libc::WIFSIGNALED(status) } } fn term_signal(status: i32) -> Signal { Signal::from_c_int(unsafe { libc::WTERMSIG(status) }).unwrap() } fn dumped_core(status: i32) -> bool { unsafe { libc::WCOREDUMP(status) } } fn stopped(status: i32) -> bool { unsafe { libc::WIFSTOPPED(status) } } fn stop_signal(status: i32) -> Signal { Signal::from_c_int(unsafe { libc::WSTOPSIG(status) }).unwrap() } fn syscall_stop(status: i32) -> bool { // From ptrace(2), setting PTRACE_O_TRACESYSGOOD has the effect // of delivering SIGTRAP | 0x80 as the signal number for syscall // stops. This allows easily distinguishing syscall stops from // genuine SIGTRAP signals. unsafe { libc::WSTOPSIG(status) == libc::SIGTRAP | 0x80 } } fn stop_additional(status: i32) -> c_int { (status >> 16) as c_int } fn continued(status: i32) -> bool { unsafe { libc::WIFCONTINUED(status) } } fn decode(pid: Pid, status: i32) -> WaitStatus { if exited(status) { WaitStatus::Exited(pid, exit_status(status)) } else if signaled(status) { WaitStatus::Signaled(pid, term_signal(status), dumped_core(status)) } else if stopped(status) { cfg_if! { if #[cfg(any(target_os = "linux", target_os = "android"))] { fn decode_stopped(pid: Pid, status: i32) -> WaitStatus { let status_additional = stop_additional(status); if syscall_stop(status) { WaitStatus::PtraceSyscall(pid) } else if status_additional == 0 { WaitStatus::Stopped(pid, stop_signal(status)) } else { WaitStatus::PtraceEvent(pid, stop_signal(status), stop_additional(status)) } } } else { fn decode_stopped(pid: Pid, status: i32) -> WaitStatus { WaitStatus::Stopped(pid, stop_signal(status)) } } } decode_stopped(pid, status) } else { assert!(continued(status)); WaitStatus::Continued(pid) } } pub fn waitpid<P: Into<Option<Pid>>>(pid: P, options: Option<WaitPidFlag>) -> Result<WaitStatus> { use self::WaitStatus::*; let mut status: i32 = 0; let option_bits = match options { Some(bits) => bits.bits(), None => 0, }; let res = unsafe { libc::waitpid( pid.into().unwrap_or(Pid::from_raw(-1)).into(), &mut status as *mut c_int, option_bits, ) }; Ok(match try!(Errno::result(res)) { 0 => StillAlive, res => decode(Pid::from_raw(res), status), }) } pub fn wait() -> Result<WaitStatus> {
waitpid(None, None) }
random_line_split
newtype-struct-drop-run.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. // pretty-expanded FIXME #23616 #![feature(unsafe_destructor)] // Make sure the destructor is run for newtype structs. use std::cell::Cell; struct Foo<'a>(&'a Cell<isize>); #[unsafe_destructor] impl<'a> Drop for Foo<'a> { fn drop(&mut self) { let Foo(i) = *self; i.set(23); } } pub fn main()
{ let y = &Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
identifier_body
newtype-struct-drop-run.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. // pretty-expanded FIXME #23616 #![feature(unsafe_destructor)] // Make sure the destructor is run for newtype structs.
#[unsafe_destructor] impl<'a> Drop for Foo<'a> { fn drop(&mut self) { let Foo(i) = *self; i.set(23); } } pub fn main() { let y = &Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
use std::cell::Cell; struct Foo<'a>(&'a Cell<isize>);
random_line_split
newtype-struct-drop-run.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. // pretty-expanded FIXME #23616 #![feature(unsafe_destructor)] // Make sure the destructor is run for newtype structs. use std::cell::Cell; struct Foo<'a>(&'a Cell<isize>); #[unsafe_destructor] impl<'a> Drop for Foo<'a> { fn drop(&mut self) { let Foo(i) = *self; i.set(23); } } pub fn
() { let y = &Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
main
identifier_name
headless.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 compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, WindowSizeData}; use profile::mem; use profile::time; /// Starts the compositor, which listens for messages on the specified port. /// /// This is the null compositor which doesn't draw anything to the screen. /// It's intended for headless testing. pub struct NullCompositor { /// The port on which we receive messages. pub port: Box<CompositorReceiver>, /// A channel to the constellation. constellation_chan: ConstellationChan, /// A channel to the time profiler. time_profiler_chan: time::ProfilerChan, /// A channel to the memory profiler. mem_profiler_chan: mem::ProfilerChan, } impl NullCompositor { fn new(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { NullCompositor { port: port, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, } } pub fn create(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { let compositor = NullCompositor::new(port, constellation_chan, time_profiler_chan, mem_profiler_chan); // Tell the constellation about the initial fake size. { let ConstellationChan(ref chan) = compositor.constellation_chan; chan.send(ConstellationMsg::ResizedWindow(WindowSizeData { initial_viewport: TypedSize2D(640_f32, 480_f32), visible_viewport: TypedSize2D(640_f32, 480_f32), device_pixel_ratio: ScaleFactor::new(1.0), })).unwrap(); } compositor } } impl CompositorEventListener for NullCompositor { fn handle_event(&mut self, _: WindowEvent) -> bool { match self.port.recv_compositor_msg() { Msg::Exit(chan) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; con_chan.send(ConstellationMsg::Exit).unwrap(); chan.send(()).unwrap(); } Msg::ShutdownComplete => { debug!("constellation completed shutdown"); return false } Msg::GetGraphicsMetadata(chan) => { chan.send(None).unwrap(); } Msg::SetFrameTree(_, response_chan, _) => { response_chan.send(()).unwrap(); } // Explicitly list ignored messages so that when we add a new one, // we'll notice and think about whether it needs a response, like // SetFrameTree. Msg::CreateOrUpdateBaseLayer(..) | Msg::CreateOrUpdateDescendantLayer(..) | Msg::SetLayerRect(..) | Msg::AssignPaintedBuffers(..) | Msg::ChangeReadyState(..) | Msg::ChangePaintState(..) | Msg::ChangeRunningAnimationsState(..) | Msg::ScrollFragmentPoint(..) | Msg::LoadComplete | Msg::PaintMsgDiscarded(..) | Msg::ScrollTimeout(..) | Msg::ChangePageTitle(..) | Msg::ChangePageUrl(..) | Msg::KeyEvent(..) | Msg::SetCursor(..) => {} Msg::PaintTaskExited(..) =>
} true } fn repaint_synchronously(&mut self) {} fn shutdown(&mut self) { // Drain compositor port, sometimes messages contain channels that are blocking // another task from finishing (i.e. SetIds) while self.port.try_recv_compositor_msg().is_some() {} self.time_profiler_chan.send(time::ProfilerMsg::Exit); self.mem_profiler_chan.send(mem::ProfilerMsg::Exit); } fn pinch_zoom_level(&self) -> f32 { 1.0 } fn get_title_for_main_frame(&self) {} }
{}
conditional_block
headless.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 compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, WindowSizeData}; use profile::mem; use profile::time; /// Starts the compositor, which listens for messages on the specified port. /// /// This is the null compositor which doesn't draw anything to the screen. /// It's intended for headless testing. pub struct NullCompositor { /// The port on which we receive messages. pub port: Box<CompositorReceiver>, /// A channel to the constellation. constellation_chan: ConstellationChan, /// A channel to the time profiler. time_profiler_chan: time::ProfilerChan, /// A channel to the memory profiler. mem_profiler_chan: mem::ProfilerChan, } impl NullCompositor { fn new(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { NullCompositor { port: port, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, } } pub fn create(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { let compositor = NullCompositor::new(port, constellation_chan, time_profiler_chan, mem_profiler_chan); // Tell the constellation about the initial fake size. { let ConstellationChan(ref chan) = compositor.constellation_chan; chan.send(ConstellationMsg::ResizedWindow(WindowSizeData { initial_viewport: TypedSize2D(640_f32, 480_f32), visible_viewport: TypedSize2D(640_f32, 480_f32), device_pixel_ratio: ScaleFactor::new(1.0), })).unwrap(); } compositor } } impl CompositorEventListener for NullCompositor { fn handle_event(&mut self, _: WindowEvent) -> bool
} // Explicitly list ignored messages so that when we add a new one, // we'll notice and think about whether it needs a response, like // SetFrameTree. Msg::CreateOrUpdateBaseLayer(..) | Msg::CreateOrUpdateDescendantLayer(..) | Msg::SetLayerRect(..) | Msg::AssignPaintedBuffers(..) | Msg::ChangeReadyState(..) | Msg::ChangePaintState(..) | Msg::ChangeRunningAnimationsState(..) | Msg::ScrollFragmentPoint(..) | Msg::LoadComplete | Msg::PaintMsgDiscarded(..) | Msg::ScrollTimeout(..) | Msg::ChangePageTitle(..) | Msg::ChangePageUrl(..) | Msg::KeyEvent(..) | Msg::SetCursor(..) => {} Msg::PaintTaskExited(..) => {} } true } fn repaint_synchronously(&mut self) {} fn shutdown(&mut self) { // Drain compositor port, sometimes messages contain channels that are blocking // another task from finishing (i.e. SetIds) while self.port.try_recv_compositor_msg().is_some() {} self.time_profiler_chan.send(time::ProfilerMsg::Exit); self.mem_profiler_chan.send(mem::ProfilerMsg::Exit); } fn pinch_zoom_level(&self) -> f32 { 1.0 } fn get_title_for_main_frame(&self) {} }
{ match self.port.recv_compositor_msg() { Msg::Exit(chan) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; con_chan.send(ConstellationMsg::Exit).unwrap(); chan.send(()).unwrap(); } Msg::ShutdownComplete => { debug!("constellation completed shutdown"); return false } Msg::GetGraphicsMetadata(chan) => { chan.send(None).unwrap(); } Msg::SetFrameTree(_, response_chan, _) => { response_chan.send(()).unwrap();
identifier_body
headless.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 compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, WindowSizeData}; use profile::mem; use profile::time; /// Starts the compositor, which listens for messages on the specified port. /// /// This is the null compositor which doesn't draw anything to the screen. /// It's intended for headless testing. pub struct NullCompositor { /// The port on which we receive messages. pub port: Box<CompositorReceiver>, /// A channel to the constellation. constellation_chan: ConstellationChan, /// A channel to the time profiler. time_profiler_chan: time::ProfilerChan, /// A channel to the memory profiler. mem_profiler_chan: mem::ProfilerChan, } impl NullCompositor { fn new(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { NullCompositor { port: port, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, } } pub fn create(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { let compositor = NullCompositor::new(port, constellation_chan, time_profiler_chan, mem_profiler_chan); // Tell the constellation about the initial fake size. { let ConstellationChan(ref chan) = compositor.constellation_chan; chan.send(ConstellationMsg::ResizedWindow(WindowSizeData { initial_viewport: TypedSize2D(640_f32, 480_f32), visible_viewport: TypedSize2D(640_f32, 480_f32), device_pixel_ratio: ScaleFactor::new(1.0), })).unwrap(); } compositor } } impl CompositorEventListener for NullCompositor { fn handle_event(&mut self, _: WindowEvent) -> bool { match self.port.recv_compositor_msg() { Msg::Exit(chan) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; con_chan.send(ConstellationMsg::Exit).unwrap(); chan.send(()).unwrap(); } Msg::ShutdownComplete => { debug!("constellation completed shutdown"); return false } Msg::GetGraphicsMetadata(chan) => { chan.send(None).unwrap(); } Msg::SetFrameTree(_, response_chan, _) => { response_chan.send(()).unwrap(); } // Explicitly list ignored messages so that when we add a new one, // we'll notice and think about whether it needs a response, like // SetFrameTree. Msg::CreateOrUpdateBaseLayer(..) | Msg::CreateOrUpdateDescendantLayer(..) | Msg::SetLayerRect(..) | Msg::AssignPaintedBuffers(..) | Msg::ChangeReadyState(..) | Msg::ChangePaintState(..) | Msg::ChangeRunningAnimationsState(..) | Msg::ScrollFragmentPoint(..) | Msg::LoadComplete | Msg::PaintMsgDiscarded(..) | Msg::ScrollTimeout(..) | Msg::ChangePageTitle(..) | Msg::ChangePageUrl(..) | Msg::KeyEvent(..) | Msg::SetCursor(..) => {} Msg::PaintTaskExited(..) => {} } true } fn repaint_synchronously(&mut self) {} fn shutdown(&mut self) { // Drain compositor port, sometimes messages contain channels that are blocking // another task from finishing (i.e. SetIds) while self.port.try_recv_compositor_msg().is_some() {} self.time_profiler_chan.send(time::ProfilerMsg::Exit); self.mem_profiler_chan.send(mem::ProfilerMsg::Exit); } fn
(&self) -> f32 { 1.0 } fn get_title_for_main_frame(&self) {} }
pinch_zoom_level
identifier_name
headless.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 compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, WindowSizeData}; use profile::mem; use profile::time; /// Starts the compositor, which listens for messages on the specified port. /// /// This is the null compositor which doesn't draw anything to the screen. /// It's intended for headless testing. pub struct NullCompositor { /// The port on which we receive messages. pub port: Box<CompositorReceiver>, /// A channel to the constellation. constellation_chan: ConstellationChan, /// A channel to the time profiler. time_profiler_chan: time::ProfilerChan, /// A channel to the memory profiler. mem_profiler_chan: mem::ProfilerChan, } impl NullCompositor { fn new(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { NullCompositor { port: port, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, } } pub fn create(port: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan) -> NullCompositor { let compositor = NullCompositor::new(port, constellation_chan, time_profiler_chan, mem_profiler_chan); // Tell the constellation about the initial fake size. { let ConstellationChan(ref chan) = compositor.constellation_chan; chan.send(ConstellationMsg::ResizedWindow(WindowSizeData { initial_viewport: TypedSize2D(640_f32, 480_f32), visible_viewport: TypedSize2D(640_f32, 480_f32), device_pixel_ratio: ScaleFactor::new(1.0), })).unwrap(); } compositor } } impl CompositorEventListener for NullCompositor { fn handle_event(&mut self, _: WindowEvent) -> bool { match self.port.recv_compositor_msg() { Msg::Exit(chan) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; con_chan.send(ConstellationMsg::Exit).unwrap(); chan.send(()).unwrap(); } Msg::ShutdownComplete => { debug!("constellation completed shutdown"); return false } Msg::GetGraphicsMetadata(chan) => { chan.send(None).unwrap(); } Msg::SetFrameTree(_, response_chan, _) => { response_chan.send(()).unwrap(); } // Explicitly list ignored messages so that when we add a new one, // we'll notice and think about whether it needs a response, like // SetFrameTree.
Msg::CreateOrUpdateDescendantLayer(..) | Msg::SetLayerRect(..) | Msg::AssignPaintedBuffers(..) | Msg::ChangeReadyState(..) | Msg::ChangePaintState(..) | Msg::ChangeRunningAnimationsState(..) | Msg::ScrollFragmentPoint(..) | Msg::LoadComplete | Msg::PaintMsgDiscarded(..) | Msg::ScrollTimeout(..) | Msg::ChangePageTitle(..) | Msg::ChangePageUrl(..) | Msg::KeyEvent(..) | Msg::SetCursor(..) => {} Msg::PaintTaskExited(..) => {} } true } fn repaint_synchronously(&mut self) {} fn shutdown(&mut self) { // Drain compositor port, sometimes messages contain channels that are blocking // another task from finishing (i.e. SetIds) while self.port.try_recv_compositor_msg().is_some() {} self.time_profiler_chan.send(time::ProfilerMsg::Exit); self.mem_profiler_chan.send(mem::ProfilerMsg::Exit); } fn pinch_zoom_level(&self) -> f32 { 1.0 } fn get_title_for_main_frame(&self) {} }
Msg::CreateOrUpdateBaseLayer(..) |
random_line_split
registry.rs
use std::collections::HashSet; use std::collections::hash_map::HashMap; use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package}; use util::{CargoResult, ChainError, Config, human, profile}; /// Source of informations about a group of packages. /// /// See also `core::Source`. pub trait Registry { /// Attempt to find the packages that match a dependency request. fn query(&mut self, name: &Dependency) -> CargoResult<Vec<Summary>>; } impl Registry for Vec<Summary> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|summary| dep.matches(*summary)) .map(|summary| summary.clone()).collect()) } } /// This structure represents a registry of known packages. It internally /// contains a number of `Box<Source>` instances which are used to load a /// `Package` from. /// /// The resolution phase of Cargo uses this to drive knowledge about new /// packages as well as querying for lists of new packages. It is here that /// sources are updated and (e.g. network operations) as well as overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the map has been updated (using network /// operations if necessary) and is ready to be queried for packages. pub struct PackageRegistry<'a, 'b: 'a> { sources: SourceMap<'a>, config: &'a Config<'b>, // A list of sources which are considered "overrides" which take precedent // when querying for packages. overrides: Vec<SourceId>, // Note that each SourceId does not take into account its `precise` field // when hashing or testing for equality. When adding a new `SourceId`, we // want to avoid duplicates in the `SourceMap` (to prevent re-updating the // same git repo twice for example), but we also want to ensure that the // loaded source is always updated. // // Sources with a `precise` field normally don't need to be updated because // their contents are already on disk, but sources without a `precise` field // almost always need to be updated. If we have a cached `Source` for a // precise `SourceId`, then when we add a new `SourceId` that is not precise // we want to ensure that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>, } #[derive(PartialEq, Eq, Clone, Copy)] enum Kind { Override, Locked, Normal, } impl<'a, 'b> PackageRegistry<'a, 'b> { pub fn new(config: &'a Config<'b>) -> PackageRegistry<'a, 'b> { PackageRegistry { sources: SourceMap::new(), source_ids: HashMap::new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package ID if the package came from the // source let mut ret = Vec::new(); for (_, source) in self.sources.sources_mut() { try!(source.download(package_ids)); let packages = try!(source.get(package_ids)); ret.extend(packages.into_iter()); } // TODO: Return earlier if fail assert!(package_ids.len() == ret.len(), "could not get packages from registry; ids={:?}; ret={:?}", package_ids, ret); Ok(ret) } pub fn move_sources(self) -> SourceMap<'a> { self.sources } fn ensure_loaded(&mut self, namespace: &SourceId) -> CargoResult<()> { match self.source_ids.get(namespace) { // We've previously loaded this source, and we've already locked it, // so we're not allowed to change it even if `namespace` has a // slightly different precise version listed. Some(&(_, Kind::Locked)) => { debug!("load/locked {}", namespace); return Ok(()) } // If the previous source was not a precise source, then we can be // sure that it's already been updated if we've already loaded it. Some(&(ref previous, _)) if previous.precise().is_none() => { debug!("load/precise {}", namespace); return Ok(()) } // If the previous source has the same precise version as we do, // then we're done, otherwise we need to need to move forward // updating this source. Some(&(ref previous, _)) => { if previous.precise() == namespace.precise() { debug!("load/match {}", namespace); return Ok(()) } debug!("load/mismatch {}", namespace); } None => { debug!("load/missing {}", namespace); } } try!(self.load(namespace, Kind::Normal)); Ok(()) } pub fn add_sources(&mut self, ids: &[SourceId]) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Locked)); } Ok(()) } pub fn add_overrides(&mut self, ids: Vec<SourceId>) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Override)); } Ok(()) } pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) { let sub_map = self.locked.entry(id.source_id().clone()) .or_insert(HashMap::new()); let sub_vec = sub_map.entry(id.name().to_string()) .or_insert(Vec::new()); sub_vec.push((id, deps)); } fn load(&mut self, source_id: &SourceId, kind: Kind) -> CargoResult<()> { (|| { let mut source = source_id.load(self.config); // Ensure the source has fetched all necessary remote data. let p = profile::start(format!("updating: {}", source_id)); try!(source.update()); drop(p); if kind == Kind::Override { self.overrides.push(source_id.clone()); } // Save off the source self.sources.insert(source_id, source); self.source_ids.insert(source_id.clone(), (source_id.clone(), kind)); Ok(()) }).chain_error(|| human(format!("Unable to update {}", source_id))) } fn query_overrides(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let mut seen = HashSet::new(); let mut ret = Vec::new(); for s in self.overrides.iter() { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); ret.extend(try!(src.query(&dep)).into_iter().filter(|s| { seen.insert(s.name().to_string()) })); } Ok(ret) } // This function is used to transform a summary to another locked summary if // possible. This is where the the concept of a lockfile comes into play. // // If a summary points at a package id which was previously locked, then we // override the summary's id itself as well as all dependencies to be // rewritten to the locked versions. This will transform the summary's // source to a precise source (listed in the locked version) as well as // transforming all of the dependencies from range requirements on imprecise // sources to exact requirements on precise sources. // // If a summary does not point at a package id which was previously locked, // we still want to avoid updating as many dependencies as possible to keep // the graph stable. In this case we map all of the summary's dependencies // to be rewritten to a locked version wherever possible. If we're unable to // map a dependency though, we just pass it on through. fn lock(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let summary = match pair { Some(&(ref precise, _)) => summary.override_id(precise.clone()), None => summary, }; summary.map_dependencies(|dep| { match pair { // If we've got a known set of overrides for this summary, then // one of a few cases can arise: // // 1. We have a lock entry for this dependency from the same // source as its listed as coming from. In this case we make // sure to lock to precisely the given package id. // // 2. We have a lock entry for this dependency, but it's from a // different source than what's listed, or the version // requirement has changed. In this case we must discard the // locked version because the dependency needs to be // re-resolved. // // 3. We don't have a lock entry for this dependency, in which // case it was likely an optional dependency which wasn't // included previously so we just pass it through anyway. Some(&(_, ref deps)) => { match deps.iter().find(|d| d.name() == dep.name()) { Some(lock) => { if dep.matches_id(lock) { dep.lock_to(lock) } else { dep } } None => dep, } } // If this summary did not have a locked version, then we query // all known locked packages to see if they match this // dependency. If anything does then we lock it to that and move // on. None => { let v = self.locked.get(dep.source_id()).and_then(|map| { map.get(dep.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| dep.matches_id(id)) }); match v { Some(&(ref id, _)) => dep.lock_to(id), None => dep } } } }) } } impl<'a, 'b> Registry for PackageRegistry<'a, 'b> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let overrides = try!(self.query_overrides(dep)); let ret = if overrides.len() == 0 { // Ensure the requested source_id is loaded try!(self.ensure_loaded(dep.source_id())); let mut ret = Vec::new(); for (id, src) in self.sources.sources_mut() { if id == dep.source_id() { ret.extend(try!(src.query(dep)).into_iter()); } } ret } else { overrides }; // post-process all returned summaries to ensure that we lock all // relevant summaries to the right versions and sources Ok(ret.into_iter().map(|summary| self.lock(summary)).collect()) } } #[cfg(test)] pub mod test { use core::{Summary, Registry, Dependency}; use util::{CargoResult}; pub struct RegistryBuilder { summaries: Vec<Summary>, overrides: Vec<Summary> } impl RegistryBuilder { pub fn
() -> RegistryBuilder { RegistryBuilder { summaries: vec!(), overrides: vec!() } } pub fn summary(mut self, summary: Summary) -> RegistryBuilder { self.summaries.push(summary); self } pub fn summaries(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.summaries.extend(summaries.into_iter()); self } pub fn add_override(mut self, summary: Summary) -> RegistryBuilder { self.overrides.push(summary); self } pub fn overrides(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.overrides.extend(summaries.into_iter()); self } fn query_overrides(&self, dep: &Dependency) -> Vec<Summary> { self.overrides.iter() .filter(|s| s.name() == dep.name()) .map(|s| s.clone()) .collect() } } impl Registry for RegistryBuilder { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { debug!("querying; dep={:?}", dep); let overrides = self.query_overrides(dep); if overrides.is_empty() { self.summaries.query(dep) } else { Ok(overrides) } } } }
new
identifier_name
registry.rs
use std::collections::HashSet; use std::collections::hash_map::HashMap; use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package}; use util::{CargoResult, ChainError, Config, human, profile}; /// Source of informations about a group of packages. /// /// See also `core::Source`. pub trait Registry { /// Attempt to find the packages that match a dependency request. fn query(&mut self, name: &Dependency) -> CargoResult<Vec<Summary>>; } impl Registry for Vec<Summary> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|summary| dep.matches(*summary)) .map(|summary| summary.clone()).collect()) } } /// This structure represents a registry of known packages. It internally /// contains a number of `Box<Source>` instances which are used to load a /// `Package` from. /// /// The resolution phase of Cargo uses this to drive knowledge about new /// packages as well as querying for lists of new packages. It is here that /// sources are updated and (e.g. network operations) as well as overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the map has been updated (using network /// operations if necessary) and is ready to be queried for packages. pub struct PackageRegistry<'a, 'b: 'a> { sources: SourceMap<'a>, config: &'a Config<'b>, // A list of sources which are considered "overrides" which take precedent // when querying for packages. overrides: Vec<SourceId>, // Note that each SourceId does not take into account its `precise` field // when hashing or testing for equality. When adding a new `SourceId`, we // want to avoid duplicates in the `SourceMap` (to prevent re-updating the // same git repo twice for example), but we also want to ensure that the // loaded source is always updated. // // Sources with a `precise` field normally don't need to be updated because // their contents are already on disk, but sources without a `precise` field // almost always need to be updated. If we have a cached `Source` for a // precise `SourceId`, then when we add a new `SourceId` that is not precise // we want to ensure that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>, } #[derive(PartialEq, Eq, Clone, Copy)] enum Kind { Override, Locked, Normal, } impl<'a, 'b> PackageRegistry<'a, 'b> { pub fn new(config: &'a Config<'b>) -> PackageRegistry<'a, 'b> { PackageRegistry { sources: SourceMap::new(), source_ids: HashMap::new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package ID if the package came from the // source let mut ret = Vec::new(); for (_, source) in self.sources.sources_mut() { try!(source.download(package_ids)); let packages = try!(source.get(package_ids)); ret.extend(packages.into_iter()); } // TODO: Return earlier if fail assert!(package_ids.len() == ret.len(), "could not get packages from registry; ids={:?}; ret={:?}", package_ids, ret); Ok(ret) } pub fn move_sources(self) -> SourceMap<'a> { self.sources } fn ensure_loaded(&mut self, namespace: &SourceId) -> CargoResult<()> { match self.source_ids.get(namespace) { // We've previously loaded this source, and we've already locked it, // so we're not allowed to change it even if `namespace` has a // slightly different precise version listed. Some(&(_, Kind::Locked)) => { debug!("load/locked {}", namespace); return Ok(()) } // If the previous source was not a precise source, then we can be // sure that it's already been updated if we've already loaded it. Some(&(ref previous, _)) if previous.precise().is_none() => { debug!("load/precise {}", namespace); return Ok(()) } // If the previous source has the same precise version as we do, // then we're done, otherwise we need to need to move forward // updating this source. Some(&(ref previous, _)) => { if previous.precise() == namespace.precise() { debug!("load/match {}", namespace); return Ok(()) } debug!("load/mismatch {}", namespace); } None => { debug!("load/missing {}", namespace); } } try!(self.load(namespace, Kind::Normal)); Ok(()) } pub fn add_sources(&mut self, ids: &[SourceId]) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Locked)); } Ok(()) } pub fn add_overrides(&mut self, ids: Vec<SourceId>) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Override)); } Ok(()) } pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) { let sub_map = self.locked.entry(id.source_id().clone()) .or_insert(HashMap::new()); let sub_vec = sub_map.entry(id.name().to_string()) .or_insert(Vec::new()); sub_vec.push((id, deps)); } fn load(&mut self, source_id: &SourceId, kind: Kind) -> CargoResult<()> { (|| { let mut source = source_id.load(self.config); // Ensure the source has fetched all necessary remote data. let p = profile::start(format!("updating: {}", source_id)); try!(source.update()); drop(p); if kind == Kind::Override { self.overrides.push(source_id.clone()); } // Save off the source self.sources.insert(source_id, source); self.source_ids.insert(source_id.clone(), (source_id.clone(), kind)); Ok(()) }).chain_error(|| human(format!("Unable to update {}", source_id))) } fn query_overrides(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let mut seen = HashSet::new(); let mut ret = Vec::new(); for s in self.overrides.iter() { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); ret.extend(try!(src.query(&dep)).into_iter().filter(|s| { seen.insert(s.name().to_string()) })); } Ok(ret) } // This function is used to transform a summary to another locked summary if // possible. This is where the the concept of a lockfile comes into play. // // If a summary points at a package id which was previously locked, then we // override the summary's id itself as well as all dependencies to be // rewritten to the locked versions. This will transform the summary's // source to a precise source (listed in the locked version) as well as // transforming all of the dependencies from range requirements on imprecise // sources to exact requirements on precise sources. // // If a summary does not point at a package id which was previously locked, // we still want to avoid updating as many dependencies as possible to keep // the graph stable. In this case we map all of the summary's dependencies // to be rewritten to a locked version wherever possible. If we're unable to // map a dependency though, we just pass it on through. fn lock(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let summary = match pair { Some(&(ref precise, _)) => summary.override_id(precise.clone()), None => summary, }; summary.map_dependencies(|dep| { match pair { // If we've got a known set of overrides for this summary, then // one of a few cases can arise: // // 1. We have a lock entry for this dependency from the same // source as its listed as coming from. In this case we make // sure to lock to precisely the given package id. // // 2. We have a lock entry for this dependency, but it's from a // different source than what's listed, or the version // requirement has changed. In this case we must discard the // locked version because the dependency needs to be // re-resolved. // // 3. We don't have a lock entry for this dependency, in which // case it was likely an optional dependency which wasn't // included previously so we just pass it through anyway. Some(&(_, ref deps)) => { match deps.iter().find(|d| d.name() == dep.name()) { Some(lock) => { if dep.matches_id(lock) { dep.lock_to(lock) } else { dep } } None => dep, } } // If this summary did not have a locked version, then we query // all known locked packages to see if they match this // dependency. If anything does then we lock it to that and move // on. None => { let v = self.locked.get(dep.source_id()).and_then(|map| { map.get(dep.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| dep.matches_id(id)) }); match v { Some(&(ref id, _)) => dep.lock_to(id), None => dep } } } }) } } impl<'a, 'b> Registry for PackageRegistry<'a, 'b> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let overrides = try!(self.query_overrides(dep)); let ret = if overrides.len() == 0 {
if id == dep.source_id() { ret.extend(try!(src.query(dep)).into_iter()); } } ret } else { overrides }; // post-process all returned summaries to ensure that we lock all // relevant summaries to the right versions and sources Ok(ret.into_iter().map(|summary| self.lock(summary)).collect()) } } #[cfg(test)] pub mod test { use core::{Summary, Registry, Dependency}; use util::{CargoResult}; pub struct RegistryBuilder { summaries: Vec<Summary>, overrides: Vec<Summary> } impl RegistryBuilder { pub fn new() -> RegistryBuilder { RegistryBuilder { summaries: vec!(), overrides: vec!() } } pub fn summary(mut self, summary: Summary) -> RegistryBuilder { self.summaries.push(summary); self } pub fn summaries(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.summaries.extend(summaries.into_iter()); self } pub fn add_override(mut self, summary: Summary) -> RegistryBuilder { self.overrides.push(summary); self } pub fn overrides(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.overrides.extend(summaries.into_iter()); self } fn query_overrides(&self, dep: &Dependency) -> Vec<Summary> { self.overrides.iter() .filter(|s| s.name() == dep.name()) .map(|s| s.clone()) .collect() } } impl Registry for RegistryBuilder { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { debug!("querying; dep={:?}", dep); let overrides = self.query_overrides(dep); if overrides.is_empty() { self.summaries.query(dep) } else { Ok(overrides) } } } }
// Ensure the requested source_id is loaded try!(self.ensure_loaded(dep.source_id())); let mut ret = Vec::new(); for (id, src) in self.sources.sources_mut() {
random_line_split
registry.rs
use std::collections::HashSet; use std::collections::hash_map::HashMap; use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package}; use util::{CargoResult, ChainError, Config, human, profile}; /// Source of informations about a group of packages. /// /// See also `core::Source`. pub trait Registry { /// Attempt to find the packages that match a dependency request. fn query(&mut self, name: &Dependency) -> CargoResult<Vec<Summary>>; } impl Registry for Vec<Summary> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|summary| dep.matches(*summary)) .map(|summary| summary.clone()).collect()) } } /// This structure represents a registry of known packages. It internally /// contains a number of `Box<Source>` instances which are used to load a /// `Package` from. /// /// The resolution phase of Cargo uses this to drive knowledge about new /// packages as well as querying for lists of new packages. It is here that /// sources are updated and (e.g. network operations) as well as overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the map has been updated (using network /// operations if necessary) and is ready to be queried for packages. pub struct PackageRegistry<'a, 'b: 'a> { sources: SourceMap<'a>, config: &'a Config<'b>, // A list of sources which are considered "overrides" which take precedent // when querying for packages. overrides: Vec<SourceId>, // Note that each SourceId does not take into account its `precise` field // when hashing or testing for equality. When adding a new `SourceId`, we // want to avoid duplicates in the `SourceMap` (to prevent re-updating the // same git repo twice for example), but we also want to ensure that the // loaded source is always updated. // // Sources with a `precise` field normally don't need to be updated because // their contents are already on disk, but sources without a `precise` field // almost always need to be updated. If we have a cached `Source` for a // precise `SourceId`, then when we add a new `SourceId` that is not precise // we want to ensure that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>, } #[derive(PartialEq, Eq, Clone, Copy)] enum Kind { Override, Locked, Normal, } impl<'a, 'b> PackageRegistry<'a, 'b> { pub fn new(config: &'a Config<'b>) -> PackageRegistry<'a, 'b> { PackageRegistry { sources: SourceMap::new(), source_ids: HashMap::new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package ID if the package came from the // source let mut ret = Vec::new(); for (_, source) in self.sources.sources_mut() { try!(source.download(package_ids)); let packages = try!(source.get(package_ids)); ret.extend(packages.into_iter()); } // TODO: Return earlier if fail assert!(package_ids.len() == ret.len(), "could not get packages from registry; ids={:?}; ret={:?}", package_ids, ret); Ok(ret) } pub fn move_sources(self) -> SourceMap<'a> { self.sources } fn ensure_loaded(&mut self, namespace: &SourceId) -> CargoResult<()> { match self.source_ids.get(namespace) { // We've previously loaded this source, and we've already locked it, // so we're not allowed to change it even if `namespace` has a // slightly different precise version listed. Some(&(_, Kind::Locked)) => { debug!("load/locked {}", namespace); return Ok(()) } // If the previous source was not a precise source, then we can be // sure that it's already been updated if we've already loaded it. Some(&(ref previous, _)) if previous.precise().is_none() => { debug!("load/precise {}", namespace); return Ok(()) } // If the previous source has the same precise version as we do, // then we're done, otherwise we need to need to move forward // updating this source. Some(&(ref previous, _)) => { if previous.precise() == namespace.precise() { debug!("load/match {}", namespace); return Ok(()) } debug!("load/mismatch {}", namespace); } None => { debug!("load/missing {}", namespace); } } try!(self.load(namespace, Kind::Normal)); Ok(()) } pub fn add_sources(&mut self, ids: &[SourceId]) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Locked)); } Ok(()) } pub fn add_overrides(&mut self, ids: Vec<SourceId>) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Override)); } Ok(()) } pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) { let sub_map = self.locked.entry(id.source_id().clone()) .or_insert(HashMap::new()); let sub_vec = sub_map.entry(id.name().to_string()) .or_insert(Vec::new()); sub_vec.push((id, deps)); } fn load(&mut self, source_id: &SourceId, kind: Kind) -> CargoResult<()> { (|| { let mut source = source_id.load(self.config); // Ensure the source has fetched all necessary remote data. let p = profile::start(format!("updating: {}", source_id)); try!(source.update()); drop(p); if kind == Kind::Override { self.overrides.push(source_id.clone()); } // Save off the source self.sources.insert(source_id, source); self.source_ids.insert(source_id.clone(), (source_id.clone(), kind)); Ok(()) }).chain_error(|| human(format!("Unable to update {}", source_id))) } fn query_overrides(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let mut seen = HashSet::new(); let mut ret = Vec::new(); for s in self.overrides.iter() { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); ret.extend(try!(src.query(&dep)).into_iter().filter(|s| { seen.insert(s.name().to_string()) })); } Ok(ret) } // This function is used to transform a summary to another locked summary if // possible. This is where the the concept of a lockfile comes into play. // // If a summary points at a package id which was previously locked, then we // override the summary's id itself as well as all dependencies to be // rewritten to the locked versions. This will transform the summary's // source to a precise source (listed in the locked version) as well as // transforming all of the dependencies from range requirements on imprecise // sources to exact requirements on precise sources. // // If a summary does not point at a package id which was previously locked, // we still want to avoid updating as many dependencies as possible to keep // the graph stable. In this case we map all of the summary's dependencies // to be rewritten to a locked version wherever possible. If we're unable to // map a dependency though, we just pass it on through. fn lock(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let summary = match pair { Some(&(ref precise, _)) => summary.override_id(precise.clone()), None => summary, }; summary.map_dependencies(|dep| { match pair { // If we've got a known set of overrides for this summary, then // one of a few cases can arise: // // 1. We have a lock entry for this dependency from the same // source as its listed as coming from. In this case we make // sure to lock to precisely the given package id. // // 2. We have a lock entry for this dependency, but it's from a // different source than what's listed, or the version // requirement has changed. In this case we must discard the // locked version because the dependency needs to be // re-resolved. // // 3. We don't have a lock entry for this dependency, in which // case it was likely an optional dependency which wasn't // included previously so we just pass it through anyway. Some(&(_, ref deps)) => { match deps.iter().find(|d| d.name() == dep.name()) { Some(lock) => { if dep.matches_id(lock) { dep.lock_to(lock) } else { dep } } None => dep, } } // If this summary did not have a locked version, then we query // all known locked packages to see if they match this // dependency. If anything does then we lock it to that and move // on. None => { let v = self.locked.get(dep.source_id()).and_then(|map| { map.get(dep.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| dep.matches_id(id)) }); match v { Some(&(ref id, _)) => dep.lock_to(id), None => dep } } } }) } } impl<'a, 'b> Registry for PackageRegistry<'a, 'b> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let overrides = try!(self.query_overrides(dep)); let ret = if overrides.len() == 0 { // Ensure the requested source_id is loaded try!(self.ensure_loaded(dep.source_id())); let mut ret = Vec::new(); for (id, src) in self.sources.sources_mut() { if id == dep.source_id() { ret.extend(try!(src.query(dep)).into_iter()); } } ret } else { overrides }; // post-process all returned summaries to ensure that we lock all // relevant summaries to the right versions and sources Ok(ret.into_iter().map(|summary| self.lock(summary)).collect()) } } #[cfg(test)] pub mod test { use core::{Summary, Registry, Dependency}; use util::{CargoResult}; pub struct RegistryBuilder { summaries: Vec<Summary>, overrides: Vec<Summary> } impl RegistryBuilder { pub fn new() -> RegistryBuilder { RegistryBuilder { summaries: vec!(), overrides: vec!() } } pub fn summary(mut self, summary: Summary) -> RegistryBuilder { self.summaries.push(summary); self } pub fn summaries(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.summaries.extend(summaries.into_iter()); self } pub fn add_override(mut self, summary: Summary) -> RegistryBuilder { self.overrides.push(summary); self } pub fn overrides(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.overrides.extend(summaries.into_iter()); self } fn query_overrides(&self, dep: &Dependency) -> Vec<Summary> { self.overrides.iter() .filter(|s| s.name() == dep.name()) .map(|s| s.clone()) .collect() } } impl Registry for RegistryBuilder { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { debug!("querying; dep={:?}", dep); let overrides = self.query_overrides(dep); if overrides.is_empty() { self.summaries.query(dep) } else
} } }
{ Ok(overrides) }
conditional_block
registry.rs
use std::collections::HashSet; use std::collections::hash_map::HashMap; use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package}; use util::{CargoResult, ChainError, Config, human, profile}; /// Source of informations about a group of packages. /// /// See also `core::Source`. pub trait Registry { /// Attempt to find the packages that match a dependency request. fn query(&mut self, name: &Dependency) -> CargoResult<Vec<Summary>>; } impl Registry for Vec<Summary> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|summary| dep.matches(*summary)) .map(|summary| summary.clone()).collect()) } } /// This structure represents a registry of known packages. It internally /// contains a number of `Box<Source>` instances which are used to load a /// `Package` from. /// /// The resolution phase of Cargo uses this to drive knowledge about new /// packages as well as querying for lists of new packages. It is here that /// sources are updated and (e.g. network operations) as well as overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the map has been updated (using network /// operations if necessary) and is ready to be queried for packages. pub struct PackageRegistry<'a, 'b: 'a> { sources: SourceMap<'a>, config: &'a Config<'b>, // A list of sources which are considered "overrides" which take precedent // when querying for packages. overrides: Vec<SourceId>, // Note that each SourceId does not take into account its `precise` field // when hashing or testing for equality. When adding a new `SourceId`, we // want to avoid duplicates in the `SourceMap` (to prevent re-updating the // same git repo twice for example), but we also want to ensure that the // loaded source is always updated. // // Sources with a `precise` field normally don't need to be updated because // their contents are already on disk, but sources without a `precise` field // almost always need to be updated. If we have a cached `Source` for a // precise `SourceId`, then when we add a new `SourceId` that is not precise // we want to ensure that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>, } #[derive(PartialEq, Eq, Clone, Copy)] enum Kind { Override, Locked, Normal, } impl<'a, 'b> PackageRegistry<'a, 'b> { pub fn new(config: &'a Config<'b>) -> PackageRegistry<'a, 'b> { PackageRegistry { sources: SourceMap::new(), source_ids: HashMap::new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package ID if the package came from the // source let mut ret = Vec::new(); for (_, source) in self.sources.sources_mut() { try!(source.download(package_ids)); let packages = try!(source.get(package_ids)); ret.extend(packages.into_iter()); } // TODO: Return earlier if fail assert!(package_ids.len() == ret.len(), "could not get packages from registry; ids={:?}; ret={:?}", package_ids, ret); Ok(ret) } pub fn move_sources(self) -> SourceMap<'a> { self.sources } fn ensure_loaded(&mut self, namespace: &SourceId) -> CargoResult<()> { match self.source_ids.get(namespace) { // We've previously loaded this source, and we've already locked it, // so we're not allowed to change it even if `namespace` has a // slightly different precise version listed. Some(&(_, Kind::Locked)) => { debug!("load/locked {}", namespace); return Ok(()) } // If the previous source was not a precise source, then we can be // sure that it's already been updated if we've already loaded it. Some(&(ref previous, _)) if previous.precise().is_none() => { debug!("load/precise {}", namespace); return Ok(()) } // If the previous source has the same precise version as we do, // then we're done, otherwise we need to need to move forward // updating this source. Some(&(ref previous, _)) => { if previous.precise() == namespace.precise() { debug!("load/match {}", namespace); return Ok(()) } debug!("load/mismatch {}", namespace); } None => { debug!("load/missing {}", namespace); } } try!(self.load(namespace, Kind::Normal)); Ok(()) } pub fn add_sources(&mut self, ids: &[SourceId]) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Locked)); } Ok(()) } pub fn add_overrides(&mut self, ids: Vec<SourceId>) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Override)); } Ok(()) } pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) { let sub_map = self.locked.entry(id.source_id().clone()) .or_insert(HashMap::new()); let sub_vec = sub_map.entry(id.name().to_string()) .or_insert(Vec::new()); sub_vec.push((id, deps)); } fn load(&mut self, source_id: &SourceId, kind: Kind) -> CargoResult<()> { (|| { let mut source = source_id.load(self.config); // Ensure the source has fetched all necessary remote data. let p = profile::start(format!("updating: {}", source_id)); try!(source.update()); drop(p); if kind == Kind::Override { self.overrides.push(source_id.clone()); } // Save off the source self.sources.insert(source_id, source); self.source_ids.insert(source_id.clone(), (source_id.clone(), kind)); Ok(()) }).chain_error(|| human(format!("Unable to update {}", source_id))) } fn query_overrides(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let mut seen = HashSet::new(); let mut ret = Vec::new(); for s in self.overrides.iter() { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); ret.extend(try!(src.query(&dep)).into_iter().filter(|s| { seen.insert(s.name().to_string()) })); } Ok(ret) } // This function is used to transform a summary to another locked summary if // possible. This is where the the concept of a lockfile comes into play. // // If a summary points at a package id which was previously locked, then we // override the summary's id itself as well as all dependencies to be // rewritten to the locked versions. This will transform the summary's // source to a precise source (listed in the locked version) as well as // transforming all of the dependencies from range requirements on imprecise // sources to exact requirements on precise sources. // // If a summary does not point at a package id which was previously locked, // we still want to avoid updating as many dependencies as possible to keep // the graph stable. In this case we map all of the summary's dependencies // to be rewritten to a locked version wherever possible. If we're unable to // map a dependency though, we just pass it on through. fn lock(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let summary = match pair { Some(&(ref precise, _)) => summary.override_id(precise.clone()), None => summary, }; summary.map_dependencies(|dep| { match pair { // If we've got a known set of overrides for this summary, then // one of a few cases can arise: // // 1. We have a lock entry for this dependency from the same // source as its listed as coming from. In this case we make // sure to lock to precisely the given package id. // // 2. We have a lock entry for this dependency, but it's from a // different source than what's listed, or the version // requirement has changed. In this case we must discard the // locked version because the dependency needs to be // re-resolved. // // 3. We don't have a lock entry for this dependency, in which // case it was likely an optional dependency which wasn't // included previously so we just pass it through anyway. Some(&(_, ref deps)) => { match deps.iter().find(|d| d.name() == dep.name()) { Some(lock) => { if dep.matches_id(lock) { dep.lock_to(lock) } else { dep } } None => dep, } } // If this summary did not have a locked version, then we query // all known locked packages to see if they match this // dependency. If anything does then we lock it to that and move // on. None => { let v = self.locked.get(dep.source_id()).and_then(|map| { map.get(dep.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| dep.matches_id(id)) }); match v { Some(&(ref id, _)) => dep.lock_to(id), None => dep } } } }) } } impl<'a, 'b> Registry for PackageRegistry<'a, 'b> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>>
} } #[cfg(test)] pub mod test { use core::{Summary, Registry, Dependency}; use util::{CargoResult}; pub struct RegistryBuilder { summaries: Vec<Summary>, overrides: Vec<Summary> } impl RegistryBuilder { pub fn new() -> RegistryBuilder { RegistryBuilder { summaries: vec!(), overrides: vec!() } } pub fn summary(mut self, summary: Summary) -> RegistryBuilder { self.summaries.push(summary); self } pub fn summaries(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.summaries.extend(summaries.into_iter()); self } pub fn add_override(mut self, summary: Summary) -> RegistryBuilder { self.overrides.push(summary); self } pub fn overrides(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.overrides.extend(summaries.into_iter()); self } fn query_overrides(&self, dep: &Dependency) -> Vec<Summary> { self.overrides.iter() .filter(|s| s.name() == dep.name()) .map(|s| s.clone()) .collect() } } impl Registry for RegistryBuilder { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { debug!("querying; dep={:?}", dep); let overrides = self.query_overrides(dep); if overrides.is_empty() { self.summaries.query(dep) } else { Ok(overrides) } } } }
{ let overrides = try!(self.query_overrides(dep)); let ret = if overrides.len() == 0 { // Ensure the requested source_id is loaded try!(self.ensure_loaded(dep.source_id())); let mut ret = Vec::new(); for (id, src) in self.sources.sources_mut() { if id == dep.source_id() { ret.extend(try!(src.query(dep)).into_iter()); } } ret } else { overrides }; // post-process all returned summaries to ensure that we lock all // relevant summaries to the right versions and sources Ok(ret.into_iter().map(|summary| self.lock(summary)).collect())
identifier_body
accept.rs
// error-pattern:Worked! extern crate nemo; use nemo::*; use nemo::session_types::*; use nemo::peano::*; fn main() { use nemo::channels::Blocking; struct MyProtocol; type SendString = Send<String, End>; type SendUsize = Send<usize, End>; type SendIsize = Send<isize, End>; type Orig = Choose<SendString, Choose<SendUsize, Finally<SendIsize>>>; type DualSendString = Recv<String, End>; type DualSendUsize = Recv<usize, End>; type DualSendIsize = Recv<isize, End>; type DualOrig = Accept<DualSendString, Accept<DualSendUsize, Finally<DualSendIsize>>>; impl Protocol for MyProtocol { type Initial = Orig; } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, Orig> for MyProtocol { fn with(this: Channel<Self, I, E, Orig>) -> Defer<Self, I> { this.choose::<SendIsize>().send(10).close() } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualOrig> for MyProtocol { fn with(this: Channel<Self, I, E, DualOrig>) -> Defer<Self, I>
} impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendString> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendString>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendUsize> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendUsize>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendIsize> for MyProtocol { fn with(this: Channel<Self, I, E, DualSendIsize>) -> Defer<Self, I> { match this.recv() { Ok((msg, sess)) => { if msg == 10 { panic!("Worked!"); } sess.close() }, Err(_) => { panic!("fail") } } } } let (client1, client2) = Blocking::new::<MyProtocol>(MyProtocol, MyProtocol); let mut client1 = client1.defer(); let mut client2 = client2.defer(); assert_eq!(false, client1.with()); // client1 chooses a protocol, sends 10, closes channel assert_eq!(true, client2.with()); // client2 accepts the protocol, defers assert_eq!(false, client2.with()); // client2 receives the isize, asserts it's 10, closes channel }
{ this.accept().ok().unwrap() }
identifier_body
accept.rs
// error-pattern:Worked! extern crate nemo; use nemo::*; use nemo::session_types::*; use nemo::peano::*; fn
() { use nemo::channels::Blocking; struct MyProtocol; type SendString = Send<String, End>; type SendUsize = Send<usize, End>; type SendIsize = Send<isize, End>; type Orig = Choose<SendString, Choose<SendUsize, Finally<SendIsize>>>; type DualSendString = Recv<String, End>; type DualSendUsize = Recv<usize, End>; type DualSendIsize = Recv<isize, End>; type DualOrig = Accept<DualSendString, Accept<DualSendUsize, Finally<DualSendIsize>>>; impl Protocol for MyProtocol { type Initial = Orig; } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, Orig> for MyProtocol { fn with(this: Channel<Self, I, E, Orig>) -> Defer<Self, I> { this.choose::<SendIsize>().send(10).close() } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualOrig> for MyProtocol { fn with(this: Channel<Self, I, E, DualOrig>) -> Defer<Self, I> { this.accept().ok().unwrap() } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendString> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendString>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendUsize> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendUsize>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendIsize> for MyProtocol { fn with(this: Channel<Self, I, E, DualSendIsize>) -> Defer<Self, I> { match this.recv() { Ok((msg, sess)) => { if msg == 10 { panic!("Worked!"); } sess.close() }, Err(_) => { panic!("fail") } } } } let (client1, client2) = Blocking::new::<MyProtocol>(MyProtocol, MyProtocol); let mut client1 = client1.defer(); let mut client2 = client2.defer(); assert_eq!(false, client1.with()); // client1 chooses a protocol, sends 10, closes channel assert_eq!(true, client2.with()); // client2 accepts the protocol, defers assert_eq!(false, client2.with()); // client2 receives the isize, asserts it's 10, closes channel }
main
identifier_name
accept.rs
// error-pattern:Worked! extern crate nemo; use nemo::*;
fn main() { use nemo::channels::Blocking; struct MyProtocol; type SendString = Send<String, End>; type SendUsize = Send<usize, End>; type SendIsize = Send<isize, End>; type Orig = Choose<SendString, Choose<SendUsize, Finally<SendIsize>>>; type DualSendString = Recv<String, End>; type DualSendUsize = Recv<usize, End>; type DualSendIsize = Recv<isize, End>; type DualOrig = Accept<DualSendString, Accept<DualSendUsize, Finally<DualSendIsize>>>; impl Protocol for MyProtocol { type Initial = Orig; } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, Orig> for MyProtocol { fn with(this: Channel<Self, I, E, Orig>) -> Defer<Self, I> { this.choose::<SendIsize>().send(10).close() } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualOrig> for MyProtocol { fn with(this: Channel<Self, I, E, DualOrig>) -> Defer<Self, I> { this.accept().ok().unwrap() } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendString> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendString>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendUsize> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendUsize>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendIsize> for MyProtocol { fn with(this: Channel<Self, I, E, DualSendIsize>) -> Defer<Self, I> { match this.recv() { Ok((msg, sess)) => { if msg == 10 { panic!("Worked!"); } sess.close() }, Err(_) => { panic!("fail") } } } } let (client1, client2) = Blocking::new::<MyProtocol>(MyProtocol, MyProtocol); let mut client1 = client1.defer(); let mut client2 = client2.defer(); assert_eq!(false, client1.with()); // client1 chooses a protocol, sends 10, closes channel assert_eq!(true, client2.with()); // client2 accepts the protocol, defers assert_eq!(false, client2.with()); // client2 receives the isize, asserts it's 10, closes channel }
use nemo::session_types::*; use nemo::peano::*;
random_line_split
accept.rs
// error-pattern:Worked! extern crate nemo; use nemo::*; use nemo::session_types::*; use nemo::peano::*; fn main() { use nemo::channels::Blocking; struct MyProtocol; type SendString = Send<String, End>; type SendUsize = Send<usize, End>; type SendIsize = Send<isize, End>; type Orig = Choose<SendString, Choose<SendUsize, Finally<SendIsize>>>; type DualSendString = Recv<String, End>; type DualSendUsize = Recv<usize, End>; type DualSendIsize = Recv<isize, End>; type DualOrig = Accept<DualSendString, Accept<DualSendUsize, Finally<DualSendIsize>>>; impl Protocol for MyProtocol { type Initial = Orig; } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, Orig> for MyProtocol { fn with(this: Channel<Self, I, E, Orig>) -> Defer<Self, I> { this.choose::<SendIsize>().send(10).close() } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualOrig> for MyProtocol { fn with(this: Channel<Self, I, E, DualOrig>) -> Defer<Self, I> { this.accept().ok().unwrap() } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendString> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendString>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendUsize> for MyProtocol { fn with(_: Channel<Self, I, E, DualSendUsize>) -> Defer<Self, I> { panic!("fail") } } impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendIsize> for MyProtocol { fn with(this: Channel<Self, I, E, DualSendIsize>) -> Defer<Self, I> { match this.recv() { Ok((msg, sess)) => { if msg == 10 { panic!("Worked!"); } sess.close() }, Err(_) =>
} } } let (client1, client2) = Blocking::new::<MyProtocol>(MyProtocol, MyProtocol); let mut client1 = client1.defer(); let mut client2 = client2.defer(); assert_eq!(false, client1.with()); // client1 chooses a protocol, sends 10, closes channel assert_eq!(true, client2.with()); // client2 accepts the protocol, defers assert_eq!(false, client2.with()); // client2 receives the isize, asserts it's 10, closes channel }
{ panic!("fail") }
conditional_block
fast_thread_local.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] use cell::{Cell, UnsafeCell}; use mem; use ptr; pub struct Key<T> { inner: UnsafeCell<Option<T>>, // Metadata to keep track of the state of the destructor. Remember that // these variables are thread-local, not global. dtor_registered: Cell<bool>, dtor_running: Cell<bool>, } unsafe impl<T> ::marker::Sync for Key<T> { } impl<T> Key<T> { pub const fn new() -> Key<T> { Key { inner: UnsafeCell::new(None), dtor_registered: Cell::new(false), dtor_running: Cell::new(false) } } pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> { unsafe { if mem::needs_drop::<T>() && self.dtor_running.get() { return None } self.register_dtor(); } Some(&self.inner) } unsafe fn register_dtor(&self) { if!mem::needs_drop::<T>() || self.dtor_registered.get() { return } register_dtor(self as *const _ as *mut u8, destroy_value::<T>); self.dtor_registered.set(true); } } pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. // // The destructor for DTORS is a little special in that it has a `while` // loop to continuously drain the list of registered destructors. It // *should* be the case that this loop always terminates because we // provide the guarantee that a TLS key cannot be set after it is // flagged for destruction. use sys_common::thread_local as os; static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors)); type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; if DTORS.get().is_null() { let v: Box<List> = box Vec::new(); DTORS.set(Box::into_raw(v) as *mut u8); } let list: &mut List = &mut *(DTORS.get() as *mut List); list.push((t, dtor)); unsafe extern fn
(mut ptr: *mut u8) { while!ptr.is_null() { let list: Box<List> = Box::from_raw(ptr as *mut List); for (ptr, dtor) in list.into_iter() { dtor(ptr); } ptr = DTORS.get(); DTORS.set(ptr::null_mut()); } } } pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { let ptr = ptr as *mut Key<T>; // Right before we run the user destructor be sure to flag the // destructor as running for this thread so calls to `get` will return // `None`. (*ptr).dtor_running.set(true); // The macOS implementation of TLS apparently had an odd aspect to it // where the pointer we have may be overwritten while this destructor // is running. Specifically if a TLS destructor re-accesses TLS it may // trigger a re-initialization of all TLS variables, paving over at // least some destroyed ones with initial values. // // This means that if we drop a TLS value in place on macOS that we could // revert the value to its original state halfway through the // destructor, which would be bad! // // Hence, we use `ptr::read` on macOS (to move to a "safe" location) // instead of drop_in_place. if cfg!(target_os = "macos") { ptr::read((*ptr).inner.get()); } else { ptr::drop_in_place((*ptr).inner.get()); } } pub fn requires_move_before_drop() -> bool { false }
run_dtors
identifier_name
fast_thread_local.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] use cell::{Cell, UnsafeCell}; use mem; use ptr; pub struct Key<T> { inner: UnsafeCell<Option<T>>, // Metadata to keep track of the state of the destructor. Remember that // these variables are thread-local, not global. dtor_registered: Cell<bool>, dtor_running: Cell<bool>, } unsafe impl<T> ::marker::Sync for Key<T> { } impl<T> Key<T> { pub const fn new() -> Key<T> { Key { inner: UnsafeCell::new(None), dtor_registered: Cell::new(false), dtor_running: Cell::new(false) } } pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> { unsafe { if mem::needs_drop::<T>() && self.dtor_running.get() { return None } self.register_dtor(); } Some(&self.inner) } unsafe fn register_dtor(&self) { if!mem::needs_drop::<T>() || self.dtor_registered.get() { return } register_dtor(self as *const _ as *mut u8, destroy_value::<T>); self.dtor_registered.set(true); } } pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. // // The destructor for DTORS is a little special in that it has a `while` // loop to continuously drain the list of registered destructors. It // *should* be the case that this loop always terminates because we // provide the guarantee that a TLS key cannot be set after it is // flagged for destruction. use sys_common::thread_local as os; static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors)); type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; if DTORS.get().is_null() { let v: Box<List> = box Vec::new(); DTORS.set(Box::into_raw(v) as *mut u8); } let list: &mut List = &mut *(DTORS.get() as *mut List); list.push((t, dtor)); unsafe extern fn run_dtors(mut ptr: *mut u8) { while!ptr.is_null() { let list: Box<List> = Box::from_raw(ptr as *mut List); for (ptr, dtor) in list.into_iter() { dtor(ptr); } ptr = DTORS.get(); DTORS.set(ptr::null_mut()); } } } pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { let ptr = ptr as *mut Key<T>; // Right before we run the user destructor be sure to flag the // destructor as running for this thread so calls to `get` will return // `None`. (*ptr).dtor_running.set(true); // The macOS implementation of TLS apparently had an odd aspect to it // where the pointer we have may be overwritten while this destructor // is running. Specifically if a TLS destructor re-accesses TLS it may // trigger a re-initialization of all TLS variables, paving over at // least some destroyed ones with initial values. // // This means that if we drop a TLS value in place on macOS that we could // revert the value to its original state halfway through the // destructor, which would be bad! // // Hence, we use `ptr::read` on macOS (to move to a "safe" location) // instead of drop_in_place. if cfg!(target_os = "macos") { ptr::read((*ptr).inner.get()); } else
} pub fn requires_move_before_drop() -> bool { false }
{ ptr::drop_in_place((*ptr).inner.get()); }
conditional_block
fast_thread_local.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] use cell::{Cell, UnsafeCell}; use mem; use ptr; pub struct Key<T> { inner: UnsafeCell<Option<T>>, // Metadata to keep track of the state of the destructor. Remember that // these variables are thread-local, not global. dtor_registered: Cell<bool>, dtor_running: Cell<bool>, } unsafe impl<T> ::marker::Sync for Key<T> { } impl<T> Key<T> { pub const fn new() -> Key<T> { Key { inner: UnsafeCell::new(None), dtor_registered: Cell::new(false), dtor_running: Cell::new(false) } } pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> { unsafe { if mem::needs_drop::<T>() && self.dtor_running.get() { return None } self.register_dtor(); } Some(&self.inner) } unsafe fn register_dtor(&self)
} pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. // // The destructor for DTORS is a little special in that it has a `while` // loop to continuously drain the list of registered destructors. It // *should* be the case that this loop always terminates because we // provide the guarantee that a TLS key cannot be set after it is // flagged for destruction. use sys_common::thread_local as os; static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors)); type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; if DTORS.get().is_null() { let v: Box<List> = box Vec::new(); DTORS.set(Box::into_raw(v) as *mut u8); } let list: &mut List = &mut *(DTORS.get() as *mut List); list.push((t, dtor)); unsafe extern fn run_dtors(mut ptr: *mut u8) { while!ptr.is_null() { let list: Box<List> = Box::from_raw(ptr as *mut List); for (ptr, dtor) in list.into_iter() { dtor(ptr); } ptr = DTORS.get(); DTORS.set(ptr::null_mut()); } } } pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { let ptr = ptr as *mut Key<T>; // Right before we run the user destructor be sure to flag the // destructor as running for this thread so calls to `get` will return // `None`. (*ptr).dtor_running.set(true); // The macOS implementation of TLS apparently had an odd aspect to it // where the pointer we have may be overwritten while this destructor // is running. Specifically if a TLS destructor re-accesses TLS it may // trigger a re-initialization of all TLS variables, paving over at // least some destroyed ones with initial values. // // This means that if we drop a TLS value in place on macOS that we could // revert the value to its original state halfway through the // destructor, which would be bad! // // Hence, we use `ptr::read` on macOS (to move to a "safe" location) // instead of drop_in_place. if cfg!(target_os = "macos") { ptr::read((*ptr).inner.get()); } else { ptr::drop_in_place((*ptr).inner.get()); } } pub fn requires_move_before_drop() -> bool { false }
{ if !mem::needs_drop::<T>() || self.dtor_registered.get() { return } register_dtor(self as *const _ as *mut u8, destroy_value::<T>); self.dtor_registered.set(true); }
identifier_body
fast_thread_local.rs
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] use cell::{Cell, UnsafeCell}; use mem; use ptr; pub struct Key<T> { inner: UnsafeCell<Option<T>>, // Metadata to keep track of the state of the destructor. Remember that // these variables are thread-local, not global. dtor_registered: Cell<bool>, dtor_running: Cell<bool>, } unsafe impl<T> ::marker::Sync for Key<T> { } impl<T> Key<T> { pub const fn new() -> Key<T> { Key { inner: UnsafeCell::new(None), dtor_registered: Cell::new(false), dtor_running: Cell::new(false) } } pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> { unsafe { if mem::needs_drop::<T>() && self.dtor_running.get() { return None } self.register_dtor(); } Some(&self.inner) } unsafe fn register_dtor(&self) { if!mem::needs_drop::<T>() || self.dtor_registered.get() { return } register_dtor(self as *const _ as *mut u8, destroy_value::<T>); self.dtor_registered.set(true); } } pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. // // The destructor for DTORS is a little special in that it has a `while` // loop to continuously drain the list of registered destructors. It // *should* be the case that this loop always terminates because we // provide the guarantee that a TLS key cannot be set after it is // flagged for destruction. use sys_common::thread_local as os; static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors)); type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; if DTORS.get().is_null() { let v: Box<List> = box Vec::new(); DTORS.set(Box::into_raw(v) as *mut u8); } let list: &mut List = &mut *(DTORS.get() as *mut List); list.push((t, dtor)); unsafe extern fn run_dtors(mut ptr: *mut u8) { while!ptr.is_null() { let list: Box<List> = Box::from_raw(ptr as *mut List); for (ptr, dtor) in list.into_iter() { dtor(ptr); } ptr = DTORS.get(); DTORS.set(ptr::null_mut()); } } } pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { let ptr = ptr as *mut Key<T>; // Right before we run the user destructor be sure to flag the // destructor as running for this thread so calls to `get` will return // `None`. (*ptr).dtor_running.set(true); // The macOS implementation of TLS apparently had an odd aspect to it // where the pointer we have may be overwritten while this destructor // is running. Specifically if a TLS destructor re-accesses TLS it may // trigger a re-initialization of all TLS variables, paving over at // least some destroyed ones with initial values. // // This means that if we drop a TLS value in place on macOS that we could // revert the value to its original state halfway through the // destructor, which would be bad! // // Hence, we use `ptr::read` on macOS (to move to a "safe" location) // instead of drop_in_place. if cfg!(target_os = "macos") { ptr::read((*ptr).inner.get()); } else { ptr::drop_in_place((*ptr).inner.get()); } } pub fn requires_move_before_drop() -> bool { false }
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
random_line_split
word_splitters.rs
//! Word splitting functionality. //! //! To wrap text into lines, long words sometimes need to be split //! across lines. The [`WordSplitter`] enum defines this //! functionality. use crate::core::{display_width, Word}; /// The `WordSplitter` enum describes where words can be split. /// /// If the textwrap crate has been compiled with the `hyphenation` /// Cargo feature enabled, you will find a /// [`WordSplitter::Hyphenation`] variant. Use this struct for /// language-aware hyphenation: /// /// ``` /// #[cfg(feature = "hyphenation")] { /// use hyphenation::{Language, Load, Standard}; /// use textwrap::{wrap, Options, WordSplitter}; /// /// let text = "Oxidation is the loss of electrons."; /// let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); /// let options = Options::new(8).word_splitter(WordSplitter::Hyphenation(dictionary)); /// assert_eq!(wrap(text, &options), vec!["Oxida-", /// "tion is", /// "the loss", /// "of elec-", /// "trons."]); /// } /// ``` /// /// Please see the documentation for the [hyphenation] crate for more /// details. /// /// [hyphenation]: https://docs.rs/hyphenation/ #[derive(Clone)] pub enum WordSplitter { /// Use this as a [`Options.word_splitter`] to avoid any kind of /// hyphenation: /// /// ``` /// use textwrap::{wrap, Options, WordSplitter}; /// /// let options = Options::new(8).word_splitter(WordSplitter::NoHyphenation); /// assert_eq!(wrap("foo bar-baz", &options), /// vec!["foo", "bar-baz"]); /// ``` /// /// [`Options.word_splitter`]: super::Options::word_splitter NoHyphenation, /// `HyphenSplitter` is the default `WordSplitter` used by /// [`Options::new`](super::Options::new). It will split words on /// existing hyphens in the word. /// /// It will only use hyphens that are surrounded by alphanumeric /// characters, which prevents a word like `"--foo-bar"` from /// being split into `"--"` and `"foo-bar"`. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// /// assert_eq!(WordSplitter::HyphenSplitter.split_points("--foo-bar"), /// vec![6]); /// ``` HyphenSplitter, /// Use a custom function as the word splitter. /// /// This varian lets you implement a custom word splitter using /// your own function. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// /// fn split_at_underscore(word: &str) -> Vec<usize> { /// word.match_indices('_').map(|(idx, _)| idx + 1).collect() /// } /// /// let word_splitter = WordSplitter::Custom(split_at_underscore); /// assert_eq!(word_splitter.split_points("a_long_identifier"), /// vec![2, 7]); /// ``` Custom(fn(word: &str) -> Vec<usize>), /// A hyphenation dictionary can be used to do language-specific /// hyphenation using patterns from the [hyphenation] crate. /// /// **Note:** Only available when the `hyphenation` Cargo feature is /// enabled. /// /// [hyphenation]: https://docs.rs/hyphenation/ #[cfg(feature = "hyphenation")] Hyphenation(hyphenation::Standard), } impl std::fmt::Debug for WordSplitter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { WordSplitter::NoHyphenation => f.write_str("NoHyphenation"), WordSplitter::HyphenSplitter => f.write_str("HyphenSplitter"), WordSplitter::Custom(_) => f.write_str("Custom(...)"), #[cfg(feature = "hyphenation")] WordSplitter::Hyphenation(dict) => write!(f, "Hyphenation({})", dict.language()), } } } impl PartialEq<WordSplitter> for WordSplitter { fn eq(&self, other: &WordSplitter) -> bool { match (self, other) { (WordSplitter::NoHyphenation, WordSplitter::NoHyphenation) => true, (WordSplitter::HyphenSplitter, WordSplitter::HyphenSplitter) => true, #[cfg(feature = "hyphenation")] (WordSplitter::Hyphenation(this_dict), WordSplitter::Hyphenation(other_dict)) => { this_dict.language() == other_dict.language() } (_, _) => false, } } } impl WordSplitter { /// Return all possible indices where `word` can be split. /// /// The indices are in the range `0..word.len()`. They point to /// the index _after_ the split point, i.e., after `-` if /// splitting on hyphens. This way, `word.split_at(idx)` will /// break the word into two well-formed pieces. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// assert_eq!(WordSplitter::NoHyphenation.split_points("cannot-be-split"), vec![]); /// assert_eq!(WordSplitter::HyphenSplitter.split_points("can-be-split"), vec![4, 7]); /// assert_eq!(WordSplitter::Custom(|word| vec![word.len()/2]).split_points("middle"), vec![3]); /// ``` pub fn
(&self, word: &str) -> Vec<usize> { match self { WordSplitter::NoHyphenation => Vec::new(), WordSplitter::HyphenSplitter => { let mut splits = Vec::new(); for (idx, _) in word.match_indices('-') { // We only use hyphens that are surrounded by alphanumeric // characters. This is to avoid splitting on repeated hyphens, // such as those found in --foo-bar. let prev = word[..idx].chars().next_back(); let next = word[idx + 1..].chars().next(); if prev.filter(|ch| ch.is_alphanumeric()).is_some() && next.filter(|ch| ch.is_alphanumeric()).is_some() { splits.push(idx + 1); // +1 due to width of '-'. } } splits } WordSplitter::Custom(splitter_func) => splitter_func(word), #[cfg(feature = "hyphenation")] WordSplitter::Hyphenation(dictionary) => { use hyphenation::Hyphenator; dictionary.hyphenate(word).breaks } } } } /// Split words into smaller words according to the split points given /// by `word_splitter`. /// /// Note that we split all words, regardless of their length. This is /// to more cleanly separate the business of splitting (including /// automatic hyphenation) from the business of word wrapping. pub fn split_words<'a, I>( words: I, word_splitter: &'a WordSplitter, ) -> impl Iterator<Item = Word<'a>> where I: IntoIterator<Item = Word<'a>>, { words.into_iter().flat_map(move |word| { let mut prev = 0; let mut split_points = word_splitter.split_points(&word).into_iter(); std::iter::from_fn(move || { if let Some(idx) = split_points.next() { let need_hyphen =!word[..idx].ends_with('-'); let w = Word { word: &word.word[prev..idx], width: display_width(&word[prev..idx]), whitespace: "", penalty: if need_hyphen { "-" } else { "" }, }; prev = idx; return Some(w); } if prev < word.word.len() || prev == 0 { let w = Word { word: &word.word[prev..], width: display_width(&word[prev..]), whitespace: word.whitespace, penalty: word.penalty, }; prev = word.word.len() + 1; return Some(w); } None }) }) } #[cfg(test)] mod tests { use super::*; // Like assert_eq!, but the left expression is an iterator. macro_rules! assert_iter_eq { ($left:expr, $right:expr) => { assert_eq!($left.collect::<Vec<_>>(), $right); }; } #[test] fn split_words_no_words() { assert_iter_eq!(split_words(vec![], &WordSplitter::HyphenSplitter), vec![]); } #[test] fn split_words_empty_word() { assert_iter_eq!( split_words(vec![Word::from(" ")], &WordSplitter::HyphenSplitter), vec![Word::from(" ")] ); } #[test] fn split_words_single_word() { assert_iter_eq!( split_words(vec![Word::from("foobar")], &WordSplitter::HyphenSplitter), vec![Word::from("foobar")] ); } #[test] fn split_words_hyphen_splitter() { assert_iter_eq!( split_words(vec![Word::from("foo-bar")], &WordSplitter::HyphenSplitter), vec![Word::from("foo-"), Word::from("bar")] ); } #[test] fn split_words_no_hyphenation() { assert_iter_eq!( split_words(vec![Word::from("foo-bar")], &WordSplitter::NoHyphenation), vec![Word::from("foo-bar")] ); } #[test] fn split_words_adds_penalty() { let fixed_split_point = |_: &str| vec![3]; assert_iter_eq!( split_words( vec![Word::from("foobar")].into_iter(), &WordSplitter::Custom(fixed_split_point) ), vec![ Word { word: "foo", width: 3, whitespace: "", penalty: "-" }, Word { word: "bar", width: 3, whitespace: "", penalty: "" } ] ); assert_iter_eq!( split_words( vec![Word::from("fo-bar")].into_iter(), &WordSplitter::Custom(fixed_split_point) ), vec![ Word { word: "fo-", width: 3, whitespace: "", penalty: "" }, Word { word: "bar", width: 3, whitespace: "", penalty: "" } ] ); } }
split_points
identifier_name
word_splitters.rs
//! Word splitting functionality. //! //! To wrap text into lines, long words sometimes need to be split //! across lines. The [`WordSplitter`] enum defines this //! functionality. use crate::core::{display_width, Word}; /// The `WordSplitter` enum describes where words can be split. /// /// If the textwrap crate has been compiled with the `hyphenation` /// Cargo feature enabled, you will find a /// [`WordSplitter::Hyphenation`] variant. Use this struct for /// language-aware hyphenation: /// /// ``` /// #[cfg(feature = "hyphenation")] { /// use hyphenation::{Language, Load, Standard}; /// use textwrap::{wrap, Options, WordSplitter}; /// /// let text = "Oxidation is the loss of electrons."; /// let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); /// let options = Options::new(8).word_splitter(WordSplitter::Hyphenation(dictionary)); /// assert_eq!(wrap(text, &options), vec!["Oxida-", /// "tion is", /// "the loss", /// "of elec-", /// "trons."]); /// } /// ``` /// /// Please see the documentation for the [hyphenation] crate for more /// details. /// /// [hyphenation]: https://docs.rs/hyphenation/ #[derive(Clone)] pub enum WordSplitter { /// Use this as a [`Options.word_splitter`] to avoid any kind of /// hyphenation: /// /// ``` /// use textwrap::{wrap, Options, WordSplitter}; /// /// let options = Options::new(8).word_splitter(WordSplitter::NoHyphenation); /// assert_eq!(wrap("foo bar-baz", &options), /// vec!["foo", "bar-baz"]); /// ``` /// /// [`Options.word_splitter`]: super::Options::word_splitter NoHyphenation, /// `HyphenSplitter` is the default `WordSplitter` used by /// [`Options::new`](super::Options::new). It will split words on /// existing hyphens in the word. /// /// It will only use hyphens that are surrounded by alphanumeric /// characters, which prevents a word like `"--foo-bar"` from /// being split into `"--"` and `"foo-bar"`. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// /// assert_eq!(WordSplitter::HyphenSplitter.split_points("--foo-bar"), /// vec![6]); /// ``` HyphenSplitter, /// Use a custom function as the word splitter. /// /// This varian lets you implement a custom word splitter using /// your own function. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// /// fn split_at_underscore(word: &str) -> Vec<usize> { /// word.match_indices('_').map(|(idx, _)| idx + 1).collect() /// } /// /// let word_splitter = WordSplitter::Custom(split_at_underscore); /// assert_eq!(word_splitter.split_points("a_long_identifier"), /// vec![2, 7]); /// ``` Custom(fn(word: &str) -> Vec<usize>), /// A hyphenation dictionary can be used to do language-specific /// hyphenation using patterns from the [hyphenation] crate. /// /// **Note:** Only available when the `hyphenation` Cargo feature is /// enabled. /// /// [hyphenation]: https://docs.rs/hyphenation/ #[cfg(feature = "hyphenation")] Hyphenation(hyphenation::Standard), } impl std::fmt::Debug for WordSplitter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { WordSplitter::NoHyphenation => f.write_str("NoHyphenation"), WordSplitter::HyphenSplitter => f.write_str("HyphenSplitter"), WordSplitter::Custom(_) => f.write_str("Custom(...)"), #[cfg(feature = "hyphenation")] WordSplitter::Hyphenation(dict) => write!(f, "Hyphenation({})", dict.language()), } } } impl PartialEq<WordSplitter> for WordSplitter { fn eq(&self, other: &WordSplitter) -> bool { match (self, other) { (WordSplitter::NoHyphenation, WordSplitter::NoHyphenation) => true, (WordSplitter::HyphenSplitter, WordSplitter::HyphenSplitter) => true, #[cfg(feature = "hyphenation")] (WordSplitter::Hyphenation(this_dict), WordSplitter::Hyphenation(other_dict)) => { this_dict.language() == other_dict.language() } (_, _) => false, } } } impl WordSplitter { /// Return all possible indices where `word` can be split. /// /// The indices are in the range `0..word.len()`. They point to /// the index _after_ the split point, i.e., after `-` if /// splitting on hyphens. This way, `word.split_at(idx)` will /// break the word into two well-formed pieces. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// assert_eq!(WordSplitter::NoHyphenation.split_points("cannot-be-split"), vec![]); /// assert_eq!(WordSplitter::HyphenSplitter.split_points("can-be-split"), vec![4, 7]); /// assert_eq!(WordSplitter::Custom(|word| vec![word.len()/2]).split_points("middle"), vec![3]); /// ``` pub fn split_points(&self, word: &str) -> Vec<usize> { match self { WordSplitter::NoHyphenation => Vec::new(), WordSplitter::HyphenSplitter => { let mut splits = Vec::new(); for (idx, _) in word.match_indices('-') { // We only use hyphens that are surrounded by alphanumeric // characters. This is to avoid splitting on repeated hyphens, // such as those found in --foo-bar. let prev = word[..idx].chars().next_back(); let next = word[idx + 1..].chars().next(); if prev.filter(|ch| ch.is_alphanumeric()).is_some() && next.filter(|ch| ch.is_alphanumeric()).is_some() { splits.push(idx + 1); // +1 due to width of '-'. } } splits } WordSplitter::Custom(splitter_func) => splitter_func(word), #[cfg(feature = "hyphenation")] WordSplitter::Hyphenation(dictionary) => { use hyphenation::Hyphenator; dictionary.hyphenate(word).breaks } } } } /// Split words into smaller words according to the split points given /// by `word_splitter`. /// /// Note that we split all words, regardless of their length. This is /// to more cleanly separate the business of splitting (including /// automatic hyphenation) from the business of word wrapping. pub fn split_words<'a, I>( words: I, word_splitter: &'a WordSplitter, ) -> impl Iterator<Item = Word<'a>> where I: IntoIterator<Item = Word<'a>>, { words.into_iter().flat_map(move |word| { let mut prev = 0; let mut split_points = word_splitter.split_points(&word).into_iter(); std::iter::from_fn(move || { if let Some(idx) = split_points.next() { let need_hyphen =!word[..idx].ends_with('-'); let w = Word { word: &word.word[prev..idx], width: display_width(&word[prev..idx]), whitespace: "", penalty: if need_hyphen { "-" } else { "" }, }; prev = idx; return Some(w); } if prev < word.word.len() || prev == 0 { let w = Word { word: &word.word[prev..], width: display_width(&word[prev..]), whitespace: word.whitespace, penalty: word.penalty, }; prev = word.word.len() + 1; return Some(w); } None }) }) } #[cfg(test)] mod tests { use super::*; // Like assert_eq!, but the left expression is an iterator. macro_rules! assert_iter_eq { ($left:expr, $right:expr) => { assert_eq!($left.collect::<Vec<_>>(), $right); }; } #[test] fn split_words_no_words() { assert_iter_eq!(split_words(vec![], &WordSplitter::HyphenSplitter), vec![]); } #[test] fn split_words_empty_word() { assert_iter_eq!( split_words(vec![Word::from(" ")], &WordSplitter::HyphenSplitter), vec![Word::from(" ")] ); } #[test] fn split_words_single_word() { assert_iter_eq!( split_words(vec![Word::from("foobar")], &WordSplitter::HyphenSplitter), vec![Word::from("foobar")] ); } #[test] fn split_words_hyphen_splitter()
#[test] fn split_words_no_hyphenation() { assert_iter_eq!( split_words(vec![Word::from("foo-bar")], &WordSplitter::NoHyphenation), vec![Word::from("foo-bar")] ); } #[test] fn split_words_adds_penalty() { let fixed_split_point = |_: &str| vec![3]; assert_iter_eq!( split_words( vec![Word::from("foobar")].into_iter(), &WordSplitter::Custom(fixed_split_point) ), vec![ Word { word: "foo", width: 3, whitespace: "", penalty: "-" }, Word { word: "bar", width: 3, whitespace: "", penalty: "" } ] ); assert_iter_eq!( split_words( vec![Word::from("fo-bar")].into_iter(), &WordSplitter::Custom(fixed_split_point) ), vec![ Word { word: "fo-", width: 3, whitespace: "", penalty: "" }, Word { word: "bar", width: 3, whitespace: "", penalty: "" } ] ); } }
{ assert_iter_eq!( split_words(vec![Word::from("foo-bar")], &WordSplitter::HyphenSplitter), vec![Word::from("foo-"), Word::from("bar")] ); }
identifier_body
word_splitters.rs
//! Word splitting functionality. //! //! To wrap text into lines, long words sometimes need to be split //! across lines. The [`WordSplitter`] enum defines this //! functionality. use crate::core::{display_width, Word}; /// The `WordSplitter` enum describes where words can be split. /// /// If the textwrap crate has been compiled with the `hyphenation` /// Cargo feature enabled, you will find a /// [`WordSplitter::Hyphenation`] variant. Use this struct for /// language-aware hyphenation: /// /// ``` /// #[cfg(feature = "hyphenation")] { /// use hyphenation::{Language, Load, Standard}; /// use textwrap::{wrap, Options, WordSplitter}; /// /// let text = "Oxidation is the loss of electrons."; /// let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); /// let options = Options::new(8).word_splitter(WordSplitter::Hyphenation(dictionary)); /// assert_eq!(wrap(text, &options), vec!["Oxida-", /// "tion is", /// "the loss", /// "of elec-", /// "trons."]); /// } /// ``` /// /// Please see the documentation for the [hyphenation] crate for more /// details. /// /// [hyphenation]: https://docs.rs/hyphenation/ #[derive(Clone)] pub enum WordSplitter { /// Use this as a [`Options.word_splitter`] to avoid any kind of /// hyphenation: /// /// ``` /// use textwrap::{wrap, Options, WordSplitter}; /// /// let options = Options::new(8).word_splitter(WordSplitter::NoHyphenation); /// assert_eq!(wrap("foo bar-baz", &options), /// vec!["foo", "bar-baz"]); /// ``` /// /// [`Options.word_splitter`]: super::Options::word_splitter NoHyphenation, /// `HyphenSplitter` is the default `WordSplitter` used by /// [`Options::new`](super::Options::new). It will split words on /// existing hyphens in the word. /// /// It will only use hyphens that are surrounded by alphanumeric /// characters, which prevents a word like `"--foo-bar"` from /// being split into `"--"` and `"foo-bar"`. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// /// assert_eq!(WordSplitter::HyphenSplitter.split_points("--foo-bar"), /// vec![6]); /// ``` HyphenSplitter, /// Use a custom function as the word splitter. /// /// This varian lets you implement a custom word splitter using /// your own function. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// /// fn split_at_underscore(word: &str) -> Vec<usize> { /// word.match_indices('_').map(|(idx, _)| idx + 1).collect() /// } /// /// let word_splitter = WordSplitter::Custom(split_at_underscore); /// assert_eq!(word_splitter.split_points("a_long_identifier"), /// vec![2, 7]); /// ``` Custom(fn(word: &str) -> Vec<usize>), /// A hyphenation dictionary can be used to do language-specific /// hyphenation using patterns from the [hyphenation] crate. /// /// **Note:** Only available when the `hyphenation` Cargo feature is /// enabled. /// /// [hyphenation]: https://docs.rs/hyphenation/ #[cfg(feature = "hyphenation")] Hyphenation(hyphenation::Standard), } impl std::fmt::Debug for WordSplitter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { WordSplitter::NoHyphenation => f.write_str("NoHyphenation"), WordSplitter::HyphenSplitter => f.write_str("HyphenSplitter"), WordSplitter::Custom(_) => f.write_str("Custom(...)"), #[cfg(feature = "hyphenation")] WordSplitter::Hyphenation(dict) => write!(f, "Hyphenation({})", dict.language()), } } } impl PartialEq<WordSplitter> for WordSplitter { fn eq(&self, other: &WordSplitter) -> bool { match (self, other) { (WordSplitter::NoHyphenation, WordSplitter::NoHyphenation) => true, (WordSplitter::HyphenSplitter, WordSplitter::HyphenSplitter) => true, #[cfg(feature = "hyphenation")] (WordSplitter::Hyphenation(this_dict), WordSplitter::Hyphenation(other_dict)) => { this_dict.language() == other_dict.language() } (_, _) => false, } } } impl WordSplitter { /// Return all possible indices where `word` can be split. /// /// The indices are in the range `0..word.len()`. They point to /// the index _after_ the split point, i.e., after `-` if /// splitting on hyphens. This way, `word.split_at(idx)` will /// break the word into two well-formed pieces. /// /// # Examples /// /// ``` /// use textwrap::WordSplitter; /// assert_eq!(WordSplitter::NoHyphenation.split_points("cannot-be-split"), vec![]); /// assert_eq!(WordSplitter::HyphenSplitter.split_points("can-be-split"), vec![4, 7]); /// assert_eq!(WordSplitter::Custom(|word| vec![word.len()/2]).split_points("middle"), vec![3]); /// ``` pub fn split_points(&self, word: &str) -> Vec<usize> { match self { WordSplitter::NoHyphenation => Vec::new(), WordSplitter::HyphenSplitter => { let mut splits = Vec::new(); for (idx, _) in word.match_indices('-') { // We only use hyphens that are surrounded by alphanumeric // characters. This is to avoid splitting on repeated hyphens, // such as those found in --foo-bar. let prev = word[..idx].chars().next_back(); let next = word[idx + 1..].chars().next(); if prev.filter(|ch| ch.is_alphanumeric()).is_some() && next.filter(|ch| ch.is_alphanumeric()).is_some() { splits.push(idx + 1); // +1 due to width of '-'. } } splits } WordSplitter::Custom(splitter_func) => splitter_func(word), #[cfg(feature = "hyphenation")] WordSplitter::Hyphenation(dictionary) => { use hyphenation::Hyphenator; dictionary.hyphenate(word).breaks } } } } /// Split words into smaller words according to the split points given /// by `word_splitter`. /// /// Note that we split all words, regardless of their length. This is /// to more cleanly separate the business of splitting (including /// automatic hyphenation) from the business of word wrapping. pub fn split_words<'a, I>( words: I, word_splitter: &'a WordSplitter, ) -> impl Iterator<Item = Word<'a>> where I: IntoIterator<Item = Word<'a>>, { words.into_iter().flat_map(move |word| { let mut prev = 0; let mut split_points = word_splitter.split_points(&word).into_iter(); std::iter::from_fn(move || { if let Some(idx) = split_points.next() { let need_hyphen =!word[..idx].ends_with('-'); let w = Word { word: &word.word[prev..idx], width: display_width(&word[prev..idx]), whitespace: "", penalty: if need_hyphen { "-" } else { "" }, }; prev = idx; return Some(w); } if prev < word.word.len() || prev == 0 { let w = Word { word: &word.word[prev..], width: display_width(&word[prev..]), whitespace: word.whitespace, penalty: word.penalty, }; prev = word.word.len() + 1; return Some(w); } None }) }) } #[cfg(test)] mod tests { use super::*; // Like assert_eq!, but the left expression is an iterator. macro_rules! assert_iter_eq {
#[test] fn split_words_no_words() { assert_iter_eq!(split_words(vec![], &WordSplitter::HyphenSplitter), vec![]); } #[test] fn split_words_empty_word() { assert_iter_eq!( split_words(vec![Word::from(" ")], &WordSplitter::HyphenSplitter), vec![Word::from(" ")] ); } #[test] fn split_words_single_word() { assert_iter_eq!( split_words(vec![Word::from("foobar")], &WordSplitter::HyphenSplitter), vec![Word::from("foobar")] ); } #[test] fn split_words_hyphen_splitter() { assert_iter_eq!( split_words(vec![Word::from("foo-bar")], &WordSplitter::HyphenSplitter), vec![Word::from("foo-"), Word::from("bar")] ); } #[test] fn split_words_no_hyphenation() { assert_iter_eq!( split_words(vec![Word::from("foo-bar")], &WordSplitter::NoHyphenation), vec![Word::from("foo-bar")] ); } #[test] fn split_words_adds_penalty() { let fixed_split_point = |_: &str| vec![3]; assert_iter_eq!( split_words( vec![Word::from("foobar")].into_iter(), &WordSplitter::Custom(fixed_split_point) ), vec![ Word { word: "foo", width: 3, whitespace: "", penalty: "-" }, Word { word: "bar", width: 3, whitespace: "", penalty: "" } ] ); assert_iter_eq!( split_words( vec![Word::from("fo-bar")].into_iter(), &WordSplitter::Custom(fixed_split_point) ), vec![ Word { word: "fo-", width: 3, whitespace: "", penalty: "" }, Word { word: "bar", width: 3, whitespace: "", penalty: "" } ] ); } }
($left:expr, $right:expr) => { assert_eq!($left.collect::<Vec<_>>(), $right); }; }
random_line_split
resources.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 std::env; use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::sync::{Once, ONCE_INIT, RwLock}; lazy_static! { static ref RES: RwLock<Option<Box<ResourceReaderMethods + Sync + Send>>> = RwLock::new(None); } pub fn set(reader: Box<ResourceReaderMethods + Sync + Send>) { *RES.write().unwrap() = Some(reader); } pub fn read_bytes(res: Resource) -> Vec<u8> { RES.read().unwrap().as_ref().expect("Resource reader not set.").read(res) } pub fn read_string(res: Resource) -> String { String::from_utf8(read_bytes(res)).unwrap() } pub fn sandbox_access_files() -> Vec<PathBuf> { RES.read().unwrap().as_ref().expect("Resource reader not set.").sandbox_access_files() } pub fn sandbox_access_files_dirs() -> Vec<PathBuf> { RES.read().unwrap().as_ref().expect("Resource reader not set.").sandbox_access_files_dirs() } pub enum Resource { Preferences, BluetoothBlocklist, DomainList, HstsPreloadList, SSLCertificates, BadCertHTML, NetErrorHTML, UserAgentCSS, ServoCSS, PresentationalHintsCSS, QuirksModeCSS, RippyPNG, } pub trait ResourceReaderMethods { fn read(&self, res: Resource) -> Vec<u8>; fn sandbox_access_files(&self) -> Vec<PathBuf>; fn sandbox_access_files_dirs(&self) -> Vec<PathBuf>;
pub fn register_resources_for_tests() { INIT.call_once(|| { struct ResourceReader; impl ResourceReaderMethods for ResourceReader { fn sandbox_access_files(&self) -> Vec<PathBuf> { vec![] } fn sandbox_access_files_dirs(&self) -> Vec<PathBuf> { vec![] } fn read(&self, file: Resource) -> Vec<u8> { let file = match file { Resource::Preferences => "prefs.json", Resource::BluetoothBlocklist => "gatt_blocklist.txt", Resource::DomainList => "public_domains.txt", Resource::HstsPreloadList => "hsts_preload.json", Resource::SSLCertificates => "certs", Resource::BadCertHTML => "badcert.html", Resource::NetErrorHTML => "neterror.html", Resource::UserAgentCSS => "user-agent.css", Resource::ServoCSS => "servo.css", Resource::PresentationalHintsCSS => "presentational-hints.css", Resource::QuirksModeCSS => "quirks-mode.css", Resource::RippyPNG => "rippy.png", }; let mut path = env::current_exe().unwrap(); path = path.canonicalize().unwrap(); while path.pop() { path.push("resources"); if path.is_dir() { break; } path.pop(); } path.push(file); let mut buffer = vec![]; File::open(path).expect(&format!("Can't find file: {}", file)) .read_to_end(&mut buffer).expect("Can't read file"); buffer } } set(Box::new(ResourceReader)); }); }
} static INIT: Once = ONCE_INIT;
random_line_split
resources.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 std::env; use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::sync::{Once, ONCE_INIT, RwLock}; lazy_static! { static ref RES: RwLock<Option<Box<ResourceReaderMethods + Sync + Send>>> = RwLock::new(None); } pub fn set(reader: Box<ResourceReaderMethods + Sync + Send>) { *RES.write().unwrap() = Some(reader); } pub fn read_bytes(res: Resource) -> Vec<u8> { RES.read().unwrap().as_ref().expect("Resource reader not set.").read(res) } pub fn read_string(res: Resource) -> String { String::from_utf8(read_bytes(res)).unwrap() } pub fn sandbox_access_files() -> Vec<PathBuf> { RES.read().unwrap().as_ref().expect("Resource reader not set.").sandbox_access_files() } pub fn sandbox_access_files_dirs() -> Vec<PathBuf> { RES.read().unwrap().as_ref().expect("Resource reader not set.").sandbox_access_files_dirs() } pub enum Resource { Preferences, BluetoothBlocklist, DomainList, HstsPreloadList, SSLCertificates, BadCertHTML, NetErrorHTML, UserAgentCSS, ServoCSS, PresentationalHintsCSS, QuirksModeCSS, RippyPNG, } pub trait ResourceReaderMethods { fn read(&self, res: Resource) -> Vec<u8>; fn sandbox_access_files(&self) -> Vec<PathBuf>; fn sandbox_access_files_dirs(&self) -> Vec<PathBuf>; } static INIT: Once = ONCE_INIT; pub fn register_resources_for_tests() { INIT.call_once(|| { struct ResourceReader; impl ResourceReaderMethods for ResourceReader { fn sandbox_access_files(&self) -> Vec<PathBuf> { vec![] } fn sandbox_access_files_dirs(&self) -> Vec<PathBuf> { vec![] } fn read(&self, file: Resource) -> Vec<u8>
break; } path.pop(); } path.push(file); let mut buffer = vec![]; File::open(path).expect(&format!("Can't find file: {}", file)) .read_to_end(&mut buffer).expect("Can't read file"); buffer } } set(Box::new(ResourceReader)); }); }
{ let file = match file { Resource::Preferences => "prefs.json", Resource::BluetoothBlocklist => "gatt_blocklist.txt", Resource::DomainList => "public_domains.txt", Resource::HstsPreloadList => "hsts_preload.json", Resource::SSLCertificates => "certs", Resource::BadCertHTML => "badcert.html", Resource::NetErrorHTML => "neterror.html", Resource::UserAgentCSS => "user-agent.css", Resource::ServoCSS => "servo.css", Resource::PresentationalHintsCSS => "presentational-hints.css", Resource::QuirksModeCSS => "quirks-mode.css", Resource::RippyPNG => "rippy.png", }; let mut path = env::current_exe().unwrap(); path = path.canonicalize().unwrap(); while path.pop() { path.push("resources"); if path.is_dir() {
identifier_body
resources.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 std::env; use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::sync::{Once, ONCE_INIT, RwLock}; lazy_static! { static ref RES: RwLock<Option<Box<ResourceReaderMethods + Sync + Send>>> = RwLock::new(None); } pub fn set(reader: Box<ResourceReaderMethods + Sync + Send>) { *RES.write().unwrap() = Some(reader); } pub fn
(res: Resource) -> Vec<u8> { RES.read().unwrap().as_ref().expect("Resource reader not set.").read(res) } pub fn read_string(res: Resource) -> String { String::from_utf8(read_bytes(res)).unwrap() } pub fn sandbox_access_files() -> Vec<PathBuf> { RES.read().unwrap().as_ref().expect("Resource reader not set.").sandbox_access_files() } pub fn sandbox_access_files_dirs() -> Vec<PathBuf> { RES.read().unwrap().as_ref().expect("Resource reader not set.").sandbox_access_files_dirs() } pub enum Resource { Preferences, BluetoothBlocklist, DomainList, HstsPreloadList, SSLCertificates, BadCertHTML, NetErrorHTML, UserAgentCSS, ServoCSS, PresentationalHintsCSS, QuirksModeCSS, RippyPNG, } pub trait ResourceReaderMethods { fn read(&self, res: Resource) -> Vec<u8>; fn sandbox_access_files(&self) -> Vec<PathBuf>; fn sandbox_access_files_dirs(&self) -> Vec<PathBuf>; } static INIT: Once = ONCE_INIT; pub fn register_resources_for_tests() { INIT.call_once(|| { struct ResourceReader; impl ResourceReaderMethods for ResourceReader { fn sandbox_access_files(&self) -> Vec<PathBuf> { vec![] } fn sandbox_access_files_dirs(&self) -> Vec<PathBuf> { vec![] } fn read(&self, file: Resource) -> Vec<u8> { let file = match file { Resource::Preferences => "prefs.json", Resource::BluetoothBlocklist => "gatt_blocklist.txt", Resource::DomainList => "public_domains.txt", Resource::HstsPreloadList => "hsts_preload.json", Resource::SSLCertificates => "certs", Resource::BadCertHTML => "badcert.html", Resource::NetErrorHTML => "neterror.html", Resource::UserAgentCSS => "user-agent.css", Resource::ServoCSS => "servo.css", Resource::PresentationalHintsCSS => "presentational-hints.css", Resource::QuirksModeCSS => "quirks-mode.css", Resource::RippyPNG => "rippy.png", }; let mut path = env::current_exe().unwrap(); path = path.canonicalize().unwrap(); while path.pop() { path.push("resources"); if path.is_dir() { break; } path.pop(); } path.push(file); let mut buffer = vec![]; File::open(path).expect(&format!("Can't find file: {}", file)) .read_to_end(&mut buffer).expect("Can't read file"); buffer } } set(Box::new(ResourceReader)); }); }
read_bytes
identifier_name
main.rs
// @adjivas - github.com/adjivas. See the LICENSE // file at the top-level directory of this distribution and at // https://github.com/adjivas/pasteur // // This file may not be copied, modified, or distributed // except according to those terms. #[macro_use] extern crate clap; extern crate pasteur; /// Default* const arguments defined by CLI. const DEFAULT_TEMPLATE: &'static str = "etc/templates"; const DEFAULT_LOCALE: &'static str = "etc/locales"; const DEFAULT_STYLE: &'static str = "etc/stylesheets"; const DEFAULT_CERT: &'static str = "etc/ca/cert.pem"; const DEFAULT_KEY: &'static str = "etc/ca/key.pem"; const DEFAULT_PROTOCOL: &'static str = "https"; const DEFAULT_ADDRESS: &'static str = "localhost"; const DEFAULT_SOCKET: &'static str = "3000"; /// The `main` function parses the arguments and /// instantiates the (http | https) server. pub fn main ()
{ let yaml = load_yaml!("cli.yml"); let options = clap::App::from_yaml(yaml).get_matches(); pasteur::new ( options.value_of("template").unwrap_or(DEFAULT_TEMPLATE), options.value_of("locale").unwrap_or(DEFAULT_LOCALE), options.value_of("style").unwrap_or(DEFAULT_STYLE), options.value_of("cert").unwrap_or(DEFAULT_CERT), options.value_of("key").unwrap_or(DEFAULT_KEY), pasteur::protocol::Protocol::from_str ( options.value_of("protocol").unwrap_or(DEFAULT_PROTOCOL) ).unwrap(), &format!("{}:{}", options.value_of("address").unwrap_or(DEFAULT_ADDRESS), options.value_of("socket").unwrap_or(DEFAULT_SOCKET) ), ); }
identifier_body
main.rs
// @adjivas - github.com/adjivas. See the LICENSE // file at the top-level directory of this distribution and at // https://github.com/adjivas/pasteur // // This file may not be copied, modified, or distributed // except according to those terms. #[macro_use] extern crate clap; extern crate pasteur; /// Default* const arguments defined by CLI. const DEFAULT_TEMPLATE: &'static str = "etc/templates"; const DEFAULT_LOCALE: &'static str = "etc/locales"; const DEFAULT_STYLE: &'static str = "etc/stylesheets"; const DEFAULT_CERT: &'static str = "etc/ca/cert.pem"; const DEFAULT_KEY: &'static str = "etc/ca/key.pem"; const DEFAULT_PROTOCOL: &'static str = "https"; const DEFAULT_ADDRESS: &'static str = "localhost"; const DEFAULT_SOCKET: &'static str = "3000"; /// The `main` function parses the arguments and /// instantiates the (http | https) server. pub fn
() { let yaml = load_yaml!("cli.yml"); let options = clap::App::from_yaml(yaml).get_matches(); pasteur::new ( options.value_of("template").unwrap_or(DEFAULT_TEMPLATE), options.value_of("locale").unwrap_or(DEFAULT_LOCALE), options.value_of("style").unwrap_or(DEFAULT_STYLE), options.value_of("cert").unwrap_or(DEFAULT_CERT), options.value_of("key").unwrap_or(DEFAULT_KEY), pasteur::protocol::Protocol::from_str ( options.value_of("protocol").unwrap_or(DEFAULT_PROTOCOL) ).unwrap(), &format!("{}:{}", options.value_of("address").unwrap_or(DEFAULT_ADDRESS), options.value_of("socket").unwrap_or(DEFAULT_SOCKET) ), ); }
main
identifier_name
main.rs
// @adjivas - github.com/adjivas. See the LICENSE // file at the top-level directory of this distribution and at // https://github.com/adjivas/pasteur // // This file may not be copied, modified, or distributed // except according to those terms.
extern crate pasteur; /// Default* const arguments defined by CLI. const DEFAULT_TEMPLATE: &'static str = "etc/templates"; const DEFAULT_LOCALE: &'static str = "etc/locales"; const DEFAULT_STYLE: &'static str = "etc/stylesheets"; const DEFAULT_CERT: &'static str = "etc/ca/cert.pem"; const DEFAULT_KEY: &'static str = "etc/ca/key.pem"; const DEFAULT_PROTOCOL: &'static str = "https"; const DEFAULT_ADDRESS: &'static str = "localhost"; const DEFAULT_SOCKET: &'static str = "3000"; /// The `main` function parses the arguments and /// instantiates the (http | https) server. pub fn main () { let yaml = load_yaml!("cli.yml"); let options = clap::App::from_yaml(yaml).get_matches(); pasteur::new ( options.value_of("template").unwrap_or(DEFAULT_TEMPLATE), options.value_of("locale").unwrap_or(DEFAULT_LOCALE), options.value_of("style").unwrap_or(DEFAULT_STYLE), options.value_of("cert").unwrap_or(DEFAULT_CERT), options.value_of("key").unwrap_or(DEFAULT_KEY), pasteur::protocol::Protocol::from_str ( options.value_of("protocol").unwrap_or(DEFAULT_PROTOCOL) ).unwrap(), &format!("{}:{}", options.value_of("address").unwrap_or(DEFAULT_ADDRESS), options.value_of("socket").unwrap_or(DEFAULT_SOCKET) ), ); }
#[macro_use] extern crate clap;
random_line_split
mine_nrd_kernel.rs
// Copyright 2021 The Grin Developers // // 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. mod chain_test_helper; use grin_chain as chain; use grin_core as core; use grin_keychain as keychain; use grin_util as util; use self::chain_test_helper::{clean_output_dir, genesis_block, init_chain}; use crate::chain::{Chain, Options}; use crate::core::core::{Block, KernelFeatures, NRDRelativeHeight, Transaction}; use crate::core::libtx::{build, reward, ProofBuilder}; use crate::core::{consensus, global, pow}; use crate::keychain::{ExtKeychain, ExtKeychainPath, Identifier, Keychain}; use chrono::Duration; fn build_block<K>(chain: &Chain, keychain: &K, key_id: &Identifier, txs: Vec<Transaction>) -> Block where K: Keychain, { let prev = chain.head_header().unwrap(); let next_header_info = consensus::next_difficulty(1, chain.difficulty_iter().unwrap()); let fee = txs.iter().map(|x| x.fee()).sum(); let reward = reward::output(keychain, &ProofBuilder::new(keychain), key_id, fee, false).unwrap(); let mut block = Block::new(&prev, &txs, next_header_info.clone().difficulty, reward).unwrap(); block.header.timestamp = prev.timestamp + Duration::seconds(60); block.header.pow.secondary_scaling = next_header_info.secondary_scaling; chain.set_txhashset_roots(&mut block).unwrap(); let edge_bits = global::min_edge_bits(); block.header.pow.proof.edge_bits = edge_bits; pow::pow_size( &mut block.header, next_header_info.difficulty, global::proofsize(), edge_bits, ) .unwrap(); block } #[test] fn mine_block_with_nrd_kernel_and_nrd_feature_enabled() { global::set_local_chain_type(global::ChainTypes::AutomatedTesting); global::set_local_nrd_enabled(true); util::init_test_logger(); let chain_dir = ".grin.nrd_kernel"; clean_output_dir(chain_dir); let keychain = ExtKeychain::from_random_seed(false).unwrap(); let pb = ProofBuilder::new(&keychain); let genesis = genesis_block(&keychain); let chain = init_chain(chain_dir, genesis.clone());
} assert_eq!(chain.head().unwrap().height, 8); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let tx = build::transaction( KernelFeatures::NoRecentDuplicate { fee: 20000.into(), relative_height: NRDRelativeHeight::new(1440).unwrap(), }, &[ build::coinbase_input(consensus::REWARD, key_id1.clone()), build::output(consensus::REWARD - 20000, key_id2.clone()), ], &keychain, &pb, ) .unwrap(); let key_id9 = ExtKeychainPath::new(1, 9, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id9, vec![tx]); chain.process_block(block, Options::MINE).unwrap(); chain.validate(false).unwrap(); clean_output_dir(chain_dir); } #[test] fn mine_invalid_block_with_nrd_kernel_and_nrd_feature_enabled_before_hf() { global::set_local_chain_type(global::ChainTypes::AutomatedTesting); global::set_local_nrd_enabled(true); util::init_test_logger(); let chain_dir = ".grin.invalid_nrd_kernel"; clean_output_dir(chain_dir); let keychain = ExtKeychain::from_random_seed(false).unwrap(); let pb = ProofBuilder::new(&keychain); let genesis = genesis_block(&keychain); let chain = init_chain(chain_dir, genesis.clone()); for n in 1..8 { let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id, vec![]); chain.process_block(block, Options::MINE).unwrap(); } assert_eq!(chain.head().unwrap().height, 7); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let tx = build::transaction( KernelFeatures::NoRecentDuplicate { fee: 20000.into(), relative_height: NRDRelativeHeight::new(1440).unwrap(), }, &[ build::coinbase_input(consensus::REWARD, key_id1.clone()), build::output(consensus::REWARD - 20000, key_id2.clone()), ], &keychain, &pb, ) .unwrap(); let key_id8 = ExtKeychainPath::new(1, 8, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id8, vec![tx]); let res = chain.process_block(block, Options::MINE); assert!(res.is_err()); clean_output_dir(chain_dir); }
for n in 1..9 { let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id, vec![]); chain.process_block(block, Options::MINE).unwrap();
random_line_split
mine_nrd_kernel.rs
// Copyright 2021 The Grin Developers // // 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. mod chain_test_helper; use grin_chain as chain; use grin_core as core; use grin_keychain as keychain; use grin_util as util; use self::chain_test_helper::{clean_output_dir, genesis_block, init_chain}; use crate::chain::{Chain, Options}; use crate::core::core::{Block, KernelFeatures, NRDRelativeHeight, Transaction}; use crate::core::libtx::{build, reward, ProofBuilder}; use crate::core::{consensus, global, pow}; use crate::keychain::{ExtKeychain, ExtKeychainPath, Identifier, Keychain}; use chrono::Duration; fn build_block<K>(chain: &Chain, keychain: &K, key_id: &Identifier, txs: Vec<Transaction>) -> Block where K: Keychain,
edge_bits, ) .unwrap(); block } #[test] fn mine_block_with_nrd_kernel_and_nrd_feature_enabled() { global::set_local_chain_type(global::ChainTypes::AutomatedTesting); global::set_local_nrd_enabled(true); util::init_test_logger(); let chain_dir = ".grin.nrd_kernel"; clean_output_dir(chain_dir); let keychain = ExtKeychain::from_random_seed(false).unwrap(); let pb = ProofBuilder::new(&keychain); let genesis = genesis_block(&keychain); let chain = init_chain(chain_dir, genesis.clone()); for n in 1..9 { let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id, vec![]); chain.process_block(block, Options::MINE).unwrap(); } assert_eq!(chain.head().unwrap().height, 8); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let tx = build::transaction( KernelFeatures::NoRecentDuplicate { fee: 20000.into(), relative_height: NRDRelativeHeight::new(1440).unwrap(), }, &[ build::coinbase_input(consensus::REWARD, key_id1.clone()), build::output(consensus::REWARD - 20000, key_id2.clone()), ], &keychain, &pb, ) .unwrap(); let key_id9 = ExtKeychainPath::new(1, 9, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id9, vec![tx]); chain.process_block(block, Options::MINE).unwrap(); chain.validate(false).unwrap(); clean_output_dir(chain_dir); } #[test] fn mine_invalid_block_with_nrd_kernel_and_nrd_feature_enabled_before_hf() { global::set_local_chain_type(global::ChainTypes::AutomatedTesting); global::set_local_nrd_enabled(true); util::init_test_logger(); let chain_dir = ".grin.invalid_nrd_kernel"; clean_output_dir(chain_dir); let keychain = ExtKeychain::from_random_seed(false).unwrap(); let pb = ProofBuilder::new(&keychain); let genesis = genesis_block(&keychain); let chain = init_chain(chain_dir, genesis.clone()); for n in 1..8 { let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id, vec![]); chain.process_block(block, Options::MINE).unwrap(); } assert_eq!(chain.head().unwrap().height, 7); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let tx = build::transaction( KernelFeatures::NoRecentDuplicate { fee: 20000.into(), relative_height: NRDRelativeHeight::new(1440).unwrap(), }, &[ build::coinbase_input(consensus::REWARD, key_id1.clone()), build::output(consensus::REWARD - 20000, key_id2.clone()), ], &keychain, &pb, ) .unwrap(); let key_id8 = ExtKeychainPath::new(1, 8, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id8, vec![tx]); let res = chain.process_block(block, Options::MINE); assert!(res.is_err()); clean_output_dir(chain_dir); }
{ let prev = chain.head_header().unwrap(); let next_header_info = consensus::next_difficulty(1, chain.difficulty_iter().unwrap()); let fee = txs.iter().map(|x| x.fee()).sum(); let reward = reward::output(keychain, &ProofBuilder::new(keychain), key_id, fee, false).unwrap(); let mut block = Block::new(&prev, &txs, next_header_info.clone().difficulty, reward).unwrap(); block.header.timestamp = prev.timestamp + Duration::seconds(60); block.header.pow.secondary_scaling = next_header_info.secondary_scaling; chain.set_txhashset_roots(&mut block).unwrap(); let edge_bits = global::min_edge_bits(); block.header.pow.proof.edge_bits = edge_bits; pow::pow_size( &mut block.header, next_header_info.difficulty, global::proofsize(),
identifier_body
mine_nrd_kernel.rs
// Copyright 2021 The Grin Developers // // 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. mod chain_test_helper; use grin_chain as chain; use grin_core as core; use grin_keychain as keychain; use grin_util as util; use self::chain_test_helper::{clean_output_dir, genesis_block, init_chain}; use crate::chain::{Chain, Options}; use crate::core::core::{Block, KernelFeatures, NRDRelativeHeight, Transaction}; use crate::core::libtx::{build, reward, ProofBuilder}; use crate::core::{consensus, global, pow}; use crate::keychain::{ExtKeychain, ExtKeychainPath, Identifier, Keychain}; use chrono::Duration; fn build_block<K>(chain: &Chain, keychain: &K, key_id: &Identifier, txs: Vec<Transaction>) -> Block where K: Keychain, { let prev = chain.head_header().unwrap(); let next_header_info = consensus::next_difficulty(1, chain.difficulty_iter().unwrap()); let fee = txs.iter().map(|x| x.fee()).sum(); let reward = reward::output(keychain, &ProofBuilder::new(keychain), key_id, fee, false).unwrap(); let mut block = Block::new(&prev, &txs, next_header_info.clone().difficulty, reward).unwrap(); block.header.timestamp = prev.timestamp + Duration::seconds(60); block.header.pow.secondary_scaling = next_header_info.secondary_scaling; chain.set_txhashset_roots(&mut block).unwrap(); let edge_bits = global::min_edge_bits(); block.header.pow.proof.edge_bits = edge_bits; pow::pow_size( &mut block.header, next_header_info.difficulty, global::proofsize(), edge_bits, ) .unwrap(); block } #[test] fn mine_block_with_nrd_kernel_and_nrd_feature_enabled() { global::set_local_chain_type(global::ChainTypes::AutomatedTesting); global::set_local_nrd_enabled(true); util::init_test_logger(); let chain_dir = ".grin.nrd_kernel"; clean_output_dir(chain_dir); let keychain = ExtKeychain::from_random_seed(false).unwrap(); let pb = ProofBuilder::new(&keychain); let genesis = genesis_block(&keychain); let chain = init_chain(chain_dir, genesis.clone()); for n in 1..9 { let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id, vec![]); chain.process_block(block, Options::MINE).unwrap(); } assert_eq!(chain.head().unwrap().height, 8); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let tx = build::transaction( KernelFeatures::NoRecentDuplicate { fee: 20000.into(), relative_height: NRDRelativeHeight::new(1440).unwrap(), }, &[ build::coinbase_input(consensus::REWARD, key_id1.clone()), build::output(consensus::REWARD - 20000, key_id2.clone()), ], &keychain, &pb, ) .unwrap(); let key_id9 = ExtKeychainPath::new(1, 9, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id9, vec![tx]); chain.process_block(block, Options::MINE).unwrap(); chain.validate(false).unwrap(); clean_output_dir(chain_dir); } #[test] fn
() { global::set_local_chain_type(global::ChainTypes::AutomatedTesting); global::set_local_nrd_enabled(true); util::init_test_logger(); let chain_dir = ".grin.invalid_nrd_kernel"; clean_output_dir(chain_dir); let keychain = ExtKeychain::from_random_seed(false).unwrap(); let pb = ProofBuilder::new(&keychain); let genesis = genesis_block(&keychain); let chain = init_chain(chain_dir, genesis.clone()); for n in 1..8 { let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id, vec![]); chain.process_block(block, Options::MINE).unwrap(); } assert_eq!(chain.head().unwrap().height, 7); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let tx = build::transaction( KernelFeatures::NoRecentDuplicate { fee: 20000.into(), relative_height: NRDRelativeHeight::new(1440).unwrap(), }, &[ build::coinbase_input(consensus::REWARD, key_id1.clone()), build::output(consensus::REWARD - 20000, key_id2.clone()), ], &keychain, &pb, ) .unwrap(); let key_id8 = ExtKeychainPath::new(1, 8, 0, 0, 0).to_identifier(); let block = build_block(&chain, &keychain, &key_id8, vec![tx]); let res = chain.process_block(block, Options::MINE); assert!(res.is_err()); clean_output_dir(chain_dir); }
mine_invalid_block_with_nrd_kernel_and_nrd_feature_enabled_before_hf
identifier_name
player_loop.rs
// Tunnul // Copyright (c) 2015, Richard Lettich // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -------------------------------------------------------------------------- // THIS IS NOT AN OFFICIAL MINECRAFT PRODUCT, // NEITHER APPROVED NOR ASSOCIATED WITH MOJANG. // This file contains the player loop and all functions for handling received packets extern crate mio; use player; use packet; use std::net::TcpStream; use std::time::Duration; use std::io::Write; use self::mio::*; // Easier to optimize than more intuitive solutions fn packet_handler(player: &mut Player, pack: &mut Packet) -> Option<&'static str> { match pack.id { 1 => chat_message(player, pack), 2 => use_entity(player, pack), 3 => is_flying(), 4 => position_update(player, pack), // 5 => look_update(player, pack), //6 => position_and_look_update(player, pack), // 7 => player_digging(player, pack), // 8 => block_placement(player, pack), //9 => held_item_update(player, pack), //10 => action(player, pack), //11 => vehichle_steer(player, pack), //12 => close_window(player, pack), //13 => click_inventory_slot(player, pack), //14 => confirm_transaction(player, pack), //15 => creative_inventory(player, pack), //16 => enchant_item(player, pack), //17 => sign_set(player, pack), //18 => player_abilities(player, pack), //19 => tab_complete(player, pack), //20 => client_settings(player, pack), //21 => spawn_request(player, pack), //22 => plugin_message(player, pack), //23 => spectate(player, pack), //24 => resource_pack_status(player, pack), _ => None, //panic!("invalid packet id"), } } // Types of Data tx's send that can unblock player thread pub enum
{ // Packet(Packet), TcpErr, // Packet already formed KeepAlive, // Fixme, Thread to thread transmission } const PLAYER_STREAM: Token = Token(0); const RECIEVER: Token = Token(1); struct MyHandler(TcpStream); impl Handler for MyHandler { type Timeout = (); type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: EventSet) { match token { PLAYER_STREAM => { println!("hi"); } _ => panic!("unexpected token"), } } } pub fn player_loop(mut player: Player) { println!("{} has joined the game", player.name); let addr = player.stream.local_addr().unwrap(); let mut stream = mio::tcp::TcpStream::connect_stream(*player.stream, &addr).unwrap(); let mut event_loop = EventLoop::<MyHandler>::new().unwrap(); event_loop.register(&stream, PLAYER_STREAM, EventSet::readable(), PollOpt::edge()).unwrap(); /* loop { // Large match Easier to optimize than more intuitive solutions match player.rx.recv().unwrap() { ReceiverData::Packet(mut pack) => { if player.health > 0 || pack.id == 0x16 { // Only allow respawn packets if dead match packet_handler(&mut player, &mut pack) { Some(_) => (),//kick_player(e), _ => (), } } }, ReceiverData::KeepAlive => { let _ = player.stream.write(&[0x2u8, 0x0u8, 0x0u8]); }, ReceiverData::TcpErr => return, } }*/ } use struct_types::Location; use to_client; use packet::Packet; use player::Player; fn chat_message(player: &Player, packet: &mut Packet) -> Option<&'static str> { unimplemented!(); } fn use_entity(player: &mut Player, packet: &mut Packet) -> Option<&'static str> { let target_id = packet.get_varint(); let interact_type = packet.getas::<u8>(); if interact_type == 2 { let interact_location = packet.get_location(); if player.location.distance(&interact_location) > 25.0 { Some("overexteding reach") } else { unimplemented!(); } } else { None } } fn is_flying() -> Option<&'static str> { None } fn position_update(player: &mut Player, packet: &mut Packet) -> Option<&'static str> { //Fixe me let new_pos = packet.get_location(); let on_ground = packet.getas::<bool>(); if player.location.distance(&new_pos) > 100.0 { return Some("moving to fast"); } //Fix me, Check for closest y block below to prevent fall damage avoiding let fall_dist = player.last_on_ground.y - new_pos.y - 3.0; if fall_dist > 0.0 && on_ground { player.health -= fall_dist as i16; player.send_health(); player.last_on_ground = new_pos.clone(); } player.location = new_pos; None }
ReceiverData
identifier_name
player_loop.rs
// Tunnul // Copyright (c) 2015, Richard Lettich // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -------------------------------------------------------------------------- // THIS IS NOT AN OFFICIAL MINECRAFT PRODUCT, // NEITHER APPROVED NOR ASSOCIATED WITH MOJANG. // This file contains the player loop and all functions for handling received packets extern crate mio; use player; use packet; use std::net::TcpStream; use std::time::Duration; use std::io::Write; use self::mio::*; // Easier to optimize than more intuitive solutions fn packet_handler(player: &mut Player, pack: &mut Packet) -> Option<&'static str> { match pack.id { 1 => chat_message(player, pack), 2 => use_entity(player, pack), 3 => is_flying(), 4 => position_update(player, pack), // 5 => look_update(player, pack), //6 => position_and_look_update(player, pack), // 7 => player_digging(player, pack), // 8 => block_placement(player, pack), //9 => held_item_update(player, pack), //10 => action(player, pack), //11 => vehichle_steer(player, pack), //12 => close_window(player, pack), //13 => click_inventory_slot(player, pack), //14 => confirm_transaction(player, pack), //15 => creative_inventory(player, pack), //16 => enchant_item(player, pack), //17 => sign_set(player, pack), //18 => player_abilities(player, pack), //19 => tab_complete(player, pack), //20 => client_settings(player, pack), //21 => spawn_request(player, pack), //22 => plugin_message(player, pack), //23 => spectate(player, pack), //24 => resource_pack_status(player, pack), _ => None, //panic!("invalid packet id"), } } // Types of Data tx's send that can unblock player thread pub enum ReceiverData { // Packet(Packet), TcpErr, // Packet already formed KeepAlive, // Fixme, Thread to thread transmission }
struct MyHandler(TcpStream); impl Handler for MyHandler { type Timeout = (); type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: EventSet) { match token { PLAYER_STREAM => { println!("hi"); } _ => panic!("unexpected token"), } } } pub fn player_loop(mut player: Player) { println!("{} has joined the game", player.name); let addr = player.stream.local_addr().unwrap(); let mut stream = mio::tcp::TcpStream::connect_stream(*player.stream, &addr).unwrap(); let mut event_loop = EventLoop::<MyHandler>::new().unwrap(); event_loop.register(&stream, PLAYER_STREAM, EventSet::readable(), PollOpt::edge()).unwrap(); /* loop { // Large match Easier to optimize than more intuitive solutions match player.rx.recv().unwrap() { ReceiverData::Packet(mut pack) => { if player.health > 0 || pack.id == 0x16 { // Only allow respawn packets if dead match packet_handler(&mut player, &mut pack) { Some(_) => (),//kick_player(e), _ => (), } } }, ReceiverData::KeepAlive => { let _ = player.stream.write(&[0x2u8, 0x0u8, 0x0u8]); }, ReceiverData::TcpErr => return, } }*/ } use struct_types::Location; use to_client; use packet::Packet; use player::Player; fn chat_message(player: &Player, packet: &mut Packet) -> Option<&'static str> { unimplemented!(); } fn use_entity(player: &mut Player, packet: &mut Packet) -> Option<&'static str> { let target_id = packet.get_varint(); let interact_type = packet.getas::<u8>(); if interact_type == 2 { let interact_location = packet.get_location(); if player.location.distance(&interact_location) > 25.0 { Some("overexteding reach") } else { unimplemented!(); } } else { None } } fn is_flying() -> Option<&'static str> { None } fn position_update(player: &mut Player, packet: &mut Packet) -> Option<&'static str> { //Fixe me let new_pos = packet.get_location(); let on_ground = packet.getas::<bool>(); if player.location.distance(&new_pos) > 100.0 { return Some("moving to fast"); } //Fix me, Check for closest y block below to prevent fall damage avoiding let fall_dist = player.last_on_ground.y - new_pos.y - 3.0; if fall_dist > 0.0 && on_ground { player.health -= fall_dist as i16; player.send_health(); player.last_on_ground = new_pos.clone(); } player.location = new_pos; None }
const PLAYER_STREAM: Token = Token(0); const RECIEVER: Token = Token(1);
random_line_split
player_loop.rs
// Tunnul // Copyright (c) 2015, Richard Lettich // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -------------------------------------------------------------------------- // THIS IS NOT AN OFFICIAL MINECRAFT PRODUCT, // NEITHER APPROVED NOR ASSOCIATED WITH MOJANG. // This file contains the player loop and all functions for handling received packets extern crate mio; use player; use packet; use std::net::TcpStream; use std::time::Duration; use std::io::Write; use self::mio::*; // Easier to optimize than more intuitive solutions fn packet_handler(player: &mut Player, pack: &mut Packet) -> Option<&'static str> { match pack.id { 1 => chat_message(player, pack), 2 => use_entity(player, pack), 3 => is_flying(), 4 => position_update(player, pack), // 5 => look_update(player, pack), //6 => position_and_look_update(player, pack), // 7 => player_digging(player, pack), // 8 => block_placement(player, pack), //9 => held_item_update(player, pack), //10 => action(player, pack), //11 => vehichle_steer(player, pack), //12 => close_window(player, pack), //13 => click_inventory_slot(player, pack), //14 => confirm_transaction(player, pack), //15 => creative_inventory(player, pack), //16 => enchant_item(player, pack), //17 => sign_set(player, pack), //18 => player_abilities(player, pack), //19 => tab_complete(player, pack), //20 => client_settings(player, pack), //21 => spawn_request(player, pack), //22 => plugin_message(player, pack), //23 => spectate(player, pack), //24 => resource_pack_status(player, pack), _ => None, //panic!("invalid packet id"), } } // Types of Data tx's send that can unblock player thread pub enum ReceiverData { // Packet(Packet), TcpErr, // Packet already formed KeepAlive, // Fixme, Thread to thread transmission } const PLAYER_STREAM: Token = Token(0); const RECIEVER: Token = Token(1); struct MyHandler(TcpStream); impl Handler for MyHandler { type Timeout = (); type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: EventSet) { match token { PLAYER_STREAM => { println!("hi"); } _ => panic!("unexpected token"), } } } pub fn player_loop(mut player: Player) { println!("{} has joined the game", player.name); let addr = player.stream.local_addr().unwrap(); let mut stream = mio::tcp::TcpStream::connect_stream(*player.stream, &addr).unwrap(); let mut event_loop = EventLoop::<MyHandler>::new().unwrap(); event_loop.register(&stream, PLAYER_STREAM, EventSet::readable(), PollOpt::edge()).unwrap(); /* loop { // Large match Easier to optimize than more intuitive solutions match player.rx.recv().unwrap() { ReceiverData::Packet(mut pack) => { if player.health > 0 || pack.id == 0x16 { // Only allow respawn packets if dead match packet_handler(&mut player, &mut pack) { Some(_) => (),//kick_player(e), _ => (), } } }, ReceiverData::KeepAlive => { let _ = player.stream.write(&[0x2u8, 0x0u8, 0x0u8]); }, ReceiverData::TcpErr => return, } }*/ } use struct_types::Location; use to_client; use packet::Packet; use player::Player; fn chat_message(player: &Player, packet: &mut Packet) -> Option<&'static str>
fn use_entity(player: &mut Player, packet: &mut Packet) -> Option<&'static str> { let target_id = packet.get_varint(); let interact_type = packet.getas::<u8>(); if interact_type == 2 { let interact_location = packet.get_location(); if player.location.distance(&interact_location) > 25.0 { Some("overexteding reach") } else { unimplemented!(); } } else { None } } fn is_flying() -> Option<&'static str> { None } fn position_update(player: &mut Player, packet: &mut Packet) -> Option<&'static str> { //Fixe me let new_pos = packet.get_location(); let on_ground = packet.getas::<bool>(); if player.location.distance(&new_pos) > 100.0 { return Some("moving to fast"); } //Fix me, Check for closest y block below to prevent fall damage avoiding let fall_dist = player.last_on_ground.y - new_pos.y - 3.0; if fall_dist > 0.0 && on_ground { player.health -= fall_dist as i16; player.send_health(); player.last_on_ground = new_pos.clone(); } player.location = new_pos; None }
{ unimplemented!(); }
identifier_body
mod.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. //! Networking primitives for TCP/UDP communication. #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use io::{self, Error, ErrorKind}; use sys_common::net as net_imp; pub use self::ip::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope}; pub use self::addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; pub use self::tcp::{TcpStream, TcpListener, Incoming}; pub use self::udp::UdpSocket; pub use self::parser::AddrParseError; mod ip; mod addr; mod tcp; mod udp; mod parser; #[cfg(test)] mod test; /// Possible values which can be passed to the `shutdown` method of `TcpStream`.
#[derive(Copy, Clone, PartialEq, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub enum Shutdown { /// Indicates that the reading portion of this stream/socket should be shut /// down. All currently blocked and future reads will return `Ok(0)`. #[stable(feature = "rust1", since = "1.0.0")] Read, /// Indicates that the writing portion of this stream/socket should be shut /// down. All currently blocked and future writes will return an error. #[stable(feature = "rust1", since = "1.0.0")] Write, /// Shut down both the reading and writing portions of this stream. /// /// See `Shutdown::Read` and `Shutdown::Write` for more information. #[stable(feature = "rust1", since = "1.0.0")] Both, } #[doc(hidden)] trait NetInt { fn from_be(i: Self) -> Self; fn to_be(&self) -> Self; } macro_rules! doit { ($($t:ident)*) => ($(impl NetInt for $t { fn from_be(i: Self) -> Self { <$t>::from_be(i) } fn to_be(&self) -> Self { <$t>::to_be(*self) } })*) } doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } fn hton<I: NetInt>(i: I) -> I { i.to_be() } fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) } fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T> where F: FnMut(&SocketAddr) -> io::Result<T> { let mut last_err = None; for addr in try!(addr.to_socket_addrs()) { match f(&addr) { Ok(l) => return Ok(l), Err(e) => last_err = Some(e), } } Err(last_err.unwrap_or_else(|| { Error::new(ErrorKind::InvalidInput, "could not resolve to any addresses") })) } /// An iterator over `SocketAddr` values returned from a host lookup operation. #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] pub struct LookupHost(net_imp::LookupHost); #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] impl Iterator for LookupHost { type Item = io::Result<SocketAddr>; fn next(&mut self) -> Option<io::Result<SocketAddr>> { self.0.next() } } /// Resolve the host specified by `host` as a number of `SocketAddr` instances. /// /// This method may perform a DNS query to resolve `host` and may also inspect /// system configuration to resolve the specified hostname. /// /// # Examples /// /// ```no_run /// #![feature(lookup_host)] /// /// use std::net; /// /// # fn foo() -> std::io::Result<()> { /// for host in try!(net::lookup_host("rust-lang.org")) { /// println!("found address: {}", try!(host)); /// } /// # Ok(()) /// # } /// ``` #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] pub fn lookup_host(host: &str) -> io::Result<LookupHost> { net_imp::lookup_host(host).map(LookupHost) } /// Resolve the given address to a hostname. /// /// This function may perform a DNS query to resolve `addr` and may also inspect /// system configuration to resolve the specified address. If the address /// cannot be resolved, it is returned in string format. #[unstable(feature = "lookup_addr", reason = "recent addition", issue = "27705")] pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> { net_imp::lookup_addr(addr) }
random_line_split
mod.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. //! Networking primitives for TCP/UDP communication. #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use io::{self, Error, ErrorKind}; use sys_common::net as net_imp; pub use self::ip::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope}; pub use self::addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; pub use self::tcp::{TcpStream, TcpListener, Incoming}; pub use self::udp::UdpSocket; pub use self::parser::AddrParseError; mod ip; mod addr; mod tcp; mod udp; mod parser; #[cfg(test)] mod test; /// Possible values which can be passed to the `shutdown` method of `TcpStream`. #[derive(Copy, Clone, PartialEq, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub enum Shutdown { /// Indicates that the reading portion of this stream/socket should be shut /// down. All currently blocked and future reads will return `Ok(0)`. #[stable(feature = "rust1", since = "1.0.0")] Read, /// Indicates that the writing portion of this stream/socket should be shut /// down. All currently blocked and future writes will return an error. #[stable(feature = "rust1", since = "1.0.0")] Write, /// Shut down both the reading and writing portions of this stream. /// /// See `Shutdown::Read` and `Shutdown::Write` for more information. #[stable(feature = "rust1", since = "1.0.0")] Both, } #[doc(hidden)] trait NetInt { fn from_be(i: Self) -> Self; fn to_be(&self) -> Self; } macro_rules! doit { ($($t:ident)*) => ($(impl NetInt for $t { fn from_be(i: Self) -> Self { <$t>::from_be(i) } fn to_be(&self) -> Self { <$t>::to_be(*self) } })*) } doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } fn hton<I: NetInt>(i: I) -> I { i.to_be() } fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) } fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T> where F: FnMut(&SocketAddr) -> io::Result<T> { let mut last_err = None; for addr in try!(addr.to_socket_addrs()) { match f(&addr) { Ok(l) => return Ok(l), Err(e) => last_err = Some(e), } } Err(last_err.unwrap_or_else(|| { Error::new(ErrorKind::InvalidInput, "could not resolve to any addresses") })) } /// An iterator over `SocketAddr` values returned from a host lookup operation. #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] pub struct LookupHost(net_imp::LookupHost); #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] impl Iterator for LookupHost { type Item = io::Result<SocketAddr>; fn
(&mut self) -> Option<io::Result<SocketAddr>> { self.0.next() } } /// Resolve the host specified by `host` as a number of `SocketAddr` instances. /// /// This method may perform a DNS query to resolve `host` and may also inspect /// system configuration to resolve the specified hostname. /// /// # Examples /// /// ```no_run /// #![feature(lookup_host)] /// /// use std::net; /// /// # fn foo() -> std::io::Result<()> { /// for host in try!(net::lookup_host("rust-lang.org")) { /// println!("found address: {}", try!(host)); /// } /// # Ok(()) /// # } /// ``` #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] pub fn lookup_host(host: &str) -> io::Result<LookupHost> { net_imp::lookup_host(host).map(LookupHost) } /// Resolve the given address to a hostname. /// /// This function may perform a DNS query to resolve `addr` and may also inspect /// system configuration to resolve the specified address. If the address /// cannot be resolved, it is returned in string format. #[unstable(feature = "lookup_addr", reason = "recent addition", issue = "27705")] pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> { net_imp::lookup_addr(addr) }
next
identifier_name
mod.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. //! Networking primitives for TCP/UDP communication. #![stable(feature = "rust1", since = "1.0.0")] use prelude::v1::*; use io::{self, Error, ErrorKind}; use sys_common::net as net_imp; pub use self::ip::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope}; pub use self::addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; pub use self::tcp::{TcpStream, TcpListener, Incoming}; pub use self::udp::UdpSocket; pub use self::parser::AddrParseError; mod ip; mod addr; mod tcp; mod udp; mod parser; #[cfg(test)] mod test; /// Possible values which can be passed to the `shutdown` method of `TcpStream`. #[derive(Copy, Clone, PartialEq, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub enum Shutdown { /// Indicates that the reading portion of this stream/socket should be shut /// down. All currently blocked and future reads will return `Ok(0)`. #[stable(feature = "rust1", since = "1.0.0")] Read, /// Indicates that the writing portion of this stream/socket should be shut /// down. All currently blocked and future writes will return an error. #[stable(feature = "rust1", since = "1.0.0")] Write, /// Shut down both the reading and writing portions of this stream. /// /// See `Shutdown::Read` and `Shutdown::Write` for more information. #[stable(feature = "rust1", since = "1.0.0")] Both, } #[doc(hidden)] trait NetInt { fn from_be(i: Self) -> Self; fn to_be(&self) -> Self; } macro_rules! doit { ($($t:ident)*) => ($(impl NetInt for $t { fn from_be(i: Self) -> Self { <$t>::from_be(i) } fn to_be(&self) -> Self { <$t>::to_be(*self) } })*) } doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } fn hton<I: NetInt>(i: I) -> I { i.to_be() } fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) } fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T> where F: FnMut(&SocketAddr) -> io::Result<T> { let mut last_err = None; for addr in try!(addr.to_socket_addrs()) { match f(&addr) { Ok(l) => return Ok(l), Err(e) => last_err = Some(e), } } Err(last_err.unwrap_or_else(|| { Error::new(ErrorKind::InvalidInput, "could not resolve to any addresses") })) } /// An iterator over `SocketAddr` values returned from a host lookup operation. #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] pub struct LookupHost(net_imp::LookupHost); #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] impl Iterator for LookupHost { type Item = io::Result<SocketAddr>; fn next(&mut self) -> Option<io::Result<SocketAddr>> { self.0.next() } } /// Resolve the host specified by `host` as a number of `SocketAddr` instances. /// /// This method may perform a DNS query to resolve `host` and may also inspect /// system configuration to resolve the specified hostname. /// /// # Examples /// /// ```no_run /// #![feature(lookup_host)] /// /// use std::net; /// /// # fn foo() -> std::io::Result<()> { /// for host in try!(net::lookup_host("rust-lang.org")) { /// println!("found address: {}", try!(host)); /// } /// # Ok(()) /// # } /// ``` #[unstable(feature = "lookup_host", reason = "unsure about the returned \ iterator and returning socket \ addresses", issue = "27705")] pub fn lookup_host(host: &str) -> io::Result<LookupHost> { net_imp::lookup_host(host).map(LookupHost) } /// Resolve the given address to a hostname. /// /// This function may perform a DNS query to resolve `addr` and may also inspect /// system configuration to resolve the specified address. If the address /// cannot be resolved, it is returned in string format. #[unstable(feature = "lookup_addr", reason = "recent addition", issue = "27705")] pub fn lookup_addr(addr: &IpAddr) -> io::Result<String>
{ net_imp::lookup_addr(addr) }
identifier_body
issue-2735-3.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; // This test should behave exactly like issue-2735-2 struct defer<'a> { b: &'a Cell<bool>, } impl<'a> Drop for defer<'a> { fn
(&mut self) { self.b.set(true); } } fn defer(b: &Cell<bool>) -> defer { defer { b: b } } pub fn main() { let dtor_ran = &Cell::new(false); defer(dtor_ran); assert!(dtor_ran.get()); }
drop
identifier_name
issue-2735-3.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; // This test should behave exactly like issue-2735-2 struct defer<'a> { b: &'a Cell<bool>, } impl<'a> Drop for defer<'a> { fn drop(&mut self) { self.b.set(true); } } fn defer(b: &Cell<bool>) -> defer
pub fn main() { let dtor_ran = &Cell::new(false); defer(dtor_ran); assert!(dtor_ran.get()); }
{ defer { b: b } }
identifier_body
issue-2735-3.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; // This test should behave exactly like issue-2735-2
impl<'a> Drop for defer<'a> { fn drop(&mut self) { self.b.set(true); } } fn defer(b: &Cell<bool>) -> defer { defer { b: b } } pub fn main() { let dtor_ran = &Cell::new(false); defer(dtor_ran); assert!(dtor_ran.get()); }
struct defer<'a> { b: &'a Cell<bool>, }
random_line_split
textobject.rs
use std::default::Default; use editor::text_editor::buffer::Mark; #[derive(Copy, Clone, Debug)] pub enum Kind { Char, Line(Anchor), Word(Anchor), // Sentence(Anchor), // Paragraph(Anchor), // Expression(Anchor), // Statement(Anchor), // Block(Anchor), } impl Kind { pub fn with_anchor(&self, anchor: Anchor) -> Kind { match *self { Kind::Char => Kind::Char, Kind::Line(_) => Kind::Line(anchor), Kind::Word(_) => Kind::Word(anchor), } } pub fn get_anchor(&self) -> Anchor { match *self { Kind::Char => Default::default(), Kind::Line(a) | Kind::Word(a) => a, } } } impl Default for Kind { fn default() -> Kind
} #[derive(Copy, Clone, Debug)] pub enum Anchor { Before, // Index just prior to TextObject Start, // First index within TextObject // Middle, // Middle index of TextObject End, // Last index within TextObject After, // First index after TextObject Same, // Same as index within current TextObject of the same Kind } impl Default for Anchor { fn default() -> Anchor { Anchor::Same } } #[derive(Copy, Clone, Debug)] pub enum Offset { Absolute(usize), Backward(usize, Mark), Forward(usize, Mark), } impl Offset { pub fn with_num(&self, n: usize) -> Offset{ match *self { Offset::Absolute(_) => Offset::Absolute(n), Offset::Backward(_, m) => Offset::Backward(n, m), Offset::Forward(_, m) => Offset::Forward(n, m), } } } impl Default for Offset { fn default() -> Offset { Offset::Forward(0, Mark::Cursor(0)) } } #[derive(Copy, Clone, Debug)] pub struct TextObject { pub kind: Kind, pub offset: Offset } impl Default for TextObject { fn default() -> TextObject { TextObject { kind: Default::default(), offset: Default::default() } } }
{ Kind::Char }
identifier_body
textobject.rs
use std::default::Default; use editor::text_editor::buffer::Mark; #[derive(Copy, Clone, Debug)] pub enum Kind { Char, Line(Anchor), Word(Anchor), // Sentence(Anchor), // Paragraph(Anchor), // Expression(Anchor), // Statement(Anchor), // Block(Anchor), } impl Kind { pub fn with_anchor(&self, anchor: Anchor) -> Kind { match *self { Kind::Char => Kind::Char, Kind::Line(_) => Kind::Line(anchor), Kind::Word(_) => Kind::Word(anchor), } } pub fn get_anchor(&self) -> Anchor { match *self { Kind::Char => Default::default(), Kind::Line(a) | Kind::Word(a) => a, } } } impl Default for Kind { fn default() -> Kind { Kind::Char } } #[derive(Copy, Clone, Debug)]
pub enum Anchor { Before, // Index just prior to TextObject Start, // First index within TextObject // Middle, // Middle index of TextObject End, // Last index within TextObject After, // First index after TextObject Same, // Same as index within current TextObject of the same Kind } impl Default for Anchor { fn default() -> Anchor { Anchor::Same } } #[derive(Copy, Clone, Debug)] pub enum Offset { Absolute(usize), Backward(usize, Mark), Forward(usize, Mark), } impl Offset { pub fn with_num(&self, n: usize) -> Offset{ match *self { Offset::Absolute(_) => Offset::Absolute(n), Offset::Backward(_, m) => Offset::Backward(n, m), Offset::Forward(_, m) => Offset::Forward(n, m), } } } impl Default for Offset { fn default() -> Offset { Offset::Forward(0, Mark::Cursor(0)) } } #[derive(Copy, Clone, Debug)] pub struct TextObject { pub kind: Kind, pub offset: Offset } impl Default for TextObject { fn default() -> TextObject { TextObject { kind: Default::default(), offset: Default::default() } } }
random_line_split
textobject.rs
use std::default::Default; use editor::text_editor::buffer::Mark; #[derive(Copy, Clone, Debug)] pub enum Kind { Char, Line(Anchor), Word(Anchor), // Sentence(Anchor), // Paragraph(Anchor), // Expression(Anchor), // Statement(Anchor), // Block(Anchor), } impl Kind { pub fn with_anchor(&self, anchor: Anchor) -> Kind { match *self { Kind::Char => Kind::Char, Kind::Line(_) => Kind::Line(anchor), Kind::Word(_) => Kind::Word(anchor), } } pub fn get_anchor(&self) -> Anchor { match *self { Kind::Char => Default::default(), Kind::Line(a) | Kind::Word(a) => a, } } } impl Default for Kind { fn default() -> Kind { Kind::Char } } #[derive(Copy, Clone, Debug)] pub enum Anchor { Before, // Index just prior to TextObject Start, // First index within TextObject // Middle, // Middle index of TextObject End, // Last index within TextObject After, // First index after TextObject Same, // Same as index within current TextObject of the same Kind } impl Default for Anchor { fn default() -> Anchor { Anchor::Same } } #[derive(Copy, Clone, Debug)] pub enum Offset { Absolute(usize), Backward(usize, Mark), Forward(usize, Mark), } impl Offset { pub fn with_num(&self, n: usize) -> Offset{ match *self { Offset::Absolute(_) => Offset::Absolute(n), Offset::Backward(_, m) => Offset::Backward(n, m), Offset::Forward(_, m) => Offset::Forward(n, m), } } } impl Default for Offset { fn default() -> Offset { Offset::Forward(0, Mark::Cursor(0)) } } #[derive(Copy, Clone, Debug)] pub struct
{ pub kind: Kind, pub offset: Offset } impl Default for TextObject { fn default() -> TextObject { TextObject { kind: Default::default(), offset: Default::default() } } }
TextObject
identifier_name
e05-atexit-type.rs
/// Exercise 7.5: Use the typedef facility of C to define a new data type Exitfunc for an exit /// handler. Redo the prototype for atexit using this data type. /// /// $ e05-atexit-type /// main is done /// first exit handler /// first exit handler /// second exit handler extern crate libc; #[macro_use(cstr)] extern crate apue; extern crate errno; use apue::LibcResult; use libc::{atexit, printf}; type Exitfunc = extern "C" fn(); fn my_atexit(f: Exitfunc) -> std::io::Result<i32> { unsafe { atexit(f).check_not_negative() } } extern "C" fn my_exit1() { unsafe { printf(cstr!("first exit handler\n")) }; } extern "C" fn
() { unsafe { printf(cstr!("second exit handler\n")) }; } fn main() { my_atexit(my_exit2).expect(&format!("can't register my_exit2: {}", errno::errno())); my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno())); my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno())); println!("main is done"); }
my_exit2
identifier_name
e05-atexit-type.rs
/// Exercise 7.5: Use the typedef facility of C to define a new data type Exitfunc for an exit /// handler. Redo the prototype for atexit using this data type. /// /// $ e05-atexit-type /// main is done /// first exit handler /// first exit handler /// second exit handler extern crate libc; #[macro_use(cstr)] extern crate apue; extern crate errno; use apue::LibcResult; use libc::{atexit, printf}; type Exitfunc = extern "C" fn(); fn my_atexit(f: Exitfunc) -> std::io::Result<i32> { unsafe { atexit(f).check_not_negative() } } extern "C" fn my_exit1()
extern "C" fn my_exit2() { unsafe { printf(cstr!("second exit handler\n")) }; } fn main() { my_atexit(my_exit2).expect(&format!("can't register my_exit2: {}", errno::errno())); my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno())); my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno())); println!("main is done"); }
{ unsafe { printf(cstr!("first exit handler\n")) }; }
identifier_body
e05-atexit-type.rs
/// Exercise 7.5: Use the typedef facility of C to define a new data type Exitfunc for an exit /// handler. Redo the prototype for atexit using this data type. /// /// $ e05-atexit-type /// main is done /// first exit handler /// first exit handler /// second exit handler extern crate libc; #[macro_use(cstr)] extern crate apue; extern crate errno; use apue::LibcResult; use libc::{atexit, printf}; type Exitfunc = extern "C" fn(); fn my_atexit(f: Exitfunc) -> std::io::Result<i32> {
unsafe { atexit(f).check_not_negative() } } extern "C" fn my_exit1() { unsafe { printf(cstr!("first exit handler\n")) }; } extern "C" fn my_exit2() { unsafe { printf(cstr!("second exit handler\n")) }; } fn main() { my_atexit(my_exit2).expect(&format!("can't register my_exit2: {}", errno::errno())); my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno())); my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno())); println!("main is done"); }
random_line_split
main.rs
extern crate iron; extern crate logger; extern crate router; extern crate hyper; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; #[macro_use] extern crate log; extern crate env_logger; use std::str::FromStr; use std::io::Read; use iron::prelude::*; use router::Router; use hyper::client::{Client, Body}; use logger::Logger; struct Forwarder { client: Client, protocol: String, domain: String, } impl Forwarder { fn forward(&self, req: &mut Request) { let mut url_base = String::new(); url_base.push_str(&self.protocol); url_base.push_str("://"); url_base.push_str(&self.domain); url_base.push_str("/"); url_base.push_str(&req.url.path().join("/")); if let Some(ref q) = req.url.query()
let mut body = Vec::new(); req.body.read_to_end(&mut body); self.client.request(req.method.clone(), &url_base) .headers(req.headers.clone()) .body(Body::BufBody(body.as_slice(), body.len())) .send() .unwrap(); } fn new(protocol: &str, domain: &str) -> Forwarder { Forwarder { client: Client::new(), protocol: String::from_str(protocol).unwrap(), domain: String::from_str(domain).unwrap()} } } fn forward(req: &mut Request) -> IronResult<Response> { let forwarder = Forwarder::new("http", "localhost:6668"); forwarder.forward(req); Ok(Response::with((iron::status::Ok, "Hello world"))) } #[derive(Serialize)] struct Stats { requests_forwarded: u64, target_requests_per_second: f64, average_requests_per_second: f64, max_requests_per_second: f64, buffer_size_in_bytes: usize, } fn stat_handler(req: &mut Request) -> IronResult<Response> { let stats = Stats { requests_forwarded: 345242, target_requests_per_second: 250., average_requests_per_second: 261., max_requests_per_second: 342., buffer_size_in_bytes: 5098231, }; Ok(Response::with((iron::status::Ok, serde_json::to_string(&stats).unwrap()))) } fn rate_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn buffer_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn get_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn set_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn main() { env_logger::init().unwrap(); let (logger_before, logger_after) = Logger::new(None); let mut forward_chain = Chain::new(forward); forward_chain.link_before(logger_before); forward_chain.link_after(logger_after); let forward_server = Iron::new(forward_chain).http("localhost:6666"); let mut router = Router::new(); router.get("/stat", stat_handler, "stat"); router.put("/rate", rate_handler, "rate"); router.delete("/buffer", buffer_handler, "buffer"); router.get("/target", get_target, "get_target"); router.put("/target", set_target, "set_target"); let admin_server = Iron::new(router).http("localhost:6667"); debug!("debug logging on"); println!("Ready"); forward_server.unwrap(); }
{ url_base.push_str("?"); url_base.push_str(q); }
conditional_block
main.rs
extern crate iron; extern crate logger; extern crate router; extern crate hyper; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; #[macro_use] extern crate log; extern crate env_logger; use std::str::FromStr; use std::io::Read; use iron::prelude::*; use router::Router; use hyper::client::{Client, Body}; use logger::Logger; struct Forwarder { client: Client, protocol: String, domain: String, } impl Forwarder { fn forward(&self, req: &mut Request) { let mut url_base = String::new(); url_base.push_str(&self.protocol); url_base.push_str("://"); url_base.push_str(&self.domain); url_base.push_str("/"); url_base.push_str(&req.url.path().join("/")); if let Some(ref q) = req.url.query() { url_base.push_str("?"); url_base.push_str(q);
} let mut body = Vec::new(); req.body.read_to_end(&mut body); self.client.request(req.method.clone(), &url_base) .headers(req.headers.clone()) .body(Body::BufBody(body.as_slice(), body.len())) .send() .unwrap(); } fn new(protocol: &str, domain: &str) -> Forwarder { Forwarder { client: Client::new(), protocol: String::from_str(protocol).unwrap(), domain: String::from_str(domain).unwrap()} } } fn forward(req: &mut Request) -> IronResult<Response> { let forwarder = Forwarder::new("http", "localhost:6668"); forwarder.forward(req); Ok(Response::with((iron::status::Ok, "Hello world"))) } #[derive(Serialize)] struct Stats { requests_forwarded: u64, target_requests_per_second: f64, average_requests_per_second: f64, max_requests_per_second: f64, buffer_size_in_bytes: usize, } fn stat_handler(req: &mut Request) -> IronResult<Response> { let stats = Stats { requests_forwarded: 345242, target_requests_per_second: 250., average_requests_per_second: 261., max_requests_per_second: 342., buffer_size_in_bytes: 5098231, }; Ok(Response::with((iron::status::Ok, serde_json::to_string(&stats).unwrap()))) } fn rate_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn buffer_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn get_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn set_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn main() { env_logger::init().unwrap(); let (logger_before, logger_after) = Logger::new(None); let mut forward_chain = Chain::new(forward); forward_chain.link_before(logger_before); forward_chain.link_after(logger_after); let forward_server = Iron::new(forward_chain).http("localhost:6666"); let mut router = Router::new(); router.get("/stat", stat_handler, "stat"); router.put("/rate", rate_handler, "rate"); router.delete("/buffer", buffer_handler, "buffer"); router.get("/target", get_target, "get_target"); router.put("/target", set_target, "set_target"); let admin_server = Iron::new(router).http("localhost:6667"); debug!("debug logging on"); println!("Ready"); forward_server.unwrap(); }
random_line_split
main.rs
extern crate iron; extern crate logger; extern crate router; extern crate hyper; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; #[macro_use] extern crate log; extern crate env_logger; use std::str::FromStr; use std::io::Read; use iron::prelude::*; use router::Router; use hyper::client::{Client, Body}; use logger::Logger; struct Forwarder { client: Client, protocol: String, domain: String, } impl Forwarder { fn forward(&self, req: &mut Request) { let mut url_base = String::new(); url_base.push_str(&self.protocol); url_base.push_str("://"); url_base.push_str(&self.domain); url_base.push_str("/"); url_base.push_str(&req.url.path().join("/")); if let Some(ref q) = req.url.query() { url_base.push_str("?"); url_base.push_str(q); } let mut body = Vec::new(); req.body.read_to_end(&mut body); self.client.request(req.method.clone(), &url_base) .headers(req.headers.clone()) .body(Body::BufBody(body.as_slice(), body.len())) .send() .unwrap(); } fn new(protocol: &str, domain: &str) -> Forwarder { Forwarder { client: Client::new(), protocol: String::from_str(protocol).unwrap(), domain: String::from_str(domain).unwrap()} } } fn forward(req: &mut Request) -> IronResult<Response> { let forwarder = Forwarder::new("http", "localhost:6668"); forwarder.forward(req); Ok(Response::with((iron::status::Ok, "Hello world"))) } #[derive(Serialize)] struct Stats { requests_forwarded: u64, target_requests_per_second: f64, average_requests_per_second: f64, max_requests_per_second: f64, buffer_size_in_bytes: usize, } fn stat_handler(req: &mut Request) -> IronResult<Response>
fn rate_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn buffer_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn get_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn set_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn main() { env_logger::init().unwrap(); let (logger_before, logger_after) = Logger::new(None); let mut forward_chain = Chain::new(forward); forward_chain.link_before(logger_before); forward_chain.link_after(logger_after); let forward_server = Iron::new(forward_chain).http("localhost:6666"); let mut router = Router::new(); router.get("/stat", stat_handler, "stat"); router.put("/rate", rate_handler, "rate"); router.delete("/buffer", buffer_handler, "buffer"); router.get("/target", get_target, "get_target"); router.put("/target", set_target, "set_target"); let admin_server = Iron::new(router).http("localhost:6667"); debug!("debug logging on"); println!("Ready"); forward_server.unwrap(); }
{ let stats = Stats { requests_forwarded: 345242, target_requests_per_second: 250., average_requests_per_second: 261., max_requests_per_second: 342., buffer_size_in_bytes: 5098231, }; Ok(Response::with((iron::status::Ok, serde_json::to_string(&stats).unwrap()))) }
identifier_body
main.rs
extern crate iron; extern crate logger; extern crate router; extern crate hyper; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; #[macro_use] extern crate log; extern crate env_logger; use std::str::FromStr; use std::io::Read; use iron::prelude::*; use router::Router; use hyper::client::{Client, Body}; use logger::Logger; struct Forwarder { client: Client, protocol: String, domain: String, } impl Forwarder { fn forward(&self, req: &mut Request) { let mut url_base = String::new(); url_base.push_str(&self.protocol); url_base.push_str("://"); url_base.push_str(&self.domain); url_base.push_str("/"); url_base.push_str(&req.url.path().join("/")); if let Some(ref q) = req.url.query() { url_base.push_str("?"); url_base.push_str(q); } let mut body = Vec::new(); req.body.read_to_end(&mut body); self.client.request(req.method.clone(), &url_base) .headers(req.headers.clone()) .body(Body::BufBody(body.as_slice(), body.len())) .send() .unwrap(); } fn new(protocol: &str, domain: &str) -> Forwarder { Forwarder { client: Client::new(), protocol: String::from_str(protocol).unwrap(), domain: String::from_str(domain).unwrap()} } } fn forward(req: &mut Request) -> IronResult<Response> { let forwarder = Forwarder::new("http", "localhost:6668"); forwarder.forward(req); Ok(Response::with((iron::status::Ok, "Hello world"))) } #[derive(Serialize)] struct Stats { requests_forwarded: u64, target_requests_per_second: f64, average_requests_per_second: f64, max_requests_per_second: f64, buffer_size_in_bytes: usize, } fn stat_handler(req: &mut Request) -> IronResult<Response> { let stats = Stats { requests_forwarded: 345242, target_requests_per_second: 250., average_requests_per_second: 261., max_requests_per_second: 342., buffer_size_in_bytes: 5098231, }; Ok(Response::with((iron::status::Ok, serde_json::to_string(&stats).unwrap()))) } fn rate_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn buffer_handler(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn get_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn set_target(req: &mut Request) -> IronResult<Response> { Ok(Response::with((iron::status::Ok, "Hello admin"))) } fn
() { env_logger::init().unwrap(); let (logger_before, logger_after) = Logger::new(None); let mut forward_chain = Chain::new(forward); forward_chain.link_before(logger_before); forward_chain.link_after(logger_after); let forward_server = Iron::new(forward_chain).http("localhost:6666"); let mut router = Router::new(); router.get("/stat", stat_handler, "stat"); router.put("/rate", rate_handler, "rate"); router.delete("/buffer", buffer_handler, "buffer"); router.get("/target", get_target, "get_target"); router.put("/target", set_target, "set_target"); let admin_server = Iron::new(router).http("localhost:6667"); debug!("debug logging on"); println!("Ready"); forward_server.unwrap(); }
main
identifier_name
worker.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::bindings::error::{Fallible, ErrorResult}; use dom::bindings::error::Error::Syntax; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::refcounted::Trusted; use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, reflect_dom_object}; use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; use dom::errorevent::ErrorEvent; use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; use dom::messageevent::MessageEvent; use script_task::{ScriptChan, ScriptMsg, Runnable}; use util::str::DOMString; use js::jsapi::JSContext; use js::jsval::{JSVal, UndefinedValue}; use url::UrlParser; use std::borrow::ToOwned; use std::cell::Cell; use std::sync::mpsc::{channel, Sender}; pub type TrustedWorkerAddress = Trusted<Worker>; #[dom_struct] pub struct Worker { eventtarget: EventTarget, refcount: Cell<uint>, global: GlobalField, /// Sender to the Receiver associated with the DedicatedWorkerGlobalScope /// this Worker created. sender: Sender<(TrustedWorkerAddress, ScriptMsg)>, } impl Worker { fn new_inherited(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Worker { Worker { eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker), refcount: Cell::new(0), global: GlobalField::from_rooted(&global), sender: sender, } } pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Temporary<Worker> { reflect_dom_object(box Worker::new_inherited(global, sender), global, WorkerBinding::Wrap) } // http://www.whatwg.org/html/#dom-worker pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Temporary<Worker>> { // Step 2-4. let worker_url = match UrlParser::new().base_url(&global.get_url()) .parse(script_url.as_slice()) { Ok(url) => url, Err(_) => return Err(Syntax), }; let resource_task = global.resource_task(); let (sender, receiver) = channel(); let worker = Worker::new(global, sender.clone()).root(); let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan()); DedicatedWorkerGlobalScope::run_worker_scope( worker_url, worker_ref, resource_task, global.script_chan(), sender, receiver); Ok(Temporary::from_rooted(worker.r())) } pub fn handle_message(address: TrustedWorkerAddress, data: StructuredCloneData) { let worker = address.to_temporary().root(); let global = worker.r().global.root(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(worker.r()); let message = data.read(global.r()); MessageEvent::dispatch_jsval(target, global.r(), message); } pub fn
(address: TrustedWorkerAddress, message: DOMString, filename: DOMString, lineno: u32, colno: u32) { let worker = address.to_temporary().root(); let global = worker.r().global.root(); let error = UndefinedValue(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(worker.r()); let errorevent = ErrorEvent::new(global.r(), "error".to_owned(), EventBubbles::Bubbles, EventCancelable::Cancelable, message, filename, lineno, colno, error).root(); let event: JSRef<Event> = EventCast::from_ref(errorevent.r()); event.fire(target); } } impl<'a> WorkerMethods for JSRef<'a, Worker> { fn PostMessage(self, cx: *mut JSContext, message: JSVal) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone()); self.sender.send((address, ScriptMsg::DOMMessage(data))).unwrap(); Ok(()) } event_handler!(message, GetOnmessage, SetOnmessage); } pub struct WorkerMessageHandler { addr: TrustedWorkerAddress, data: StructuredCloneData, } impl WorkerMessageHandler { pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler { WorkerMessageHandler { addr: addr, data: data, } } } impl Runnable for WorkerMessageHandler { fn handler(self: Box<WorkerMessageHandler>) { let this = *self; Worker::handle_message(this.addr, this.data); } }
handle_error_message
identifier_name
worker.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::bindings::error::{Fallible, ErrorResult}; use dom::bindings::error::Error::Syntax; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::refcounted::Trusted; use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, reflect_dom_object}; use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; use dom::errorevent::ErrorEvent; use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; use dom::messageevent::MessageEvent; use script_task::{ScriptChan, ScriptMsg, Runnable}; use util::str::DOMString; use js::jsapi::JSContext; use js::jsval::{JSVal, UndefinedValue}; use url::UrlParser; use std::borrow::ToOwned; use std::cell::Cell; use std::sync::mpsc::{channel, Sender}; pub type TrustedWorkerAddress = Trusted<Worker>; #[dom_struct] pub struct Worker { eventtarget: EventTarget, refcount: Cell<uint>, global: GlobalField, /// Sender to the Receiver associated with the DedicatedWorkerGlobalScope /// this Worker created. sender: Sender<(TrustedWorkerAddress, ScriptMsg)>, } impl Worker { fn new_inherited(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Worker { Worker { eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker), refcount: Cell::new(0), global: GlobalField::from_rooted(&global), sender: sender, } } pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Temporary<Worker> { reflect_dom_object(box Worker::new_inherited(global, sender), global, WorkerBinding::Wrap) } // http://www.whatwg.org/html/#dom-worker pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Temporary<Worker>> { // Step 2-4. let worker_url = match UrlParser::new().base_url(&global.get_url()) .parse(script_url.as_slice()) { Ok(url) => url, Err(_) => return Err(Syntax), }; let resource_task = global.resource_task(); let (sender, receiver) = channel(); let worker = Worker::new(global, sender.clone()).root(); let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan()); DedicatedWorkerGlobalScope::run_worker_scope( worker_url, worker_ref, resource_task, global.script_chan(), sender, receiver); Ok(Temporary::from_rooted(worker.r())) } pub fn handle_message(address: TrustedWorkerAddress, data: StructuredCloneData) { let worker = address.to_temporary().root(); let global = worker.r().global.root(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(worker.r());
} pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString, filename: DOMString, lineno: u32, colno: u32) { let worker = address.to_temporary().root(); let global = worker.r().global.root(); let error = UndefinedValue(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(worker.r()); let errorevent = ErrorEvent::new(global.r(), "error".to_owned(), EventBubbles::Bubbles, EventCancelable::Cancelable, message, filename, lineno, colno, error).root(); let event: JSRef<Event> = EventCast::from_ref(errorevent.r()); event.fire(target); } } impl<'a> WorkerMethods for JSRef<'a, Worker> { fn PostMessage(self, cx: *mut JSContext, message: JSVal) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone()); self.sender.send((address, ScriptMsg::DOMMessage(data))).unwrap(); Ok(()) } event_handler!(message, GetOnmessage, SetOnmessage); } pub struct WorkerMessageHandler { addr: TrustedWorkerAddress, data: StructuredCloneData, } impl WorkerMessageHandler { pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler { WorkerMessageHandler { addr: addr, data: data, } } } impl Runnable for WorkerMessageHandler { fn handler(self: Box<WorkerMessageHandler>) { let this = *self; Worker::handle_message(this.addr, this.data); } }
let message = data.read(global.r()); MessageEvent::dispatch_jsval(target, global.r(), message);
random_line_split