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
move_semantics2.rs
// Make me compile without changing line 9! Scroll down for hints :) pub fn main()
fn fill_vec(vec: &mut Vec<i32>) { vec.push(22); vec.push(44); vec.push(66); } // So `vec0` is being *moved* into the function `fill_vec` when we call it on // line 6, which means it gets dropped at the end of `fill_vec`, which means we // can't use `vec0` again on line 9 (or anywhere else in `main` after the // `fill_vec` call for that matter). We could fix this in a few ways, try them // all! // 1. Make another, separate version of the data that's in `vec0` and pass that // to `fill_vec` instead. // 2. Make `fill_vec` borrow its argument instead of taking ownership of it, // and then copy the data within the function in order to return an owned // `Vec<i32>` // 3. Make `fill_vec` *mutably* borrow its argument (which will need to be // mutable), modify it directly, then not return anything. Then you can get rid // of `vec1` entirely -- note that this will change what gets printed by the // first `println!`
{ let mut vec0 = Vec::new(); fill_vec(&mut vec0); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); vec0.push(88); println!("{} has length {} content `{:?}`", "vec1", vec0.len(), vec0); }
identifier_body
move_semantics2.rs
// Make me compile without changing line 9! Scroll down for hints :) pub fn main() { let mut vec0 = Vec::new(); fill_vec(&mut vec0); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); vec0.push(88); println!("{} has length {} content `{:?}`", "vec1", vec0.len(), vec0); } fn fill_vec(vec: &mut Vec<i32>) { vec.push(22); vec.push(44); vec.push(66); } // So `vec0` is being *moved* into the function `fill_vec` when we call it on
// `fill_vec` call for that matter). We could fix this in a few ways, try them // all! // 1. Make another, separate version of the data that's in `vec0` and pass that // to `fill_vec` instead. // 2. Make `fill_vec` borrow its argument instead of taking ownership of it, // and then copy the data within the function in order to return an owned // `Vec<i32>` // 3. Make `fill_vec` *mutably* borrow its argument (which will need to be // mutable), modify it directly, then not return anything. Then you can get rid // of `vec1` entirely -- note that this will change what gets printed by the // first `println!`
// line 6, which means it gets dropped at the end of `fill_vec`, which means we // can't use `vec0` again on line 9 (or anywhere else in `main` after the
random_line_split
move_semantics2.rs
// Make me compile without changing line 9! Scroll down for hints :) pub fn main() { let mut vec0 = Vec::new(); fill_vec(&mut vec0); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); vec0.push(88); println!("{} has length {} content `{:?}`", "vec1", vec0.len(), vec0); } fn
(vec: &mut Vec<i32>) { vec.push(22); vec.push(44); vec.push(66); } // So `vec0` is being *moved* into the function `fill_vec` when we call it on // line 6, which means it gets dropped at the end of `fill_vec`, which means we // can't use `vec0` again on line 9 (or anywhere else in `main` after the // `fill_vec` call for that matter). We could fix this in a few ways, try them // all! // 1. Make another, separate version of the data that's in `vec0` and pass that // to `fill_vec` instead. // 2. Make `fill_vec` borrow its argument instead of taking ownership of it, // and then copy the data within the function in order to return an owned // `Vec<i32>` // 3. Make `fill_vec` *mutably* borrow its argument (which will need to be // mutable), modify it directly, then not return anything. Then you can get rid // of `vec1` entirely -- note that this will change what gets printed by the // first `println!`
fill_vec
identifier_name
contact_model.rs
#![allow(missing_docs)] use downcast_rs::Downcast; use na::{DVector, RealField}; use ncollide::query::ContactId; use crate::detection::ColliderContactManifold; use crate::material::MaterialsCoefficientsTable; use crate::object::{BodyHandle, BodySet, ColliderHandle}; use crate::solver::{ConstraintSet, IntegrationParameters}; /// The modeling of a contact. pub trait ContactModel<N: RealField, Handle: BodyHandle, CollHandle: ColliderHandle>: Downcast + Send + Sync { /// Maximum number of velocity constraint to be generated for each contact. fn num_velocity_constraints( &self, manifold: &ColliderContactManifold<N, Handle, CollHandle>, ) -> usize; /// Generate all constraints for the given contact manifolds. fn constraints( &mut self, parameters: &IntegrationParameters<N>, material_coefficients: &MaterialsCoefficientsTable<N>, bodies: &dyn BodySet<N, Handle = Handle>, ext_vels: &DVector<N>,
manifolds: &[ColliderContactManifold<N, Handle, CollHandle>], ground_j_id: &mut usize, j_id: &mut usize, jacobians: &mut [N], constraints: &mut ConstraintSet<N, Handle, CollHandle, ContactId>, ); /// Stores all the impulses found by the solver into a cache for warmstarting. fn cache_impulses(&mut self, constraints: &ConstraintSet<N, Handle, CollHandle, ContactId>); } impl_downcast!(ContactModel<N, Handle, CollHandle> where N: RealField, Handle: BodyHandle, CollHandle: ColliderHandle);
random_line_split
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #[macro_use] extern crate capnp_rpc; pub mod calculator_capnp { include!(concat!(env!("OUT_DIR"), "/calculator_capnp.rs")); } pub mod client; pub mod server; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box<dyn std::error::Error>> { let args: Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main().await, "server" => return server::main().await, _ => () } } println!("usage: {} [client | server] ADDRESS", args[0]); Ok(()) }
random_line_split
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #[macro_use] extern crate capnp_rpc; pub mod calculator_capnp { include!(concat!(env!("OUT_DIR"), "/calculator_capnp.rs")); } pub mod client; pub mod server; #[tokio::main(flavor = "current_thread")] async fn
() -> Result<(), Box<dyn std::error::Error>> { let args: Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main().await, "server" => return server::main().await, _ => () } } println!("usage: {} [client | server] ADDRESS", args[0]); Ok(()) }
main
identifier_name
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #[macro_use] extern crate capnp_rpc; pub mod calculator_capnp { include!(concat!(env!("OUT_DIR"), "/calculator_capnp.rs")); } pub mod client; pub mod server; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box<dyn std::error::Error>>
{ let args: Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main().await, "server" => return server::main().await, _ => () } } println!("usage: {} [client | server] ADDRESS", args[0]); Ok(()) }
identifier_body
get.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> 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 // use std::path::PathBuf; use libimagrt::runtime::Runtime; use libimagerror::trace::trace_error_exit; use libimagstore::storeid::StoreId; use retrieve::print_entry; pub fn
(rt: &Runtime) { let scmd = rt.cli().subcommand_matches("get").unwrap(); let id = scmd.value_of("id").unwrap(); // safe by clap let path = PathBuf::from(id); let store = Some(rt.store().path().clone()); let path = StoreId::new(store, path).unwrap_or_else(|e| trace_error_exit(&e, 1)); debug!("path = {:?}", path); let _ = match rt.store().get(path) { Ok(Some(entry)) => print_entry(rt, scmd, entry), Ok(None) => info!("No entry found"), Err(e) => trace_error_exit(&e, 1), }; }
get
identifier_name
get.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> 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 // use std::path::PathBuf; use libimagrt::runtime::Runtime; use libimagerror::trace::trace_error_exit;
use libimagstore::storeid::StoreId; use retrieve::print_entry; pub fn get(rt: &Runtime) { let scmd = rt.cli().subcommand_matches("get").unwrap(); let id = scmd.value_of("id").unwrap(); // safe by clap let path = PathBuf::from(id); let store = Some(rt.store().path().clone()); let path = StoreId::new(store, path).unwrap_or_else(|e| trace_error_exit(&e, 1)); debug!("path = {:?}", path); let _ = match rt.store().get(path) { Ok(Some(entry)) => print_entry(rt, scmd, entry), Ok(None) => info!("No entry found"), Err(e) => trace_error_exit(&e, 1), }; }
random_line_split
get.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> 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 // use std::path::PathBuf; use libimagrt::runtime::Runtime; use libimagerror::trace::trace_error_exit; use libimagstore::storeid::StoreId; use retrieve::print_entry; pub fn get(rt: &Runtime)
{ let scmd = rt.cli().subcommand_matches("get").unwrap(); let id = scmd.value_of("id").unwrap(); // safe by clap let path = PathBuf::from(id); let store = Some(rt.store().path().clone()); let path = StoreId::new(store, path).unwrap_or_else(|e| trace_error_exit(&e, 1)); debug!("path = {:?}", path); let _ = match rt.store().get(path) { Ok(Some(entry)) => print_entry(rt, scmd, entry), Ok(None) => info!("No entry found"), Err(e) => trace_error_exit(&e, 1), }; }
identifier_body
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize = 0o177777_776_000_000_000_0000; static MEMORY_CONTROLLER: Once<Mutex<MemoryController>> = Once::new(); pub struct MemoryController { active_table: paging::ActivePageTable, frame_allocator: AreaFrameAllocator, } impl MemoryController { pub fn map(&mut self, page: Page, flags: EntryFlags) { self.active_table.map(page, flags, &mut self.frame_allocator); } //TODO impl } pub fn controller<'a>() -> MutexGuard<'a, MemoryController> { MEMORY_CONTROLLER.try().expect("Memory not yet initialized").lock() } //TODO Figure out if we want Copy and Clone on this #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub struct Frame { number: usize, } impl Frame { fn containing_address(address: PhysicalAddress) -> Frame { Frame { number: address.get() / PAGE_SIZE } } fn start_address(&self) -> PhysicalAddress { PhysicalAddress::new(self.number * PAGE_SIZE) } fn range_inclusive(start: Frame, end: Frame) -> FrameIter { FrameIter { start: start, end: end, } } } struct FrameIter { start: Frame, end: Frame, } impl Iterator for FrameIter { type Item = Frame; fn next(&mut self) -> Option<Frame> { if self.start <= self.end { let frame = self.start.clone(); self.start.number += 1; Some(frame) } else { None } } } pub trait FrameAllocator { fn allocate_frame(&mut self) -> Option<Frame>; fn deallocate_frame(&mut self, frame: Frame); } /// Align downwards. Returns the greatest x with alignment `align` /// so that x <= addr. The alignment must be a power of 2. pub fn align_down(addr: usize, align: usize) -> usize
/// Align upwards. Returns the smallest x with alignment `align` /// so that x >= addr. The alignment must be a power of 2. pub fn align_up(addr: usize, align: usize) -> usize { align_down(addr + align - 1, align) } pub fn init(boot_info: &::bootinfo::BootInfo) { println!("Initializing Memory"); areas::init(boot_info); info::init(boot_info); let mut frame_allocator = area_frame_allocator::AreaFrameAllocator::new(PhysicalAddress::new(0), info::kernel().end_physical()); let active_table = paging::remap(&mut frame_allocator); MEMORY_CONTROLLER.call_once(|| { Mutex::new(MemoryController { active_table, frame_allocator, }) }); }
{ if align.is_power_of_two() { addr & !(align - 1) } else if align == 0 { addr } else { panic!("`align` must be a power of 2"); } }
identifier_body
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize = 0o177777_776_000_000_000_0000; static MEMORY_CONTROLLER: Once<Mutex<MemoryController>> = Once::new(); pub struct MemoryController { active_table: paging::ActivePageTable, frame_allocator: AreaFrameAllocator, } impl MemoryController { pub fn map(&mut self, page: Page, flags: EntryFlags) { self.active_table.map(page, flags, &mut self.frame_allocator); } //TODO impl } pub fn controller<'a>() -> MutexGuard<'a, MemoryController> {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub struct Frame { number: usize, } impl Frame { fn containing_address(address: PhysicalAddress) -> Frame { Frame { number: address.get() / PAGE_SIZE } } fn start_address(&self) -> PhysicalAddress { PhysicalAddress::new(self.number * PAGE_SIZE) } fn range_inclusive(start: Frame, end: Frame) -> FrameIter { FrameIter { start: start, end: end, } } } struct FrameIter { start: Frame, end: Frame, } impl Iterator for FrameIter { type Item = Frame; fn next(&mut self) -> Option<Frame> { if self.start <= self.end { let frame = self.start.clone(); self.start.number += 1; Some(frame) } else { None } } } pub trait FrameAllocator { fn allocate_frame(&mut self) -> Option<Frame>; fn deallocate_frame(&mut self, frame: Frame); } /// Align downwards. Returns the greatest x with alignment `align` /// so that x <= addr. The alignment must be a power of 2. pub fn align_down(addr: usize, align: usize) -> usize { if align.is_power_of_two() { addr &!(align - 1) } else if align == 0 { addr } else { panic!("`align` must be a power of 2"); } } /// Align upwards. Returns the smallest x with alignment `align` /// so that x >= addr. The alignment must be a power of 2. pub fn align_up(addr: usize, align: usize) -> usize { align_down(addr + align - 1, align) } pub fn init(boot_info: &::bootinfo::BootInfo) { println!("Initializing Memory"); areas::init(boot_info); info::init(boot_info); let mut frame_allocator = area_frame_allocator::AreaFrameAllocator::new(PhysicalAddress::new(0), info::kernel().end_physical()); let active_table = paging::remap(&mut frame_allocator); MEMORY_CONTROLLER.call_once(|| { Mutex::new(MemoryController { active_table, frame_allocator, }) }); }
MEMORY_CONTROLLER.try().expect("Memory not yet initialized").lock() } //TODO Figure out if we want Copy and Clone on this
random_line_split
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize = 0o177777_776_000_000_000_0000; static MEMORY_CONTROLLER: Once<Mutex<MemoryController>> = Once::new(); pub struct MemoryController { active_table: paging::ActivePageTable, frame_allocator: AreaFrameAllocator, } impl MemoryController { pub fn map(&mut self, page: Page, flags: EntryFlags) { self.active_table.map(page, flags, &mut self.frame_allocator); } //TODO impl } pub fn controller<'a>() -> MutexGuard<'a, MemoryController> { MEMORY_CONTROLLER.try().expect("Memory not yet initialized").lock() } //TODO Figure out if we want Copy and Clone on this #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub struct Frame { number: usize, } impl Frame { fn containing_address(address: PhysicalAddress) -> Frame { Frame { number: address.get() / PAGE_SIZE } } fn start_address(&self) -> PhysicalAddress { PhysicalAddress::new(self.number * PAGE_SIZE) } fn range_inclusive(start: Frame, end: Frame) -> FrameIter { FrameIter { start: start, end: end, } } } struct FrameIter { start: Frame, end: Frame, } impl Iterator for FrameIter { type Item = Frame; fn next(&mut self) -> Option<Frame> { if self.start <= self.end { let frame = self.start.clone(); self.start.number += 1; Some(frame) } else { None } } } pub trait FrameAllocator { fn allocate_frame(&mut self) -> Option<Frame>; fn deallocate_frame(&mut self, frame: Frame); } /// Align downwards. Returns the greatest x with alignment `align` /// so that x <= addr. The alignment must be a power of 2. pub fn align_down(addr: usize, align: usize) -> usize { if align.is_power_of_two()
else if align == 0 { addr } else { panic!("`align` must be a power of 2"); } } /// Align upwards. Returns the smallest x with alignment `align` /// so that x >= addr. The alignment must be a power of 2. pub fn align_up(addr: usize, align: usize) -> usize { align_down(addr + align - 1, align) } pub fn init(boot_info: &::bootinfo::BootInfo) { println!("Initializing Memory"); areas::init(boot_info); info::init(boot_info); let mut frame_allocator = area_frame_allocator::AreaFrameAllocator::new(PhysicalAddress::new(0), info::kernel().end_physical()); let active_table = paging::remap(&mut frame_allocator); MEMORY_CONTROLLER.call_once(|| { Mutex::new(MemoryController { active_table, frame_allocator, }) }); }
{ addr & !(align - 1) }
conditional_block
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize = 0o177777_776_000_000_000_0000; static MEMORY_CONTROLLER: Once<Mutex<MemoryController>> = Once::new(); pub struct MemoryController { active_table: paging::ActivePageTable, frame_allocator: AreaFrameAllocator, } impl MemoryController { pub fn map(&mut self, page: Page, flags: EntryFlags) { self.active_table.map(page, flags, &mut self.frame_allocator); } //TODO impl } pub fn controller<'a>() -> MutexGuard<'a, MemoryController> { MEMORY_CONTROLLER.try().expect("Memory not yet initialized").lock() } //TODO Figure out if we want Copy and Clone on this #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub struct Frame { number: usize, } impl Frame { fn containing_address(address: PhysicalAddress) -> Frame { Frame { number: address.get() / PAGE_SIZE } } fn start_address(&self) -> PhysicalAddress { PhysicalAddress::new(self.number * PAGE_SIZE) } fn
(start: Frame, end: Frame) -> FrameIter { FrameIter { start: start, end: end, } } } struct FrameIter { start: Frame, end: Frame, } impl Iterator for FrameIter { type Item = Frame; fn next(&mut self) -> Option<Frame> { if self.start <= self.end { let frame = self.start.clone(); self.start.number += 1; Some(frame) } else { None } } } pub trait FrameAllocator { fn allocate_frame(&mut self) -> Option<Frame>; fn deallocate_frame(&mut self, frame: Frame); } /// Align downwards. Returns the greatest x with alignment `align` /// so that x <= addr. The alignment must be a power of 2. pub fn align_down(addr: usize, align: usize) -> usize { if align.is_power_of_two() { addr &!(align - 1) } else if align == 0 { addr } else { panic!("`align` must be a power of 2"); } } /// Align upwards. Returns the smallest x with alignment `align` /// so that x >= addr. The alignment must be a power of 2. pub fn align_up(addr: usize, align: usize) -> usize { align_down(addr + align - 1, align) } pub fn init(boot_info: &::bootinfo::BootInfo) { println!("Initializing Memory"); areas::init(boot_info); info::init(boot_info); let mut frame_allocator = area_frame_allocator::AreaFrameAllocator::new(PhysicalAddress::new(0), info::kernel().end_physical()); let active_table = paging::remap(&mut frame_allocator); MEMORY_CONTROLLER.call_once(|| { Mutex::new(MemoryController { active_table, frame_allocator, }) }); }
range_inclusive
identifier_name
utils.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_char, c_int, c_void, size_t, uint32_t, uint64_t}; #[repr(C)] pub type wl_argument = uint64_t; #[repr(C)] pub struct wl_array { pub size: size_t, pub alloc: size_t, pub data: *mut c_void, } #[repr(C)] pub type wl_dispatcher_func_t = extern fn( _: *const c_void, _: *mut c_void, _: uint32_t, _: *const wl_message, _: *mut wl_argument); #[repr(C)] pub type wl_fixed_t = uint32_t; #[repr(C)] pub struct wl_interface { pub name: *const c_char, pub version: c_int, pub method_count: c_int, pub methods: *const wl_message, pub event_count: c_int, pub events: *const wl_message, } #[repr(C)] pub struct wl_list { pub prev: *mut wl_list, pub next: *mut wl_list, } #[repr(C)] pub type wl_log_func_t = extern fn(_: *const c_char,...); #[repr(C)] pub struct wl_message { pub name: *const c_char, pub signature: *const c_char, pub types: *mut *const wl_interface, } #[repr(C)] pub struct
;
wl_object
identifier_name
utils.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_char, c_int, c_void, size_t, uint32_t, uint64_t}; #[repr(C)] pub type wl_argument = uint64_t; #[repr(C)] pub struct wl_array { pub size: size_t, pub alloc: size_t, pub data: *mut c_void, } #[repr(C)] pub type wl_dispatcher_func_t = extern fn( _: *const c_void, _: *mut c_void, _: uint32_t, _: *const wl_message, _: *mut wl_argument); #[repr(C)] pub type wl_fixed_t = uint32_t; #[repr(C)] pub struct wl_interface { pub name: *const c_char, pub version: c_int, pub method_count: c_int, pub methods: *const wl_message, pub event_count: c_int, pub events: *const wl_message, } #[repr(C)] pub struct wl_list { pub prev: *mut wl_list,
pub next: *mut wl_list, } #[repr(C)] pub type wl_log_func_t = extern fn(_: *const c_char,...); #[repr(C)] pub struct wl_message { pub name: *const c_char, pub signature: *const c_char, pub types: *mut *const wl_interface, } #[repr(C)] pub struct wl_object;
random_line_split
4_04_system_of_systems.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // example 4-04: System of Systems use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { systems: Vec<ParticleSystem>, } // A simple particle type struct Particle { position: Point2<f32>, velocity: Vector2<f32>, acceleration: Vector2<f32>, life_span: f32, } impl Particle { fn new(l: Point2<f32>) -> Self { let acceleration = vec2(0.0, 0.05); let velocity = vec2(random_f32() * 2.0 - 1.0, random_f32() - 2.0); let position = l; let life_span = 255.0; Particle { acceleration, velocity, position, life_span, } } // Method to update position fn update(&mut self) { self.velocity += self.acceleration; self.position -= self.velocity; self.life_span -= 2.0; } // Method to display fn display(&self, draw: &Draw) { let size = 12.0; draw.ellipse() .xy(self.position) .w_h(size, size) .rgba(0.5, 0.5, 0.5, self.life_span / 255.0) .stroke(rgba(0.0, 0.0, 0.0, self.life_span / 255.0)) .stroke_weight(2.0); } // Is the particle still useful? fn is_dead(&self) -> bool { if self.life_span < 0.0 { true } else { false } } }
struct ParticleSystem { particles: Vec<Particle>, origin: Point2<f32>, } impl ParticleSystem { fn new(num: i32, position: Point2<f32>) -> Self { let origin = position; // An origin point for where particles are birthed let mut particles = Vec::new(); // Initialise the Vector for _i in 0..num { particles.push(Particle::new(origin)); // Add "num" amount of particles to the vector } ParticleSystem { origin, particles } } fn add_particle(&mut self) { self.particles.push(Particle::new(self.origin)); } fn update(&mut self) { for i in (0..self.particles.len()).rev() { self.particles[i].update(); if self.particles[i].is_dead() { self.particles.remove(i); } } } fn draw(&self, draw: &Draw) { for p in self.particles.iter() { p.display(&draw); } } // A method to test if the particle system still has particles fn _dead(&self) -> bool { if self.particles.is_empty() { true } else { false } } } fn model(app: &App) -> Model { app.new_window() .size(640, 360) .mouse_pressed(mouse_pressed) .view(view) .build() .unwrap(); let systems = Vec::new(); Model { systems } } fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) { m.systems .push(ParticleSystem::new(1, pt2(app.mouse.x, app.mouse.y))); } fn update(_app: &App, m: &mut Model, _update: Update) { for ps in m.systems.iter_mut() { ps.add_particle(); ps.update(); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); for i in 0..m.systems.len() { m.systems[i].draw(&draw); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); }
random_line_split
4_04_system_of_systems.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // example 4-04: System of Systems use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { systems: Vec<ParticleSystem>, } // A simple particle type struct Particle { position: Point2<f32>, velocity: Vector2<f32>, acceleration: Vector2<f32>, life_span: f32, } impl Particle { fn new(l: Point2<f32>) -> Self { let acceleration = vec2(0.0, 0.05); let velocity = vec2(random_f32() * 2.0 - 1.0, random_f32() - 2.0); let position = l; let life_span = 255.0; Particle { acceleration, velocity, position, life_span, } } // Method to update position fn update(&mut self) { self.velocity += self.acceleration; self.position -= self.velocity; self.life_span -= 2.0; } // Method to display fn display(&self, draw: &Draw) { let size = 12.0; draw.ellipse() .xy(self.position) .w_h(size, size) .rgba(0.5, 0.5, 0.5, self.life_span / 255.0) .stroke(rgba(0.0, 0.0, 0.0, self.life_span / 255.0)) .stroke_weight(2.0); } // Is the particle still useful? fn is_dead(&self) -> bool { if self.life_span < 0.0 { true } else
} } struct ParticleSystem { particles: Vec<Particle>, origin: Point2<f32>, } impl ParticleSystem { fn new(num: i32, position: Point2<f32>) -> Self { let origin = position; // An origin point for where particles are birthed let mut particles = Vec::new(); // Initialise the Vector for _i in 0..num { particles.push(Particle::new(origin)); // Add "num" amount of particles to the vector } ParticleSystem { origin, particles } } fn add_particle(&mut self) { self.particles.push(Particle::new(self.origin)); } fn update(&mut self) { for i in (0..self.particles.len()).rev() { self.particles[i].update(); if self.particles[i].is_dead() { self.particles.remove(i); } } } fn draw(&self, draw: &Draw) { for p in self.particles.iter() { p.display(&draw); } } // A method to test if the particle system still has particles fn _dead(&self) -> bool { if self.particles.is_empty() { true } else { false } } } fn model(app: &App) -> Model { app.new_window() .size(640, 360) .mouse_pressed(mouse_pressed) .view(view) .build() .unwrap(); let systems = Vec::new(); Model { systems } } fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) { m.systems .push(ParticleSystem::new(1, pt2(app.mouse.x, app.mouse.y))); } fn update(_app: &App, m: &mut Model, _update: Update) { for ps in m.systems.iter_mut() { ps.add_particle(); ps.update(); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); for i in 0..m.systems.len() { m.systems[i].draw(&draw); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); }
{ false }
conditional_block
4_04_system_of_systems.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // example 4-04: System of Systems use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct
{ systems: Vec<ParticleSystem>, } // A simple particle type struct Particle { position: Point2<f32>, velocity: Vector2<f32>, acceleration: Vector2<f32>, life_span: f32, } impl Particle { fn new(l: Point2<f32>) -> Self { let acceleration = vec2(0.0, 0.05); let velocity = vec2(random_f32() * 2.0 - 1.0, random_f32() - 2.0); let position = l; let life_span = 255.0; Particle { acceleration, velocity, position, life_span, } } // Method to update position fn update(&mut self) { self.velocity += self.acceleration; self.position -= self.velocity; self.life_span -= 2.0; } // Method to display fn display(&self, draw: &Draw) { let size = 12.0; draw.ellipse() .xy(self.position) .w_h(size, size) .rgba(0.5, 0.5, 0.5, self.life_span / 255.0) .stroke(rgba(0.0, 0.0, 0.0, self.life_span / 255.0)) .stroke_weight(2.0); } // Is the particle still useful? fn is_dead(&self) -> bool { if self.life_span < 0.0 { true } else { false } } } struct ParticleSystem { particles: Vec<Particle>, origin: Point2<f32>, } impl ParticleSystem { fn new(num: i32, position: Point2<f32>) -> Self { let origin = position; // An origin point for where particles are birthed let mut particles = Vec::new(); // Initialise the Vector for _i in 0..num { particles.push(Particle::new(origin)); // Add "num" amount of particles to the vector } ParticleSystem { origin, particles } } fn add_particle(&mut self) { self.particles.push(Particle::new(self.origin)); } fn update(&mut self) { for i in (0..self.particles.len()).rev() { self.particles[i].update(); if self.particles[i].is_dead() { self.particles.remove(i); } } } fn draw(&self, draw: &Draw) { for p in self.particles.iter() { p.display(&draw); } } // A method to test if the particle system still has particles fn _dead(&self) -> bool { if self.particles.is_empty() { true } else { false } } } fn model(app: &App) -> Model { app.new_window() .size(640, 360) .mouse_pressed(mouse_pressed) .view(view) .build() .unwrap(); let systems = Vec::new(); Model { systems } } fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) { m.systems .push(ParticleSystem::new(1, pt2(app.mouse.x, app.mouse.y))); } fn update(_app: &App, m: &mut Model, _update: Update) { for ps in m.systems.iter_mut() { ps.add_particle(); ps.update(); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); for i in 0..m.systems.len() { m.systems[i].draw(&draw); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); }
Model
identifier_name
mongo.rs
extern crate bson; extern crate mongo_driver; use bson::Bson; use mongo_driver::CommandAndFindOptions; use mongo_driver::client::{ClientPool, Uri}; use mongo_driver::collection::UpdateOptions; use mongo_driver::flags::UpdateFlag; use config::DBConfig; use objects::{utils, Object}; use storage::error::{StoreError, StoreResult}; use storage::storage::{Storage, StorageStatus}; pub struct
{ config: DBConfig, pool: ClientPool, } impl MongoStore { pub fn new(config: &DBConfig) -> StoreResult<MongoStore> { let conn = MongoStore::conn( config.username.as_str(), config.password.as_str(), config.host.as_str(), config.port, ); let uri = Uri::new(conn.clone()).ok_or(StoreError::UriParseError(conn))?; let pool = ClientPool::new(uri, None); Ok(MongoStore { config: config.clone(), pool: pool, }) } fn conn(user: &str, pass: &str, host: &str, port: u16) -> String { format!("mongodb://{}:{}@{}:{}", user, pass, host, port) } } impl Storage<Object> for MongoStore { fn get(&self, id: &str, obj_type: &str) -> Option<StoreResult<Object>> { let query = doc!{ "_id" => id }; let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), obj_type); let res = coll.find(&query, None).ok().and_then(|mut cursor| { cursor.next().map(|res| { res.or_else(|err| { error!("Failed to get {} from the Mongo store due to {}", id, err); Err(StoreError::StorageFindError) }).and_then(|doc| { Object::from_bson(utils::map_bson_dates_to_string(Bson::Document(doc))) .map_err(StoreError::InvalidItemError) }) }) }); res } fn put(&self, item: &Object) -> StoreResult<StorageStatus> { item.as_document() .map_err(StoreError::InvalidItemError) .and_then(|doc| { let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), item.object_type.as_str()); let id = item.id.as_str(); let filter = doc! { "_id" => id }; let mut opts = UpdateOptions::default(); opts.update_flags.add(UpdateFlag::Upsert); coll.update(&filter, &doc, Some(&opts)) .map(|_| StorageStatus::Available) .or_else(|_| Err(StoreError::StorageWriteError)) }) } fn updated_at(&self) -> Option<i64> { let collections = vec!["asset", "episode", "season", "show", "special"]; let mut opts = CommandAndFindOptions::default(); opts.limit = 1; let client = self.pool.pop(); collections .iter() .filter_map(|coll_name| { let coll = client.get_collection(self.config.name.as_str(), *coll_name); let query = doc! { "$query" => {}, "$orderby" => { "attributes.updated_at" => -1 } }; let res = coll.find(&query, Some(&opts)) .ok() .and_then(|mut cursor| cursor.next()) .and_then(|result| result.ok()) .and_then(|mut document| { document .remove("attributes") .and_then(|attributes| match attributes { bson::Bson::Document(mut attr) => match attr.remove("updated_at") { Some(bson::Bson::UtcDatetime(datetime)) => { Some(datetime.timestamp()) } _ => None, }, _ => None, }) }); res }) .fold(None, |max, cur| match max { Some(val) => Some(::std::cmp::max(val, cur)), None => Some(cur), }) } }
MongoStore
identifier_name
mongo.rs
extern crate bson; extern crate mongo_driver; use bson::Bson; use mongo_driver::CommandAndFindOptions; use mongo_driver::client::{ClientPool, Uri}; use mongo_driver::collection::UpdateOptions;
use config::DBConfig; use objects::{utils, Object}; use storage::error::{StoreError, StoreResult}; use storage::storage::{Storage, StorageStatus}; pub struct MongoStore { config: DBConfig, pool: ClientPool, } impl MongoStore { pub fn new(config: &DBConfig) -> StoreResult<MongoStore> { let conn = MongoStore::conn( config.username.as_str(), config.password.as_str(), config.host.as_str(), config.port, ); let uri = Uri::new(conn.clone()).ok_or(StoreError::UriParseError(conn))?; let pool = ClientPool::new(uri, None); Ok(MongoStore { config: config.clone(), pool: pool, }) } fn conn(user: &str, pass: &str, host: &str, port: u16) -> String { format!("mongodb://{}:{}@{}:{}", user, pass, host, port) } } impl Storage<Object> for MongoStore { fn get(&self, id: &str, obj_type: &str) -> Option<StoreResult<Object>> { let query = doc!{ "_id" => id }; let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), obj_type); let res = coll.find(&query, None).ok().and_then(|mut cursor| { cursor.next().map(|res| { res.or_else(|err| { error!("Failed to get {} from the Mongo store due to {}", id, err); Err(StoreError::StorageFindError) }).and_then(|doc| { Object::from_bson(utils::map_bson_dates_to_string(Bson::Document(doc))) .map_err(StoreError::InvalidItemError) }) }) }); res } fn put(&self, item: &Object) -> StoreResult<StorageStatus> { item.as_document() .map_err(StoreError::InvalidItemError) .and_then(|doc| { let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), item.object_type.as_str()); let id = item.id.as_str(); let filter = doc! { "_id" => id }; let mut opts = UpdateOptions::default(); opts.update_flags.add(UpdateFlag::Upsert); coll.update(&filter, &doc, Some(&opts)) .map(|_| StorageStatus::Available) .or_else(|_| Err(StoreError::StorageWriteError)) }) } fn updated_at(&self) -> Option<i64> { let collections = vec!["asset", "episode", "season", "show", "special"]; let mut opts = CommandAndFindOptions::default(); opts.limit = 1; let client = self.pool.pop(); collections .iter() .filter_map(|coll_name| { let coll = client.get_collection(self.config.name.as_str(), *coll_name); let query = doc! { "$query" => {}, "$orderby" => { "attributes.updated_at" => -1 } }; let res = coll.find(&query, Some(&opts)) .ok() .and_then(|mut cursor| cursor.next()) .and_then(|result| result.ok()) .and_then(|mut document| { document .remove("attributes") .and_then(|attributes| match attributes { bson::Bson::Document(mut attr) => match attr.remove("updated_at") { Some(bson::Bson::UtcDatetime(datetime)) => { Some(datetime.timestamp()) } _ => None, }, _ => None, }) }); res }) .fold(None, |max, cur| match max { Some(val) => Some(::std::cmp::max(val, cur)), None => Some(cur), }) } }
use mongo_driver::flags::UpdateFlag;
random_line_split
mongo.rs
extern crate bson; extern crate mongo_driver; use bson::Bson; use mongo_driver::CommandAndFindOptions; use mongo_driver::client::{ClientPool, Uri}; use mongo_driver::collection::UpdateOptions; use mongo_driver::flags::UpdateFlag; use config::DBConfig; use objects::{utils, Object}; use storage::error::{StoreError, StoreResult}; use storage::storage::{Storage, StorageStatus}; pub struct MongoStore { config: DBConfig, pool: ClientPool, } impl MongoStore { pub fn new(config: &DBConfig) -> StoreResult<MongoStore> { let conn = MongoStore::conn( config.username.as_str(), config.password.as_str(), config.host.as_str(), config.port, ); let uri = Uri::new(conn.clone()).ok_or(StoreError::UriParseError(conn))?; let pool = ClientPool::new(uri, None); Ok(MongoStore { config: config.clone(), pool: pool, }) } fn conn(user: &str, pass: &str, host: &str, port: u16) -> String { format!("mongodb://{}:{}@{}:{}", user, pass, host, port) } } impl Storage<Object> for MongoStore { fn get(&self, id: &str, obj_type: &str) -> Option<StoreResult<Object>> { let query = doc!{ "_id" => id }; let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), obj_type); let res = coll.find(&query, None).ok().and_then(|mut cursor| { cursor.next().map(|res| { res.or_else(|err| { error!("Failed to get {} from the Mongo store due to {}", id, err); Err(StoreError::StorageFindError) }).and_then(|doc| { Object::from_bson(utils::map_bson_dates_to_string(Bson::Document(doc))) .map_err(StoreError::InvalidItemError) }) }) }); res } fn put(&self, item: &Object) -> StoreResult<StorageStatus> { item.as_document() .map_err(StoreError::InvalidItemError) .and_then(|doc| { let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), item.object_type.as_str()); let id = item.id.as_str(); let filter = doc! { "_id" => id }; let mut opts = UpdateOptions::default(); opts.update_flags.add(UpdateFlag::Upsert); coll.update(&filter, &doc, Some(&opts)) .map(|_| StorageStatus::Available) .or_else(|_| Err(StoreError::StorageWriteError)) }) } fn updated_at(&self) -> Option<i64> { let collections = vec!["asset", "episode", "season", "show", "special"]; let mut opts = CommandAndFindOptions::default(); opts.limit = 1; let client = self.pool.pop(); collections .iter() .filter_map(|coll_name| { let coll = client.get_collection(self.config.name.as_str(), *coll_name); let query = doc! { "$query" => {}, "$orderby" => { "attributes.updated_at" => -1 } }; let res = coll.find(&query, Some(&opts)) .ok() .and_then(|mut cursor| cursor.next()) .and_then(|result| result.ok()) .and_then(|mut document| { document .remove("attributes") .and_then(|attributes| match attributes { bson::Bson::Document(mut attr) => match attr.remove("updated_at") { Some(bson::Bson::UtcDatetime(datetime)) =>
_ => None, }, _ => None, }) }); res }) .fold(None, |max, cur| match max { Some(val) => Some(::std::cmp::max(val, cur)), None => Some(cur), }) } }
{ Some(datetime.timestamp()) }
conditional_block
heap.rs
use std::cell::UnsafeCell; use std::mem; use std::ptr; /// `BytesRef` refers to a slice in tantivy's custom `Heap`. #[derive(Copy, Clone)] pub struct BytesRef { pub start: u32, pub stop: u32, } /// Object that can be allocated in tantivy's custom `Heap`. pub trait HeapAllocable { fn with_addr(addr: u32) -> Self; } /// Tantivy's custom `Heap`. pub struct Heap { inner: UnsafeCell<InnerHeap>, } #[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref))] impl Heap { /// Creates a new heap with a given capacity pub fn with_capacity(num_bytes: usize) -> Heap { Heap { inner: UnsafeCell::new(InnerHeap::with_capacity(num_bytes)) } } fn inner(&self) -> &mut InnerHeap { unsafe { &mut *self.inner.get() } } /// Clears the heap. All the underlying data is lost. /// /// This heap does not support deallocation. /// This method is the only way to free memory. pub fn clear(&self) { self.inner().clear(); } /// Return the heap capacity. pub fn capacity(&self) -> u32 { self.inner().capacity() } /// Return amount of free space, in bytes. pub fn num_free_bytes(&self) -> u32 { self.inner().num_free_bytes() } /// Allocate a given amount of space and returns an address /// in the Heap. pub fn allocate_space(&self, num_bytes: usize) -> u32 { self.inner().allocate_space(num_bytes) } /// Allocate an object in the heap pub fn allocate_object<V: HeapAllocable>(&self) -> (u32, &mut V) { let addr = self.inner().allocate_space(mem::size_of::<V>()); let v: V = V::with_addr(addr); self.inner().set(addr, &v); (addr, self.inner().get_mut_ref(addr)) } /// Stores a `&[u8]` in the heap and returns the destination BytesRef. pub fn allocate_and_set(&self, data: &[u8]) -> BytesRef { self.inner().allocate_and_set(data) } /// Fetches the `&[u8]` stored on the slice defined by the `BytesRef` /// given as argumetn pub fn get_slice(&self, bytes_ref: BytesRef) -> &[u8] { self.inner().get_slice(bytes_ref.start, bytes_ref.stop) } /// Stores an item's data in the heap, at the given `address`. pub fn set<Item>(&self, addr: u32, val: &Item) { self.inner().set(addr, val); } /// Returns a mutable reference for an object at a given Item. pub fn get_mut_ref<Item>(&self, addr: u32) -> &mut Item { self.inner().get_mut_ref(addr) } /// Returns a mutable reference to an `Item` at a given `addr`. #[cfg(test)] pub fn get_ref<Item>(&self, addr: u32) -> &mut Item { self.get_mut_ref(addr) } } struct InnerHeap { buffer: Vec<u8>, used: u32, has_been_resized: bool, } impl InnerHeap { pub fn with_capacity(num_bytes: usize) -> InnerHeap { let buffer: Vec<u8> = vec![0u8; num_bytes]; InnerHeap { buffer: buffer, used: 0u32, has_been_resized: false, } } pub fn clear(&mut self) { self.used = 0u32; } pub fn capacity(&self) -> u32 { self.buffer.len() as u32 } // Returns the number of free bytes. If the buffer // has reached it's capacity and overflowed to another buffer, return 0. pub fn num_free_bytes(&self) -> u32 { if self.has_been_resized
else { (self.buffer.len() as u32) - self.used } } pub fn allocate_space(&mut self, num_bytes: usize) -> u32 { let addr = self.used; self.used += num_bytes as u32; let buffer_len = self.buffer.len(); if self.used > buffer_len as u32 { self.buffer.resize(buffer_len * 2, 0u8); self.has_been_resized = true } addr } fn get_slice(&self, start: u32, stop: u32) -> &[u8] { &self.buffer[start as usize..stop as usize] } fn get_mut_slice(&mut self, start: u32, stop: u32) -> &mut [u8] { &mut self.buffer[start as usize..stop as usize] } fn allocate_and_set(&mut self, data: &[u8]) -> BytesRef { let start = self.allocate_space(data.len()); let stop = start + data.len() as u32; self.get_mut_slice(start, stop).clone_from_slice(data); BytesRef { start: start as u32, stop: stop as u32, } } fn get_mut(&mut self, addr: u32) -> *mut u8 { let addr_isize = addr as isize; unsafe { self.buffer.as_mut_ptr().offset(addr_isize) } } fn get_mut_ref<Item>(&mut self, addr: u32) -> &mut Item { let v_ptr_u8 = self.get_mut(addr) as *mut u8; let v_ptr = v_ptr_u8 as *mut Item; unsafe { &mut *v_ptr } } fn set<Item>(&mut self, addr: u32, val: &Item) { let v_ptr: *const Item = val as *const Item; let v_ptr_u8: *const u8 = v_ptr as *const u8; debug_assert!(addr + mem::size_of::<Item>() as u32 <= self.used); unsafe { let dest_ptr: *mut u8 = self.get_mut(addr); ptr::copy(v_ptr_u8, dest_ptr, mem::size_of::<Item>()); } } }
{ 0u32 }
conditional_block
heap.rs
use std::cell::UnsafeCell; use std::mem; use std::ptr; /// `BytesRef` refers to a slice in tantivy's custom `Heap`. #[derive(Copy, Clone)] pub struct BytesRef { pub start: u32, pub stop: u32, } /// Object that can be allocated in tantivy's custom `Heap`. pub trait HeapAllocable { fn with_addr(addr: u32) -> Self; } /// Tantivy's custom `Heap`. pub struct Heap { inner: UnsafeCell<InnerHeap>, } #[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref))] impl Heap { /// Creates a new heap with a given capacity pub fn with_capacity(num_bytes: usize) -> Heap { Heap { inner: UnsafeCell::new(InnerHeap::with_capacity(num_bytes)) } } fn inner(&self) -> &mut InnerHeap { unsafe { &mut *self.inner.get() } } /// Clears the heap. All the underlying data is lost. /// /// This heap does not support deallocation. /// This method is the only way to free memory. pub fn clear(&self) { self.inner().clear(); } /// Return the heap capacity. pub fn capacity(&self) -> u32 { self.inner().capacity() } /// Return amount of free space, in bytes. pub fn num_free_bytes(&self) -> u32 { self.inner().num_free_bytes() } /// Allocate a given amount of space and returns an address /// in the Heap. pub fn allocate_space(&self, num_bytes: usize) -> u32 { self.inner().allocate_space(num_bytes) } /// Allocate an object in the heap pub fn allocate_object<V: HeapAllocable>(&self) -> (u32, &mut V) { let addr = self.inner().allocate_space(mem::size_of::<V>()); let v: V = V::with_addr(addr); self.inner().set(addr, &v); (addr, self.inner().get_mut_ref(addr)) } /// Stores a `&[u8]` in the heap and returns the destination BytesRef. pub fn allocate_and_set(&self, data: &[u8]) -> BytesRef { self.inner().allocate_and_set(data) } /// Fetches the `&[u8]` stored on the slice defined by the `BytesRef` /// given as argumetn pub fn get_slice(&self, bytes_ref: BytesRef) -> &[u8] { self.inner().get_slice(bytes_ref.start, bytes_ref.stop) } /// Stores an item's data in the heap, at the given `address`. pub fn set<Item>(&self, addr: u32, val: &Item) { self.inner().set(addr, val); } /// Returns a mutable reference for an object at a given Item. pub fn get_mut_ref<Item>(&self, addr: u32) -> &mut Item { self.inner().get_mut_ref(addr) } /// Returns a mutable reference to an `Item` at a given `addr`. #[cfg(test)] pub fn get_ref<Item>(&self, addr: u32) -> &mut Item { self.get_mut_ref(addr) } } struct InnerHeap { buffer: Vec<u8>, used: u32, has_been_resized: bool, } impl InnerHeap { pub fn with_capacity(num_bytes: usize) -> InnerHeap { let buffer: Vec<u8> = vec![0u8; num_bytes]; InnerHeap { buffer: buffer, used: 0u32, has_been_resized: false, } } pub fn clear(&mut self) { self.used = 0u32; } pub fn capacity(&self) -> u32 { self.buffer.len() as u32 } // Returns the number of free bytes. If the buffer // has reached it's capacity and overflowed to another buffer, return 0. pub fn num_free_bytes(&self) -> u32 { if self.has_been_resized { 0u32 } else { (self.buffer.len() as u32) - self.used } } pub fn allocate_space(&mut self, num_bytes: usize) -> u32 { let addr = self.used; self.used += num_bytes as u32; let buffer_len = self.buffer.len(); if self.used > buffer_len as u32 { self.buffer.resize(buffer_len * 2, 0u8); self.has_been_resized = true } addr }
fn get_slice(&self, start: u32, stop: u32) -> &[u8] { &self.buffer[start as usize..stop as usize] } fn get_mut_slice(&mut self, start: u32, stop: u32) -> &mut [u8] { &mut self.buffer[start as usize..stop as usize] } fn allocate_and_set(&mut self, data: &[u8]) -> BytesRef { let start = self.allocate_space(data.len()); let stop = start + data.len() as u32; self.get_mut_slice(start, stop).clone_from_slice(data); BytesRef { start: start as u32, stop: stop as u32, } } fn get_mut(&mut self, addr: u32) -> *mut u8 { let addr_isize = addr as isize; unsafe { self.buffer.as_mut_ptr().offset(addr_isize) } } fn get_mut_ref<Item>(&mut self, addr: u32) -> &mut Item { let v_ptr_u8 = self.get_mut(addr) as *mut u8; let v_ptr = v_ptr_u8 as *mut Item; unsafe { &mut *v_ptr } } fn set<Item>(&mut self, addr: u32, val: &Item) { let v_ptr: *const Item = val as *const Item; let v_ptr_u8: *const u8 = v_ptr as *const u8; debug_assert!(addr + mem::size_of::<Item>() as u32 <= self.used); unsafe { let dest_ptr: *mut u8 = self.get_mut(addr); ptr::copy(v_ptr_u8, dest_ptr, mem::size_of::<Item>()); } } }
random_line_split
heap.rs
use std::cell::UnsafeCell; use std::mem; use std::ptr; /// `BytesRef` refers to a slice in tantivy's custom `Heap`. #[derive(Copy, Clone)] pub struct BytesRef { pub start: u32, pub stop: u32, } /// Object that can be allocated in tantivy's custom `Heap`. pub trait HeapAllocable { fn with_addr(addr: u32) -> Self; } /// Tantivy's custom `Heap`. pub struct Heap { inner: UnsafeCell<InnerHeap>, } #[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref))] impl Heap { /// Creates a new heap with a given capacity pub fn with_capacity(num_bytes: usize) -> Heap { Heap { inner: UnsafeCell::new(InnerHeap::with_capacity(num_bytes)) } } fn inner(&self) -> &mut InnerHeap { unsafe { &mut *self.inner.get() } } /// Clears the heap. All the underlying data is lost. /// /// This heap does not support deallocation. /// This method is the only way to free memory. pub fn clear(&self) { self.inner().clear(); } /// Return the heap capacity. pub fn capacity(&self) -> u32 { self.inner().capacity() } /// Return amount of free space, in bytes. pub fn num_free_bytes(&self) -> u32 { self.inner().num_free_bytes() } /// Allocate a given amount of space and returns an address /// in the Heap. pub fn allocate_space(&self, num_bytes: usize) -> u32 { self.inner().allocate_space(num_bytes) } /// Allocate an object in the heap pub fn allocate_object<V: HeapAllocable>(&self) -> (u32, &mut V) { let addr = self.inner().allocate_space(mem::size_of::<V>()); let v: V = V::with_addr(addr); self.inner().set(addr, &v); (addr, self.inner().get_mut_ref(addr)) } /// Stores a `&[u8]` in the heap and returns the destination BytesRef. pub fn allocate_and_set(&self, data: &[u8]) -> BytesRef { self.inner().allocate_and_set(data) } /// Fetches the `&[u8]` stored on the slice defined by the `BytesRef` /// given as argumetn pub fn get_slice(&self, bytes_ref: BytesRef) -> &[u8] { self.inner().get_slice(bytes_ref.start, bytes_ref.stop) } /// Stores an item's data in the heap, at the given `address`. pub fn set<Item>(&self, addr: u32, val: &Item) { self.inner().set(addr, val); } /// Returns a mutable reference for an object at a given Item. pub fn get_mut_ref<Item>(&self, addr: u32) -> &mut Item { self.inner().get_mut_ref(addr) } /// Returns a mutable reference to an `Item` at a given `addr`. #[cfg(test)] pub fn get_ref<Item>(&self, addr: u32) -> &mut Item { self.get_mut_ref(addr) } } struct InnerHeap { buffer: Vec<u8>, used: u32, has_been_resized: bool, } impl InnerHeap { pub fn with_capacity(num_bytes: usize) -> InnerHeap { let buffer: Vec<u8> = vec![0u8; num_bytes]; InnerHeap { buffer: buffer, used: 0u32, has_been_resized: false, } } pub fn clear(&mut self) { self.used = 0u32; } pub fn capacity(&self) -> u32 { self.buffer.len() as u32 } // Returns the number of free bytes. If the buffer // has reached it's capacity and overflowed to another buffer, return 0. pub fn num_free_bytes(&self) -> u32 { if self.has_been_resized { 0u32 } else { (self.buffer.len() as u32) - self.used } } pub fn allocate_space(&mut self, num_bytes: usize) -> u32 { let addr = self.used; self.used += num_bytes as u32; let buffer_len = self.buffer.len(); if self.used > buffer_len as u32 { self.buffer.resize(buffer_len * 2, 0u8); self.has_been_resized = true } addr } fn get_slice(&self, start: u32, stop: u32) -> &[u8] { &self.buffer[start as usize..stop as usize] } fn
(&mut self, start: u32, stop: u32) -> &mut [u8] { &mut self.buffer[start as usize..stop as usize] } fn allocate_and_set(&mut self, data: &[u8]) -> BytesRef { let start = self.allocate_space(data.len()); let stop = start + data.len() as u32; self.get_mut_slice(start, stop).clone_from_slice(data); BytesRef { start: start as u32, stop: stop as u32, } } fn get_mut(&mut self, addr: u32) -> *mut u8 { let addr_isize = addr as isize; unsafe { self.buffer.as_mut_ptr().offset(addr_isize) } } fn get_mut_ref<Item>(&mut self, addr: u32) -> &mut Item { let v_ptr_u8 = self.get_mut(addr) as *mut u8; let v_ptr = v_ptr_u8 as *mut Item; unsafe { &mut *v_ptr } } fn set<Item>(&mut self, addr: u32, val: &Item) { let v_ptr: *const Item = val as *const Item; let v_ptr_u8: *const u8 = v_ptr as *const u8; debug_assert!(addr + mem::size_of::<Item>() as u32 <= self.used); unsafe { let dest_ptr: *mut u8 = self.get_mut(addr); ptr::copy(v_ptr_u8, dest_ptr, mem::size_of::<Item>()); } } }
get_mut_slice
identifier_name
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmllinkelement::{HTMLLinkElement, RequestGenerationId}; use crate::dom::node::{containing_shadow_root, document_from_node, window_from_node}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::shadowroot::ShadowRoot; use crate::fetch::create_a_potential_cors_request; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use cssparser::SourceLocation; use encoding_rs::UTF_8; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use mime::{self, Mime}; use msg::constellation_msg::PipelineId; use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder}; use net_traits::{ FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy, }; use net_traits::{ResourceFetchTiming, ResourceTimingType}; use parking_lot::RwLock; use servo_arc::Arc; use servo_url::ImmutableOrigin; use servo_url::ServoUrl; use std::mem; use std::sync::atomic::AtomicBool; use std::sync::Mutex; use style::media_queries::MediaList; use style::parser::ParserContext; use style::shared_lock::{Locked, SharedRwLock}; use style::stylesheets::import_rule::ImportSheet; use style::stylesheets::StylesheetLoader as StyleStylesheetLoader; use style::stylesheets::{ CssRules, ImportRule, Namespaces, Origin, Stylesheet, StylesheetContents, }; use style::values::CssUrl; pub trait StylesheetOwner { /// Returns whether this element was inserted by the parser (i.e., it should /// trigger a document-load-blocking load). fn parser_inserted(&self) -> bool; /// Which referrer policy should loads triggered by this owner follow, or /// `None` for the default. fn referrer_policy(&self) -> Option<ReferrerPolicy>; /// Notes that a new load is pending to finish. fn increment_pending_loads_count(&self); /// Returns None if there are still pending loads, or whether any load has /// failed since the loads started. fn load_finished(&self, successful: bool) -> Option<bool>; /// Sets origin_clean flag. fn set_origin_clean(&self, origin_clean: bool); } pub enum StylesheetContextSource { // NB: `media` is just an option so we avoid cloning it. LinkElement { media: Option<MediaList> }, Import(Arc<Stylesheet>), } /// The context required for asynchronously loading an external stylesheet. pub struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLElement>, source: StylesheetContextSource, url: ServoUrl, metadata: Option<Metadata>, /// The response body received to date. data: Vec<u8>, /// The node document for elem when the load was initiated. document: Trusted<Document>, shadow_root: Option<Trusted<ShadowRoot>>, origin_clean: bool, /// A token which must match the generation id of the `HTMLLinkElement` for it to load the stylesheet. /// This is ignored for `HTMLStyleElement` and imports. request_generation_id: Option<RequestGenerationId>, resource_timing: ResourceFetchTiming, } impl PreInvoke for StylesheetContext {} impl FetchResponseListener for StylesheetContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { if let Ok(FetchMetadata::Filtered { ref filtered,.. }) = metadata { match *filtered { FilteredMetadata::Opaque | FilteredMetadata::OpaqueRedirect(_) => { self.origin_clean = false; }, _ => {}, } } self.metadata = metadata.ok().map(|m| match m { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_,.. } => unsafe_, }); } fn process_response_chunk(&mut self, mut payload: Vec<u8>) { self.data.append(&mut payload); } fn process_response_eof(&mut self, status: Result<ResourceFetchTiming, NetworkError>) { let elem = self.elem.root(); let document = self.document.root(); let mut successful = false; if status.is_ok() { let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }; let is_css = metadata.content_type.map_or(false, |ct| { let mime: Mime = ct.into_inner().into(); mime.type_() == mime::TEXT && mime.subtype() == mime::CSS }); let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8; let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s); let final_url = metadata.final_url; let win = window_from_node(&*elem); let loader = StylesheetLoader::for_element(&elem); match self.source { StylesheetContextSource::LinkElement { ref mut media } => { let link = elem.downcast::<HTMLLinkElement>().unwrap(); // We must first check whether the generations of the context and the element match up, // else we risk applying the wrong stylesheet when responses come out-of-order. let is_stylesheet_load_applicable = self .request_generation_id .map_or(true, |gen| gen == link.get_request_generation_id()); if is_stylesheet_load_applicable { let shared_lock = document.style_shared_lock().clone(); let sheet = Arc::new(Stylesheet::from_bytes( &data, final_url, protocol_encoding_label, Some(environment_encoding), Origin::Author, media.take().unwrap(), shared_lock, Some(&loader), win.css_error_reporter(), document.quirks_mode(), )); if link.is_alternate() { sheet.set_disabled(true); } link.set_stylesheet(sheet); } }, StylesheetContextSource::Import(ref stylesheet) => { Stylesheet::update_from_bytes( &stylesheet, &data, protocol_encoding_label, Some(environment_encoding), final_url, Some(&loader), win.css_error_reporter(), ); }, } if let Some(ref shadow_root) = self.shadow_root { shadow_root.root().invalidate_stylesheets(); } else { document.invalidate_stylesheets(); } // FIXME: Revisit once consensus is reached at: // https://github.com/whatwg/html/issues/1142 successful = metadata.status.map_or(false, |(code, _)| code == 200); } let owner = elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); owner.set_origin_clean(self.origin_clean); if owner.parser_inserted() { document.decrement_script_blocking_stylesheet_count(); } document.finish_load(LoadType::Stylesheet(self.url.clone())); if let Some(any_failed) = owner.load_finished(successful) { let event = if any_failed { atom!("error") } else { atom!("load") }; elem.upcast::<EventTarget>().fire_event(event); } } fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming
fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for StylesheetContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { let initiator_type = InitiatorType::LocalName( self.elem .root() .upcast::<Element>() .local_name() .to_string(), ); (initiator_type, self.url.clone()) } fn resource_timing_global(&self) -> DomRoot<GlobalScope> { document_from_node(&*self.elem.root()).global() } } pub struct StylesheetLoader<'a> { elem: &'a HTMLElement, } impl<'a> StylesheetLoader<'a> { pub fn for_element(element: &'a HTMLElement) -> Self { StylesheetLoader { elem: element } } } impl<'a> StylesheetLoader<'a> { pub fn load( &self, source: StylesheetContextSource, url: ServoUrl, cors_setting: Option<CorsSettings>, integrity_metadata: String, ) { let document = document_from_node(self.elem); let shadow_root = containing_shadow_root(self.elem).map(|sr| Trusted::new(&*sr)); let gen = self .elem .downcast::<HTMLLinkElement>() .map(HTMLLinkElement::get_request_generation_id); let context = ::std::sync::Arc::new(Mutex::new(StylesheetContext { elem: Trusted::new(&*self.elem), source: source, url: url.clone(), metadata: None, data: vec![], document: Trusted::new(&*document), shadow_root, origin_clean: true, request_generation_id: gen, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let (task_source, canceller) = document .window() .task_manager() .networking_task_source_with_canceller(); let listener = NetworkListener { context, task_source, canceller: Some(canceller), }; ROUTER.add_route( action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); }), ); let owner = self .elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); let referrer_policy = owner .referrer_policy() .or_else(|| document.get_referrer_policy()); owner.increment_pending_loads_count(); if owner.parser_inserted() { document.increment_script_blocking_stylesheet_count(); } let request = stylesheet_fetch_request( url.clone(), cors_setting, document.origin().immutable().clone(), self.elem.global().pipeline_id(), Referrer::ReferrerUrl(document.url()), referrer_policy, integrity_metadata, ); document.fetch_async(LoadType::Stylesheet(url), request, action_sender); } } // This function is also used to prefetch a stylesheet in `script::dom::servoparser::prefetch`. // https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource pub(crate) fn stylesheet_fetch_request( url: ServoUrl, cors_setting: Option<CorsSettings>, origin: ImmutableOrigin, pipeline_id: PipelineId, referrer: Referrer, referrer_policy: Option<ReferrerPolicy>, integrity_metadata: String, ) -> RequestBuilder { create_a_potential_cors_request(url, Destination::Style, cors_setting, None) .origin(origin) .pipeline_id(Some(pipeline_id)) .referrer(Some(referrer)) .referrer_policy(referrer_policy) .integrity_metadata(integrity_metadata) } impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> { /// Request a stylesheet after parsing a given `@import` rule, and return /// the constructed `@import` rule. fn request_stylesheet( &self, url: CssUrl, source_location: SourceLocation, context: &ParserContext, lock: &SharedRwLock, media: Arc<Locked<MediaList>>, ) -> Arc<Locked<ImportRule>> { let sheet = Arc::new(Stylesheet { contents: StylesheetContents { rules: CssRules::new(Vec::new(), lock), origin: context.stylesheet_origin, url_data: RwLock::new(context.url_data.clone()), quirks_mode: context.quirks_mode, namespaces: RwLock::new(Namespaces::default()), source_map_url: RwLock::new(None), source_url: RwLock::new(None), }, media: media, shared_lock: lock.clone(), disabled: AtomicBool::new(false), }); let stylesheet = ImportSheet(sheet.clone()); let import = ImportRule { url, source_location, stylesheet, }; let url = match import.url.url().cloned() { Some(url) => url, None => return Arc::new(lock.wrap(import)), }; // TODO (mrnayak) : Whether we should use the original loader's CORS // setting? Fix this when spec has more details. let source = StylesheetContextSource::Import(sheet.clone()); self.load(source, url, None, "".to_owned()); Arc::new(lock.wrap(import)) } }
{ &mut self.resource_timing }
identifier_body
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmllinkelement::{HTMLLinkElement, RequestGenerationId}; use crate::dom::node::{containing_shadow_root, document_from_node, window_from_node}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::shadowroot::ShadowRoot; use crate::fetch::create_a_potential_cors_request; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use cssparser::SourceLocation; use encoding_rs::UTF_8; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use mime::{self, Mime}; use msg::constellation_msg::PipelineId; use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder}; use net_traits::{ FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy, }; use net_traits::{ResourceFetchTiming, ResourceTimingType}; use parking_lot::RwLock; use servo_arc::Arc; use servo_url::ImmutableOrigin; use servo_url::ServoUrl; use std::mem; use std::sync::atomic::AtomicBool; use std::sync::Mutex; use style::media_queries::MediaList; use style::parser::ParserContext; use style::shared_lock::{Locked, SharedRwLock}; use style::stylesheets::import_rule::ImportSheet; use style::stylesheets::StylesheetLoader as StyleStylesheetLoader; use style::stylesheets::{ CssRules, ImportRule, Namespaces, Origin, Stylesheet, StylesheetContents, }; use style::values::CssUrl; pub trait StylesheetOwner { /// Returns whether this element was inserted by the parser (i.e., it should /// trigger a document-load-blocking load). fn parser_inserted(&self) -> bool; /// Which referrer policy should loads triggered by this owner follow, or /// `None` for the default. fn referrer_policy(&self) -> Option<ReferrerPolicy>; /// Notes that a new load is pending to finish. fn increment_pending_loads_count(&self); /// Returns None if there are still pending loads, or whether any load has /// failed since the loads started. fn load_finished(&self, successful: bool) -> Option<bool>; /// Sets origin_clean flag. fn set_origin_clean(&self, origin_clean: bool); } pub enum
{ // NB: `media` is just an option so we avoid cloning it. LinkElement { media: Option<MediaList> }, Import(Arc<Stylesheet>), } /// The context required for asynchronously loading an external stylesheet. pub struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLElement>, source: StylesheetContextSource, url: ServoUrl, metadata: Option<Metadata>, /// The response body received to date. data: Vec<u8>, /// The node document for elem when the load was initiated. document: Trusted<Document>, shadow_root: Option<Trusted<ShadowRoot>>, origin_clean: bool, /// A token which must match the generation id of the `HTMLLinkElement` for it to load the stylesheet. /// This is ignored for `HTMLStyleElement` and imports. request_generation_id: Option<RequestGenerationId>, resource_timing: ResourceFetchTiming, } impl PreInvoke for StylesheetContext {} impl FetchResponseListener for StylesheetContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { if let Ok(FetchMetadata::Filtered { ref filtered,.. }) = metadata { match *filtered { FilteredMetadata::Opaque | FilteredMetadata::OpaqueRedirect(_) => { self.origin_clean = false; }, _ => {}, } } self.metadata = metadata.ok().map(|m| match m { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_,.. } => unsafe_, }); } fn process_response_chunk(&mut self, mut payload: Vec<u8>) { self.data.append(&mut payload); } fn process_response_eof(&mut self, status: Result<ResourceFetchTiming, NetworkError>) { let elem = self.elem.root(); let document = self.document.root(); let mut successful = false; if status.is_ok() { let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }; let is_css = metadata.content_type.map_or(false, |ct| { let mime: Mime = ct.into_inner().into(); mime.type_() == mime::TEXT && mime.subtype() == mime::CSS }); let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8; let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s); let final_url = metadata.final_url; let win = window_from_node(&*elem); let loader = StylesheetLoader::for_element(&elem); match self.source { StylesheetContextSource::LinkElement { ref mut media } => { let link = elem.downcast::<HTMLLinkElement>().unwrap(); // We must first check whether the generations of the context and the element match up, // else we risk applying the wrong stylesheet when responses come out-of-order. let is_stylesheet_load_applicable = self .request_generation_id .map_or(true, |gen| gen == link.get_request_generation_id()); if is_stylesheet_load_applicable { let shared_lock = document.style_shared_lock().clone(); let sheet = Arc::new(Stylesheet::from_bytes( &data, final_url, protocol_encoding_label, Some(environment_encoding), Origin::Author, media.take().unwrap(), shared_lock, Some(&loader), win.css_error_reporter(), document.quirks_mode(), )); if link.is_alternate() { sheet.set_disabled(true); } link.set_stylesheet(sheet); } }, StylesheetContextSource::Import(ref stylesheet) => { Stylesheet::update_from_bytes( &stylesheet, &data, protocol_encoding_label, Some(environment_encoding), final_url, Some(&loader), win.css_error_reporter(), ); }, } if let Some(ref shadow_root) = self.shadow_root { shadow_root.root().invalidate_stylesheets(); } else { document.invalidate_stylesheets(); } // FIXME: Revisit once consensus is reached at: // https://github.com/whatwg/html/issues/1142 successful = metadata.status.map_or(false, |(code, _)| code == 200); } let owner = elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); owner.set_origin_clean(self.origin_clean); if owner.parser_inserted() { document.decrement_script_blocking_stylesheet_count(); } document.finish_load(LoadType::Stylesheet(self.url.clone())); if let Some(any_failed) = owner.load_finished(successful) { let event = if any_failed { atom!("error") } else { atom!("load") }; elem.upcast::<EventTarget>().fire_event(event); } } fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming { &mut self.resource_timing } fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for StylesheetContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { let initiator_type = InitiatorType::LocalName( self.elem .root() .upcast::<Element>() .local_name() .to_string(), ); (initiator_type, self.url.clone()) } fn resource_timing_global(&self) -> DomRoot<GlobalScope> { document_from_node(&*self.elem.root()).global() } } pub struct StylesheetLoader<'a> { elem: &'a HTMLElement, } impl<'a> StylesheetLoader<'a> { pub fn for_element(element: &'a HTMLElement) -> Self { StylesheetLoader { elem: element } } } impl<'a> StylesheetLoader<'a> { pub fn load( &self, source: StylesheetContextSource, url: ServoUrl, cors_setting: Option<CorsSettings>, integrity_metadata: String, ) { let document = document_from_node(self.elem); let shadow_root = containing_shadow_root(self.elem).map(|sr| Trusted::new(&*sr)); let gen = self .elem .downcast::<HTMLLinkElement>() .map(HTMLLinkElement::get_request_generation_id); let context = ::std::sync::Arc::new(Mutex::new(StylesheetContext { elem: Trusted::new(&*self.elem), source: source, url: url.clone(), metadata: None, data: vec![], document: Trusted::new(&*document), shadow_root, origin_clean: true, request_generation_id: gen, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let (task_source, canceller) = document .window() .task_manager() .networking_task_source_with_canceller(); let listener = NetworkListener { context, task_source, canceller: Some(canceller), }; ROUTER.add_route( action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); }), ); let owner = self .elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); let referrer_policy = owner .referrer_policy() .or_else(|| document.get_referrer_policy()); owner.increment_pending_loads_count(); if owner.parser_inserted() { document.increment_script_blocking_stylesheet_count(); } let request = stylesheet_fetch_request( url.clone(), cors_setting, document.origin().immutable().clone(), self.elem.global().pipeline_id(), Referrer::ReferrerUrl(document.url()), referrer_policy, integrity_metadata, ); document.fetch_async(LoadType::Stylesheet(url), request, action_sender); } } // This function is also used to prefetch a stylesheet in `script::dom::servoparser::prefetch`. // https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource pub(crate) fn stylesheet_fetch_request( url: ServoUrl, cors_setting: Option<CorsSettings>, origin: ImmutableOrigin, pipeline_id: PipelineId, referrer: Referrer, referrer_policy: Option<ReferrerPolicy>, integrity_metadata: String, ) -> RequestBuilder { create_a_potential_cors_request(url, Destination::Style, cors_setting, None) .origin(origin) .pipeline_id(Some(pipeline_id)) .referrer(Some(referrer)) .referrer_policy(referrer_policy) .integrity_metadata(integrity_metadata) } impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> { /// Request a stylesheet after parsing a given `@import` rule, and return /// the constructed `@import` rule. fn request_stylesheet( &self, url: CssUrl, source_location: SourceLocation, context: &ParserContext, lock: &SharedRwLock, media: Arc<Locked<MediaList>>, ) -> Arc<Locked<ImportRule>> { let sheet = Arc::new(Stylesheet { contents: StylesheetContents { rules: CssRules::new(Vec::new(), lock), origin: context.stylesheet_origin, url_data: RwLock::new(context.url_data.clone()), quirks_mode: context.quirks_mode, namespaces: RwLock::new(Namespaces::default()), source_map_url: RwLock::new(None), source_url: RwLock::new(None), }, media: media, shared_lock: lock.clone(), disabled: AtomicBool::new(false), }); let stylesheet = ImportSheet(sheet.clone()); let import = ImportRule { url, source_location, stylesheet, }; let url = match import.url.url().cloned() { Some(url) => url, None => return Arc::new(lock.wrap(import)), }; // TODO (mrnayak) : Whether we should use the original loader's CORS // setting? Fix this when spec has more details. let source = StylesheetContextSource::Import(sheet.clone()); self.load(source, url, None, "".to_owned()); Arc::new(lock.wrap(import)) } }
StylesheetContextSource
identifier_name
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmllinkelement::{HTMLLinkElement, RequestGenerationId}; use crate::dom::node::{containing_shadow_root, document_from_node, window_from_node}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::shadowroot::ShadowRoot; use crate::fetch::create_a_potential_cors_request; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use cssparser::SourceLocation; use encoding_rs::UTF_8; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use mime::{self, Mime}; use msg::constellation_msg::PipelineId; use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder}; use net_traits::{ FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy, }; use net_traits::{ResourceFetchTiming, ResourceTimingType}; use parking_lot::RwLock; use servo_arc::Arc; use servo_url::ImmutableOrigin; use servo_url::ServoUrl; use std::mem; use std::sync::atomic::AtomicBool; use std::sync::Mutex; use style::media_queries::MediaList; use style::parser::ParserContext; use style::shared_lock::{Locked, SharedRwLock}; use style::stylesheets::import_rule::ImportSheet; use style::stylesheets::StylesheetLoader as StyleStylesheetLoader; use style::stylesheets::{ CssRules, ImportRule, Namespaces, Origin, Stylesheet, StylesheetContents, }; use style::values::CssUrl; pub trait StylesheetOwner { /// Returns whether this element was inserted by the parser (i.e., it should /// trigger a document-load-blocking load). fn parser_inserted(&self) -> bool; /// Which referrer policy should loads triggered by this owner follow, or /// `None` for the default. fn referrer_policy(&self) -> Option<ReferrerPolicy>; /// Notes that a new load is pending to finish. fn increment_pending_loads_count(&self); /// Returns None if there are still pending loads, or whether any load has /// failed since the loads started. fn load_finished(&self, successful: bool) -> Option<bool>; /// Sets origin_clean flag. fn set_origin_clean(&self, origin_clean: bool); } pub enum StylesheetContextSource { // NB: `media` is just an option so we avoid cloning it. LinkElement { media: Option<MediaList> }, Import(Arc<Stylesheet>), } /// The context required for asynchronously loading an external stylesheet. pub struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLElement>, source: StylesheetContextSource, url: ServoUrl, metadata: Option<Metadata>, /// The response body received to date. data: Vec<u8>, /// The node document for elem when the load was initiated. document: Trusted<Document>, shadow_root: Option<Trusted<ShadowRoot>>, origin_clean: bool, /// A token which must match the generation id of the `HTMLLinkElement` for it to load the stylesheet. /// This is ignored for `HTMLStyleElement` and imports. request_generation_id: Option<RequestGenerationId>, resource_timing: ResourceFetchTiming, } impl PreInvoke for StylesheetContext {} impl FetchResponseListener for StylesheetContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { if let Ok(FetchMetadata::Filtered { ref filtered,.. }) = metadata { match *filtered { FilteredMetadata::Opaque | FilteredMetadata::OpaqueRedirect(_) => { self.origin_clean = false; }, _ => {}, } } self.metadata = metadata.ok().map(|m| match m { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_,.. } => unsafe_, }); } fn process_response_chunk(&mut self, mut payload: Vec<u8>) { self.data.append(&mut payload); } fn process_response_eof(&mut self, status: Result<ResourceFetchTiming, NetworkError>) { let elem = self.elem.root(); let document = self.document.root(); let mut successful = false; if status.is_ok() { let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }; let is_css = metadata.content_type.map_or(false, |ct| { let mime: Mime = ct.into_inner().into(); mime.type_() == mime::TEXT && mime.subtype() == mime::CSS }); let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8; let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s); let final_url = metadata.final_url; let win = window_from_node(&*elem); let loader = StylesheetLoader::for_element(&elem); match self.source { StylesheetContextSource::LinkElement { ref mut media } => { let link = elem.downcast::<HTMLLinkElement>().unwrap(); // We must first check whether the generations of the context and the element match up, // else we risk applying the wrong stylesheet when responses come out-of-order. let is_stylesheet_load_applicable = self .request_generation_id .map_or(true, |gen| gen == link.get_request_generation_id()); if is_stylesheet_load_applicable { let shared_lock = document.style_shared_lock().clone(); let sheet = Arc::new(Stylesheet::from_bytes( &data, final_url, protocol_encoding_label, Some(environment_encoding), Origin::Author, media.take().unwrap(), shared_lock, Some(&loader), win.css_error_reporter(), document.quirks_mode(), )); if link.is_alternate() { sheet.set_disabled(true); } link.set_stylesheet(sheet); } }, StylesheetContextSource::Import(ref stylesheet) =>
, } if let Some(ref shadow_root) = self.shadow_root { shadow_root.root().invalidate_stylesheets(); } else { document.invalidate_stylesheets(); } // FIXME: Revisit once consensus is reached at: // https://github.com/whatwg/html/issues/1142 successful = metadata.status.map_or(false, |(code, _)| code == 200); } let owner = elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); owner.set_origin_clean(self.origin_clean); if owner.parser_inserted() { document.decrement_script_blocking_stylesheet_count(); } document.finish_load(LoadType::Stylesheet(self.url.clone())); if let Some(any_failed) = owner.load_finished(successful) { let event = if any_failed { atom!("error") } else { atom!("load") }; elem.upcast::<EventTarget>().fire_event(event); } } fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming { &mut self.resource_timing } fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for StylesheetContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { let initiator_type = InitiatorType::LocalName( self.elem .root() .upcast::<Element>() .local_name() .to_string(), ); (initiator_type, self.url.clone()) } fn resource_timing_global(&self) -> DomRoot<GlobalScope> { document_from_node(&*self.elem.root()).global() } } pub struct StylesheetLoader<'a> { elem: &'a HTMLElement, } impl<'a> StylesheetLoader<'a> { pub fn for_element(element: &'a HTMLElement) -> Self { StylesheetLoader { elem: element } } } impl<'a> StylesheetLoader<'a> { pub fn load( &self, source: StylesheetContextSource, url: ServoUrl, cors_setting: Option<CorsSettings>, integrity_metadata: String, ) { let document = document_from_node(self.elem); let shadow_root = containing_shadow_root(self.elem).map(|sr| Trusted::new(&*sr)); let gen = self .elem .downcast::<HTMLLinkElement>() .map(HTMLLinkElement::get_request_generation_id); let context = ::std::sync::Arc::new(Mutex::new(StylesheetContext { elem: Trusted::new(&*self.elem), source: source, url: url.clone(), metadata: None, data: vec![], document: Trusted::new(&*document), shadow_root, origin_clean: true, request_generation_id: gen, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let (task_source, canceller) = document .window() .task_manager() .networking_task_source_with_canceller(); let listener = NetworkListener { context, task_source, canceller: Some(canceller), }; ROUTER.add_route( action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); }), ); let owner = self .elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); let referrer_policy = owner .referrer_policy() .or_else(|| document.get_referrer_policy()); owner.increment_pending_loads_count(); if owner.parser_inserted() { document.increment_script_blocking_stylesheet_count(); } let request = stylesheet_fetch_request( url.clone(), cors_setting, document.origin().immutable().clone(), self.elem.global().pipeline_id(), Referrer::ReferrerUrl(document.url()), referrer_policy, integrity_metadata, ); document.fetch_async(LoadType::Stylesheet(url), request, action_sender); } } // This function is also used to prefetch a stylesheet in `script::dom::servoparser::prefetch`. // https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource pub(crate) fn stylesheet_fetch_request( url: ServoUrl, cors_setting: Option<CorsSettings>, origin: ImmutableOrigin, pipeline_id: PipelineId, referrer: Referrer, referrer_policy: Option<ReferrerPolicy>, integrity_metadata: String, ) -> RequestBuilder { create_a_potential_cors_request(url, Destination::Style, cors_setting, None) .origin(origin) .pipeline_id(Some(pipeline_id)) .referrer(Some(referrer)) .referrer_policy(referrer_policy) .integrity_metadata(integrity_metadata) } impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> { /// Request a stylesheet after parsing a given `@import` rule, and return /// the constructed `@import` rule. fn request_stylesheet( &self, url: CssUrl, source_location: SourceLocation, context: &ParserContext, lock: &SharedRwLock, media: Arc<Locked<MediaList>>, ) -> Arc<Locked<ImportRule>> { let sheet = Arc::new(Stylesheet { contents: StylesheetContents { rules: CssRules::new(Vec::new(), lock), origin: context.stylesheet_origin, url_data: RwLock::new(context.url_data.clone()), quirks_mode: context.quirks_mode, namespaces: RwLock::new(Namespaces::default()), source_map_url: RwLock::new(None), source_url: RwLock::new(None), }, media: media, shared_lock: lock.clone(), disabled: AtomicBool::new(false), }); let stylesheet = ImportSheet(sheet.clone()); let import = ImportRule { url, source_location, stylesheet, }; let url = match import.url.url().cloned() { Some(url) => url, None => return Arc::new(lock.wrap(import)), }; // TODO (mrnayak) : Whether we should use the original loader's CORS // setting? Fix this when spec has more details. let source = StylesheetContextSource::Import(sheet.clone()); self.load(source, url, None, "".to_owned()); Arc::new(lock.wrap(import)) } }
{ Stylesheet::update_from_bytes( &stylesheet, &data, protocol_encoding_label, Some(environment_encoding), final_url, Some(&loader), win.css_error_reporter(), ); }
conditional_block
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmllinkelement::{HTMLLinkElement, RequestGenerationId}; use crate::dom::node::{containing_shadow_root, document_from_node, window_from_node}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::shadowroot::ShadowRoot; use crate::fetch::create_a_potential_cors_request; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use cssparser::SourceLocation; use encoding_rs::UTF_8; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use mime::{self, Mime}; use msg::constellation_msg::PipelineId; use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder}; use net_traits::{ FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy, }; use net_traits::{ResourceFetchTiming, ResourceTimingType}; use parking_lot::RwLock; use servo_arc::Arc; use servo_url::ImmutableOrigin; use servo_url::ServoUrl; use std::mem; use std::sync::atomic::AtomicBool; use std::sync::Mutex; use style::media_queries::MediaList; use style::parser::ParserContext; use style::shared_lock::{Locked, SharedRwLock}; use style::stylesheets::import_rule::ImportSheet; use style::stylesheets::StylesheetLoader as StyleStylesheetLoader; use style::stylesheets::{ CssRules, ImportRule, Namespaces, Origin, Stylesheet, StylesheetContents, }; use style::values::CssUrl; pub trait StylesheetOwner { /// Returns whether this element was inserted by the parser (i.e., it should /// trigger a document-load-blocking load). fn parser_inserted(&self) -> bool; /// Which referrer policy should loads triggered by this owner follow, or /// `None` for the default. fn referrer_policy(&self) -> Option<ReferrerPolicy>; /// Notes that a new load is pending to finish. fn increment_pending_loads_count(&self); /// Returns None if there are still pending loads, or whether any load has /// failed since the loads started. fn load_finished(&self, successful: bool) -> Option<bool>; /// Sets origin_clean flag. fn set_origin_clean(&self, origin_clean: bool); } pub enum StylesheetContextSource { // NB: `media` is just an option so we avoid cloning it. LinkElement { media: Option<MediaList> }, Import(Arc<Stylesheet>), } /// The context required for asynchronously loading an external stylesheet. pub struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLElement>, source: StylesheetContextSource, url: ServoUrl, metadata: Option<Metadata>, /// The response body received to date. data: Vec<u8>, /// The node document for elem when the load was initiated. document: Trusted<Document>, shadow_root: Option<Trusted<ShadowRoot>>, origin_clean: bool, /// A token which must match the generation id of the `HTMLLinkElement` for it to load the stylesheet. /// This is ignored for `HTMLStyleElement` and imports. request_generation_id: Option<RequestGenerationId>, resource_timing: ResourceFetchTiming, } impl PreInvoke for StylesheetContext {} impl FetchResponseListener for StylesheetContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { if let Ok(FetchMetadata::Filtered { ref filtered,.. }) = metadata { match *filtered { FilteredMetadata::Opaque | FilteredMetadata::OpaqueRedirect(_) => { self.origin_clean = false; }, _ => {}, } } self.metadata = metadata.ok().map(|m| match m { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_,.. } => unsafe_, }); } fn process_response_chunk(&mut self, mut payload: Vec<u8>) { self.data.append(&mut payload); } fn process_response_eof(&mut self, status: Result<ResourceFetchTiming, NetworkError>) { let elem = self.elem.root(); let document = self.document.root(); let mut successful = false; if status.is_ok() { let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }; let is_css = metadata.content_type.map_or(false, |ct| { let mime: Mime = ct.into_inner().into(); mime.type_() == mime::TEXT && mime.subtype() == mime::CSS }); let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8; let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s); let final_url = metadata.final_url; let win = window_from_node(&*elem); let loader = StylesheetLoader::for_element(&elem); match self.source { StylesheetContextSource::LinkElement { ref mut media } => { let link = elem.downcast::<HTMLLinkElement>().unwrap(); // We must first check whether the generations of the context and the element match up, // else we risk applying the wrong stylesheet when responses come out-of-order. let is_stylesheet_load_applicable = self .request_generation_id .map_or(true, |gen| gen == link.get_request_generation_id()); if is_stylesheet_load_applicable { let shared_lock = document.style_shared_lock().clone(); let sheet = Arc::new(Stylesheet::from_bytes( &data, final_url, protocol_encoding_label, Some(environment_encoding), Origin::Author, media.take().unwrap(), shared_lock, Some(&loader), win.css_error_reporter(), document.quirks_mode(), )); if link.is_alternate() { sheet.set_disabled(true); } link.set_stylesheet(sheet); } }, StylesheetContextSource::Import(ref stylesheet) => { Stylesheet::update_from_bytes( &stylesheet, &data, protocol_encoding_label, Some(environment_encoding), final_url, Some(&loader), win.css_error_reporter(), ); }, } if let Some(ref shadow_root) = self.shadow_root { shadow_root.root().invalidate_stylesheets(); } else { document.invalidate_stylesheets(); } // FIXME: Revisit once consensus is reached at: // https://github.com/whatwg/html/issues/1142 successful = metadata.status.map_or(false, |(code, _)| code == 200); } let owner = elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); owner.set_origin_clean(self.origin_clean); if owner.parser_inserted() { document.decrement_script_blocking_stylesheet_count(); } document.finish_load(LoadType::Stylesheet(self.url.clone())); if let Some(any_failed) = owner.load_finished(successful) { let event = if any_failed { atom!("error") } else { atom!("load") }; elem.upcast::<EventTarget>().fire_event(event); } } fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming { &mut self.resource_timing } fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for StylesheetContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { let initiator_type = InitiatorType::LocalName( self.elem .root() .upcast::<Element>() .local_name() .to_string(), ); (initiator_type, self.url.clone()) } fn resource_timing_global(&self) -> DomRoot<GlobalScope> { document_from_node(&*self.elem.root()).global() } } pub struct StylesheetLoader<'a> { elem: &'a HTMLElement, } impl<'a> StylesheetLoader<'a> { pub fn for_element(element: &'a HTMLElement) -> Self { StylesheetLoader { elem: element } } } impl<'a> StylesheetLoader<'a> {
&self, source: StylesheetContextSource, url: ServoUrl, cors_setting: Option<CorsSettings>, integrity_metadata: String, ) { let document = document_from_node(self.elem); let shadow_root = containing_shadow_root(self.elem).map(|sr| Trusted::new(&*sr)); let gen = self .elem .downcast::<HTMLLinkElement>() .map(HTMLLinkElement::get_request_generation_id); let context = ::std::sync::Arc::new(Mutex::new(StylesheetContext { elem: Trusted::new(&*self.elem), source: source, url: url.clone(), metadata: None, data: vec![], document: Trusted::new(&*document), shadow_root, origin_clean: true, request_generation_id: gen, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let (task_source, canceller) = document .window() .task_manager() .networking_task_source_with_canceller(); let listener = NetworkListener { context, task_source, canceller: Some(canceller), }; ROUTER.add_route( action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); }), ); let owner = self .elem .upcast::<Element>() .as_stylesheet_owner() .expect("Stylesheet not loaded by <style> or <link> element!"); let referrer_policy = owner .referrer_policy() .or_else(|| document.get_referrer_policy()); owner.increment_pending_loads_count(); if owner.parser_inserted() { document.increment_script_blocking_stylesheet_count(); } let request = stylesheet_fetch_request( url.clone(), cors_setting, document.origin().immutable().clone(), self.elem.global().pipeline_id(), Referrer::ReferrerUrl(document.url()), referrer_policy, integrity_metadata, ); document.fetch_async(LoadType::Stylesheet(url), request, action_sender); } } // This function is also used to prefetch a stylesheet in `script::dom::servoparser::prefetch`. // https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource pub(crate) fn stylesheet_fetch_request( url: ServoUrl, cors_setting: Option<CorsSettings>, origin: ImmutableOrigin, pipeline_id: PipelineId, referrer: Referrer, referrer_policy: Option<ReferrerPolicy>, integrity_metadata: String, ) -> RequestBuilder { create_a_potential_cors_request(url, Destination::Style, cors_setting, None) .origin(origin) .pipeline_id(Some(pipeline_id)) .referrer(Some(referrer)) .referrer_policy(referrer_policy) .integrity_metadata(integrity_metadata) } impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> { /// Request a stylesheet after parsing a given `@import` rule, and return /// the constructed `@import` rule. fn request_stylesheet( &self, url: CssUrl, source_location: SourceLocation, context: &ParserContext, lock: &SharedRwLock, media: Arc<Locked<MediaList>>, ) -> Arc<Locked<ImportRule>> { let sheet = Arc::new(Stylesheet { contents: StylesheetContents { rules: CssRules::new(Vec::new(), lock), origin: context.stylesheet_origin, url_data: RwLock::new(context.url_data.clone()), quirks_mode: context.quirks_mode, namespaces: RwLock::new(Namespaces::default()), source_map_url: RwLock::new(None), source_url: RwLock::new(None), }, media: media, shared_lock: lock.clone(), disabled: AtomicBool::new(false), }); let stylesheet = ImportSheet(sheet.clone()); let import = ImportRule { url, source_location, stylesheet, }; let url = match import.url.url().cloned() { Some(url) => url, None => return Arc::new(lock.wrap(import)), }; // TODO (mrnayak) : Whether we should use the original loader's CORS // setting? Fix this when spec has more details. let source = StylesheetContextSource::Import(sheet.clone()); self.load(source, url, None, "".to_owned()); Arc::new(lock.wrap(import)) } }
pub fn load(
random_line_split
solve.rs
// http://rosettacode.org/wiki/24_game/Solve //! Modeled after [the Scala solution] //! //! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(slice_patterns)] extern crate num; extern crate permutohedron; use num::rational::{Ratio, Rational}; use num::traits::Zero; use permutohedron::Heap; /// convenience macro to create a fixed-sized vector of rationals by writing `rational![1, 2,...]` /// instead of `[Ratio::<isize>::from_integer(1), Ratio::<isize>::from_integer(2),...]` macro_rules! rationals( ($($e:expr),+) => ([$(Ratio::<isize>::from_integer($e)),+]) ); fn main() { let mut r = rationals![1, 3, 7, 9]; let sol = solve(&mut r[..], 24).unwrap_or("no solution found".to_string()); println!("{}", sol); } /// for a vector of rationals r, find the combination of arithmentic operations that yield /// `target_val` as a result (if such combination exists) fn solve(r: &mut [Rational], target_val: isize) -> Option<String> { // need to sort because next_permutation() // returns permutations in lexicographic order r.sort(); loop { let all_ops = compute_all_operations(r); for &(res, ref ops) in &all_ops { if res == Ratio::from_integer(target_val) { return Some(ops.to_string()); } } let mut perm = Heap::new(r); if perm.next_permutation() == None { return None; } } } /// applies all the valid combinations of + - * and / to the numbers in l and for each combination /// creates a tuple with the result and the expression in String form returns all (result, /// expression in string form) results in a vector fn compute_all_operations(l: &[Rational]) -> Vec<(Rational, String)> { match l { [] => vec![], [x] => vec![(x, (format!("{}", x)))], [x, rest..] => { let mut rt = Vec::new(); for &(y, ref exp) in &compute_all_operations(rest) { let mut sub = vec![(x * y, "*"), (x + y, "+"), (x - y, "-")]; if y!= Zero::zero() { sub.push((x / y, "/")); } for &(z, ref op) in &sub { let aux = (z, (format!("({} {} {})", x, op, exp))); rt.push(aux); } } rt } } } #[test] fn test_rationals_macro() { assert_eq!(// without the rationals! macro [Ratio::from_integer(1), Ratio::from_integer(2), Ratio::from_integer(3), Ratio::from_integer(4)], // with the rationals! macro (rationals![1, 2, 3, 4])); } #[test] #[ignore] fn
() { let mut r = rationals![1, 3, 7, 9]; assert_eq!(solve(&mut r[..], 24), Some("(9 / (3 / (1 + 7)))".to_string())); }
test_solve
identifier_name
solve.rs
// http://rosettacode.org/wiki/24_game/Solve //! Modeled after [the Scala solution] //! //! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(slice_patterns)] extern crate num; extern crate permutohedron; use num::rational::{Ratio, Rational}; use num::traits::Zero; use permutohedron::Heap; /// convenience macro to create a fixed-sized vector of rationals by writing `rational![1, 2,...]` /// instead of `[Ratio::<isize>::from_integer(1), Ratio::<isize>::from_integer(2),...]` macro_rules! rationals( ($($e:expr),+) => ([$(Ratio::<isize>::from_integer($e)),+]) ); fn main()
/// for a vector of rationals r, find the combination of arithmentic operations that yield /// `target_val` as a result (if such combination exists) fn solve(r: &mut [Rational], target_val: isize) -> Option<String> { // need to sort because next_permutation() // returns permutations in lexicographic order r.sort(); loop { let all_ops = compute_all_operations(r); for &(res, ref ops) in &all_ops { if res == Ratio::from_integer(target_val) { return Some(ops.to_string()); } } let mut perm = Heap::new(r); if perm.next_permutation() == None { return None; } } } /// applies all the valid combinations of + - * and / to the numbers in l and for each combination /// creates a tuple with the result and the expression in String form returns all (result, /// expression in string form) results in a vector fn compute_all_operations(l: &[Rational]) -> Vec<(Rational, String)> { match l { [] => vec![], [x] => vec![(x, (format!("{}", x)))], [x, rest..] => { let mut rt = Vec::new(); for &(y, ref exp) in &compute_all_operations(rest) { let mut sub = vec![(x * y, "*"), (x + y, "+"), (x - y, "-")]; if y!= Zero::zero() { sub.push((x / y, "/")); } for &(z, ref op) in &sub { let aux = (z, (format!("({} {} {})", x, op, exp))); rt.push(aux); } } rt } } } #[test] fn test_rationals_macro() { assert_eq!(// without the rationals! macro [Ratio::from_integer(1), Ratio::from_integer(2), Ratio::from_integer(3), Ratio::from_integer(4)], // with the rationals! macro (rationals![1, 2, 3, 4])); } #[test] #[ignore] fn test_solve() { let mut r = rationals![1, 3, 7, 9]; assert_eq!(solve(&mut r[..], 24), Some("(9 / (3 / (1 + 7)))".to_string())); }
{ let mut r = rationals![1, 3, 7, 9]; let sol = solve(&mut r[..], 24).unwrap_or("no solution found".to_string()); println!("{}", sol); }
identifier_body
solve.rs
// http://rosettacode.org/wiki/24_game/Solve //! Modeled after [the Scala solution] //! //! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(slice_patterns)] extern crate num; extern crate permutohedron; use num::rational::{Ratio, Rational}; use num::traits::Zero; use permutohedron::Heap; /// convenience macro to create a fixed-sized vector of rationals by writing `rational![1, 2,...]` /// instead of `[Ratio::<isize>::from_integer(1), Ratio::<isize>::from_integer(2),...]` macro_rules! rationals( ($($e:expr),+) => ([$(Ratio::<isize>::from_integer($e)),+]) ); fn main() { let mut r = rationals![1, 3, 7, 9]; let sol = solve(&mut r[..], 24).unwrap_or("no solution found".to_string()); println!("{}", sol); } /// for a vector of rationals r, find the combination of arithmentic operations that yield /// `target_val` as a result (if such combination exists) fn solve(r: &mut [Rational], target_val: isize) -> Option<String> { // need to sort because next_permutation() // returns permutations in lexicographic order r.sort(); loop { let all_ops = compute_all_operations(r); for &(res, ref ops) in &all_ops { if res == Ratio::from_integer(target_val) { return Some(ops.to_string()); } } let mut perm = Heap::new(r); if perm.next_permutation() == None { return None; } } } /// applies all the valid combinations of + - * and / to the numbers in l and for each combination /// creates a tuple with the result and the expression in String form returns all (result, /// expression in string form) results in a vector fn compute_all_operations(l: &[Rational]) -> Vec<(Rational, String)> { match l { [] => vec![], [x] => vec![(x, (format!("{}", x)))], [x, rest..] => { let mut rt = Vec::new(); for &(y, ref exp) in &compute_all_operations(rest) { let mut sub = vec![(x * y, "*"), (x + y, "+"), (x - y, "-")]; if y!= Zero::zero() { sub.push((x / y, "/")); } for &(z, ref op) in &sub { let aux = (z, (format!("({} {} {})", x, op, exp))); rt.push(aux); } } rt } } } #[test] fn test_rationals_macro() { assert_eq!(// without the rationals! macro [Ratio::from_integer(1), Ratio::from_integer(2), Ratio::from_integer(3), Ratio::from_integer(4)], // with the rationals! macro (rationals![1, 2, 3, 4])); } #[test]
fn test_solve() { let mut r = rationals![1, 3, 7, 9]; assert_eq!(solve(&mut r[..], 24), Some("(9 / (3 / (1 + 7)))".to_string())); }
#[ignore]
random_line_split
self_authentication.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
// // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. //! Self-authentication example. // For explanation of lint checks, run `rustc -W help` or see // https://github. // com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings)] #![deny(deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations, missing_debug_implementations, variant_size_differences)] #![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))] #![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout))] /* extern crate safe_core; #[macro_use] extern crate maidsafe_utilities; extern crate routing; extern crate tokio_core; #[macro_use] extern crate unwrap; use routing::client_errors::MutationError; use safe_core::core::{Client, CoreError}; use tokio_core::channel; use tokio_core::reactor::Core; fn main() { unwrap!(maidsafe_utilities::log::init(true)); let el = unwrap!(Core::new()); let el_h = el.handle(); let (core_tx, _core_rx) = unwrap!(channel::channel(&el_h)); let (net_tx, _net_rx) = unwrap!(channel::channel(&el_h)); let mut secret_0 = String::new(); let mut secret_1 = String::new(); println!("\nDo you already have an account created (enter Y for yes)?"); let mut user_option = String::new(); let _ = std::io::stdin().read_line(&mut user_option); user_option = user_option.trim().to_string(); if user_option!= "Y" && user_option!= "y" { println!("\n\tAccount Creation"); println!("\t================"); println!("\n------------ Enter account-locator ---------------"); let _ = std::io::stdin().read_line(&mut secret_0); secret_0 = secret_0.trim().to_string(); println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string(); // Account Creation { println!("\nTrying to create an account..."); match Client::registered::<()>(&secret_0, &secret_1, el_h.clone(), core_tx.clone(), net_tx.clone()) { Ok(_) => (), Err(CoreError::MutationFailure { reason: MutationError::AccountExists,.. }) => { println!("ERROR: This domain is already taken. Please retry with different \ Keyword and/or PIN"); return; } Err(err) => panic!("{:?}", err), } println!("Account Created Successfully!!"); } println!("\n\n\tAuto Account Login"); println!("\t=================="); // Log into the created account { println!("\nTrying to log into the created account using supplied credentials..."); let _ = unwrap!(Client::login::<()>(&secret_0, &secret_1, el_h.clone(), core_tx.clone(), net_tx.clone())); println!("Account Login Successful!!"); } } println!("\n\n\tManual Account Login"); println!("\t===================="); loop { secret_0 = String::new(); secret_1 = String::new(); let el_h2 = el_h.clone(); println!("\n------------ Enter account-locator ---------------"); let _ = std::io::stdin().read_line(&mut secret_0); secret_0 = secret_0.trim().to_string(); println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string(); // Log into the created account { println!("\nTrying to log in..."); match Client::login(&secret_0, &secret_1, el_h2, core_tx.clone(), net_tx.clone()) { Ok(_) => { println!("Account Login Successful!!"); break; } Err(error) => println!("ERROR: Account Login Failed!!\nReason: {:?}\n\n", error), } } } } */ /// main fn main() {}
// // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied.
random_line_split
self_authentication.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. //! Self-authentication example. // For explanation of lint checks, run `rustc -W help` or see // https://github. // com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings)] #![deny(deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations, missing_debug_implementations, variant_size_differences)] #![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))] #![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout))] /* extern crate safe_core; #[macro_use] extern crate maidsafe_utilities; extern crate routing; extern crate tokio_core; #[macro_use] extern crate unwrap; use routing::client_errors::MutationError; use safe_core::core::{Client, CoreError}; use tokio_core::channel; use tokio_core::reactor::Core; fn main() { unwrap!(maidsafe_utilities::log::init(true)); let el = unwrap!(Core::new()); let el_h = el.handle(); let (core_tx, _core_rx) = unwrap!(channel::channel(&el_h)); let (net_tx, _net_rx) = unwrap!(channel::channel(&el_h)); let mut secret_0 = String::new(); let mut secret_1 = String::new(); println!("\nDo you already have an account created (enter Y for yes)?"); let mut user_option = String::new(); let _ = std::io::stdin().read_line(&mut user_option); user_option = user_option.trim().to_string(); if user_option!= "Y" && user_option!= "y" { println!("\n\tAccount Creation"); println!("\t================"); println!("\n------------ Enter account-locator ---------------"); let _ = std::io::stdin().read_line(&mut secret_0); secret_0 = secret_0.trim().to_string(); println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string(); // Account Creation { println!("\nTrying to create an account..."); match Client::registered::<()>(&secret_0, &secret_1, el_h.clone(), core_tx.clone(), net_tx.clone()) { Ok(_) => (), Err(CoreError::MutationFailure { reason: MutationError::AccountExists,.. }) => { println!("ERROR: This domain is already taken. Please retry with different \ Keyword and/or PIN"); return; } Err(err) => panic!("{:?}", err), } println!("Account Created Successfully!!"); } println!("\n\n\tAuto Account Login"); println!("\t=================="); // Log into the created account { println!("\nTrying to log into the created account using supplied credentials..."); let _ = unwrap!(Client::login::<()>(&secret_0, &secret_1, el_h.clone(), core_tx.clone(), net_tx.clone())); println!("Account Login Successful!!"); } } println!("\n\n\tManual Account Login"); println!("\t===================="); loop { secret_0 = String::new(); secret_1 = String::new(); let el_h2 = el_h.clone(); println!("\n------------ Enter account-locator ---------------"); let _ = std::io::stdin().read_line(&mut secret_0); secret_0 = secret_0.trim().to_string(); println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string(); // Log into the created account { println!("\nTrying to log in..."); match Client::login(&secret_0, &secret_1, el_h2, core_tx.clone(), net_tx.clone()) { Ok(_) => { println!("Account Login Successful!!"); break; } Err(error) => println!("ERROR: Account Login Failed!!\nReason: {:?}\n\n", error), } } } } */ /// main fn
() {}
main
identifier_name
self_authentication.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. //! Self-authentication example. // For explanation of lint checks, run `rustc -W help` or see // https://github. // com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings)] #![deny(deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations, missing_debug_implementations, variant_size_differences)] #![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))] #![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout))] /* extern crate safe_core; #[macro_use] extern crate maidsafe_utilities; extern crate routing; extern crate tokio_core; #[macro_use] extern crate unwrap; use routing::client_errors::MutationError; use safe_core::core::{Client, CoreError}; use tokio_core::channel; use tokio_core::reactor::Core; fn main() { unwrap!(maidsafe_utilities::log::init(true)); let el = unwrap!(Core::new()); let el_h = el.handle(); let (core_tx, _core_rx) = unwrap!(channel::channel(&el_h)); let (net_tx, _net_rx) = unwrap!(channel::channel(&el_h)); let mut secret_0 = String::new(); let mut secret_1 = String::new(); println!("\nDo you already have an account created (enter Y for yes)?"); let mut user_option = String::new(); let _ = std::io::stdin().read_line(&mut user_option); user_option = user_option.trim().to_string(); if user_option!= "Y" && user_option!= "y" { println!("\n\tAccount Creation"); println!("\t================"); println!("\n------------ Enter account-locator ---------------"); let _ = std::io::stdin().read_line(&mut secret_0); secret_0 = secret_0.trim().to_string(); println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string(); // Account Creation { println!("\nTrying to create an account..."); match Client::registered::<()>(&secret_0, &secret_1, el_h.clone(), core_tx.clone(), net_tx.clone()) { Ok(_) => (), Err(CoreError::MutationFailure { reason: MutationError::AccountExists,.. }) => { println!("ERROR: This domain is already taken. Please retry with different \ Keyword and/or PIN"); return; } Err(err) => panic!("{:?}", err), } println!("Account Created Successfully!!"); } println!("\n\n\tAuto Account Login"); println!("\t=================="); // Log into the created account { println!("\nTrying to log into the created account using supplied credentials..."); let _ = unwrap!(Client::login::<()>(&secret_0, &secret_1, el_h.clone(), core_tx.clone(), net_tx.clone())); println!("Account Login Successful!!"); } } println!("\n\n\tManual Account Login"); println!("\t===================="); loop { secret_0 = String::new(); secret_1 = String::new(); let el_h2 = el_h.clone(); println!("\n------------ Enter account-locator ---------------"); let _ = std::io::stdin().read_line(&mut secret_0); secret_0 = secret_0.trim().to_string(); println!("\n------------ Enter password ---------------"); let _ = std::io::stdin().read_line(&mut secret_1); secret_1 = secret_1.trim().to_string(); // Log into the created account { println!("\nTrying to log in..."); match Client::login(&secret_0, &secret_1, el_h2, core_tx.clone(), net_tx.clone()) { Ok(_) => { println!("Account Login Successful!!"); break; } Err(error) => println!("ERROR: Account Login Failed!!\nReason: {:?}\n\n", error), } } } } */ /// main fn main()
{}
identifier_body
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; use dom::document::DocumentSource; use dom::window::{Window, WindowHelpers}; use parse::html::{HTMLInput, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: JS<Window>, //XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: JSRef<Window>) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: JS::from_rooted(window), } } pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window), DOMParserBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<DOMParser>> {
Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn ParseFromString(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>> { let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentSource::FromParser).root(); parse_html(document.r(), HTMLInput::InputString(s), &url); document.r().set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document.r())) } Text_xml => { //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type), None, DocumentSource::NotFromParser)) } } } }
random_line_split
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; use dom::document::DocumentSource; use dom::window::{Window, WindowHelpers}; use parse::html::{HTMLInput, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: JS<Window>, //XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: JSRef<Window>) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: JS::from_rooted(window), } } pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window), DOMParserBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<DOMParser>> { Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn
(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>> { let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentSource::FromParser).root(); parse_html(document.r(), HTMLInput::InputString(s), &url); document.r().set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document.r())) } Text_xml => { //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type), None, DocumentSource::NotFromParser)) } } } }
ParseFromString
identifier_name
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; use dom::document::DocumentSource; use dom::window::{Window, WindowHelpers}; use parse::html::{HTMLInput, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: JS<Window>, //XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: JSRef<Window>) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: JS::from_rooted(window), } } pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window), DOMParserBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<DOMParser>> { Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn ParseFromString(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>> { let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentSource::FromParser).root(); parse_html(document.r(), HTMLInput::InputString(s), &url); document.r().set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document.r())) } Text_xml =>
} } }
{ //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type), None, DocumentSource::NotFromParser)) }
conditional_block
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; use dom::document::DocumentSource; use dom::window::{Window, WindowHelpers}; use parse::html::{HTMLInput, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: JS<Window>, //XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: JSRef<Window>) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: JS::from_rooted(window), } } pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window), DOMParserBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<DOMParser>> { Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn ParseFromString(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>>
None, DocumentSource::NotFromParser)) } } } }
{ let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentSource::FromParser).root(); parse_html(document.r(), HTMLInput::InputString(s), &url); document.r().set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document.r())) } Text_xml => { //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type),
identifier_body
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; #[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement } impl HTMLAppletElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAppletElement
#[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAppletElement> { let element = HTMLAppletElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap) } } impl HTMLAppletElementMethods for HTMLAppletElement { // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_atomic_setter!(SetName, "name"); } impl VirtualMethods for HTMLAppletElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
{ HTMLAppletElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; #[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement } impl HTMLAppletElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAppletElement> { let element = HTMLAppletElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap) } } impl HTMLAppletElementMethods for HTMLAppletElement { // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_atomic_setter!(SetName, "name"); } impl VirtualMethods for HTMLAppletElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
new
identifier_name
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; #[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement } impl HTMLAppletElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAppletElement> { let element = HTMLAppletElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap) } } impl HTMLAppletElementMethods for HTMLAppletElement { // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name
impl VirtualMethods for HTMLAppletElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
make_atomic_setter!(SetName, "name"); }
random_line_split
test_client.rs
t your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Test client. use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder}; use util::*; use rlp::*; use ethkey::{Generator, Random}; use devtools::*; use transaction::{Transaction, LocalizedTransaction, PendingTransaction, SignedTransaction, Action}; use blockchain::TreeRoute; use client::{ BlockChainClient, MiningBlockChainClient, EngineClient, BlockChainInfo, BlockStatus, BlockId, TransactionId, UncleId, TraceId, TraceFilter, LastHashes, CallAnalytics, BlockImportError, ProvingBlockChainClient, }; use db::{NUM_COLUMNS, COL_STATE}; use header::{Header as BlockHeader, BlockNumber}; use filter::Filter; use log_entry::LocalizedLogEntry; use receipt::{Receipt, LocalizedReceipt}; use blockchain::extras::BlockReceipts; use error::{ImportResult}; use evm::{Factory as EvmFactory, VMType, Schedule}; use miner::{Miner, MinerService, TransactionImportResult}; use spec::Spec; use types::mode::Mode; use types::pruning_info::PruningInfo; use verification::queue::QueueInfo; use block::{OpenBlock, SealedBlock}; use executive::Executed; use error::CallError; use trace::LocalizedTrace; use state_db::StateDB; use encoded; /// Test client. pub struct TestBlockChainClient { /// Blocks. pub blocks: RwLock<HashMap<H256, Bytes>>, /// Mapping of numbers to hashes. pub numbers: RwLock<HashMap<usize, H256>>, /// Genesis block hash. pub genesis_hash: H256, /// Last block hash. pub last_hash: RwLock<H256>, /// Extra data do set for each block pub extra_data: Bytes, /// Difficulty. pub difficulty: RwLock<U256>, /// Balances. pub balances: RwLock<HashMap<Address, U256>>, /// Nonces. pub nonces: RwLock<HashMap<Address, U256>>, /// Storage. pub storage: RwLock<HashMap<(Address, H256), H256>>, /// Code. pub code: RwLock<HashMap<Address, Bytes>>, /// Execution result. pub execution_result: RwLock<Option<Result<Executed, CallError>>>, /// Transaction receipts. pub receipts: RwLock<HashMap<TransactionId, LocalizedReceipt>>, /// Logs pub logs: RwLock<Vec<LocalizedLogEntry>>, /// Block queue size. pub queue_size: AtomicUsize, /// Miner pub miner: Arc<Miner>, /// Spec pub spec: Spec, /// VM Factory pub vm_factory: EvmFactory, /// Timestamp assigned to latest sealed block pub latest_block_timestamp: RwLock<u64>, /// Ancient block info. pub ancient_block: RwLock<Option<(H256, u64)>>, /// First block info. pub first_block: RwLock<Option<(H256, u64)>>, /// Traces to return pub traces: RwLock<Option<Vec<LocalizedTrace>>>, /// Pruning history size to report. pub history: RwLock<Option<u64>>, } /// Used for generating test client blocks. #[derive(Clone)] pub enum EachBlockWith { /// Plain block. Nothing, /// Block with an uncle. Uncle, /// Block with a transaction. Transaction, /// Block with an uncle and transaction. UncleAndTransaction } impl Default for TestBlockChainClient { fn default() -> Self { TestBlockChainClient::new() } } impl TestBlockChainClient { /// Creates new test client. pub fn new() -> Self { Self::new_with_extra_data(Bytes::new()) } /// Creates new test client with specified extra data for each block pub fn new_with_extra_data(extra_data: Bytes) -> Self { let spec = Spec::new_test(); TestBlockChainClient::new_with_spec_and_extra(spec, extra_data) } /// Create test client with custom spec. pub fn new_with_spec(spec: Spec) -> Self { TestBlockChainClient::new_with_spec_and_extra(spec, Bytes::new()) } /// Create test client with custom spec and extra data. pub fn new_with_spec_and_extra(spec: Spec, extra_data: Bytes) -> Self { let genesis_block = spec.genesis_block(); let genesis_hash = spec.genesis_header().hash(); let mut client = TestBlockChainClient { blocks: RwLock::new(HashMap::new()), numbers: RwLock::new(HashMap::new()), genesis_hash: H256::new(), extra_data: extra_data, last_hash: RwLock::new(H256::new()), difficulty: RwLock::new(spec.genesis_header().difficulty().clone()), balances: RwLock::new(HashMap::new()), nonces: RwLock::new(HashMap::new()), storage: RwLock::new(HashMap::new()), code: RwLock::new(HashMap::new()), execution_result: RwLock::new(None), receipts: RwLock::new(HashMap::new()), logs: RwLock::new(Vec::new()), queue_size: AtomicUsize::new(0), miner: Arc::new(Miner::with_spec(&spec)), spec: spec, vm_factory: EvmFactory::new(VMType::Interpreter, 1024 * 1024), latest_block_timestamp: RwLock::new(10_000_000), ancient_block: RwLock::new(None), first_block: RwLock::new(None), traces: RwLock::new(None), history: RwLock::new(None), }; // insert genesis hash. client.blocks.get_mut().insert(genesis_hash, genesis_block); client.numbers.get_mut().insert(0, genesis_hash); *client.last_hash.get_mut() = genesis_hash; client.genesis_hash = genesis_hash; client } /// Set the transaction receipt result pub fn set_transaction_receipt(&self, id: TransactionId, receipt: LocalizedReceipt) { self.receipts.write().insert(id, receipt); } /// Set the execution result. pub fn set_execution_result(&self, result: Result<Executed, CallError>) { *self.execution_result.write() = Some(result); } /// Set the balance of account `address` to `balance`. pub fn set_balance(&self, address: Address, balance: U256) { self.balances.write().insert(address, balance); } /// Set nonce of account `address` to `nonce`. pub fn set_nonce(&self, address: Address, nonce: U256) { self.nonces.write().insert(address, nonce); } /// Set `code` at `address`. pub fn set_code(&self, address: Address, code: Bytes) { self.code.write().insert(address, code); } /// Set storage `position` to `value` for account `address`. pub fn set_storage(&self, address: Address, position: H256, value: H256) { self.storage.write().insert((address, position), value); } /// Set block queue size for testing pub fn set_queue_size(&self, size: usize) { self.queue_size.store(size, AtomicOrder::Relaxed); } /// Set timestamp assigned to latest sealed block pub fn set_latest_block_timestamp(&self, ts: u64) { *self.latest_block_timestamp.write() = ts; } /// Set logs to return for each logs call. pub fn set_logs(&self, logs: Vec<LocalizedLogEntry>) { *self.logs.write() = logs; } /// Add blocks to test client. pub fn add_blocks(&self, count: usize, with: EachBlockWith) { let len = self.numbers.read().len(); for n in len..(len + count) { let mut header = BlockHeader::new(); header.set_difficulty(From::from(n)); header.set_parent_hash(self.last_hash.read().clone()); header.set_number(n as BlockNumber); header.set_gas_limit(U256::from(1_000_000)); header.set_extra_data(self.extra_data.clone()); let uncles = match with { EachBlockWith::Uncle | EachBlockWith::UncleAndTransaction => { let mut uncles = RlpStream::new_list(1); let mut uncle_header = BlockHeader::new(); uncle_header.set_difficulty(From::from(n)); uncle_header.set_parent_hash(self.last_hash.read().clone()); uncle_header.set_number(n as BlockNumber); uncles.append(&uncle_header); header.set_uncles_hash(uncles.as_raw().sha3()); uncles }, _ => RlpStream::new_list(0) }; let txs = match with { EachBlockWith::Transaction | EachBlockWith::UncleAndTransaction => { let mut txs = RlpStream::new_list(1); let keypair = Random.generate().unwrap(); // Update nonces value self.nonces.write().insert(keypair.address(), U256::one()); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(200_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); txs.append(&signed_tx); txs.out() }, _ => ::rlp::EMPTY_LIST_RLP.to_vec() }; let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&txs, 1); rlp.append_raw(uncles.as_raw(), 1); self.import_block(rlp.as_raw().to_vec()).unwrap(); } } /// Make a bad block by setting invalid extra data. pub fn corrupt_block(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_extra_data(b"This extra data is way too long to be considered valid".to_vec()); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// Make a bad block by setting invalid parent hash. pub fn corrupt_block_parent(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_parent_hash(H256::from(42)); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// TODO: pub fn block_hash_delta_minus(&mut self, delta: usize) -> H256 { let blocks_read = self.numbers.read(); let index = blocks_read.len() - delta; blocks_read[&index].clone() } fn block_hash(&self, id: BlockId) -> Option<H256> { match id { BlockId::Hash(hash) => Some(hash), BlockId::Number(n) => self.numbers.read().get(&(n as usize)).cloned(), BlockId::Earliest => self.numbers.read().get(&0).cloned(), BlockId::Latest | BlockId::Pending => self.numbers.read().get(&(self.numbers.read().len() - 1)).cloned() } } /// Inserts a transaction to miners transactions queue. pub fn insert_transaction_to_queue(&self) { let keypair = Random.generate().unwrap(); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(20_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); self.set_balance(signed_tx.sender(), U256::from(10_000_000_000_000_000_000u64)); let res = self.miner.import_external_transactions(self, vec![signed_tx.into()]); let res = res.into_iter().next().unwrap().expect("Successful import"); assert_eq!(res, TransactionImportResult::Current); } /// Set reported history size. pub fn set_history(&self, h: Option<u64>) { *self.history.write() = h; } } pub fn get_temp_state_db() -> GuardedTempResult<StateDB> { let temp = RandomTempPath::new(); let db = Database::open(&DatabaseConfig::with_columns(NUM_COLUMNS), temp.as_str()).unwrap(); let journal_db = journaldb::new(Arc::new(db), journaldb::Algorithm::EarlyMerge, COL_STATE); let state_db = StateDB::new(journal_db, 1024 * 1024); GuardedTempResult { _temp: temp, result: Some(state_db) } } impl MiningBlockChainClient for TestBlockChainClient { fn latest_schedule(&self) -> Schedule { Schedule::new_post_eip150(24576, true, true, true) } fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { let engine = &*self.spec.engine; let genesis_header = self.spec.genesis_header(); let mut db_result = get_temp_state_db(); let db = self.spec.ensure_db_good(db_result.take(), &Default::default()).unwrap(); let last_hashes = vec![genesis_header.hash()]; let mut open_block = OpenBlock::new( engine, Default::default(), false, db, &genesis_header, Arc::new(last_hashes), author, gas_range_target, extra_data ).expect("Opening block for tests will not fail."); // TODO [todr] Override timestamp for predictability (set_timestamp_now kind of sucks) open_block.set_timestamp(*self.latest_block_timestamp.read()); open_block } fn vm_factory(&self) -> &EvmFactory { &self.vm_factory } fn import_sealed_block(&self, _block: SealedBlock) -> ImportResult { Ok(H256::default()) } fn broadcast_proposal_block(&self, _block: SealedBlock) {} } impl BlockChainClient for TestBlockChainClient { fn call(&self, _t: &SignedTransaction, _block: BlockId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn estimate_gas(&self, _t: &SignedTransaction, _block: BlockId) -> Result<U256, CallError> { Ok(21000.into()) } fn replay(&self, _id: TransactionId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> { Some(U256::zero()) } fn block_hash(&self, id: BlockId) -> Option<H256> { Self::block_hash(self, id) } fn nonce(&self, address: &Address, id: BlockId) -> Option<U256> { match id { BlockId::Latest => Some(self.nonces.read().get(address).cloned().unwrap_or(self.spec.params.account_start_nonce)), _ => None, } } fn storage_root(&self, _address: &Address, _id: BlockId) -> Option<H256> { None } fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockId::Latest).unwrap() } fn code(&self, address: &Address, id: BlockId) -> Option<Option<Bytes>> { match id { BlockId::Latest => Some(self.code.read().get(address).cloned()), _ => None, } } fn balance(&self, address: &Address, id: BlockId) -> Option<U256> { if let BlockId::Latest = id { Some(self.balances.read().get(address).cloned().unwrap_or_else(U256::zero)) } else { None } } fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockId::Latest).unwrap() } fn storage_at(&self, address: &Address, position: &H256, id: BlockId) -> Option<H256> { if let BlockId::Latest = id { Some(self.storage.read().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)) } else { None } } fn list_accounts(&self, _id: BlockId, _after: Option<&Address>, _count: u64) -> Option<Vec<Address>> { None } fn list_storage(&self, _id: BlockId, _account: &Address, _after: Option<&H256>, _count: u64) -> Option<Vec<H256>> { None } fn transaction(&self, _id: TransactionId) -> Option<LocalizedTransaction> { None // Simple default. } fn transaction_block(&self, _id: TransactionId) -> Option<H256> { None // Simple default. } fn uncle(&self, _id: UncleId) -> Option<encoded::Header> { None // Simple default. } fn uncle_extra_info(&self, _id: UncleId) -> Option<BTreeMap<String, String>> { None } fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> { self.receipts.read().get(&id).cloned() } fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockId, _to_block: BlockId) -> Option<Vec<BlockNumber>> { unimplemented!(); } fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry> { let mut logs = self.logs.read().clone();
let len = logs.len(); match filter.limit { Some(limit) if limit <= len => logs.split_off(len - limit), _ => logs, } } fn last_hashes(&self) -> LastHashes { unimplemented!(); } fn best_block_header(&self) -> encoded::Header { self.block_header(BlockId::Hash(self.chain_info().best_block_hash)) .expect("Best block always has header.") } fn block_header(&self, id: BlockId) -> Option<encoded::Header> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec())) .map(encoded::Header::new) } fn block_number(&self, _id: BlockId) -> Option<BlockNumber> { unimplemented!() } fn block_body(&self, id: BlockId) -> Option<encoded::Body> { self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).map(|r| { let mut stream = RlpStream::new_list(2); stream.append_raw(Rlp::new(r).at(1).as_raw(), 1); stream.append_raw(Rlp::new(r).at(2).as_raw(), 1); encoded::Body::new(stream.out()) })) } fn block(&self, id: BlockId) -> Option<encoded::Block> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).cloned()) .map(encoded::Block::new) } fn block_extra_info(&self, id: BlockId) -> Option<BTreeMap<String, String>> { self.block(id) .map(|block| block.view().header()) .map(|header| self.spec.engine.extra_info(&header)) } fn block_status(&self, id: BlockId) -> BlockStatus { match id { BlockId::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain, BlockId::Hash(ref hash) if self.blocks.read().get(hash).is_some() => BlockStatus::InChain, BlockId::Latest | BlockId::Pending | BlockId::Earliest => BlockStatus::InChain, _ => BlockStatus::Unknown, } } // works only if blocks are one after another 1 -> 2 -> 3 fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> { Some(TreeRoute { ancestor: H256::new(), index: 0, blocks: { let numbers_read = self.numbers.read(); let mut adding = false; let mut blocks = Vec::new(); for (_, hash) in numbers_read.iter().sort_by(|tuple1, tuple2| tuple1.0.cmp(tuple2.0)) { if hash == to { if adding { blocks.push(hash.clone()); } adding = false; break; } if hash == from { adding = true; } if adding { blocks.push(hash.clone()); } } if adding { Vec::new() } else { blocks } } }) } fn find_uncles(&self, _hash: &H256) -> Option<Vec<H256>> { None } // TODO: returns just hashes instead of node state rlp(?) fn state_data(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let mut rlp = RlpStream::new(); rlp.append(&hash.clone()); return Some(rlp.out()); } None } fn block_receipts(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let receipt = BlockReceipts::new(vec![Receipt::new( H256::zero(), U256::zero(), vec![])]); let mut rlp = RlpStream::new(); rlp.append(&receipt); return Some(rlp.out()); } None } fn import_block(&self, b: Bytes) -> Result<H256, BlockImportError> { let header = Rlp::new(&b).val_at::<BlockHeader>(0); let h = header.hash(); let number: usize = header.number() as usize; if number > self.blocks.read().len() { panic!("Unexpected block number. Expected {}, got {}", self.blocks.read().len(), number); } if number > 0 { match self.blocks.read().get(header.parent_hash()) { Some(parent) => { let parent = Rlp::new(parent).val_at::<BlockHeader>(0); if parent.number()!= (header.number() - 1) { panic!("Unexpected block parent"); } }, None => { panic!("Unknown block parent {:?} for block {}", header.parent_hash(), number); } } } let len = self.numbers.read().len(); if number == len { { let mut difficulty = self.difficulty.write(); *difficulty = *difficulty + header.difficulty().clone(); } mem::replace(&mut *self.last_hash.write(), h.clone()); self.blocks.write().insert(h.clone(), b); self.numbers.write().insert(number, h.clone()); let mut parent_hash = header.parent_hash().clone(); if number > 0 { let mut n = number - 1; while n > 0 && self.numbers.read()[&n]!= parent_hash { *self.numbers.write().get_mut(&n).unwrap() = parent_hash.clone(); n -= 1; parent_hash = Rlp::new(&self.blocks.read()[&parent_hash]).val_at::<BlockHeader>(0).parent_hash().clone(); } } } else { self.blocks.write().insert(h.clone(), b.to_vec()); } Ok(h) } fn import_block_with_receipts(&self, b: Bytes, _r: Bytes) -> Result<H256, BlockImportError> { self.import_block(b) } fn queue_info(&self) -> QueueInfo { QueueInfo { verified_queue_size: self.queue_size.load(AtomicOrder::Relaxed), unverified_queue_size: 0, verifying_queue_size: 0, max_queue_size: 0, max_mem_use: 0, mem_used: 0, } } fn clear_queue(&self) { } fn additional_params(&self) -> BTreeMap<String, String> { Default::default() } fn chain_info(&self) -> BlockChainInfo { BlockChainInfo { total_difficulty: *self.difficulty.read(), pending_total_difficulty: *self.difficulty.read(), genesis_hash: self.genesis_hash.clone(), best_block_hash: self.last_hash.read().clone(), best_block_number: self.blocks.read().len() as BlockNumber - 1, first_block_hash: self.first_block.read().as_ref().map(|x| x.0), first_block_number: self.first_block.read().as_ref().map(|x| x.1), ancient_block_hash: self.ancient_block.read().as_ref().map(|x| x.0), ancient_block_number: self.ancient_block.read().as_ref().map(|x| x.1) } } fn filter_traces(&self, _filter: TraceFilter) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn trace(&self, _trace: TraceId) -> Option<LocalizedTrace> { self.traces.read().clone().and_then(|vec| vec.into_iter().next()) } fn transaction_traces(&self, _trace: TransactionId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn block_traces(&self, _trace: BlockId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn queue_transactions(&self, transactions: Vec<Bytes>, _peer_id: usize) { // import right here let txs = transactions.into_iter().filter_map(|bytes| UntrustedRlp::new(&bytes).as_val().ok()).collect(); self.miner.import_external_transactions(self, txs); } fn queue_consensus_message(&self, message: Bytes) { self.spec.engine.handle_message(&message).unwrap(); } fn ready_transactions(&self) -> Vec<PendingTransaction> { self.miner.ready_transactions(self.chain_info().best_block_number) } fn signing_network_id(&self) -> Option<u64> { None } fn mode(&self) -> Mode { Mode::Active } fn set_mode(&self, _: Mode) { unimplemented!(); } fn disable(&self) { unimplemented!(); } fn pruning_info(&self) -> PruningInfo { let best_num = self.chain_info().best_block_number; PruningInfo { earliest_chain: 1, earliest_state: self.history.read().as_ref().map(|x| best_num - x).unwrap_or(0), } } fn call_contract(&self, _address: Address, _data: Bytes) -> Result<Bytes, String> { Ok(vec![]) } fn registrar_address(&self) -> Option<Address> { None } fn registry_address(&self, _name: String) -> Option<Address> { None } } impl ProvingBlockChainClient for TestBlockChainClient { fn prove_storage(&self, _: H256, _: H256, _: u32, _: BlockId) -> Vec<Bytes> { Vec::new() } fn prove_account(&self, _: H256, _: u32, _: BlockId) -> Vec<Bytes> {
random_line_split
test_client.rs
your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Test client. use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder}; use util::*; use rlp::*; use ethkey::{Generator, Random}; use devtools::*; use transaction::{Transaction, LocalizedTransaction, PendingTransaction, SignedTransaction, Action}; use blockchain::TreeRoute; use client::{ BlockChainClient, MiningBlockChainClient, EngineClient, BlockChainInfo, BlockStatus, BlockId, TransactionId, UncleId, TraceId, TraceFilter, LastHashes, CallAnalytics, BlockImportError, ProvingBlockChainClient, }; use db::{NUM_COLUMNS, COL_STATE}; use header::{Header as BlockHeader, BlockNumber}; use filter::Filter; use log_entry::LocalizedLogEntry; use receipt::{Receipt, LocalizedReceipt}; use blockchain::extras::BlockReceipts; use error::{ImportResult}; use evm::{Factory as EvmFactory, VMType, Schedule}; use miner::{Miner, MinerService, TransactionImportResult}; use spec::Spec; use types::mode::Mode; use types::pruning_info::PruningInfo; use verification::queue::QueueInfo; use block::{OpenBlock, SealedBlock}; use executive::Executed; use error::CallError; use trace::LocalizedTrace; use state_db::StateDB; use encoded; /// Test client. pub struct TestBlockChainClient { /// Blocks. pub blocks: RwLock<HashMap<H256, Bytes>>, /// Mapping of numbers to hashes. pub numbers: RwLock<HashMap<usize, H256>>, /// Genesis block hash. pub genesis_hash: H256, /// Last block hash. pub last_hash: RwLock<H256>, /// Extra data do set for each block pub extra_data: Bytes, /// Difficulty. pub difficulty: RwLock<U256>, /// Balances. pub balances: RwLock<HashMap<Address, U256>>, /// Nonces. pub nonces: RwLock<HashMap<Address, U256>>, /// Storage. pub storage: RwLock<HashMap<(Address, H256), H256>>, /// Code. pub code: RwLock<HashMap<Address, Bytes>>, /// Execution result. pub execution_result: RwLock<Option<Result<Executed, CallError>>>, /// Transaction receipts. pub receipts: RwLock<HashMap<TransactionId, LocalizedReceipt>>, /// Logs pub logs: RwLock<Vec<LocalizedLogEntry>>, /// Block queue size. pub queue_size: AtomicUsize, /// Miner pub miner: Arc<Miner>, /// Spec pub spec: Spec, /// VM Factory pub vm_factory: EvmFactory, /// Timestamp assigned to latest sealed block pub latest_block_timestamp: RwLock<u64>, /// Ancient block info. pub ancient_block: RwLock<Option<(H256, u64)>>, /// First block info. pub first_block: RwLock<Option<(H256, u64)>>, /// Traces to return pub traces: RwLock<Option<Vec<LocalizedTrace>>>, /// Pruning history size to report. pub history: RwLock<Option<u64>>, } /// Used for generating test client blocks. #[derive(Clone)] pub enum EachBlockWith { /// Plain block. Nothing, /// Block with an uncle. Uncle, /// Block with a transaction. Transaction, /// Block with an uncle and transaction. UncleAndTransaction } impl Default for TestBlockChainClient { fn default() -> Self { TestBlockChainClient::new() } } impl TestBlockChainClient { /// Creates new test client. pub fn new() -> Self { Self::new_with_extra_data(Bytes::new()) } /// Creates new test client with specified extra data for each block pub fn new_with_extra_data(extra_data: Bytes) -> Self { let spec = Spec::new_test(); TestBlockChainClient::new_with_spec_and_extra(spec, extra_data) } /// Create test client with custom spec. pub fn new_with_spec(spec: Spec) -> Self { TestBlockChainClient::new_with_spec_and_extra(spec, Bytes::new()) } /// Create test client with custom spec and extra data. pub fn new_with_spec_and_extra(spec: Spec, extra_data: Bytes) -> Self { let genesis_block = spec.genesis_block(); let genesis_hash = spec.genesis_header().hash(); let mut client = TestBlockChainClient { blocks: RwLock::new(HashMap::new()), numbers: RwLock::new(HashMap::new()), genesis_hash: H256::new(), extra_data: extra_data, last_hash: RwLock::new(H256::new()), difficulty: RwLock::new(spec.genesis_header().difficulty().clone()), balances: RwLock::new(HashMap::new()), nonces: RwLock::new(HashMap::new()), storage: RwLock::new(HashMap::new()), code: RwLock::new(HashMap::new()), execution_result: RwLock::new(None), receipts: RwLock::new(HashMap::new()), logs: RwLock::new(Vec::new()), queue_size: AtomicUsize::new(0), miner: Arc::new(Miner::with_spec(&spec)), spec: spec, vm_factory: EvmFactory::new(VMType::Interpreter, 1024 * 1024), latest_block_timestamp: RwLock::new(10_000_000), ancient_block: RwLock::new(None), first_block: RwLock::new(None), traces: RwLock::new(None), history: RwLock::new(None), }; // insert genesis hash. client.blocks.get_mut().insert(genesis_hash, genesis_block); client.numbers.get_mut().insert(0, genesis_hash); *client.last_hash.get_mut() = genesis_hash; client.genesis_hash = genesis_hash; client } /// Set the transaction receipt result pub fn set_transaction_receipt(&self, id: TransactionId, receipt: LocalizedReceipt) { self.receipts.write().insert(id, receipt); } /// Set the execution result. pub fn set_execution_result(&self, result: Result<Executed, CallError>) { *self.execution_result.write() = Some(result); } /// Set the balance of account `address` to `balance`. pub fn set_balance(&self, address: Address, balance: U256) { self.balances.write().insert(address, balance); } /// Set nonce of account `address` to `nonce`. pub fn set_nonce(&self, address: Address, nonce: U256) { self.nonces.write().insert(address, nonce); } /// Set `code` at `address`. pub fn set_code(&self, address: Address, code: Bytes) { self.code.write().insert(address, code); } /// Set storage `position` to `value` for account `address`. pub fn set_storage(&self, address: Address, position: H256, value: H256) { self.storage.write().insert((address, position), value); } /// Set block queue size for testing pub fn set_queue_size(&self, size: usize) { self.queue_size.store(size, AtomicOrder::Relaxed); } /// Set timestamp assigned to latest sealed block pub fn set_latest_block_timestamp(&self, ts: u64) { *self.latest_block_timestamp.write() = ts; } /// Set logs to return for each logs call. pub fn set_logs(&self, logs: Vec<LocalizedLogEntry>) { *self.logs.write() = logs; } /// Add blocks to test client. pub fn add_blocks(&self, count: usize, with: EachBlockWith) { let len = self.numbers.read().len(); for n in len..(len + count) { let mut header = BlockHeader::new(); header.set_difficulty(From::from(n)); header.set_parent_hash(self.last_hash.read().clone()); header.set_number(n as BlockNumber); header.set_gas_limit(U256::from(1_000_000)); header.set_extra_data(self.extra_data.clone()); let uncles = match with { EachBlockWith::Uncle | EachBlockWith::UncleAndTransaction => { let mut uncles = RlpStream::new_list(1); let mut uncle_header = BlockHeader::new(); uncle_header.set_difficulty(From::from(n)); uncle_header.set_parent_hash(self.last_hash.read().clone()); uncle_header.set_number(n as BlockNumber); uncles.append(&uncle_header); header.set_uncles_hash(uncles.as_raw().sha3()); uncles }, _ => RlpStream::new_list(0) }; let txs = match with { EachBlockWith::Transaction | EachBlockWith::UncleAndTransaction => { let mut txs = RlpStream::new_list(1); let keypair = Random.generate().unwrap(); // Update nonces value self.nonces.write().insert(keypair.address(), U256::one()); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(200_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); txs.append(&signed_tx); txs.out() }, _ => ::rlp::EMPTY_LIST_RLP.to_vec() }; let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&txs, 1); rlp.append_raw(uncles.as_raw(), 1); self.import_block(rlp.as_raw().to_vec()).unwrap(); } } /// Make a bad block by setting invalid extra data. pub fn corrupt_block(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_extra_data(b"This extra data is way too long to be considered valid".to_vec()); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// Make a bad block by setting invalid parent hash. pub fn corrupt_block_parent(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_parent_hash(H256::from(42)); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// TODO: pub fn block_hash_delta_minus(&mut self, delta: usize) -> H256 { let blocks_read = self.numbers.read(); let index = blocks_read.len() - delta; blocks_read[&index].clone() } fn block_hash(&self, id: BlockId) -> Option<H256> { match id { BlockId::Hash(hash) => Some(hash), BlockId::Number(n) => self.numbers.read().get(&(n as usize)).cloned(), BlockId::Earliest => self.numbers.read().get(&0).cloned(), BlockId::Latest | BlockId::Pending => self.numbers.read().get(&(self.numbers.read().len() - 1)).cloned() } } /// Inserts a transaction to miners transactions queue. pub fn insert_transaction_to_queue(&self) { let keypair = Random.generate().unwrap(); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(20_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); self.set_balance(signed_tx.sender(), U256::from(10_000_000_000_000_000_000u64)); let res = self.miner.import_external_transactions(self, vec![signed_tx.into()]); let res = res.into_iter().next().unwrap().expect("Successful import"); assert_eq!(res, TransactionImportResult::Current); } /// Set reported history size. pub fn set_history(&self, h: Option<u64>) { *self.history.write() = h; } } pub fn get_temp_state_db() -> GuardedTempResult<StateDB> { let temp = RandomTempPath::new(); let db = Database::open(&DatabaseConfig::with_columns(NUM_COLUMNS), temp.as_str()).unwrap(); let journal_db = journaldb::new(Arc::new(db), journaldb::Algorithm::EarlyMerge, COL_STATE); let state_db = StateDB::new(journal_db, 1024 * 1024); GuardedTempResult { _temp: temp, result: Some(state_db) } } impl MiningBlockChainClient for TestBlockChainClient { fn latest_schedule(&self) -> Schedule { Schedule::new_post_eip150(24576, true, true, true) } fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { let engine = &*self.spec.engine; let genesis_header = self.spec.genesis_header(); let mut db_result = get_temp_state_db(); let db = self.spec.ensure_db_good(db_result.take(), &Default::default()).unwrap(); let last_hashes = vec![genesis_header.hash()]; let mut open_block = OpenBlock::new( engine, Default::default(), false, db, &genesis_header, Arc::new(last_hashes), author, gas_range_target, extra_data ).expect("Opening block for tests will not fail."); // TODO [todr] Override timestamp for predictability (set_timestamp_now kind of sucks) open_block.set_timestamp(*self.latest_block_timestamp.read()); open_block } fn vm_factory(&self) -> &EvmFactory { &self.vm_factory } fn import_sealed_block(&self, _block: SealedBlock) -> ImportResult { Ok(H256::default()) } fn broadcast_proposal_block(&self, _block: SealedBlock) {} } impl BlockChainClient for TestBlockChainClient { fn call(&self, _t: &SignedTransaction, _block: BlockId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn estimate_gas(&self, _t: &SignedTransaction, _block: BlockId) -> Result<U256, CallError> { Ok(21000.into()) } fn replay(&self, _id: TransactionId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> { Some(U256::zero()) } fn block_hash(&self, id: BlockId) -> Option<H256> { Self::block_hash(self, id) } fn nonce(&self, address: &Address, id: BlockId) -> Option<U256> { match id { BlockId::Latest => Some(self.nonces.read().get(address).cloned().unwrap_or(self.spec.params.account_start_nonce)), _ => None, } } fn storage_root(&self, _address: &Address, _id: BlockId) -> Option<H256> { None } fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockId::Latest).unwrap() } fn code(&self, address: &Address, id: BlockId) -> Option<Option<Bytes>> { match id { BlockId::Latest => Some(self.code.read().get(address).cloned()), _ => None, } } fn balance(&self, address: &Address, id: BlockId) -> Option<U256> { if let BlockId::Latest = id { Some(self.balances.read().get(address).cloned().unwrap_or_else(U256::zero)) } else { None } } fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockId::Latest).unwrap() } fn storage_at(&self, address: &Address, position: &H256, id: BlockId) -> Option<H256> { if let BlockId::Latest = id { Some(self.storage.read().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)) } else { None } } fn list_accounts(&self, _id: BlockId, _after: Option<&Address>, _count: u64) -> Option<Vec<Address>> { None } fn list_storage(&self, _id: BlockId, _account: &Address, _after: Option<&H256>, _count: u64) -> Option<Vec<H256>> { None } fn transaction(&self, _id: TransactionId) -> Option<LocalizedTransaction> { None // Simple default. } fn transaction_block(&self, _id: TransactionId) -> Option<H256> { None // Simple default. } fn uncle(&self, _id: UncleId) -> Option<encoded::Header> { None // Simple default. } fn uncle_extra_info(&self, _id: UncleId) -> Option<BTreeMap<String, String>> { None } fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> { self.receipts.read().get(&id).cloned() } fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockId, _to_block: BlockId) -> Option<Vec<BlockNumber>> { unimplemented!(); } fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry> { let mut logs = self.logs.read().clone(); let len = logs.len(); match filter.limit { Some(limit) if limit <= len => logs.split_off(len - limit), _ => logs, } } fn last_hashes(&self) -> LastHashes { unimplemented!(); } fn best_block_header(&self) -> encoded::Header { self.block_header(BlockId::Hash(self.chain_info().best_block_hash)) .expect("Best block always has header.") } fn block_header(&self, id: BlockId) -> Option<encoded::Header> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec())) .map(encoded::Header::new) } fn block_number(&self, _id: BlockId) -> Option<BlockNumber> { unimplemented!() } fn block_body(&self, id: BlockId) -> Option<encoded::Body> { self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).map(|r| { let mut stream = RlpStream::new_list(2); stream.append_raw(Rlp::new(r).at(1).as_raw(), 1); stream.append_raw(Rlp::new(r).at(2).as_raw(), 1); encoded::Body::new(stream.out()) })) } fn
(&self, id: BlockId) -> Option<encoded::Block> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).cloned()) .map(encoded::Block::new) } fn block_extra_info(&self, id: BlockId) -> Option<BTreeMap<String, String>> { self.block(id) .map(|block| block.view().header()) .map(|header| self.spec.engine.extra_info(&header)) } fn block_status(&self, id: BlockId) -> BlockStatus { match id { BlockId::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain, BlockId::Hash(ref hash) if self.blocks.read().get(hash).is_some() => BlockStatus::InChain, BlockId::Latest | BlockId::Pending | BlockId::Earliest => BlockStatus::InChain, _ => BlockStatus::Unknown, } } // works only if blocks are one after another 1 -> 2 -> 3 fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> { Some(TreeRoute { ancestor: H256::new(), index: 0, blocks: { let numbers_read = self.numbers.read(); let mut adding = false; let mut blocks = Vec::new(); for (_, hash) in numbers_read.iter().sort_by(|tuple1, tuple2| tuple1.0.cmp(tuple2.0)) { if hash == to { if adding { blocks.push(hash.clone()); } adding = false; break; } if hash == from { adding = true; } if adding { blocks.push(hash.clone()); } } if adding { Vec::new() } else { blocks } } }) } fn find_uncles(&self, _hash: &H256) -> Option<Vec<H256>> { None } // TODO: returns just hashes instead of node state rlp(?) fn state_data(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let mut rlp = RlpStream::new(); rlp.append(&hash.clone()); return Some(rlp.out()); } None } fn block_receipts(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let receipt = BlockReceipts::new(vec![Receipt::new( H256::zero(), U256::zero(), vec![])]); let mut rlp = RlpStream::new(); rlp.append(&receipt); return Some(rlp.out()); } None } fn import_block(&self, b: Bytes) -> Result<H256, BlockImportError> { let header = Rlp::new(&b).val_at::<BlockHeader>(0); let h = header.hash(); let number: usize = header.number() as usize; if number > self.blocks.read().len() { panic!("Unexpected block number. Expected {}, got {}", self.blocks.read().len(), number); } if number > 0 { match self.blocks.read().get(header.parent_hash()) { Some(parent) => { let parent = Rlp::new(parent).val_at::<BlockHeader>(0); if parent.number()!= (header.number() - 1) { panic!("Unexpected block parent"); } }, None => { panic!("Unknown block parent {:?} for block {}", header.parent_hash(), number); } } } let len = self.numbers.read().len(); if number == len { { let mut difficulty = self.difficulty.write(); *difficulty = *difficulty + header.difficulty().clone(); } mem::replace(&mut *self.last_hash.write(), h.clone()); self.blocks.write().insert(h.clone(), b); self.numbers.write().insert(number, h.clone()); let mut parent_hash = header.parent_hash().clone(); if number > 0 { let mut n = number - 1; while n > 0 && self.numbers.read()[&n]!= parent_hash { *self.numbers.write().get_mut(&n).unwrap() = parent_hash.clone(); n -= 1; parent_hash = Rlp::new(&self.blocks.read()[&parent_hash]).val_at::<BlockHeader>(0).parent_hash().clone(); } } } else { self.blocks.write().insert(h.clone(), b.to_vec()); } Ok(h) } fn import_block_with_receipts(&self, b: Bytes, _r: Bytes) -> Result<H256, BlockImportError> { self.import_block(b) } fn queue_info(&self) -> QueueInfo { QueueInfo { verified_queue_size: self.queue_size.load(AtomicOrder::Relaxed), unverified_queue_size: 0, verifying_queue_size: 0, max_queue_size: 0, max_mem_use: 0, mem_used: 0, } } fn clear_queue(&self) { } fn additional_params(&self) -> BTreeMap<String, String> { Default::default() } fn chain_info(&self) -> BlockChainInfo { BlockChainInfo { total_difficulty: *self.difficulty.read(), pending_total_difficulty: *self.difficulty.read(), genesis_hash: self.genesis_hash.clone(), best_block_hash: self.last_hash.read().clone(), best_block_number: self.blocks.read().len() as BlockNumber - 1, first_block_hash: self.first_block.read().as_ref().map(|x| x.0), first_block_number: self.first_block.read().as_ref().map(|x| x.1), ancient_block_hash: self.ancient_block.read().as_ref().map(|x| x.0), ancient_block_number: self.ancient_block.read().as_ref().map(|x| x.1) } } fn filter_traces(&self, _filter: TraceFilter) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn trace(&self, _trace: TraceId) -> Option<LocalizedTrace> { self.traces.read().clone().and_then(|vec| vec.into_iter().next()) } fn transaction_traces(&self, _trace: TransactionId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn block_traces(&self, _trace: BlockId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn queue_transactions(&self, transactions: Vec<Bytes>, _peer_id: usize) { // import right here let txs = transactions.into_iter().filter_map(|bytes| UntrustedRlp::new(&bytes).as_val().ok()).collect(); self.miner.import_external_transactions(self, txs); } fn queue_consensus_message(&self, message: Bytes) { self.spec.engine.handle_message(&message).unwrap(); } fn ready_transactions(&self) -> Vec<PendingTransaction> { self.miner.ready_transactions(self.chain_info().best_block_number) } fn signing_network_id(&self) -> Option<u64> { None } fn mode(&self) -> Mode { Mode::Active } fn set_mode(&self, _: Mode) { unimplemented!(); } fn disable(&self) { unimplemented!(); } fn pruning_info(&self) -> PruningInfo { let best_num = self.chain_info().best_block_number; PruningInfo { earliest_chain: 1, earliest_state: self.history.read().as_ref().map(|x| best_num - x).unwrap_or(0), } } fn call_contract(&self, _address: Address, _data: Bytes) -> Result<Bytes, String> { Ok(vec![]) } fn registrar_address(&self) -> Option<Address> { None } fn registry_address(&self, _name: String) -> Option<Address> { None } } impl ProvingBlockChainClient for TestBlockChainClient { fn prove_storage(&self, _: H256, _: H256, _: u32, _: BlockId) -> Vec<Bytes> { Vec::new() } fn prove_account(&self, _: H256, _: u32, _: BlockId) -> Vec<Bytes> {
block
identifier_name
test_client.rs
your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Test client. use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder}; use util::*; use rlp::*; use ethkey::{Generator, Random}; use devtools::*; use transaction::{Transaction, LocalizedTransaction, PendingTransaction, SignedTransaction, Action}; use blockchain::TreeRoute; use client::{ BlockChainClient, MiningBlockChainClient, EngineClient, BlockChainInfo, BlockStatus, BlockId, TransactionId, UncleId, TraceId, TraceFilter, LastHashes, CallAnalytics, BlockImportError, ProvingBlockChainClient, }; use db::{NUM_COLUMNS, COL_STATE}; use header::{Header as BlockHeader, BlockNumber}; use filter::Filter; use log_entry::LocalizedLogEntry; use receipt::{Receipt, LocalizedReceipt}; use blockchain::extras::BlockReceipts; use error::{ImportResult}; use evm::{Factory as EvmFactory, VMType, Schedule}; use miner::{Miner, MinerService, TransactionImportResult}; use spec::Spec; use types::mode::Mode; use types::pruning_info::PruningInfo; use verification::queue::QueueInfo; use block::{OpenBlock, SealedBlock}; use executive::Executed; use error::CallError; use trace::LocalizedTrace; use state_db::StateDB; use encoded; /// Test client. pub struct TestBlockChainClient { /// Blocks. pub blocks: RwLock<HashMap<H256, Bytes>>, /// Mapping of numbers to hashes. pub numbers: RwLock<HashMap<usize, H256>>, /// Genesis block hash. pub genesis_hash: H256, /// Last block hash. pub last_hash: RwLock<H256>, /// Extra data do set for each block pub extra_data: Bytes, /// Difficulty. pub difficulty: RwLock<U256>, /// Balances. pub balances: RwLock<HashMap<Address, U256>>, /// Nonces. pub nonces: RwLock<HashMap<Address, U256>>, /// Storage. pub storage: RwLock<HashMap<(Address, H256), H256>>, /// Code. pub code: RwLock<HashMap<Address, Bytes>>, /// Execution result. pub execution_result: RwLock<Option<Result<Executed, CallError>>>, /// Transaction receipts. pub receipts: RwLock<HashMap<TransactionId, LocalizedReceipt>>, /// Logs pub logs: RwLock<Vec<LocalizedLogEntry>>, /// Block queue size. pub queue_size: AtomicUsize, /// Miner pub miner: Arc<Miner>, /// Spec pub spec: Spec, /// VM Factory pub vm_factory: EvmFactory, /// Timestamp assigned to latest sealed block pub latest_block_timestamp: RwLock<u64>, /// Ancient block info. pub ancient_block: RwLock<Option<(H256, u64)>>, /// First block info. pub first_block: RwLock<Option<(H256, u64)>>, /// Traces to return pub traces: RwLock<Option<Vec<LocalizedTrace>>>, /// Pruning history size to report. pub history: RwLock<Option<u64>>, } /// Used for generating test client blocks. #[derive(Clone)] pub enum EachBlockWith { /// Plain block. Nothing, /// Block with an uncle. Uncle, /// Block with a transaction. Transaction, /// Block with an uncle and transaction. UncleAndTransaction } impl Default for TestBlockChainClient { fn default() -> Self { TestBlockChainClient::new() } } impl TestBlockChainClient { /// Creates new test client. pub fn new() -> Self { Self::new_with_extra_data(Bytes::new()) } /// Creates new test client with specified extra data for each block pub fn new_with_extra_data(extra_data: Bytes) -> Self { let spec = Spec::new_test(); TestBlockChainClient::new_with_spec_and_extra(spec, extra_data) } /// Create test client with custom spec. pub fn new_with_spec(spec: Spec) -> Self { TestBlockChainClient::new_with_spec_and_extra(spec, Bytes::new()) } /// Create test client with custom spec and extra data. pub fn new_with_spec_and_extra(spec: Spec, extra_data: Bytes) -> Self { let genesis_block = spec.genesis_block(); let genesis_hash = spec.genesis_header().hash(); let mut client = TestBlockChainClient { blocks: RwLock::new(HashMap::new()), numbers: RwLock::new(HashMap::new()), genesis_hash: H256::new(), extra_data: extra_data, last_hash: RwLock::new(H256::new()), difficulty: RwLock::new(spec.genesis_header().difficulty().clone()), balances: RwLock::new(HashMap::new()), nonces: RwLock::new(HashMap::new()), storage: RwLock::new(HashMap::new()), code: RwLock::new(HashMap::new()), execution_result: RwLock::new(None), receipts: RwLock::new(HashMap::new()), logs: RwLock::new(Vec::new()), queue_size: AtomicUsize::new(0), miner: Arc::new(Miner::with_spec(&spec)), spec: spec, vm_factory: EvmFactory::new(VMType::Interpreter, 1024 * 1024), latest_block_timestamp: RwLock::new(10_000_000), ancient_block: RwLock::new(None), first_block: RwLock::new(None), traces: RwLock::new(None), history: RwLock::new(None), }; // insert genesis hash. client.blocks.get_mut().insert(genesis_hash, genesis_block); client.numbers.get_mut().insert(0, genesis_hash); *client.last_hash.get_mut() = genesis_hash; client.genesis_hash = genesis_hash; client } /// Set the transaction receipt result pub fn set_transaction_receipt(&self, id: TransactionId, receipt: LocalizedReceipt) { self.receipts.write().insert(id, receipt); } /// Set the execution result. pub fn set_execution_result(&self, result: Result<Executed, CallError>) { *self.execution_result.write() = Some(result); } /// Set the balance of account `address` to `balance`. pub fn set_balance(&self, address: Address, balance: U256) { self.balances.write().insert(address, balance); } /// Set nonce of account `address` to `nonce`. pub fn set_nonce(&self, address: Address, nonce: U256) { self.nonces.write().insert(address, nonce); } /// Set `code` at `address`. pub fn set_code(&self, address: Address, code: Bytes) { self.code.write().insert(address, code); } /// Set storage `position` to `value` for account `address`. pub fn set_storage(&self, address: Address, position: H256, value: H256) { self.storage.write().insert((address, position), value); } /// Set block queue size for testing pub fn set_queue_size(&self, size: usize) { self.queue_size.store(size, AtomicOrder::Relaxed); } /// Set timestamp assigned to latest sealed block pub fn set_latest_block_timestamp(&self, ts: u64) { *self.latest_block_timestamp.write() = ts; } /// Set logs to return for each logs call. pub fn set_logs(&self, logs: Vec<LocalizedLogEntry>) { *self.logs.write() = logs; } /// Add blocks to test client. pub fn add_blocks(&self, count: usize, with: EachBlockWith) { let len = self.numbers.read().len(); for n in len..(len + count) { let mut header = BlockHeader::new(); header.set_difficulty(From::from(n)); header.set_parent_hash(self.last_hash.read().clone()); header.set_number(n as BlockNumber); header.set_gas_limit(U256::from(1_000_000)); header.set_extra_data(self.extra_data.clone()); let uncles = match with { EachBlockWith::Uncle | EachBlockWith::UncleAndTransaction => { let mut uncles = RlpStream::new_list(1); let mut uncle_header = BlockHeader::new(); uncle_header.set_difficulty(From::from(n)); uncle_header.set_parent_hash(self.last_hash.read().clone()); uncle_header.set_number(n as BlockNumber); uncles.append(&uncle_header); header.set_uncles_hash(uncles.as_raw().sha3()); uncles }, _ => RlpStream::new_list(0) }; let txs = match with { EachBlockWith::Transaction | EachBlockWith::UncleAndTransaction => { let mut txs = RlpStream::new_list(1); let keypair = Random.generate().unwrap(); // Update nonces value self.nonces.write().insert(keypair.address(), U256::one()); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(200_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); txs.append(&signed_tx); txs.out() }, _ => ::rlp::EMPTY_LIST_RLP.to_vec() }; let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&txs, 1); rlp.append_raw(uncles.as_raw(), 1); self.import_block(rlp.as_raw().to_vec()).unwrap(); } } /// Make a bad block by setting invalid extra data. pub fn corrupt_block(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_extra_data(b"This extra data is way too long to be considered valid".to_vec()); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// Make a bad block by setting invalid parent hash. pub fn corrupt_block_parent(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_parent_hash(H256::from(42)); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// TODO: pub fn block_hash_delta_minus(&mut self, delta: usize) -> H256 { let blocks_read = self.numbers.read(); let index = blocks_read.len() - delta; blocks_read[&index].clone() } fn block_hash(&self, id: BlockId) -> Option<H256> { match id { BlockId::Hash(hash) => Some(hash), BlockId::Number(n) => self.numbers.read().get(&(n as usize)).cloned(), BlockId::Earliest => self.numbers.read().get(&0).cloned(), BlockId::Latest | BlockId::Pending => self.numbers.read().get(&(self.numbers.read().len() - 1)).cloned() } } /// Inserts a transaction to miners transactions queue. pub fn insert_transaction_to_queue(&self) { let keypair = Random.generate().unwrap(); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(20_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); self.set_balance(signed_tx.sender(), U256::from(10_000_000_000_000_000_000u64)); let res = self.miner.import_external_transactions(self, vec![signed_tx.into()]); let res = res.into_iter().next().unwrap().expect("Successful import"); assert_eq!(res, TransactionImportResult::Current); } /// Set reported history size. pub fn set_history(&self, h: Option<u64>) { *self.history.write() = h; } } pub fn get_temp_state_db() -> GuardedTempResult<StateDB> { let temp = RandomTempPath::new(); let db = Database::open(&DatabaseConfig::with_columns(NUM_COLUMNS), temp.as_str()).unwrap(); let journal_db = journaldb::new(Arc::new(db), journaldb::Algorithm::EarlyMerge, COL_STATE); let state_db = StateDB::new(journal_db, 1024 * 1024); GuardedTempResult { _temp: temp, result: Some(state_db) } } impl MiningBlockChainClient for TestBlockChainClient { fn latest_schedule(&self) -> Schedule { Schedule::new_post_eip150(24576, true, true, true) } fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { let engine = &*self.spec.engine; let genesis_header = self.spec.genesis_header(); let mut db_result = get_temp_state_db(); let db = self.spec.ensure_db_good(db_result.take(), &Default::default()).unwrap(); let last_hashes = vec![genesis_header.hash()]; let mut open_block = OpenBlock::new( engine, Default::default(), false, db, &genesis_header, Arc::new(last_hashes), author, gas_range_target, extra_data ).expect("Opening block for tests will not fail."); // TODO [todr] Override timestamp for predictability (set_timestamp_now kind of sucks) open_block.set_timestamp(*self.latest_block_timestamp.read()); open_block } fn vm_factory(&self) -> &EvmFactory { &self.vm_factory } fn import_sealed_block(&self, _block: SealedBlock) -> ImportResult { Ok(H256::default()) } fn broadcast_proposal_block(&self, _block: SealedBlock) {} } impl BlockChainClient for TestBlockChainClient { fn call(&self, _t: &SignedTransaction, _block: BlockId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn estimate_gas(&self, _t: &SignedTransaction, _block: BlockId) -> Result<U256, CallError> { Ok(21000.into()) } fn replay(&self, _id: TransactionId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> { Some(U256::zero()) } fn block_hash(&self, id: BlockId) -> Option<H256> { Self::block_hash(self, id) } fn nonce(&self, address: &Address, id: BlockId) -> Option<U256> { match id { BlockId::Latest => Some(self.nonces.read().get(address).cloned().unwrap_or(self.spec.params.account_start_nonce)), _ => None, } } fn storage_root(&self, _address: &Address, _id: BlockId) -> Option<H256> { None } fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockId::Latest).unwrap() } fn code(&self, address: &Address, id: BlockId) -> Option<Option<Bytes>> { match id { BlockId::Latest => Some(self.code.read().get(address).cloned()), _ => None, } } fn balance(&self, address: &Address, id: BlockId) -> Option<U256> { if let BlockId::Latest = id { Some(self.balances.read().get(address).cloned().unwrap_or_else(U256::zero)) } else { None } } fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockId::Latest).unwrap() } fn storage_at(&self, address: &Address, position: &H256, id: BlockId) -> Option<H256> { if let BlockId::Latest = id { Some(self.storage.read().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)) } else { None } } fn list_accounts(&self, _id: BlockId, _after: Option<&Address>, _count: u64) -> Option<Vec<Address>> { None } fn list_storage(&self, _id: BlockId, _account: &Address, _after: Option<&H256>, _count: u64) -> Option<Vec<H256>> { None } fn transaction(&self, _id: TransactionId) -> Option<LocalizedTransaction> { None // Simple default. } fn transaction_block(&self, _id: TransactionId) -> Option<H256> { None // Simple default. } fn uncle(&self, _id: UncleId) -> Option<encoded::Header> { None // Simple default. } fn uncle_extra_info(&self, _id: UncleId) -> Option<BTreeMap<String, String>> { None } fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> { self.receipts.read().get(&id).cloned() } fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockId, _to_block: BlockId) -> Option<Vec<BlockNumber>> { unimplemented!(); } fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry> { let mut logs = self.logs.read().clone(); let len = logs.len(); match filter.limit { Some(limit) if limit <= len => logs.split_off(len - limit), _ => logs, } } fn last_hashes(&self) -> LastHashes { unimplemented!(); } fn best_block_header(&self) -> encoded::Header { self.block_header(BlockId::Hash(self.chain_info().best_block_hash)) .expect("Best block always has header.") } fn block_header(&self, id: BlockId) -> Option<encoded::Header> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec())) .map(encoded::Header::new) } fn block_number(&self, _id: BlockId) -> Option<BlockNumber> { unimplemented!() } fn block_body(&self, id: BlockId) -> Option<encoded::Body> { self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).map(|r| { let mut stream = RlpStream::new_list(2); stream.append_raw(Rlp::new(r).at(1).as_raw(), 1); stream.append_raw(Rlp::new(r).at(2).as_raw(), 1); encoded::Body::new(stream.out()) })) } fn block(&self, id: BlockId) -> Option<encoded::Block> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).cloned()) .map(encoded::Block::new) } fn block_extra_info(&self, id: BlockId) -> Option<BTreeMap<String, String>> { self.block(id) .map(|block| block.view().header()) .map(|header| self.spec.engine.extra_info(&header)) } fn block_status(&self, id: BlockId) -> BlockStatus
// works only if blocks are one after another 1 -> 2 -> 3 fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> { Some(TreeRoute { ancestor: H256::new(), index: 0, blocks: { let numbers_read = self.numbers.read(); let mut adding = false; let mut blocks = Vec::new(); for (_, hash) in numbers_read.iter().sort_by(|tuple1, tuple2| tuple1.0.cmp(tuple2.0)) { if hash == to { if adding { blocks.push(hash.clone()); } adding = false; break; } if hash == from { adding = true; } if adding { blocks.push(hash.clone()); } } if adding { Vec::new() } else { blocks } } }) } fn find_uncles(&self, _hash: &H256) -> Option<Vec<H256>> { None } // TODO: returns just hashes instead of node state rlp(?) fn state_data(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let mut rlp = RlpStream::new(); rlp.append(&hash.clone()); return Some(rlp.out()); } None } fn block_receipts(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let receipt = BlockReceipts::new(vec![Receipt::new( H256::zero(), U256::zero(), vec![])]); let mut rlp = RlpStream::new(); rlp.append(&receipt); return Some(rlp.out()); } None } fn import_block(&self, b: Bytes) -> Result<H256, BlockImportError> { let header = Rlp::new(&b).val_at::<BlockHeader>(0); let h = header.hash(); let number: usize = header.number() as usize; if number > self.blocks.read().len() { panic!("Unexpected block number. Expected {}, got {}", self.blocks.read().len(), number); } if number > 0 { match self.blocks.read().get(header.parent_hash()) { Some(parent) => { let parent = Rlp::new(parent).val_at::<BlockHeader>(0); if parent.number()!= (header.number() - 1) { panic!("Unexpected block parent"); } }, None => { panic!("Unknown block parent {:?} for block {}", header.parent_hash(), number); } } } let len = self.numbers.read().len(); if number == len { { let mut difficulty = self.difficulty.write(); *difficulty = *difficulty + header.difficulty().clone(); } mem::replace(&mut *self.last_hash.write(), h.clone()); self.blocks.write().insert(h.clone(), b); self.numbers.write().insert(number, h.clone()); let mut parent_hash = header.parent_hash().clone(); if number > 0 { let mut n = number - 1; while n > 0 && self.numbers.read()[&n]!= parent_hash { *self.numbers.write().get_mut(&n).unwrap() = parent_hash.clone(); n -= 1; parent_hash = Rlp::new(&self.blocks.read()[&parent_hash]).val_at::<BlockHeader>(0).parent_hash().clone(); } } } else { self.blocks.write().insert(h.clone(), b.to_vec()); } Ok(h) } fn import_block_with_receipts(&self, b: Bytes, _r: Bytes) -> Result<H256, BlockImportError> { self.import_block(b) } fn queue_info(&self) -> QueueInfo { QueueInfo { verified_queue_size: self.queue_size.load(AtomicOrder::Relaxed), unverified_queue_size: 0, verifying_queue_size: 0, max_queue_size: 0, max_mem_use: 0, mem_used: 0, } } fn clear_queue(&self) { } fn additional_params(&self) -> BTreeMap<String, String> { Default::default() } fn chain_info(&self) -> BlockChainInfo { BlockChainInfo { total_difficulty: *self.difficulty.read(), pending_total_difficulty: *self.difficulty.read(), genesis_hash: self.genesis_hash.clone(), best_block_hash: self.last_hash.read().clone(), best_block_number: self.blocks.read().len() as BlockNumber - 1, first_block_hash: self.first_block.read().as_ref().map(|x| x.0), first_block_number: self.first_block.read().as_ref().map(|x| x.1), ancient_block_hash: self.ancient_block.read().as_ref().map(|x| x.0), ancient_block_number: self.ancient_block.read().as_ref().map(|x| x.1) } } fn filter_traces(&self, _filter: TraceFilter) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn trace(&self, _trace: TraceId) -> Option<LocalizedTrace> { self.traces.read().clone().and_then(|vec| vec.into_iter().next()) } fn transaction_traces(&self, _trace: TransactionId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn block_traces(&self, _trace: BlockId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn queue_transactions(&self, transactions: Vec<Bytes>, _peer_id: usize) { // import right here let txs = transactions.into_iter().filter_map(|bytes| UntrustedRlp::new(&bytes).as_val().ok()).collect(); self.miner.import_external_transactions(self, txs); } fn queue_consensus_message(&self, message: Bytes) { self.spec.engine.handle_message(&message).unwrap(); } fn ready_transactions(&self) -> Vec<PendingTransaction> { self.miner.ready_transactions(self.chain_info().best_block_number) } fn signing_network_id(&self) -> Option<u64> { None } fn mode(&self) -> Mode { Mode::Active } fn set_mode(&self, _: Mode) { unimplemented!(); } fn disable(&self) { unimplemented!(); } fn pruning_info(&self) -> PruningInfo { let best_num = self.chain_info().best_block_number; PruningInfo { earliest_chain: 1, earliest_state: self.history.read().as_ref().map(|x| best_num - x).unwrap_or(0), } } fn call_contract(&self, _address: Address, _data: Bytes) -> Result<Bytes, String> { Ok(vec![]) } fn registrar_address(&self) -> Option<Address> { None } fn registry_address(&self, _name: String) -> Option<Address> { None } } impl ProvingBlockChainClient for TestBlockChainClient { fn prove_storage(&self, _: H256, _: H256, _: u32, _: BlockId) -> Vec<Bytes> { Vec::new() } fn prove_account(&self, _: H256, _: u32, _: BlockId) -> Vec<Bytes> {
{ match id { BlockId::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain, BlockId::Hash(ref hash) if self.blocks.read().get(hash).is_some() => BlockStatus::InChain, BlockId::Latest | BlockId::Pending | BlockId::Earliest => BlockStatus::InChain, _ => BlockStatus::Unknown, } }
identifier_body
test_client.rs
your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Test client. use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder}; use util::*; use rlp::*; use ethkey::{Generator, Random}; use devtools::*; use transaction::{Transaction, LocalizedTransaction, PendingTransaction, SignedTransaction, Action}; use blockchain::TreeRoute; use client::{ BlockChainClient, MiningBlockChainClient, EngineClient, BlockChainInfo, BlockStatus, BlockId, TransactionId, UncleId, TraceId, TraceFilter, LastHashes, CallAnalytics, BlockImportError, ProvingBlockChainClient, }; use db::{NUM_COLUMNS, COL_STATE}; use header::{Header as BlockHeader, BlockNumber}; use filter::Filter; use log_entry::LocalizedLogEntry; use receipt::{Receipt, LocalizedReceipt}; use blockchain::extras::BlockReceipts; use error::{ImportResult}; use evm::{Factory as EvmFactory, VMType, Schedule}; use miner::{Miner, MinerService, TransactionImportResult}; use spec::Spec; use types::mode::Mode; use types::pruning_info::PruningInfo; use verification::queue::QueueInfo; use block::{OpenBlock, SealedBlock}; use executive::Executed; use error::CallError; use trace::LocalizedTrace; use state_db::StateDB; use encoded; /// Test client. pub struct TestBlockChainClient { /// Blocks. pub blocks: RwLock<HashMap<H256, Bytes>>, /// Mapping of numbers to hashes. pub numbers: RwLock<HashMap<usize, H256>>, /// Genesis block hash. pub genesis_hash: H256, /// Last block hash. pub last_hash: RwLock<H256>, /// Extra data do set for each block pub extra_data: Bytes, /// Difficulty. pub difficulty: RwLock<U256>, /// Balances. pub balances: RwLock<HashMap<Address, U256>>, /// Nonces. pub nonces: RwLock<HashMap<Address, U256>>, /// Storage. pub storage: RwLock<HashMap<(Address, H256), H256>>, /// Code. pub code: RwLock<HashMap<Address, Bytes>>, /// Execution result. pub execution_result: RwLock<Option<Result<Executed, CallError>>>, /// Transaction receipts. pub receipts: RwLock<HashMap<TransactionId, LocalizedReceipt>>, /// Logs pub logs: RwLock<Vec<LocalizedLogEntry>>, /// Block queue size. pub queue_size: AtomicUsize, /// Miner pub miner: Arc<Miner>, /// Spec pub spec: Spec, /// VM Factory pub vm_factory: EvmFactory, /// Timestamp assigned to latest sealed block pub latest_block_timestamp: RwLock<u64>, /// Ancient block info. pub ancient_block: RwLock<Option<(H256, u64)>>, /// First block info. pub first_block: RwLock<Option<(H256, u64)>>, /// Traces to return pub traces: RwLock<Option<Vec<LocalizedTrace>>>, /// Pruning history size to report. pub history: RwLock<Option<u64>>, } /// Used for generating test client blocks. #[derive(Clone)] pub enum EachBlockWith { /// Plain block. Nothing, /// Block with an uncle. Uncle, /// Block with a transaction. Transaction, /// Block with an uncle and transaction. UncleAndTransaction } impl Default for TestBlockChainClient { fn default() -> Self { TestBlockChainClient::new() } } impl TestBlockChainClient { /// Creates new test client. pub fn new() -> Self { Self::new_with_extra_data(Bytes::new()) } /// Creates new test client with specified extra data for each block pub fn new_with_extra_data(extra_data: Bytes) -> Self { let spec = Spec::new_test(); TestBlockChainClient::new_with_spec_and_extra(spec, extra_data) } /// Create test client with custom spec. pub fn new_with_spec(spec: Spec) -> Self { TestBlockChainClient::new_with_spec_and_extra(spec, Bytes::new()) } /// Create test client with custom spec and extra data. pub fn new_with_spec_and_extra(spec: Spec, extra_data: Bytes) -> Self { let genesis_block = spec.genesis_block(); let genesis_hash = spec.genesis_header().hash(); let mut client = TestBlockChainClient { blocks: RwLock::new(HashMap::new()), numbers: RwLock::new(HashMap::new()), genesis_hash: H256::new(), extra_data: extra_data, last_hash: RwLock::new(H256::new()), difficulty: RwLock::new(spec.genesis_header().difficulty().clone()), balances: RwLock::new(HashMap::new()), nonces: RwLock::new(HashMap::new()), storage: RwLock::new(HashMap::new()), code: RwLock::new(HashMap::new()), execution_result: RwLock::new(None), receipts: RwLock::new(HashMap::new()), logs: RwLock::new(Vec::new()), queue_size: AtomicUsize::new(0), miner: Arc::new(Miner::with_spec(&spec)), spec: spec, vm_factory: EvmFactory::new(VMType::Interpreter, 1024 * 1024), latest_block_timestamp: RwLock::new(10_000_000), ancient_block: RwLock::new(None), first_block: RwLock::new(None), traces: RwLock::new(None), history: RwLock::new(None), }; // insert genesis hash. client.blocks.get_mut().insert(genesis_hash, genesis_block); client.numbers.get_mut().insert(0, genesis_hash); *client.last_hash.get_mut() = genesis_hash; client.genesis_hash = genesis_hash; client } /// Set the transaction receipt result pub fn set_transaction_receipt(&self, id: TransactionId, receipt: LocalizedReceipt) { self.receipts.write().insert(id, receipt); } /// Set the execution result. pub fn set_execution_result(&self, result: Result<Executed, CallError>) { *self.execution_result.write() = Some(result); } /// Set the balance of account `address` to `balance`. pub fn set_balance(&self, address: Address, balance: U256) { self.balances.write().insert(address, balance); } /// Set nonce of account `address` to `nonce`. pub fn set_nonce(&self, address: Address, nonce: U256) { self.nonces.write().insert(address, nonce); } /// Set `code` at `address`. pub fn set_code(&self, address: Address, code: Bytes) { self.code.write().insert(address, code); } /// Set storage `position` to `value` for account `address`. pub fn set_storage(&self, address: Address, position: H256, value: H256) { self.storage.write().insert((address, position), value); } /// Set block queue size for testing pub fn set_queue_size(&self, size: usize) { self.queue_size.store(size, AtomicOrder::Relaxed); } /// Set timestamp assigned to latest sealed block pub fn set_latest_block_timestamp(&self, ts: u64) { *self.latest_block_timestamp.write() = ts; } /// Set logs to return for each logs call. pub fn set_logs(&self, logs: Vec<LocalizedLogEntry>) { *self.logs.write() = logs; } /// Add blocks to test client. pub fn add_blocks(&self, count: usize, with: EachBlockWith) { let len = self.numbers.read().len(); for n in len..(len + count) { let mut header = BlockHeader::new(); header.set_difficulty(From::from(n)); header.set_parent_hash(self.last_hash.read().clone()); header.set_number(n as BlockNumber); header.set_gas_limit(U256::from(1_000_000)); header.set_extra_data(self.extra_data.clone()); let uncles = match with { EachBlockWith::Uncle | EachBlockWith::UncleAndTransaction => { let mut uncles = RlpStream::new_list(1); let mut uncle_header = BlockHeader::new(); uncle_header.set_difficulty(From::from(n)); uncle_header.set_parent_hash(self.last_hash.read().clone()); uncle_header.set_number(n as BlockNumber); uncles.append(&uncle_header); header.set_uncles_hash(uncles.as_raw().sha3()); uncles }, _ => RlpStream::new_list(0) }; let txs = match with { EachBlockWith::Transaction | EachBlockWith::UncleAndTransaction => { let mut txs = RlpStream::new_list(1); let keypair = Random.generate().unwrap(); // Update nonces value self.nonces.write().insert(keypair.address(), U256::one()); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(200_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); txs.append(&signed_tx); txs.out() }, _ => ::rlp::EMPTY_LIST_RLP.to_vec() }; let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&txs, 1); rlp.append_raw(uncles.as_raw(), 1); self.import_block(rlp.as_raw().to_vec()).unwrap(); } } /// Make a bad block by setting invalid extra data. pub fn corrupt_block(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_extra_data(b"This extra data is way too long to be considered valid".to_vec()); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// Make a bad block by setting invalid parent hash. pub fn corrupt_block_parent(&self, n: BlockNumber) { let hash = self.block_hash(BlockId::Number(n)).unwrap(); let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode(); header.set_parent_hash(H256::from(42)); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); rlp.append_raw(&::rlp::NULL_RLP, 1); self.blocks.write().insert(hash, rlp.out()); } /// TODO: pub fn block_hash_delta_minus(&mut self, delta: usize) -> H256 { let blocks_read = self.numbers.read(); let index = blocks_read.len() - delta; blocks_read[&index].clone() } fn block_hash(&self, id: BlockId) -> Option<H256> { match id { BlockId::Hash(hash) => Some(hash), BlockId::Number(n) => self.numbers.read().get(&(n as usize)).cloned(), BlockId::Earliest => self.numbers.read().get(&0).cloned(), BlockId::Latest | BlockId::Pending => self.numbers.read().get(&(self.numbers.read().len() - 1)).cloned() } } /// Inserts a transaction to miners transactions queue. pub fn insert_transaction_to_queue(&self) { let keypair = Random.generate().unwrap(); let tx = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), gas: U256::from(100_000), gas_price: U256::from(20_000_000_000u64), nonce: U256::zero() }; let signed_tx = tx.sign(keypair.secret(), None); self.set_balance(signed_tx.sender(), U256::from(10_000_000_000_000_000_000u64)); let res = self.miner.import_external_transactions(self, vec![signed_tx.into()]); let res = res.into_iter().next().unwrap().expect("Successful import"); assert_eq!(res, TransactionImportResult::Current); } /// Set reported history size. pub fn set_history(&self, h: Option<u64>) { *self.history.write() = h; } } pub fn get_temp_state_db() -> GuardedTempResult<StateDB> { let temp = RandomTempPath::new(); let db = Database::open(&DatabaseConfig::with_columns(NUM_COLUMNS), temp.as_str()).unwrap(); let journal_db = journaldb::new(Arc::new(db), journaldb::Algorithm::EarlyMerge, COL_STATE); let state_db = StateDB::new(journal_db, 1024 * 1024); GuardedTempResult { _temp: temp, result: Some(state_db) } } impl MiningBlockChainClient for TestBlockChainClient { fn latest_schedule(&self) -> Schedule { Schedule::new_post_eip150(24576, true, true, true) } fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { let engine = &*self.spec.engine; let genesis_header = self.spec.genesis_header(); let mut db_result = get_temp_state_db(); let db = self.spec.ensure_db_good(db_result.take(), &Default::default()).unwrap(); let last_hashes = vec![genesis_header.hash()]; let mut open_block = OpenBlock::new( engine, Default::default(), false, db, &genesis_header, Arc::new(last_hashes), author, gas_range_target, extra_data ).expect("Opening block for tests will not fail."); // TODO [todr] Override timestamp for predictability (set_timestamp_now kind of sucks) open_block.set_timestamp(*self.latest_block_timestamp.read()); open_block } fn vm_factory(&self) -> &EvmFactory { &self.vm_factory } fn import_sealed_block(&self, _block: SealedBlock) -> ImportResult { Ok(H256::default()) } fn broadcast_proposal_block(&self, _block: SealedBlock) {} } impl BlockChainClient for TestBlockChainClient { fn call(&self, _t: &SignedTransaction, _block: BlockId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn estimate_gas(&self, _t: &SignedTransaction, _block: BlockId) -> Result<U256, CallError> { Ok(21000.into()) } fn replay(&self, _id: TransactionId, _analytics: CallAnalytics) -> Result<Executed, CallError> { self.execution_result.read().clone().unwrap() } fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> { Some(U256::zero()) } fn block_hash(&self, id: BlockId) -> Option<H256> { Self::block_hash(self, id) } fn nonce(&self, address: &Address, id: BlockId) -> Option<U256> { match id { BlockId::Latest => Some(self.nonces.read().get(address).cloned().unwrap_or(self.spec.params.account_start_nonce)), _ => None, } } fn storage_root(&self, _address: &Address, _id: BlockId) -> Option<H256> { None } fn latest_nonce(&self, address: &Address) -> U256 { self.nonce(address, BlockId::Latest).unwrap() } fn code(&self, address: &Address, id: BlockId) -> Option<Option<Bytes>> { match id { BlockId::Latest => Some(self.code.read().get(address).cloned()), _ => None, } } fn balance(&self, address: &Address, id: BlockId) -> Option<U256> { if let BlockId::Latest = id
else { None } } fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockId::Latest).unwrap() } fn storage_at(&self, address: &Address, position: &H256, id: BlockId) -> Option<H256> { if let BlockId::Latest = id { Some(self.storage.read().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)) } else { None } } fn list_accounts(&self, _id: BlockId, _after: Option<&Address>, _count: u64) -> Option<Vec<Address>> { None } fn list_storage(&self, _id: BlockId, _account: &Address, _after: Option<&H256>, _count: u64) -> Option<Vec<H256>> { None } fn transaction(&self, _id: TransactionId) -> Option<LocalizedTransaction> { None // Simple default. } fn transaction_block(&self, _id: TransactionId) -> Option<H256> { None // Simple default. } fn uncle(&self, _id: UncleId) -> Option<encoded::Header> { None // Simple default. } fn uncle_extra_info(&self, _id: UncleId) -> Option<BTreeMap<String, String>> { None } fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> { self.receipts.read().get(&id).cloned() } fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockId, _to_block: BlockId) -> Option<Vec<BlockNumber>> { unimplemented!(); } fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry> { let mut logs = self.logs.read().clone(); let len = logs.len(); match filter.limit { Some(limit) if limit <= len => logs.split_off(len - limit), _ => logs, } } fn last_hashes(&self) -> LastHashes { unimplemented!(); } fn best_block_header(&self) -> encoded::Header { self.block_header(BlockId::Hash(self.chain_info().best_block_hash)) .expect("Best block always has header.") } fn block_header(&self, id: BlockId) -> Option<encoded::Header> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec())) .map(encoded::Header::new) } fn block_number(&self, _id: BlockId) -> Option<BlockNumber> { unimplemented!() } fn block_body(&self, id: BlockId) -> Option<encoded::Body> { self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).map(|r| { let mut stream = RlpStream::new_list(2); stream.append_raw(Rlp::new(r).at(1).as_raw(), 1); stream.append_raw(Rlp::new(r).at(2).as_raw(), 1); encoded::Body::new(stream.out()) })) } fn block(&self, id: BlockId) -> Option<encoded::Block> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).cloned()) .map(encoded::Block::new) } fn block_extra_info(&self, id: BlockId) -> Option<BTreeMap<String, String>> { self.block(id) .map(|block| block.view().header()) .map(|header| self.spec.engine.extra_info(&header)) } fn block_status(&self, id: BlockId) -> BlockStatus { match id { BlockId::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain, BlockId::Hash(ref hash) if self.blocks.read().get(hash).is_some() => BlockStatus::InChain, BlockId::Latest | BlockId::Pending | BlockId::Earliest => BlockStatus::InChain, _ => BlockStatus::Unknown, } } // works only if blocks are one after another 1 -> 2 -> 3 fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> { Some(TreeRoute { ancestor: H256::new(), index: 0, blocks: { let numbers_read = self.numbers.read(); let mut adding = false; let mut blocks = Vec::new(); for (_, hash) in numbers_read.iter().sort_by(|tuple1, tuple2| tuple1.0.cmp(tuple2.0)) { if hash == to { if adding { blocks.push(hash.clone()); } adding = false; break; } if hash == from { adding = true; } if adding { blocks.push(hash.clone()); } } if adding { Vec::new() } else { blocks } } }) } fn find_uncles(&self, _hash: &H256) -> Option<Vec<H256>> { None } // TODO: returns just hashes instead of node state rlp(?) fn state_data(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let mut rlp = RlpStream::new(); rlp.append(&hash.clone()); return Some(rlp.out()); } None } fn block_receipts(&self, hash: &H256) -> Option<Bytes> { // starts with 'f'? if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let receipt = BlockReceipts::new(vec![Receipt::new( H256::zero(), U256::zero(), vec![])]); let mut rlp = RlpStream::new(); rlp.append(&receipt); return Some(rlp.out()); } None } fn import_block(&self, b: Bytes) -> Result<H256, BlockImportError> { let header = Rlp::new(&b).val_at::<BlockHeader>(0); let h = header.hash(); let number: usize = header.number() as usize; if number > self.blocks.read().len() { panic!("Unexpected block number. Expected {}, got {}", self.blocks.read().len(), number); } if number > 0 { match self.blocks.read().get(header.parent_hash()) { Some(parent) => { let parent = Rlp::new(parent).val_at::<BlockHeader>(0); if parent.number()!= (header.number() - 1) { panic!("Unexpected block parent"); } }, None => { panic!("Unknown block parent {:?} for block {}", header.parent_hash(), number); } } } let len = self.numbers.read().len(); if number == len { { let mut difficulty = self.difficulty.write(); *difficulty = *difficulty + header.difficulty().clone(); } mem::replace(&mut *self.last_hash.write(), h.clone()); self.blocks.write().insert(h.clone(), b); self.numbers.write().insert(number, h.clone()); let mut parent_hash = header.parent_hash().clone(); if number > 0 { let mut n = number - 1; while n > 0 && self.numbers.read()[&n]!= parent_hash { *self.numbers.write().get_mut(&n).unwrap() = parent_hash.clone(); n -= 1; parent_hash = Rlp::new(&self.blocks.read()[&parent_hash]).val_at::<BlockHeader>(0).parent_hash().clone(); } } } else { self.blocks.write().insert(h.clone(), b.to_vec()); } Ok(h) } fn import_block_with_receipts(&self, b: Bytes, _r: Bytes) -> Result<H256, BlockImportError> { self.import_block(b) } fn queue_info(&self) -> QueueInfo { QueueInfo { verified_queue_size: self.queue_size.load(AtomicOrder::Relaxed), unverified_queue_size: 0, verifying_queue_size: 0, max_queue_size: 0, max_mem_use: 0, mem_used: 0, } } fn clear_queue(&self) { } fn additional_params(&self) -> BTreeMap<String, String> { Default::default() } fn chain_info(&self) -> BlockChainInfo { BlockChainInfo { total_difficulty: *self.difficulty.read(), pending_total_difficulty: *self.difficulty.read(), genesis_hash: self.genesis_hash.clone(), best_block_hash: self.last_hash.read().clone(), best_block_number: self.blocks.read().len() as BlockNumber - 1, first_block_hash: self.first_block.read().as_ref().map(|x| x.0), first_block_number: self.first_block.read().as_ref().map(|x| x.1), ancient_block_hash: self.ancient_block.read().as_ref().map(|x| x.0), ancient_block_number: self.ancient_block.read().as_ref().map(|x| x.1) } } fn filter_traces(&self, _filter: TraceFilter) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn trace(&self, _trace: TraceId) -> Option<LocalizedTrace> { self.traces.read().clone().and_then(|vec| vec.into_iter().next()) } fn transaction_traces(&self, _trace: TransactionId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn block_traces(&self, _trace: BlockId) -> Option<Vec<LocalizedTrace>> { self.traces.read().clone() } fn queue_transactions(&self, transactions: Vec<Bytes>, _peer_id: usize) { // import right here let txs = transactions.into_iter().filter_map(|bytes| UntrustedRlp::new(&bytes).as_val().ok()).collect(); self.miner.import_external_transactions(self, txs); } fn queue_consensus_message(&self, message: Bytes) { self.spec.engine.handle_message(&message).unwrap(); } fn ready_transactions(&self) -> Vec<PendingTransaction> { self.miner.ready_transactions(self.chain_info().best_block_number) } fn signing_network_id(&self) -> Option<u64> { None } fn mode(&self) -> Mode { Mode::Active } fn set_mode(&self, _: Mode) { unimplemented!(); } fn disable(&self) { unimplemented!(); } fn pruning_info(&self) -> PruningInfo { let best_num = self.chain_info().best_block_number; PruningInfo { earliest_chain: 1, earliest_state: self.history.read().as_ref().map(|x| best_num - x).unwrap_or(0), } } fn call_contract(&self, _address: Address, _data: Bytes) -> Result<Bytes, String> { Ok(vec![]) } fn registrar_address(&self) -> Option<Address> { None } fn registry_address(&self, _name: String) -> Option<Address> { None } } impl ProvingBlockChainClient for TestBlockChainClient { fn prove_storage(&self, _: H256, _: H256, _: u32, _: BlockId) -> Vec<Bytes> { Vec::new() } fn prove_account(&self, _: H256, _: u32, _: BlockId) -> Vec<Bytes> {
{ Some(self.balances.read().get(address).cloned().unwrap_or_else(U256::zero)) }
conditional_block
cleanup-rvalue-scopes-cf.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that the borrow checker prevents pointers to temporaries // with statement lifetimes from escaping. #[feature(macro_rules)]; use std::ops::Drop; static mut FLAGS: u64 = 0; struct Box<T> { f: T } struct AddFlags { bits: u64 } fn AddFlags(bits: u64) -> AddFlags { AddFlags { bits: bits } } fn arg<'a>(x: &'a AddFlags) -> &'a AddFlags { x } impl AddFlags { fn get<'a>(&'a self) -> &'a AddFlags { self } } pub fn main() { let _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough
let _x = AddFlags(1).get(); //~ ERROR value does not live long enough let _x = &*arg(&AddFlags(1)); //~ ERROR value does not live long enough let ref _x = *arg(&AddFlags(1)); //~ ERROR value does not live long enough let &ref _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough let _x = AddFlags(1).get(); //~ ERROR value does not live long enough let Box { f: _x } = Box { f: AddFlags(1).get() }; //~ ERROR value does not live long enough }
random_line_split
cleanup-rvalue-scopes-cf.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that the borrow checker prevents pointers to temporaries // with statement lifetimes from escaping. #[feature(macro_rules)]; use std::ops::Drop; static mut FLAGS: u64 = 0; struct Box<T> { f: T } struct
{ bits: u64 } fn AddFlags(bits: u64) -> AddFlags { AddFlags { bits: bits } } fn arg<'a>(x: &'a AddFlags) -> &'a AddFlags { x } impl AddFlags { fn get<'a>(&'a self) -> &'a AddFlags { self } } pub fn main() { let _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough let _x = AddFlags(1).get(); //~ ERROR value does not live long enough let _x = &*arg(&AddFlags(1)); //~ ERROR value does not live long enough let ref _x = *arg(&AddFlags(1)); //~ ERROR value does not live long enough let &ref _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough let _x = AddFlags(1).get(); //~ ERROR value does not live long enough let Box { f: _x } = Box { f: AddFlags(1).get() }; //~ ERROR value does not live long enough }
AddFlags
identifier_name
mod.rs
pub mod semantic; #[derive(Debug)] pub struct Program(pub Vec<Function>); #[derive(Debug)] pub struct Function { pub name: String, pub returns: Type, pub statements: Vec<Statement> } #[derive(Debug)] pub enum Statement { Block(Vec<Statement>), Declare(Type, String, Expression), Assign(String, Expression), Return(Expression), Print(Expression) } #[derive(Debug, Clone)] pub enum Expression { Int(i32), Char(char), Bool(bool), Str(String), Identifier(String), FunctionCall(String), ArrayLiteral(Vec<Expression>), Unary(UnaryOp, Box<Expression>), Binary(BinaryOp, Box<Expression>, Box<Expression>) } #[derive(Debug, Clone)] pub enum
{ Neg } #[derive(Debug, Clone)] pub enum BinaryOp { Add, Sub, Mul, Div, Mod } #[derive(Debug, Clone)] pub enum Type { Unknown, Error, Any, Void, Int, Char, Bool, Str, Array(Box<Type>), Pair(Box<Type>, Box<Type>) } impl PartialEq for Type { fn eq(&self, other: &Type) -> bool { match *self { Type::Unknown => false, Type::Error => false, Type::Any => true, Type::Void => match *other { Type::Void => true, _ => false }, Type::Int => match *other { Type::Int => true, _ => false }, Type::Char => match *other { Type::Char => true, _ => false }, Type::Bool => match *other { Type::Bool => true, _ => false }, Type::Str => match *other { Type::Str => true, _ => false }, Type::Array(ref i) => match *other { Type::Array(ref i2) => i == i2, _ => false }, _ => false } } }
UnaryOp
identifier_name
mod.rs
pub mod semantic; #[derive(Debug)] pub struct Program(pub Vec<Function>); #[derive(Debug)] pub struct Function { pub name: String, pub returns: Type, pub statements: Vec<Statement> } #[derive(Debug)] pub enum Statement { Block(Vec<Statement>), Declare(Type, String, Expression), Assign(String, Expression), Return(Expression), Print(Expression) } #[derive(Debug, Clone)] pub enum Expression { Int(i32), Char(char), Bool(bool), Str(String), Identifier(String), FunctionCall(String), ArrayLiteral(Vec<Expression>), Unary(UnaryOp, Box<Expression>), Binary(BinaryOp, Box<Expression>, Box<Expression>) } #[derive(Debug, Clone)] pub enum UnaryOp { Neg } #[derive(Debug, Clone)] pub enum BinaryOp { Add, Sub, Mul,
} #[derive(Debug, Clone)] pub enum Type { Unknown, Error, Any, Void, Int, Char, Bool, Str, Array(Box<Type>), Pair(Box<Type>, Box<Type>) } impl PartialEq for Type { fn eq(&self, other: &Type) -> bool { match *self { Type::Unknown => false, Type::Error => false, Type::Any => true, Type::Void => match *other { Type::Void => true, _ => false }, Type::Int => match *other { Type::Int => true, _ => false }, Type::Char => match *other { Type::Char => true, _ => false }, Type::Bool => match *other { Type::Bool => true, _ => false }, Type::Str => match *other { Type::Str => true, _ => false }, Type::Array(ref i) => match *other { Type::Array(ref i2) => i == i2, _ => false }, _ => false } } }
Div, Mod
random_line_split
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[jstraceable] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(self, offset: Finite<f64>, color: String) { let default_black = RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0, }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle
}
{ let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }, CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } }
identifier_body
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[jstraceable] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(self, offset: Finite<f64>, color: String) { let default_black = RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0, }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> {
FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }, CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => {
random_line_split
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[jstraceable] pub enum
{ Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(self, offset: Finite<f64>, color: String) { let default_black = RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0, }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }, CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
CanvasGradientStyle
identifier_name
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[jstraceable] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(self, offset: Finite<f64>, color: String) { let default_black = RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0, }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }, CanvasGradientStyle::Radial(ref gradient) =>
} } }
{ FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) }
conditional_block
track.rs
use chill::DocumentId; use id3::Tag; use Uri; #[derive(Serialize, Deserialize, Debug)] pub struct Track { #[serde(rename="type")] _type: String, pub name: String, pub number: u32, pub artist: DocumentId, pub album: DocumentId, pub uris: Vec<Uri>, } impl Track { pub fn new(name: &str, number: u32, artist: DocumentId, album: DocumentId, uris: Vec<Uri>) -> Self { Track { _type: "track".into(), name: name.into(), number: number, artist: artist, album: album, uris: uris, } } } #[derive(Serialize, Deserialize, Debug)] pub struct
{ pub name: String, pub number: u32, pub artist: String, pub album: String, pub uri: Uri, } impl DecodedTrack { pub fn from_tag(tag: Tag, uri: Uri) -> Option<DecodedTrack> { let artist = match tag.artist() { Some(artist) => artist, None => return None, }; let album = match tag.album() { Some(album) => album, None => return None, }; let name = match tag.title() { Some(name) => name, None => return None, }; let number = match tag.track() { Some(number) => number, None => return None, }; Some(DecodedTrack { artist: artist.into(), album: album.into(), name: name.into(), number: number, uri: uri, }) } }
DecodedTrack
identifier_name
track.rs
use chill::DocumentId; use id3::Tag; use Uri; #[derive(Serialize, Deserialize, Debug)] pub struct Track { #[serde(rename="type")] _type: String, pub name: String, pub number: u32, pub artist: DocumentId, pub album: DocumentId, pub uris: Vec<Uri>, } impl Track { pub fn new(name: &str, number: u32, artist: DocumentId, album: DocumentId, uris: Vec<Uri>) -> Self { Track { _type: "track".into(), name: name.into(), number: number, artist: artist, album: album, uris: uris, } }
#[derive(Serialize, Deserialize, Debug)] pub struct DecodedTrack { pub name: String, pub number: u32, pub artist: String, pub album: String, pub uri: Uri, } impl DecodedTrack { pub fn from_tag(tag: Tag, uri: Uri) -> Option<DecodedTrack> { let artist = match tag.artist() { Some(artist) => artist, None => return None, }; let album = match tag.album() { Some(album) => album, None => return None, }; let name = match tag.title() { Some(name) => name, None => return None, }; let number = match tag.track() { Some(number) => number, None => return None, }; Some(DecodedTrack { artist: artist.into(), album: album.into(), name: name.into(), number: number, uri: uri, }) } }
}
random_line_split
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), ]; const USAGE: &'static str = r#" portmidi-rs: play-twinkle-twinkle Usage: play [-v | --verbose] <device-id> Options: -h --help Show this screen. -v --verbose Print what's being done Omitting <device-id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_device_id: i32, flag_verbose: bool, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwrap() { println!("{}", dev); } } fn main() { // initialize the PortMidi context. let context = pm::PortMidi::new().unwrap(); // setup the command line interface let args: Args = docopt::Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|err| { print_devices(&context); err.exit(); }); let out_port = context .device(args.arg_device_id) .and_then(|dev| context.output_port(dev, 1024)) .unwrap(); play(out_port, args.flag_verbose).unwrap() } fn
(mut out_port: pm::OutputPort, verbose: bool) -> pm::Result<()> { for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_on) } out_port.write_message(note_on)?; // note hold time before sending note off thread::sleep(Duration::from_millis(dur as u64 * 400)); let note_off = MidiMessage { status: 0x80 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_off); } out_port.write_message(note_off)?; // short pause thread::sleep(Duration::from_millis(100)); } Ok(()) }
play
identifier_name
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), ]; const USAGE: &'static str = r#" portmidi-rs: play-twinkle-twinkle Usage: play [-v | --verbose] <device-id> Options: -h --help Show this screen. -v --verbose Print what's being done Omitting <device-id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_device_id: i32, flag_verbose: bool, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwrap() { println!("{}", dev); } } fn main() { // initialize the PortMidi context. let context = pm::PortMidi::new().unwrap(); // setup the command line interface let args: Args = docopt::Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|err| { print_devices(&context); err.exit(); }); let out_port = context .device(args.arg_device_id) .and_then(|dev| context.output_port(dev, 1024)) .unwrap(); play(out_port, args.flag_verbose).unwrap() } fn play(mut out_port: pm::OutputPort, verbose: bool) -> pm::Result<()>
}; if verbose { println!("{}", note_off); } out_port.write_message(note_off)?; // short pause thread::sleep(Duration::from_millis(100)); } Ok(()) }
{ for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_on) } out_port.write_message(note_on)?; // note hold time before sending note off thread::sleep(Duration::from_millis(dur as u64 * 400)); let note_off = MidiMessage { status: 0x80 + CHANNEL, data1: note, data2: 100, data3: 0,
identifier_body
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), ]; const USAGE: &'static str = r#" portmidi-rs: play-twinkle-twinkle Usage: play [-v | --verbose] <device-id>
Options: -h --help Show this screen. -v --verbose Print what's being done Omitting <device-id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_device_id: i32, flag_verbose: bool, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwrap() { println!("{}", dev); } } fn main() { // initialize the PortMidi context. let context = pm::PortMidi::new().unwrap(); // setup the command line interface let args: Args = docopt::Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|err| { print_devices(&context); err.exit(); }); let out_port = context .device(args.arg_device_id) .and_then(|dev| context.output_port(dev, 1024)) .unwrap(); play(out_port, args.flag_verbose).unwrap() } fn play(mut out_port: pm::OutputPort, verbose: bool) -> pm::Result<()> { for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_on) } out_port.write_message(note_on)?; // note hold time before sending note off thread::sleep(Duration::from_millis(dur as u64 * 400)); let note_off = MidiMessage { status: 0x80 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_off); } out_port.write_message(note_off)?; // short pause thread::sleep(Duration::from_millis(100)); } Ok(()) }
random_line_split
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (67, 1), (67, 1), (65, 1), (65, 1), (64, 1), (64, 1), (62, 2), (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1), (64, 1), (64, 1), (62, 1), (62, 1), (60, 2), ]; const USAGE: &'static str = r#" portmidi-rs: play-twinkle-twinkle Usage: play [-v | --verbose] <device-id> Options: -h --help Show this screen. -v --verbose Print what's being done Omitting <device-id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_device_id: i32, flag_verbose: bool, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwrap() { println!("{}", dev); } } fn main() { // initialize the PortMidi context. let context = pm::PortMidi::new().unwrap(); // setup the command line interface let args: Args = docopt::Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|err| { print_devices(&context); err.exit(); }); let out_port = context .device(args.arg_device_id) .and_then(|dev| context.output_port(dev, 1024)) .unwrap(); play(out_port, args.flag_verbose).unwrap() } fn play(mut out_port: pm::OutputPort, verbose: bool) -> pm::Result<()> { for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose
out_port.write_message(note_on)?; // note hold time before sending note off thread::sleep(Duration::from_millis(dur as u64 * 400)); let note_off = MidiMessage { status: 0x80 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_off); } out_port.write_message(note_off)?; // short pause thread::sleep(Duration::from_millis(100)); } Ok(()) }
{ println!("{}", note_on) }
conditional_block
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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 *
* See the License for the specific language governing permissions and * limitations under the License. */ //! Parser for AAAA text form use std::net::Ipv6Addr; use std::str::FromStr; use crate::error::*; /// Parse the RData from a set of Tokens pub fn parse<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv6Addr> { let address: Ipv6Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv6 address".to_string()))) .and_then(|s| Ipv6Addr::from_str(s).map_err(Into::into))?; Ok(address) }
* 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.
random_line_split
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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. */ //! Parser for AAAA text form use std::net::Ipv6Addr; use std::str::FromStr; use crate::error::*; /// Parse the RData from a set of Tokens pub fn parse<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv6Addr>
{ let address: Ipv6Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv6 address".to_string()))) .and_then(|s| Ipv6Addr::from_str(s).map_err(Into::into))?; Ok(address) }
identifier_body
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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. */ //! Parser for AAAA text form use std::net::Ipv6Addr; use std::str::FromStr; use crate::error::*; /// Parse the RData from a set of Tokens pub fn
<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv6Addr> { let address: Ipv6Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv6 address".to_string()))) .and_then(|s| Ipv6Addr::from_str(s).map_err(Into::into))?; Ok(address) }
parse
identifier_name
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // #[test] fn
() { tink_daead::init(); let kh = tink_core::keyset::Handle::new(&tink_daead::aes_siv_key_template()).unwrap(); // NOTE: save the keyset to a safe location. DO NOT hardcode it in source code. // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets. let d = tink_daead::new(&kh).unwrap(); let msg = b"this data needs to be encrypted"; let aad = b"this data needs to be authenticated, but not encrypted"; let ct1 = d.encrypt_deterministically(msg, aad).unwrap(); let pt = d.decrypt_deterministically(&ct1, aad).unwrap(); let ct2 = d.encrypt_deterministically(msg, aad).unwrap(); assert_eq!(ct1, ct2, "ct1!= ct2"); println!("Ciphertext: {}", base64::encode(&ct1)); println!("Original plaintext: {}", std::str::from_utf8(msg).unwrap()); println!("Decrypted Plaintext: {}", std::str::from_utf8(&pt).unwrap()); assert_eq!(msg, &pt[..]); } #[test] fn test_deterministic_aead_init() { // Check for AES-SIV key manager. tink_daead::init(); assert!(tink_core::registry::get_key_manager(tink_tests::AES_SIV_TYPE_URL).is_ok()); }
example
identifier_name
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // #[test] fn example() { tink_daead::init(); let kh = tink_core::keyset::Handle::new(&tink_daead::aes_siv_key_template()).unwrap(); // NOTE: save the keyset to a safe location. DO NOT hardcode it in source code.
// Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets. let d = tink_daead::new(&kh).unwrap(); let msg = b"this data needs to be encrypted"; let aad = b"this data needs to be authenticated, but not encrypted"; let ct1 = d.encrypt_deterministically(msg, aad).unwrap(); let pt = d.decrypt_deterministically(&ct1, aad).unwrap(); let ct2 = d.encrypt_deterministically(msg, aad).unwrap(); assert_eq!(ct1, ct2, "ct1!= ct2"); println!("Ciphertext: {}", base64::encode(&ct1)); println!("Original plaintext: {}", std::str::from_utf8(msg).unwrap()); println!("Decrypted Plaintext: {}", std::str::from_utf8(&pt).unwrap()); assert_eq!(msg, &pt[..]); } #[test] fn test_deterministic_aead_init() { // Check for AES-SIV key manager. tink_daead::init(); assert!(tink_core::registry::get_key_manager(tink_tests::AES_SIV_TYPE_URL).is_ok()); }
random_line_split
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // #[test] fn example()
assert_eq!(msg, &pt[..]); } #[test] fn test_deterministic_aead_init() { // Check for AES-SIV key manager. tink_daead::init(); assert!(tink_core::registry::get_key_manager(tink_tests::AES_SIV_TYPE_URL).is_ok()); }
{ tink_daead::init(); let kh = tink_core::keyset::Handle::new(&tink_daead::aes_siv_key_template()).unwrap(); // NOTE: save the keyset to a safe location. DO NOT hardcode it in source code. // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets. let d = tink_daead::new(&kh).unwrap(); let msg = b"this data needs to be encrypted"; let aad = b"this data needs to be authenticated, but not encrypted"; let ct1 = d.encrypt_deterministically(msg, aad).unwrap(); let pt = d.decrypt_deterministically(&ct1, aad).unwrap(); let ct2 = d.encrypt_deterministically(msg, aad).unwrap(); assert_eq!(ct1, ct2, "ct1 != ct2"); println!("Ciphertext: {}", base64::encode(&ct1)); println!("Original plaintext: {}", std::str::from_utf8(msg).unwrap()); println!("Decrypted Plaintext: {}", std::str::from_utf8(&pt).unwrap());
identifier_body
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<Ix>, pub port: u32, } pub fn port<Ix: IndexType>(node: NodeIndex<Ix>, port: u32) -> Port<Ix> { Port{node: node, port: port} } pub struct PortNumbered<N, Ix: IndexType = u32> { dag: Dag<N, Edge, Ix>, } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn new() -> PortNumbered<N, Ix> { PortNumbered { dag: Dag::new(), } } pub fn edges<'a>(&'a self) -> Edges<'a, Ix> { Edges(self.dag.raw_edges(), 0) } pub fn parents(&self, node: NodeIndex<Ix>) -> Parents<N, Ix> { Parents(&self.dag, self.dag.parents(node)) } pub fn children(&self, node: NodeIndex<Ix>) -> Children<N, Ix> { Children(&self.dag, self.dag.children(node)) } pub fn update_edge(&mut self, src: Port<Ix>, trg: Port<Ix>) -> Result<EdgeIndex<Ix>, WouldBreak> { let replaced = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port); let result = self.dag.update_edge(src.node, trg.node, Edge{source: src.port, target: trg.port}).map_err(Into::into); if let Ok(_) = result { if let Some(e) = replaced { self.dag.remove_edge(e); } } result } pub fn remove_edge_to_port(&mut self, trg: Port<Ix>) -> Option<Port<Ix>> { if let Some(e) = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port) { let result = port(self.dag.edge_endpoints(e).unwrap().0, self.dag.edge_weight(e).unwrap().source); self.dag.remove_edge(e); Some(result) } else { None } } pub fn remove_outgoing_edges(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> { self.dag.add_node(weight) } pub fn remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N> { self.dag.remove_node(node) } pub fn node_weight(&self, node: NodeIndex<Ix>) -> Option<&N> { self.dag.node_weight(node) } pub fn node_weight_mut(&mut self, node: NodeIndex<Ix>) -> Option<&mut N> { self.dag.node_weight_mut(node) } pub fn raw_nodes(&self) -> ::daggy::RawNodes<N, Ix> { self.dag.raw_nodes() } pub fn edge_count(&self) -> usize { self.dag.edge_count() } pub fn node_count(&self) -> usize { self.dag.node_count() } pub fn graph(&self) -> &PetGraph<N, Edge, Ix> { self.dag.graph() } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WouldBreak { WouldCycle, WouldUnport, } impl From<WouldCycle<Edge>> for WouldBreak { fn from(_: WouldCycle<Edge>) -> Self { WouldBreak::WouldCycle } } pub struct Edges<'a, Ix: IndexType>(::daggy::RawEdges<'a, Edge, Ix>, usize); impl<'a, Ix: IndexType> Iterator for Edges<'a, Ix> { type Item = (Port<Ix>, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if self.1 < self.0.len() { let e = &self.0[self.1]; self.1 += 1; Some((port(e.source(), e.weight.source), port(e.target(), e.weight.target))) } else { None } } } pub struct Parents<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Parents<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Parents<'a, N, Ix> { type Item = (Port<Ix>, u32); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0)
else { None } } } pub struct Children<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Children<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Children<'a, N, Ix> { type Item = (u32, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0) { let edge = self.0.edge_weight(edge).unwrap(); Some((edge.source, port(node, edge.target))) } else { None } } }
{ let edge = self.0.edge_weight(edge).unwrap(); Some((port(node, edge.source), edge.target)) }
conditional_block
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<Ix>, pub port: u32, } pub fn port<Ix: IndexType>(node: NodeIndex<Ix>, port: u32) -> Port<Ix> { Port{node: node, port: port} } pub struct PortNumbered<N, Ix: IndexType = u32> { dag: Dag<N, Edge, Ix>, } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn new() -> PortNumbered<N, Ix> { PortNumbered { dag: Dag::new(), } } pub fn edges<'a>(&'a self) -> Edges<'a, Ix> { Edges(self.dag.raw_edges(), 0) } pub fn parents(&self, node: NodeIndex<Ix>) -> Parents<N, Ix> { Parents(&self.dag, self.dag.parents(node)) } pub fn children(&self, node: NodeIndex<Ix>) -> Children<N, Ix> { Children(&self.dag, self.dag.children(node)) } pub fn update_edge(&mut self, src: Port<Ix>, trg: Port<Ix>) -> Result<EdgeIndex<Ix>, WouldBreak> { let replaced = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port); let result = self.dag.update_edge(src.node, trg.node, Edge{source: src.port, target: trg.port}).map_err(Into::into); if let Ok(_) = result { if let Some(e) = replaced { self.dag.remove_edge(e); } } result } pub fn remove_edge_to_port(&mut self, trg: Port<Ix>) -> Option<Port<Ix>> { if let Some(e) = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port) { let result = port(self.dag.edge_endpoints(e).unwrap().0, self.dag.edge_weight(e).unwrap().source); self.dag.remove_edge(e); Some(result) } else { None }
} pub fn remove_outgoing_edges(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> { self.dag.add_node(weight) } pub fn remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N> { self.dag.remove_node(node) } pub fn node_weight(&self, node: NodeIndex<Ix>) -> Option<&N> { self.dag.node_weight(node) } pub fn node_weight_mut(&mut self, node: NodeIndex<Ix>) -> Option<&mut N> { self.dag.node_weight_mut(node) } pub fn raw_nodes(&self) -> ::daggy::RawNodes<N, Ix> { self.dag.raw_nodes() } pub fn edge_count(&self) -> usize { self.dag.edge_count() } pub fn node_count(&self) -> usize { self.dag.node_count() } pub fn graph(&self) -> &PetGraph<N, Edge, Ix> { self.dag.graph() } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WouldBreak { WouldCycle, WouldUnport, } impl From<WouldCycle<Edge>> for WouldBreak { fn from(_: WouldCycle<Edge>) -> Self { WouldBreak::WouldCycle } } pub struct Edges<'a, Ix: IndexType>(::daggy::RawEdges<'a, Edge, Ix>, usize); impl<'a, Ix: IndexType> Iterator for Edges<'a, Ix> { type Item = (Port<Ix>, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if self.1 < self.0.len() { let e = &self.0[self.1]; self.1 += 1; Some((port(e.source(), e.weight.source), port(e.target(), e.weight.target))) } else { None } } } pub struct Parents<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Parents<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Parents<'a, N, Ix> { type Item = (Port<Ix>, u32); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0) { let edge = self.0.edge_weight(edge).unwrap(); Some((port(node, edge.source), edge.target)) } else { None } } } pub struct Children<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Children<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Children<'a, N, Ix> { type Item = (u32, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0) { let edge = self.0.edge_weight(edge).unwrap(); Some((edge.source, port(node, edge.target))) } else { None } } }
random_line_split
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<Ix>, pub port: u32, } pub fn port<Ix: IndexType>(node: NodeIndex<Ix>, port: u32) -> Port<Ix> { Port{node: node, port: port} } pub struct PortNumbered<N, Ix: IndexType = u32> { dag: Dag<N, Edge, Ix>, } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn new() -> PortNumbered<N, Ix> { PortNumbered { dag: Dag::new(), } } pub fn edges<'a>(&'a self) -> Edges<'a, Ix> { Edges(self.dag.raw_edges(), 0) } pub fn parents(&self, node: NodeIndex<Ix>) -> Parents<N, Ix> { Parents(&self.dag, self.dag.parents(node)) } pub fn children(&self, node: NodeIndex<Ix>) -> Children<N, Ix> { Children(&self.dag, self.dag.children(node)) } pub fn update_edge(&mut self, src: Port<Ix>, trg: Port<Ix>) -> Result<EdgeIndex<Ix>, WouldBreak> { let replaced = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port); let result = self.dag.update_edge(src.node, trg.node, Edge{source: src.port, target: trg.port}).map_err(Into::into); if let Ok(_) = result { if let Some(e) = replaced { self.dag.remove_edge(e); } } result } pub fn remove_edge_to_port(&mut self, trg: Port<Ix>) -> Option<Port<Ix>> { if let Some(e) = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port) { let result = port(self.dag.edge_endpoints(e).unwrap().0, self.dag.edge_weight(e).unwrap().source); self.dag.remove_edge(e); Some(result) } else { None } } pub fn remove_outgoing_edges(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> { self.dag.add_node(weight) } pub fn remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N> { self.dag.remove_node(node) } pub fn node_weight(&self, node: NodeIndex<Ix>) -> Option<&N> { self.dag.node_weight(node) } pub fn node_weight_mut(&mut self, node: NodeIndex<Ix>) -> Option<&mut N> { self.dag.node_weight_mut(node) } pub fn raw_nodes(&self) -> ::daggy::RawNodes<N, Ix> { self.dag.raw_nodes() } pub fn edge_count(&self) -> usize { self.dag.edge_count() } pub fn node_count(&self) -> usize { self.dag.node_count() } pub fn graph(&self) -> &PetGraph<N, Edge, Ix> { self.dag.graph() } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WouldBreak { WouldCycle, WouldUnport, } impl From<WouldCycle<Edge>> for WouldBreak { fn from(_: WouldCycle<Edge>) -> Self
} pub struct Edges<'a, Ix: IndexType>(::daggy::RawEdges<'a, Edge, Ix>, usize); impl<'a, Ix: IndexType> Iterator for Edges<'a, Ix> { type Item = (Port<Ix>, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if self.1 < self.0.len() { let e = &self.0[self.1]; self.1 += 1; Some((port(e.source(), e.weight.source), port(e.target(), e.weight.target))) } else { None } } } pub struct Parents<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Parents<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Parents<'a, N, Ix> { type Item = (Port<Ix>, u32); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0) { let edge = self.0.edge_weight(edge).unwrap(); Some((port(node, edge.source), edge.target)) } else { None } } } pub struct Children<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Children<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Children<'a, N, Ix> { type Item = (u32, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0) { let edge = self.0.edge_weight(edge).unwrap(); Some((edge.source, port(node, edge.target))) } else { None } } }
{ WouldBreak::WouldCycle }
identifier_body
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<Ix>, pub port: u32, } pub fn port<Ix: IndexType>(node: NodeIndex<Ix>, port: u32) -> Port<Ix> { Port{node: node, port: port} } pub struct PortNumbered<N, Ix: IndexType = u32> { dag: Dag<N, Edge, Ix>, } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn new() -> PortNumbered<N, Ix> { PortNumbered { dag: Dag::new(), } } pub fn edges<'a>(&'a self) -> Edges<'a, Ix> { Edges(self.dag.raw_edges(), 0) } pub fn parents(&self, node: NodeIndex<Ix>) -> Parents<N, Ix> { Parents(&self.dag, self.dag.parents(node)) } pub fn children(&self, node: NodeIndex<Ix>) -> Children<N, Ix> { Children(&self.dag, self.dag.children(node)) } pub fn update_edge(&mut self, src: Port<Ix>, trg: Port<Ix>) -> Result<EdgeIndex<Ix>, WouldBreak> { let replaced = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port); let result = self.dag.update_edge(src.node, trg.node, Edge{source: src.port, target: trg.port}).map_err(Into::into); if let Ok(_) = result { if let Some(e) = replaced { self.dag.remove_edge(e); } } result } pub fn remove_edge_to_port(&mut self, trg: Port<Ix>) -> Option<Port<Ix>> { if let Some(e) = self.dag.parents(trg.node).find_edge(&self.dag, |dag, e, _| dag.edge_weight(e).unwrap().target == trg.port) { let result = port(self.dag.edge_endpoints(e).unwrap().0, self.dag.edge_weight(e).unwrap().source); self.dag.remove_edge(e); Some(result) } else { None } } pub fn
(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> { self.dag.add_node(weight) } pub fn remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N> { self.dag.remove_node(node) } pub fn node_weight(&self, node: NodeIndex<Ix>) -> Option<&N> { self.dag.node_weight(node) } pub fn node_weight_mut(&mut self, node: NodeIndex<Ix>) -> Option<&mut N> { self.dag.node_weight_mut(node) } pub fn raw_nodes(&self) -> ::daggy::RawNodes<N, Ix> { self.dag.raw_nodes() } pub fn edge_count(&self) -> usize { self.dag.edge_count() } pub fn node_count(&self) -> usize { self.dag.node_count() } pub fn graph(&self) -> &PetGraph<N, Edge, Ix> { self.dag.graph() } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WouldBreak { WouldCycle, WouldUnport, } impl From<WouldCycle<Edge>> for WouldBreak { fn from(_: WouldCycle<Edge>) -> Self { WouldBreak::WouldCycle } } pub struct Edges<'a, Ix: IndexType>(::daggy::RawEdges<'a, Edge, Ix>, usize); impl<'a, Ix: IndexType> Iterator for Edges<'a, Ix> { type Item = (Port<Ix>, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if self.1 < self.0.len() { let e = &self.0[self.1]; self.1 += 1; Some((port(e.source(), e.weight.source), port(e.target(), e.weight.target))) } else { None } } } pub struct Parents<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Parents<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Parents<'a, N, Ix> { type Item = (Port<Ix>, u32); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0) { let edge = self.0.edge_weight(edge).unwrap(); Some((port(node, edge.source), edge.target)) } else { None } } } pub struct Children<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Children<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Children<'a, N, Ix> { type Item = (u32, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, node)) = self.1.next(self.0) { let edge = self.0.edge_weight(edge).unwrap(); Some((edge.source, port(node, edge.target))) } else { None } } }
remove_outgoing_edges
identifier_name
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword;
// #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use config::Config; use clap::ArgMatches; use colored::*; use question::{Answer, Question}; use std::process; use std::{env, fs}; fn main() { /* This makes panic! pretty */ // setup_panic!(); /* Define our CLI App */ let m = cli::create().get_matches(); /* In this block we can unwrap quite viciously because clap will protect us */ match m.subcommand() { ("setup", Some(m)) => handle_setup(m), ("load", Some(m)) => handle_load(m), ("generate", Some(m)) => handle_generate(m), _ => println!("Missing arguments: type `poke --help` for more help!"), } } fn handle_generate(matches: &ArgMatches) { if!ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap(), &format!("{}_local", name), ); ssh::send_key( ssh::get_directory() .join(&format!("{}_local.pub", &name)) .to_str() .unwrap(), &addr, ); } fn handle_setup(matches: &ArgMatches) { let ks_path = String::from(matches.value_of("path").unwrap()); /* Either create or load existing config */ let mut cfg = Config::load().unwrap_or_else(|| Config::create_empty()); cfg.if_no_keystore(|| { let cont = Question::new("Keystore already registered. Change location?") .default(Answer::NO) .show_defaults() .confirm(); if cont == Answer::NO { println!("Aborting re-setup!"); process::exit(2); } }); /* Set the new keystore path & sync */ cfg.set_keystore(&ks_path); cfg.sync(); /* Get a desired user password */ let pass = rpassword::prompt_password_stdout("Set a keystore password: ").unwrap(); let pass_confirm = rpassword::prompt_password_stdout("Confirm the password: ").unwrap(); if pass!= pass_confirm { eprintln!("{}", "The two passwords did not match!".red()); process::exit(2); } let pub_path = keywoman::generate_root(ks_path, pass); /* Print about our success */ println!(""); println!("{}", "✨ A new keystore was generated for you ✨".green()); println!("Your root public key can be found here: '{}'", pub_path); } fn handle_load(matches: &ArgMatches) {}
extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml;
random_line_split
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use config::Config; use clap::ArgMatches; use colored::*; use question::{Answer, Question}; use std::process; use std::{env, fs}; fn main() { /* This makes panic! pretty */ // setup_panic!(); /* Define our CLI App */ let m = cli::create().get_matches(); /* In this block we can unwrap quite viciously because clap will protect us */ match m.subcommand() { ("setup", Some(m)) => handle_setup(m), ("load", Some(m)) => handle_load(m), ("generate", Some(m)) => handle_generate(m), _ => println!("Missing arguments: type `poke --help` for more help!"), } } fn
(matches: &ArgMatches) { if!ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap(), &format!("{}_local", name), ); ssh::send_key( ssh::get_directory() .join(&format!("{}_local.pub", &name)) .to_str() .unwrap(), &addr, ); } fn handle_setup(matches: &ArgMatches) { let ks_path = String::from(matches.value_of("path").unwrap()); /* Either create or load existing config */ let mut cfg = Config::load().unwrap_or_else(|| Config::create_empty()); cfg.if_no_keystore(|| { let cont = Question::new("Keystore already registered. Change location?") .default(Answer::NO) .show_defaults() .confirm(); if cont == Answer::NO { println!("Aborting re-setup!"); process::exit(2); } }); /* Set the new keystore path & sync */ cfg.set_keystore(&ks_path); cfg.sync(); /* Get a desired user password */ let pass = rpassword::prompt_password_stdout("Set a keystore password: ").unwrap(); let pass_confirm = rpassword::prompt_password_stdout("Confirm the password: ").unwrap(); if pass!= pass_confirm { eprintln!("{}", "The two passwords did not match!".red()); process::exit(2); } let pub_path = keywoman::generate_root(ks_path, pass); /* Print about our success */ println!(""); println!("{}", "✨ A new keystore was generated for you ✨".green()); println!("Your root public key can be found here: '{}'", pub_path); } fn handle_load(matches: &ArgMatches) {}
handle_generate
identifier_name
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use config::Config; use clap::ArgMatches; use colored::*; use question::{Answer, Question}; use std::process; use std::{env, fs}; fn main() { /* This makes panic! pretty */ // setup_panic!(); /* Define our CLI App */ let m = cli::create().get_matches(); /* In this block we can unwrap quite viciously because clap will protect us */ match m.subcommand() { ("setup", Some(m)) => handle_setup(m), ("load", Some(m)) => handle_load(m), ("generate", Some(m)) => handle_generate(m), _ => println!("Missing arguments: type `poke --help` for more help!"), } } fn handle_generate(matches: &ArgMatches) { if!ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap(), &format!("{}_local", name), ); ssh::send_key( ssh::get_directory() .join(&format!("{}_local.pub", &name)) .to_str() .unwrap(), &addr, ); } fn handle_setup(matches: &ArgMatches) { let ks_path = String::from(matches.value_of("path").unwrap()); /* Either create or load existing config */ let mut cfg = Config::load().unwrap_or_else(|| Config::create_empty()); cfg.if_no_keystore(|| { let cont = Question::new("Keystore already registered. Change location?") .default(Answer::NO) .show_defaults() .confirm(); if cont == Answer::NO { println!("Aborting re-setup!"); process::exit(2); } }); /* Set the new keystore path & sync */ cfg.set_keystore(&ks_path); cfg.sync(); /* Get a desired user password */ let pass = rpassword::prompt_password_stdout("Set a keystore password: ").unwrap(); let pass_confirm = rpassword::prompt_password_stdout("Confirm the password: ").unwrap(); if pass!= pass_confirm
let pub_path = keywoman::generate_root(ks_path, pass); /* Print about our success */ println!(""); println!("{}", "✨ A new keystore was generated for you ✨".green()); println!("Your root public key can be found here: '{}'", pub_path); } fn handle_load(matches: &ArgMatches) {}
{ eprintln!("{}", "The two passwords did not match!".red()); process::exit(2); }
conditional_block
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use config::Config; use clap::ArgMatches; use colored::*; use question::{Answer, Question}; use std::process; use std::{env, fs}; fn main()
fn handle_generate(matches: &ArgMatches) { if!ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap(), &format!("{}_local", name), ); ssh::send_key( ssh::get_directory() .join(&format!("{}_local.pub", &name)) .to_str() .unwrap(), &addr, ); } fn handle_setup(matches: &ArgMatches) { let ks_path = String::from(matches.value_of("path").unwrap()); /* Either create or load existing config */ let mut cfg = Config::load().unwrap_or_else(|| Config::create_empty()); cfg.if_no_keystore(|| { let cont = Question::new("Keystore already registered. Change location?") .default(Answer::NO) .show_defaults() .confirm(); if cont == Answer::NO { println!("Aborting re-setup!"); process::exit(2); } }); /* Set the new keystore path & sync */ cfg.set_keystore(&ks_path); cfg.sync(); /* Get a desired user password */ let pass = rpassword::prompt_password_stdout("Set a keystore password: ").unwrap(); let pass_confirm = rpassword::prompt_password_stdout("Confirm the password: ").unwrap(); if pass!= pass_confirm { eprintln!("{}", "The two passwords did not match!".red()); process::exit(2); } let pub_path = keywoman::generate_root(ks_path, pass); /* Print about our success */ println!(""); println!("{}", "✨ A new keystore was generated for you ✨".green()); println!("Your root public key can be found here: '{}'", pub_path); } fn handle_load(matches: &ArgMatches) {}
{ /* This makes panic! pretty */ // setup_panic!(); /* Define our CLI App */ let m = cli::create().get_matches(); /* In this block we can unwrap quite viciously because clap will protect us */ match m.subcommand() { ("setup", Some(m)) => handle_setup(m), ("load", Some(m)) => handle_load(m), ("generate", Some(m)) => handle_generate(m), _ => println!("Missing arguments: type `poke --help` for more help!"), } }
identifier_body
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied(x) if x.role() == Some(role) => return c, x => println!("{:?} doesn't match desired role ({:?})", x, role), } } } pub fn
() -> Coordinate { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let row: u8 = match input.trim().parse() { Ok(r) if r <= 14 => r, _ => { println!("bad row"); continue; } }; input.clear(); print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let col: u8 = match input.trim().parse() { Ok(c) if c <= 14 => c, _ => { println!("bad col"); continue; } }; match Coordinate::new(row, col) { None => { println!("coordinate out of playable range"); continue; } Some(c) => return c, } } } // pub fn write_search_graph(graph: &mcts::ThudGraph, state: &ThudState) { // println!("to play: {:?}", state.active_role()); // match graph.get_node(state) { // None => println!("no matching node for game state"), // Some(node) => { // write_board(state.cells()); // write_node_tree(&node, 0, &mut HashSet::new()); // }, // } // } // fn write_node_tree<'a>(n: &mcts::ThudNode<'a>, indentation_level: usize, visited_nodes: &mut HashSet<usize>) { // if visited_nodes.insert(n.get_id()) { // let children = n.get_child_list(); // for i in 0..children.len() { // let e = children.get_edge(i); // let edge_data = e.get_data(); // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // print!("{}: {:?}: {:?}--", e.get_id(), edge_data.action, edge_data.statistics); // let target = children.get_edge(i).get_target(); // println!("{}", target.get_id()); // write_node_tree(&target, indentation_level + 1, visited_nodes); // } // } else { // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // println!("Printed ({})", n.get_id()); // } // } pub fn select_one<'a, T>(items: &'a [T]) -> Option<&'a T> where T: fmt::Debug, { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); for (i, item) in items.iter().enumerate() { println!("{}) {:?}", i, item); } print!("select? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); input .trim() .parse::<usize>() .ok() .and_then(|i| items.get(i)) }
read_coordinate
identifier_name
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied(x) if x.role() == Some(role) => return c, x => println!("{:?} doesn't match desired role ({:?})", x, role), } } } pub fn read_coordinate() -> Coordinate { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let row: u8 = match input.trim().parse() { Ok(r) if r <= 14 => r, _ => { println!("bad row"); continue; } }; input.clear(); print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let col: u8 = match input.trim().parse() { Ok(c) if c <= 14 => c, _ =>
}; match Coordinate::new(row, col) { None => { println!("coordinate out of playable range"); continue; } Some(c) => return c, } } } // pub fn write_search_graph(graph: &mcts::ThudGraph, state: &ThudState) { // println!("to play: {:?}", state.active_role()); // match graph.get_node(state) { // None => println!("no matching node for game state"), // Some(node) => { // write_board(state.cells()); // write_node_tree(&node, 0, &mut HashSet::new()); // }, // } // } // fn write_node_tree<'a>(n: &mcts::ThudNode<'a>, indentation_level: usize, visited_nodes: &mut HashSet<usize>) { // if visited_nodes.insert(n.get_id()) { // let children = n.get_child_list(); // for i in 0..children.len() { // let e = children.get_edge(i); // let edge_data = e.get_data(); // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // print!("{}: {:?}: {:?}--", e.get_id(), edge_data.action, edge_data.statistics); // let target = children.get_edge(i).get_target(); // println!("{}", target.get_id()); // write_node_tree(&target, indentation_level + 1, visited_nodes); // } // } else { // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // println!("Printed ({})", n.get_id()); // } // } pub fn select_one<'a, T>(items: &'a [T]) -> Option<&'a T> where T: fmt::Debug, { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); for (i, item) in items.iter().enumerate() { println!("{}) {:?}", i, item); } print!("select? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); input .trim() .parse::<usize>() .ok() .and_then(|i| items.get(i)) }
{ println!("bad col"); continue; }
conditional_block
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied(x) if x.role() == Some(role) => return c, x => println!("{:?} doesn't match desired role ({:?})", x, role), } } } pub fn read_coordinate() -> Coordinate
print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let col: u8 = match input.trim().parse() { Ok(c) if c <= 14 => c, _ => { println!("bad col"); continue; } }; match Coordinate::new(row, col) { None => { println!("coordinate out of playable range"); continue; } Some(c) => return c, } } } // pub fn write_search_graph(graph: &mcts::ThudGraph, state: &ThudState) { // println!("to play: {:?}", state.active_role()); // match graph.get_node(state) { // None => println!("no matching node for game state"), // Some(node) => { // write_board(state.cells()); // write_node_tree(&node, 0, &mut HashSet::new()); // }, // } // } // fn write_node_tree<'a>(n: &mcts::ThudNode<'a>, indentation_level: usize, visited_nodes: &mut HashSet<usize>) { // if visited_nodes.insert(n.get_id()) { // let children = n.get_child_list(); // for i in 0..children.len() { // let e = children.get_edge(i); // let edge_data = e.get_data(); // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // print!("{}: {:?}: {:?}--", e.get_id(), edge_data.action, edge_data.statistics); // let target = children.get_edge(i).get_target(); // println!("{}", target.get_id()); // write_node_tree(&target, indentation_level + 1, visited_nodes); // } // } else { // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // println!("Printed ({})", n.get_id()); // } // } pub fn select_one<'a, T>(items: &'a [T]) -> Option<&'a T> where T: fmt::Debug, { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); for (i, item) in items.iter().enumerate() { println!("{}) {:?}", i, item); } print!("select? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); input .trim() .parse::<usize>() .ok() .and_then(|i| items.get(i)) }
{ let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let row: u8 = match input.trim().parse() { Ok(r) if r <= 14 => r, _ => { println!("bad row"); continue; } }; input.clear();
identifier_body
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied(x) if x.role() == Some(role) => return c, x => println!("{:?} doesn't match desired role ({:?})", x, role), } } } pub fn read_coordinate() -> Coordinate { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? ");
.expect("could not read from stdin"); let row: u8 = match input.trim().parse() { Ok(r) if r <= 14 => r, _ => { println!("bad row"); continue; } }; input.clear(); print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let col: u8 = match input.trim().parse() { Ok(c) if c <= 14 => c, _ => { println!("bad col"); continue; } }; match Coordinate::new(row, col) { None => { println!("coordinate out of playable range"); continue; } Some(c) => return c, } } } // pub fn write_search_graph(graph: &mcts::ThudGraph, state: &ThudState) { // println!("to play: {:?}", state.active_role()); // match graph.get_node(state) { // None => println!("no matching node for game state"), // Some(node) => { // write_board(state.cells()); // write_node_tree(&node, 0, &mut HashSet::new()); // }, // } // } // fn write_node_tree<'a>(n: &mcts::ThudNode<'a>, indentation_level: usize, visited_nodes: &mut HashSet<usize>) { // if visited_nodes.insert(n.get_id()) { // let children = n.get_child_list(); // for i in 0..children.len() { // let e = children.get_edge(i); // let edge_data = e.get_data(); // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // print!("{}: {:?}: {:?}--", e.get_id(), edge_data.action, edge_data.statistics); // let target = children.get_edge(i).get_target(); // println!("{}", target.get_id()); // write_node_tree(&target, indentation_level + 1, visited_nodes); // } // } else { // print!("+"); // for _ in 0..(indentation_level + 1) { // print!("-"); // } // println!("Printed ({})", n.get_id()); // } // } pub fn select_one<'a, T>(items: &'a [T]) -> Option<&'a T> where T: fmt::Debug, { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); for (i, item) in items.iter().enumerate() { println!("{}) {:?}", i, item); } print!("select? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); input .trim() .parse::<usize>() .ok() .and_then(|i| items.get(i)) }
stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok()
random_line_split
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print *the_a_ref // gdb-check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // gdb-command:print *the_b_ref // gdb-check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // gdb-command:print *univariant_ref // gdb-check:$3 = {{4820353753753434}} #![allow(unused_variable)] #![feature(struct_variant)] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz(); } fn zzz() {()}
// http://rust-lang.org/COPYRIGHT.
random_line_split
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print *the_a_ref // gdb-check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // gdb-command:print *the_b_ref // gdb-check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // gdb-command:print *univariant_ref // gdb-check:$3 = {{4820353753753434}} #![allow(unused_variable)] #![feature(struct_variant)] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main()
} fn zzz() {()}
{ // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz();
identifier_body
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print *the_a_ref // gdb-check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // gdb-command:print *the_b_ref // gdb-check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // gdb-command:print *univariant_ref // gdb-check:$3 = {{4820353753753434}} #![allow(unused_variable)] #![feature(struct_variant)] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz(); } fn
() {()}
zzz
identifier_name
macros.rs
// Most of our lookups follow the same pattern - macro out the repetition. macro_rules! ares_call { ( $ares_call:ident, $channel:expr, $name:expr, $dns_class:expr, $query_type:expr, $callback:expr, $handler:expr ) => {{ let c_name = CString::new($name).unwrap(); let c_arg = Box::into_raw(Box::new($handler)); unsafe { c_ares_sys::$ares_call(
$dns_class as c_int, $query_type as c_int, Some($callback), c_arg as *mut c_void, ); } panic::propagate(); }}; } macro_rules! ares_query { ($($arg:tt)*) => { ares_call!(ares_query, $($arg)*) } } macro_rules! ares_search { ($($arg:tt)*) => { ares_call!(ares_search, $($arg)*) } } // Most of our `ares_callback` implementations are much the same - macro out the repetition. macro_rules! ares_callback { ($arg:expr, $status:expr, $abuf:expr, $alen:expr, $parser:expr) => {{ panic::catch(|| { let result = if $status == c_ares_sys::ARES_SUCCESS { let data = slice::from_raw_parts($abuf, $alen as usize); $parser(data) } else { Err(Error::from($status)) }; let handler = Box::from_raw($arg); handler(result); }); }}; }
$channel, c_name.as_ptr(),
random_line_split
lib.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. //! Simple ANSI color library #![crate_id = "term#0.10"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] #![feature(macro_rules)] #![deny(missing_doc)] extern crate collections; use std::io; use std::os; use terminfo::TermInfo; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; pub mod terminfo; // FIXME (#2807): Windows support. /// Terminal color definitions pub mod color { /// Number for a terminal color pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16; pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; } /// Terminal attributes pub mod attr { /// Terminal attributes for use with term.attr(). /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(super::color::Color), /// Convenience attribute to set the background color BackgroundColor(super::color::Color) } } fn cap_for_attr(attr: attr::Attr) -> &'static str { match attr { attr::Bold => "bold", attr::Dim => "dim", attr::Italic(true) => "sitm", attr::Italic(false) => "ritm", attr::Underline(true) => "smul", attr::Underline(false) => "rmul", attr::Blink => "blink", attr::Standout(true) => "smso", attr::Standout(false) => "rmso", attr::Reverse => "rev", attr::Secure => "invis", attr::ForegroundColor(_) => "setaf", attr::BackgroundColor(_) => "setab" } } /// A Terminal that knows how many colors it supports, with a reference to its /// parsed TermInfo database record. pub struct Terminal<T> { priv num_colors: u16, priv out: T, priv ti: ~TermInfo } impl<T: Writer> Terminal<T> { /// Returns a wrapped output stream (`Terminal<T>`) as a `Result`. /// /// Returns `Err()` if the TERM environment variable is undefined. /// TERM should be set to something like `xterm-color` or `screen-256color`. /// /// Returns `Err()` on failure to open the terminfo database correctly. /// Also, in the event that the individual terminfo database entry can not /// be parsed. pub fn new(out: T) -> Result<Terminal<T>, ~str> { let term = match os::getenv("TERM") { Some(t) => t, None => return Err(~"TERM environment variable undefined") }; let entry = open(term); if entry.is_err() { if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); } let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc}); } /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn fg(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setaf")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn
(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setab")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the given terminal attribute, if supported. /// Returns `Ok(true)` if the attribute was supported, `Ok(false)` otherwise, /// and `Err(e)` if there was an I/O error. pub fn attr(&mut self, attr: attr::Attr) -> io::IoResult<bool> { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { let s = expand(parm.unwrap().as_slice(), [], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } } } /// Returns whether the given terminal attribute is supported. pub fn supports_attr(&self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => { self.num_colors > 0 } _ => { let cap = cap_for_attr(attr); self.ti.strings.find_equiv(&cap).is_some() } } } /// Resets all terminal attributes and color to the default. /// Returns `Ok()`. pub fn reset(&mut self) -> io::IoResult<()> { let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap = self.ti.strings.find_equiv(&("op")); } } let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| { expand(op.as_slice(), [], &mut Variables::new()) }); if s.is_ok() { return self.out.write(s.unwrap().as_slice()) } Ok(()) } fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else { color } } /// Returns the contained stream pub fn unwrap(self) -> T { self.out } /// Gets an immutable reference to the stream inside pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } /// Gets a mutable reference to the stream inside pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } impl<T: Writer> Writer for Terminal<T> { fn write(&mut self, buf: &[u8]) -> io::IoResult<()> { self.out.write(buf) } fn flush(&mut self) -> io::IoResult<()> { self.out.flush() } }
bg
identifier_name
lib.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. //! Simple ANSI color library #![crate_id = "term#0.10"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] #![feature(macro_rules)] #![deny(missing_doc)] extern crate collections; use std::io; use std::os; use terminfo::TermInfo; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; pub mod terminfo; // FIXME (#2807): Windows support. /// Terminal color definitions pub mod color { /// Number for a terminal color pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16; pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; } /// Terminal attributes pub mod attr { /// Terminal attributes for use with term.attr(). /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(super::color::Color), /// Convenience attribute to set the background color BackgroundColor(super::color::Color) } } fn cap_for_attr(attr: attr::Attr) -> &'static str { match attr { attr::Bold => "bold", attr::Dim => "dim", attr::Italic(true) => "sitm", attr::Italic(false) => "ritm", attr::Underline(true) => "smul", attr::Underline(false) => "rmul", attr::Blink => "blink", attr::Standout(true) => "smso", attr::Standout(false) => "rmso", attr::Reverse => "rev", attr::Secure => "invis", attr::ForegroundColor(_) => "setaf", attr::BackgroundColor(_) => "setab" } } /// A Terminal that knows how many colors it supports, with a reference to its /// parsed TermInfo database record. pub struct Terminal<T> { priv num_colors: u16, priv out: T, priv ti: ~TermInfo } impl<T: Writer> Terminal<T> { /// Returns a wrapped output stream (`Terminal<T>`) as a `Result`. /// /// Returns `Err()` if the TERM environment variable is undefined. /// TERM should be set to something like `xterm-color` or `screen-256color`. /// /// Returns `Err()` on failure to open the terminfo database correctly. /// Also, in the event that the individual terminfo database entry can not /// be parsed. pub fn new(out: T) -> Result<Terminal<T>, ~str> { let term = match os::getenv("TERM") { Some(t) => t, None => return Err(~"TERM environment variable undefined") }; let entry = open(term); if entry.is_err() { if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); }
if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc}); } /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn fg(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setaf")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn bg(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setab")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the given terminal attribute, if supported. /// Returns `Ok(true)` if the attribute was supported, `Ok(false)` otherwise, /// and `Err(e)` if there was an I/O error. pub fn attr(&mut self, attr: attr::Attr) -> io::IoResult<bool> { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { let s = expand(parm.unwrap().as_slice(), [], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } } } /// Returns whether the given terminal attribute is supported. pub fn supports_attr(&self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => { self.num_colors > 0 } _ => { let cap = cap_for_attr(attr); self.ti.strings.find_equiv(&cap).is_some() } } } /// Resets all terminal attributes and color to the default. /// Returns `Ok()`. pub fn reset(&mut self) -> io::IoResult<()> { let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap = self.ti.strings.find_equiv(&("op")); } } let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| { expand(op.as_slice(), [], &mut Variables::new()) }); if s.is_ok() { return self.out.write(s.unwrap().as_slice()) } Ok(()) } fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else { color } } /// Returns the contained stream pub fn unwrap(self) -> T { self.out } /// Gets an immutable reference to the stream inside pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } /// Gets a mutable reference to the stream inside pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } impl<T: Writer> Writer for Terminal<T> { fn write(&mut self, buf: &[u8]) -> io::IoResult<()> { self.out.write(buf) } fn flush(&mut self) -> io::IoResult<()> { self.out.flush() } }
let mut file = entry.unwrap(); let ti = parse(&mut file, false);
random_line_split
lib.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. //! Simple ANSI color library #![crate_id = "term#0.10"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] #![feature(macro_rules)] #![deny(missing_doc)] extern crate collections; use std::io; use std::os; use terminfo::TermInfo; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; pub mod terminfo; // FIXME (#2807): Windows support. /// Terminal color definitions pub mod color { /// Number for a terminal color pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16; pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; } /// Terminal attributes pub mod attr { /// Terminal attributes for use with term.attr(). /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(super::color::Color), /// Convenience attribute to set the background color BackgroundColor(super::color::Color) } } fn cap_for_attr(attr: attr::Attr) -> &'static str { match attr { attr::Bold => "bold", attr::Dim => "dim", attr::Italic(true) => "sitm", attr::Italic(false) => "ritm", attr::Underline(true) => "smul", attr::Underline(false) => "rmul", attr::Blink => "blink", attr::Standout(true) => "smso", attr::Standout(false) => "rmso", attr::Reverse => "rev", attr::Secure => "invis", attr::ForegroundColor(_) => "setaf", attr::BackgroundColor(_) => "setab" } } /// A Terminal that knows how many colors it supports, with a reference to its /// parsed TermInfo database record. pub struct Terminal<T> { priv num_colors: u16, priv out: T, priv ti: ~TermInfo } impl<T: Writer> Terminal<T> { /// Returns a wrapped output stream (`Terminal<T>`) as a `Result`. /// /// Returns `Err()` if the TERM environment variable is undefined. /// TERM should be set to something like `xterm-color` or `screen-256color`. /// /// Returns `Err()` on failure to open the terminfo database correctly. /// Also, in the event that the individual terminfo database entry can not /// be parsed. pub fn new(out: T) -> Result<Terminal<T>, ~str> { let term = match os::getenv("TERM") { Some(t) => t, None => return Err(~"TERM environment variable undefined") }; let entry = open(term); if entry.is_err() { if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); } let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc}); } /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn fg(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setaf")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn bg(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setab")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the given terminal attribute, if supported. /// Returns `Ok(true)` if the attribute was supported, `Ok(false)` otherwise, /// and `Err(e)` if there was an I/O error. pub fn attr(&mut self, attr: attr::Attr) -> io::IoResult<bool> { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { let s = expand(parm.unwrap().as_slice(), [], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } } } /// Returns whether the given terminal attribute is supported. pub fn supports_attr(&self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => { self.num_colors > 0 } _ => { let cap = cap_for_attr(attr); self.ti.strings.find_equiv(&cap).is_some() } } } /// Resets all terminal attributes and color to the default. /// Returns `Ok()`. pub fn reset(&mut self) -> io::IoResult<()>
fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else { color } } /// Returns the contained stream pub fn unwrap(self) -> T { self.out } /// Gets an immutable reference to the stream inside pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } /// Gets a mutable reference to the stream inside pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } impl<T: Writer> Writer for Terminal<T> { fn write(&mut self, buf: &[u8]) -> io::IoResult<()> { self.out.write(buf) } fn flush(&mut self) -> io::IoResult<()> { self.out.flush() } }
{ let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap = self.ti.strings.find_equiv(&("op")); } } let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| { expand(op.as_slice(), [], &mut Variables::new()) }); if s.is_ok() { return self.out.write(s.unwrap().as_slice()) } Ok(()) }
identifier_body
lib.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. //! Simple ANSI color library #![crate_id = "term#0.10"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] #![feature(macro_rules)] #![deny(missing_doc)] extern crate collections; use std::io; use std::os; use terminfo::TermInfo; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; pub mod terminfo; // FIXME (#2807): Windows support. /// Terminal color definitions pub mod color { /// Number for a terminal color pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16; pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; } /// Terminal attributes pub mod attr { /// Terminal attributes for use with term.attr(). /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(super::color::Color), /// Convenience attribute to set the background color BackgroundColor(super::color::Color) } } fn cap_for_attr(attr: attr::Attr) -> &'static str { match attr { attr::Bold => "bold", attr::Dim => "dim", attr::Italic(true) => "sitm", attr::Italic(false) => "ritm", attr::Underline(true) => "smul", attr::Underline(false) => "rmul", attr::Blink => "blink", attr::Standout(true) => "smso", attr::Standout(false) => "rmso", attr::Reverse => "rev", attr::Secure => "invis", attr::ForegroundColor(_) => "setaf", attr::BackgroundColor(_) => "setab" } } /// A Terminal that knows how many colors it supports, with a reference to its /// parsed TermInfo database record. pub struct Terminal<T> { priv num_colors: u16, priv out: T, priv ti: ~TermInfo } impl<T: Writer> Terminal<T> { /// Returns a wrapped output stream (`Terminal<T>`) as a `Result`. /// /// Returns `Err()` if the TERM environment variable is undefined. /// TERM should be set to something like `xterm-color` or `screen-256color`. /// /// Returns `Err()` on failure to open the terminfo database correctly. /// Also, in the event that the individual terminfo database entry can not /// be parsed. pub fn new(out: T) -> Result<Terminal<T>, ~str> { let term = match os::getenv("TERM") { Some(t) => t, None => return Err(~"TERM environment variable undefined") }; let entry = open(term); if entry.is_err()
let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc}); } /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn fg(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setaf")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. pub fn bg(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setab")) .unwrap() .as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } /// Sets the given terminal attribute, if supported. /// Returns `Ok(true)` if the attribute was supported, `Ok(false)` otherwise, /// and `Err(e)` if there was an I/O error. pub fn attr(&mut self, attr: attr::Attr) -> io::IoResult<bool> { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { let s = expand(parm.unwrap().as_slice(), [], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } } } /// Returns whether the given terminal attribute is supported. pub fn supports_attr(&self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => { self.num_colors > 0 } _ => { let cap = cap_for_attr(attr); self.ti.strings.find_equiv(&cap).is_some() } } } /// Resets all terminal attributes and color to the default. /// Returns `Ok()`. pub fn reset(&mut self) -> io::IoResult<()> { let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap = self.ti.strings.find_equiv(&("op")); } } let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| { expand(op.as_slice(), [], &mut Variables::new()) }); if s.is_ok() { return self.out.write(s.unwrap().as_slice()) } Ok(()) } fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else { color } } /// Returns the contained stream pub fn unwrap(self) -> T { self.out } /// Gets an immutable reference to the stream inside pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } /// Gets a mutable reference to the stream inside pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } impl<T: Writer> Writer for Terminal<T> { fn write(&mut self, buf: &[u8]) -> io::IoResult<()> { self.out.write(buf) } fn flush(&mut self) -> io::IoResult<()> { self.out.flush() } }
{ if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); }
conditional_block
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ------------------------------------------------------ pub struct Action { message: Message } impl Action { pub fn new(message: Message) -> Box<Action> { Box::new(Action { message: message }) } } impl ActionHandler for Action { fn
(&mut self, bot: &mut Bot, _: &BotConfig, _: &mut EventQueue) -> ActionGroup { if let Some(server) = bot.get_server(&self.message.server_id) { server.silence_active_effects() } vec![] } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [SilenceActiveEffects] Server #{}", self.message.server_id ) } }
run
identifier_name
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ------------------------------------------------------ pub struct Action { message: Message } impl Action { pub fn new(message: Message) -> Box<Action> { Box::new(Action { message: message }) } } impl ActionHandler for Action { fn run(&mut self, bot: &mut Bot, _: &BotConfig, _: &mut EventQueue) -> ActionGroup { if let Some(server) = bot.get_server(&self.message.server_id)
vec![] } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [SilenceActiveEffects] Server #{}", self.message.server_id ) } }
{ server.silence_active_effects() }
conditional_block
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt;
// Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ------------------------------------------------------ pub struct Action { message: Message } impl Action { pub fn new(message: Message) -> Box<Action> { Box::new(Action { message: message }) } } impl ActionHandler for Action { fn run(&mut self, bot: &mut Bot, _: &BotConfig, _: &mut EventQueue) -> ActionGroup { if let Some(server) = bot.get_server(&self.message.server_id) { server.silence_active_effects() } vec![] } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [SilenceActiveEffects] Server #{}", self.message.server_id ) } }
random_line_split
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::ExtendableEventBinding; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::event::Event; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; use js::jsapi::JSContext; use js::rust::HandleValue; use servo_atoms::Atom; // https://w3c.github.io/ServiceWorker/#extendable-event #[dom_struct] pub struct ExtendableEvent { event: Event, extensions_allowed: bool } impl ExtendableEvent { pub fn new_inherited() -> ExtendableEvent { ExtendableEvent { event: Event::new_inherited(), extensions_allowed: true } } pub fn new(worker: &ServiceWorkerGlobalScope, type_: Atom, bubbles: bool, cancelable: bool) -> DomRoot<ExtendableEvent> { let ev = reflect_dom_object( Box::new(ExtendableEvent::new_inherited()), worker, ExtendableEventBinding::Wrap ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor(worker: &ServiceWorkerGlobalScope, type_: DOMString, init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<DomRoot<ExtendableEvent>> { Ok(ExtendableEvent::new(worker, Atom::from(type_), init.parent.bubbles, init.parent.cancelable)) } // https://w3c.github.io/ServiceWorker/#wait-until-method pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { // Step 1 if!self.extensions_allowed { return Err(Error::InvalidState); } // Step 2 // TODO add a extended_promises array to enqueue the `val` Ok(()) } // https://dom.spec.whatwg.org/#dom-event-istrusted pub fn IsTrusted(&self) -> bool { self.event.IsTrusted() } } impl Default for ExtendableEventBinding::ExtendableEventInit { fn
() -> ExtendableEventBinding::ExtendableEventInit { ExtendableEventBinding::ExtendableEventInit { parent: EventBinding::EventInit::default(), } } }
default
identifier_name
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::ExtendableEventBinding; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::event::Event; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; use js::jsapi::JSContext; use js::rust::HandleValue; use servo_atoms::Atom; // https://w3c.github.io/ServiceWorker/#extendable-event #[dom_struct] pub struct ExtendableEvent { event: Event, extensions_allowed: bool } impl ExtendableEvent { pub fn new_inherited() -> ExtendableEvent { ExtendableEvent { event: Event::new_inherited(), extensions_allowed: true } } pub fn new(worker: &ServiceWorkerGlobalScope, type_: Atom, bubbles: bool, cancelable: bool) -> DomRoot<ExtendableEvent> { let ev = reflect_dom_object( Box::new(ExtendableEvent::new_inherited()), worker, ExtendableEventBinding::Wrap ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor(worker: &ServiceWorkerGlobalScope, type_: DOMString, init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<DomRoot<ExtendableEvent>> { Ok(ExtendableEvent::new(worker, Atom::from(type_), init.parent.bubbles, init.parent.cancelable)) } // https://w3c.github.io/ServiceWorker/#wait-until-method pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { // Step 1 if!self.extensions_allowed
// Step 2 // TODO add a extended_promises array to enqueue the `val` Ok(()) } // https://dom.spec.whatwg.org/#dom-event-istrusted pub fn IsTrusted(&self) -> bool { self.event.IsTrusted() } } impl Default for ExtendableEventBinding::ExtendableEventInit { fn default() -> ExtendableEventBinding::ExtendableEventInit { ExtendableEventBinding::ExtendableEventInit { parent: EventBinding::EventInit::default(), } } }
{ return Err(Error::InvalidState); }
conditional_block
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::ExtendableEventBinding; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::event::Event; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; use js::jsapi::JSContext; use js::rust::HandleValue; use servo_atoms::Atom; // https://w3c.github.io/ServiceWorker/#extendable-event #[dom_struct] pub struct ExtendableEvent { event: Event, extensions_allowed: bool } impl ExtendableEvent { pub fn new_inherited() -> ExtendableEvent { ExtendableEvent { event: Event::new_inherited(), extensions_allowed: true } } pub fn new(worker: &ServiceWorkerGlobalScope, type_: Atom, bubbles: bool, cancelable: bool) -> DomRoot<ExtendableEvent> { let ev = reflect_dom_object( Box::new(ExtendableEvent::new_inherited()), worker, ExtendableEventBinding::Wrap ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor(worker: &ServiceWorkerGlobalScope, type_: DOMString, init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<DomRoot<ExtendableEvent>> { Ok(ExtendableEvent::new(worker, Atom::from(type_), init.parent.bubbles, init.parent.cancelable)) } // https://w3c.github.io/ServiceWorker/#wait-until-method pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { // Step 1 if!self.extensions_allowed { return Err(Error::InvalidState); } // Step 2 // TODO add a extended_promises array to enqueue the `val` Ok(()) } // https://dom.spec.whatwg.org/#dom-event-istrusted pub fn IsTrusted(&self) -> bool { self.event.IsTrusted() } } impl Default for ExtendableEventBinding::ExtendableEventInit { fn default() -> ExtendableEventBinding::ExtendableEventInit { ExtendableEventBinding::ExtendableEventInit { parent: EventBinding::EventInit::default(),
} }
}
random_line_split
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::ExtendableEventBinding; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::event::Event; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; use js::jsapi::JSContext; use js::rust::HandleValue; use servo_atoms::Atom; // https://w3c.github.io/ServiceWorker/#extendable-event #[dom_struct] pub struct ExtendableEvent { event: Event, extensions_allowed: bool } impl ExtendableEvent { pub fn new_inherited() -> ExtendableEvent { ExtendableEvent { event: Event::new_inherited(), extensions_allowed: true } } pub fn new(worker: &ServiceWorkerGlobalScope, type_: Atom, bubbles: bool, cancelable: bool) -> DomRoot<ExtendableEvent> { let ev = reflect_dom_object( Box::new(ExtendableEvent::new_inherited()), worker, ExtendableEventBinding::Wrap ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor(worker: &ServiceWorkerGlobalScope, type_: DOMString, init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<DomRoot<ExtendableEvent>>
// https://w3c.github.io/ServiceWorker/#wait-until-method pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { // Step 1 if!self.extensions_allowed { return Err(Error::InvalidState); } // Step 2 // TODO add a extended_promises array to enqueue the `val` Ok(()) } // https://dom.spec.whatwg.org/#dom-event-istrusted pub fn IsTrusted(&self) -> bool { self.event.IsTrusted() } } impl Default for ExtendableEventBinding::ExtendableEventInit { fn default() -> ExtendableEventBinding::ExtendableEventInit { ExtendableEventBinding::ExtendableEventInit { parent: EventBinding::EventInit::default(), } } }
{ Ok(ExtendableEvent::new(worker, Atom::from(type_), init.parent.bubbles, init.parent.cancelable)) }
identifier_body
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T])
// Skip NaNs already in place while rnan > 0 && v[rnan].is_nan() { rnan -= 1; } let mut p = rnan; while p > 0 { p -= 1; if v[p].is_nan() { v.swap(p, rnan); rnan -= 1; } } // Sort the non-NaN part with efficient comparisons sort_by(&mut v[..rnan + 1], &|x: &T, y: &T| unsafe { x.partial_cmp(y).unchecked_unwrap() }); let left = find_first_zero(&v[..rnan + 1]); // Count zeros of each type and then fill them in in the right order let mut zeros = 0; let mut neg_zeros = 0; for x in v[left..].iter() { if *x!= zero() { break; } if x.is_sign_negative() { neg_zeros += 1; } else { zeros += 1; } } for x in v[left..].iter_mut() { if neg_zeros > 0 { *x = Float::neg_zero(); neg_zeros -= 1; } else if zeros > 0 { *x = zero(); zeros -= 1; } else { break; } } } /// Find the first zero in `v`. /// If there is no zero, it return v.len() - 1 fn find_first_zero<T: Float>(v: &[T]) -> usize { if v.len() == 0 { return 0; } let mut hi = v.len() - 1; let mut left = 0; while left < hi { let mid = ((hi - left) / 2) + left; if v[mid] < zero() { left = mid + 1; } else { hi = mid; } } while left < v.len() && v[left] < zero() { left += 1; } return left; }
{ /* * We don't have hardware support for a total order on floats. NaN is not * smaller or greater than any number. We want NaNs to be last, so we could * just use is_nan() in the comparison function. It turns out that this hurts * performance a lot, and in most cases we probably don't have any NaNs anyway. * * The solution is to first move all NaNs to the end of the array, and then * sort the remainder with efficient comparisons. After sorting, the zeros * might be in the wrong order since -0 and 0 compare equal. We want * -0 to be sorted before 0. We binary search to find the interval containing * all zeros and perform a counting sort on it. */ if v.len() <= 1 { return; } // First we move all NaNs to the end let mut rnan = v.len() - 1;
identifier_body
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T]) { /* * We don't have hardware support for a total order on floats. NaN is not * smaller or greater than any number. We want NaNs to be last, so we could * just use is_nan() in the comparison function. It turns out that this hurts * performance a lot, and in most cases we probably don't have any NaNs anyway. * * The solution is to first move all NaNs to the end of the array, and then * sort the remainder with efficient comparisons. After sorting, the zeros * might be in the wrong order since -0 and 0 compare equal. We want * -0 to be sorted before 0. We binary search to find the interval containing * all zeros and perform a counting sort on it. */ if v.len() <= 1 { return; } // First we move all NaNs to the end let mut rnan = v.len() - 1; // Skip NaNs already in place while rnan > 0 && v[rnan].is_nan() { rnan -= 1; } let mut p = rnan; while p > 0 { p -= 1; if v[p].is_nan() { v.swap(p, rnan); rnan -= 1; } } // Sort the non-NaN part with efficient comparisons sort_by(&mut v[..rnan + 1], &|x: &T, y: &T| unsafe { x.partial_cmp(y).unchecked_unwrap() }); let left = find_first_zero(&v[..rnan + 1]);
for x in v[left..].iter() { if *x!= zero() { break; } if x.is_sign_negative() { neg_zeros += 1; } else { zeros += 1; } } for x in v[left..].iter_mut() { if neg_zeros > 0 { *x = Float::neg_zero(); neg_zeros -= 1; } else if zeros > 0 { *x = zero(); zeros -= 1; } else { break; } } } /// Find the first zero in `v`. /// If there is no zero, it return v.len() - 1 fn find_first_zero<T: Float>(v: &[T]) -> usize { if v.len() == 0 { return 0; } let mut hi = v.len() - 1; let mut left = 0; while left < hi { let mid = ((hi - left) / 2) + left; if v[mid] < zero() { left = mid + 1; } else { hi = mid; } } while left < v.len() && v[left] < zero() { left += 1; } return left; }
// Count zeros of each type and then fill them in in the right order let mut zeros = 0; let mut neg_zeros = 0;
random_line_split
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T]) { /* * We don't have hardware support for a total order on floats. NaN is not * smaller or greater than any number. We want NaNs to be last, so we could * just use is_nan() in the comparison function. It turns out that this hurts * performance a lot, and in most cases we probably don't have any NaNs anyway. * * The solution is to first move all NaNs to the end of the array, and then * sort the remainder with efficient comparisons. After sorting, the zeros * might be in the wrong order since -0 and 0 compare equal. We want * -0 to be sorted before 0. We binary search to find the interval containing * all zeros and perform a counting sort on it. */ if v.len() <= 1 { return; } // First we move all NaNs to the end let mut rnan = v.len() - 1; // Skip NaNs already in place while rnan > 0 && v[rnan].is_nan() { rnan -= 1; } let mut p = rnan; while p > 0 { p -= 1; if v[p].is_nan() { v.swap(p, rnan); rnan -= 1; } } // Sort the non-NaN part with efficient comparisons sort_by(&mut v[..rnan + 1], &|x: &T, y: &T| unsafe { x.partial_cmp(y).unchecked_unwrap() }); let left = find_first_zero(&v[..rnan + 1]); // Count zeros of each type and then fill them in in the right order let mut zeros = 0; let mut neg_zeros = 0; for x in v[left..].iter() { if *x!= zero() { break; } if x.is_sign_negative() { neg_zeros += 1; } else { zeros += 1; } } for x in v[left..].iter_mut() { if neg_zeros > 0 { *x = Float::neg_zero(); neg_zeros -= 1; } else if zeros > 0 { *x = zero(); zeros -= 1; } else { break; } } } /// Find the first zero in `v`. /// If there is no zero, it return v.len() - 1 fn
<T: Float>(v: &[T]) -> usize { if v.len() == 0 { return 0; } let mut hi = v.len() - 1; let mut left = 0; while left < hi { let mid = ((hi - left) / 2) + left; if v[mid] < zero() { left = mid + 1; } else { hi = mid; } } while left < v.len() && v[left] < zero() { left += 1; } return left; }
find_first_zero
identifier_name
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T]) { /* * We don't have hardware support for a total order on floats. NaN is not * smaller or greater than any number. We want NaNs to be last, so we could * just use is_nan() in the comparison function. It turns out that this hurts * performance a lot, and in most cases we probably don't have any NaNs anyway. * * The solution is to first move all NaNs to the end of the array, and then * sort the remainder with efficient comparisons. After sorting, the zeros * might be in the wrong order since -0 and 0 compare equal. We want * -0 to be sorted before 0. We binary search to find the interval containing * all zeros and perform a counting sort on it. */ if v.len() <= 1 { return; } // First we move all NaNs to the end let mut rnan = v.len() - 1; // Skip NaNs already in place while rnan > 0 && v[rnan].is_nan() { rnan -= 1; } let mut p = rnan; while p > 0 { p -= 1; if v[p].is_nan() { v.swap(p, rnan); rnan -= 1; } } // Sort the non-NaN part with efficient comparisons sort_by(&mut v[..rnan + 1], &|x: &T, y: &T| unsafe { x.partial_cmp(y).unchecked_unwrap() }); let left = find_first_zero(&v[..rnan + 1]); // Count zeros of each type and then fill them in in the right order let mut zeros = 0; let mut neg_zeros = 0; for x in v[left..].iter() { if *x!= zero() { break; } if x.is_sign_negative() { neg_zeros += 1; } else
} for x in v[left..].iter_mut() { if neg_zeros > 0 { *x = Float::neg_zero(); neg_zeros -= 1; } else if zeros > 0 { *x = zero(); zeros -= 1; } else { break; } } } /// Find the first zero in `v`. /// If there is no zero, it return v.len() - 1 fn find_first_zero<T: Float>(v: &[T]) -> usize { if v.len() == 0 { return 0; } let mut hi = v.len() - 1; let mut left = 0; while left < hi { let mid = ((hi - left) / 2) + left; if v[mid] < zero() { left = mid + 1; } else { hi = mid; } } while left < v.len() && v[left] < zero() { left += 1; } return left; }
{ zeros += 1; }
conditional_block
unix.rs
/* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid}; #[path = "../../common/c_types.rs"] mod c_types; extern { pub fn geteuid() -> libc::uid_t; } pub unsafe fn
() -> Result<String> { // Get effective user id let uid = geteuid(); // Try to find username for uid let passwd: *const c_passwd = getpwuid(uid); if passwd.is_null() { return Err(Error::last_os_error()) } // Extract username from passwd struct let pw_name: *const libc::c_char = (*passwd).pw_name; let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string(); Ok(username) }
getusername
identifier_name
unix.rs
/* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid}; #[path = "../../common/c_types.rs"] mod c_types; extern { pub fn geteuid() -> libc::uid_t;
pub unsafe fn getusername() -> Result<String> { // Get effective user id let uid = geteuid(); // Try to find username for uid let passwd: *const c_passwd = getpwuid(uid); if passwd.is_null() { return Err(Error::last_os_error()) } // Extract username from passwd struct let pw_name: *const libc::c_char = (*passwd).pw_name; let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string(); Ok(username) }
}
random_line_split
unix.rs
/* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid}; #[path = "../../common/c_types.rs"] mod c_types; extern { pub fn geteuid() -> libc::uid_t; } pub unsafe fn getusername() -> Result<String> { // Get effective user id let uid = geteuid(); // Try to find username for uid let passwd: *const c_passwd = getpwuid(uid); if passwd.is_null()
// Extract username from passwd struct let pw_name: *const libc::c_char = (*passwd).pw_name; let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string(); Ok(username) }
{ return Err(Error::last_os_error()) }
conditional_block