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
block_retrieval.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::block::Block; use anyhow::ensure; use diem_crypto::hash::HashValue; use diem_types::validator_verifier::ValidatorVerifier; use serde::{Deserialize, Serialize}; use short_hex_str::AsShortHexStr; use std::fmt; pub const MAX_BLOCKS_PER_REQUEST: u64 = 10; /// RPC to get a chain of block of the given length starting from the given block id. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockRetrievalRequest { block_id: HashValue, num_blocks: u64, } impl BlockRetrievalRequest { pub fn new(block_id: HashValue, num_blocks: u64) -> Self { Self { block_id, num_blocks, } } pub fn block_id(&self) -> HashValue { self.block_id } pub fn num_blocks(&self) -> u64 { self.num_blocks } } impl fmt::Display for BlockRetrievalRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[BlockRetrievalRequest starting from id {} with {} blocks]", self.block_id, self.num_blocks ) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum BlockRetrievalStatus { // Successfully fill in the request. Succeeded, // Can not find the block corresponding to block_id. IdNotFound, // Can not find enough blocks but find some. NotEnoughBlocks, } /// Carries the returned blocks and the retrieval status. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct
{ status: BlockRetrievalStatus, blocks: Vec<Block>, } impl BlockRetrievalResponse { pub fn new(status: BlockRetrievalStatus, blocks: Vec<Block>) -> Self { Self { status, blocks } } pub fn status(&self) -> BlockRetrievalStatus { self.status.clone() } pub fn blocks(&self) -> &Vec<Block> { &self.blocks } pub fn verify( &self, block_id: HashValue, num_blocks: u64, sig_verifier: &ValidatorVerifier, ) -> anyhow::Result<()> { ensure!( self.status!= BlockRetrievalStatus::Succeeded || self.blocks.len() as u64 == num_blocks, "not enough blocks returned, expect {}, get {}", num_blocks, self.blocks.len(), ); self.blocks .iter() .try_fold(block_id, |expected_id, block| { block.validate_signature(sig_verifier)?; block.verify_well_formed()?; ensure!( block.id() == expected_id, "blocks doesn't form a chain: expect {}, get {}", expected_id, block.id() ); Ok(block.parent_id()) }) .map(|_| ()) } } impl fmt::Display for BlockRetrievalResponse { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.status() { BlockRetrievalStatus::Succeeded => { write!( f, "[BlockRetrievalResponse: status: {:?}, num_blocks: {}, block_ids: ", self.status(), self.blocks().len(), )?; f.debug_list() .entries(self.blocks.iter().map(|b| b.id().short_str())) .finish()?; write!(f, "]") } _ => write!(f, "[BlockRetrievalResponse: status: {:?}]", self.status()), } } }
BlockRetrievalResponse
identifier_name
block_retrieval.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::block::Block; use anyhow::ensure; use diem_crypto::hash::HashValue; use diem_types::validator_verifier::ValidatorVerifier; use serde::{Deserialize, Serialize}; use short_hex_str::AsShortHexStr; use std::fmt; pub const MAX_BLOCKS_PER_REQUEST: u64 = 10; /// RPC to get a chain of block of the given length starting from the given block id. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockRetrievalRequest { block_id: HashValue, num_blocks: u64, } impl BlockRetrievalRequest { pub fn new(block_id: HashValue, num_blocks: u64) -> Self { Self { block_id, num_blocks, } } pub fn block_id(&self) -> HashValue { self.block_id } pub fn num_blocks(&self) -> u64 { self.num_blocks } } impl fmt::Display for BlockRetrievalRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum BlockRetrievalStatus { // Successfully fill in the request. Succeeded, // Can not find the block corresponding to block_id. IdNotFound, // Can not find enough blocks but find some. NotEnoughBlocks, } /// Carries the returned blocks and the retrieval status. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockRetrievalResponse { status: BlockRetrievalStatus, blocks: Vec<Block>, } impl BlockRetrievalResponse { pub fn new(status: BlockRetrievalStatus, blocks: Vec<Block>) -> Self { Self { status, blocks } } pub fn status(&self) -> BlockRetrievalStatus { self.status.clone() } pub fn blocks(&self) -> &Vec<Block> { &self.blocks } pub fn verify( &self, block_id: HashValue, num_blocks: u64, sig_verifier: &ValidatorVerifier, ) -> anyhow::Result<()> { ensure!( self.status!= BlockRetrievalStatus::Succeeded || self.blocks.len() as u64 == num_blocks, "not enough blocks returned, expect {}, get {}", num_blocks, self.blocks.len(), ); self.blocks .iter() .try_fold(block_id, |expected_id, block| { block.validate_signature(sig_verifier)?; block.verify_well_formed()?; ensure!( block.id() == expected_id, "blocks doesn't form a chain: expect {}, get {}", expected_id, block.id() ); Ok(block.parent_id()) }) .map(|_| ()) } } impl fmt::Display for BlockRetrievalResponse { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.status() { BlockRetrievalStatus::Succeeded => { write!( f, "[BlockRetrievalResponse: status: {:?}, num_blocks: {}, block_ids: ", self.status(), self.blocks().len(), )?; f.debug_list() .entries(self.blocks.iter().map(|b| b.id().short_str())) .finish()?; write!(f, "]") } _ => write!(f, "[BlockRetrievalResponse: status: {:?}]", self.status()), } } }
{ write!( f, "[BlockRetrievalRequest starting from id {} with {} blocks]", self.block_id, self.num_blocks ) }
identifier_body
block_retrieval.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::block::Block; use anyhow::ensure; use diem_crypto::hash::HashValue; use diem_types::validator_verifier::ValidatorVerifier; use serde::{Deserialize, Serialize}; use short_hex_str::AsShortHexStr; use std::fmt; pub const MAX_BLOCKS_PER_REQUEST: u64 = 10; /// RPC to get a chain of block of the given length starting from the given block id. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockRetrievalRequest { block_id: HashValue, num_blocks: u64, } impl BlockRetrievalRequest { pub fn new(block_id: HashValue, num_blocks: u64) -> Self { Self { block_id, num_blocks, } } pub fn block_id(&self) -> HashValue { self.block_id } pub fn num_blocks(&self) -> u64 { self.num_blocks } } impl fmt::Display for BlockRetrievalRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[BlockRetrievalRequest starting from id {} with {} blocks]", self.block_id, self.num_blocks ) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum BlockRetrievalStatus { // Successfully fill in the request. Succeeded, // Can not find the block corresponding to block_id. IdNotFound, // Can not find enough blocks but find some. NotEnoughBlocks, } /// Carries the returned blocks and the retrieval status. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockRetrievalResponse { status: BlockRetrievalStatus, blocks: Vec<Block>, } impl BlockRetrievalResponse { pub fn new(status: BlockRetrievalStatus, blocks: Vec<Block>) -> Self { Self { status, blocks } } pub fn status(&self) -> BlockRetrievalStatus { self.status.clone() } pub fn blocks(&self) -> &Vec<Block> { &self.blocks } pub fn verify( &self, block_id: HashValue, num_blocks: u64, sig_verifier: &ValidatorVerifier, ) -> anyhow::Result<()> { ensure!( self.status!= BlockRetrievalStatus::Succeeded || self.blocks.len() as u64 == num_blocks, "not enough blocks returned, expect {}, get {}", num_blocks, self.blocks.len(), ); self.blocks .iter() .try_fold(block_id, |expected_id, block| { block.validate_signature(sig_verifier)?; block.verify_well_formed()?; ensure!( block.id() == expected_id, "blocks doesn't form a chain: expect {}, get {}", expected_id, block.id() ); Ok(block.parent_id()) }) .map(|_| ()) } } impl fmt::Display for BlockRetrievalResponse { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.status() { BlockRetrievalStatus::Succeeded =>
_ => write!(f, "[BlockRetrievalResponse: status: {:?}]", self.status()), } } }
{ write!( f, "[BlockRetrievalResponse: status: {:?}, num_blocks: {}, block_ids: ", self.status(), self.blocks().len(), )?; f.debug_list() .entries(self.blocks.iter().map(|b| b.id().short_str())) .finish()?; write!(f, "]") }
conditional_block
block_retrieval.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::block::Block; use anyhow::ensure; use diem_crypto::hash::HashValue; use diem_types::validator_verifier::ValidatorVerifier; use serde::{Deserialize, Serialize}; use short_hex_str::AsShortHexStr; use std::fmt; pub const MAX_BLOCKS_PER_REQUEST: u64 = 10; /// RPC to get a chain of block of the given length starting from the given block id. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockRetrievalRequest { block_id: HashValue, num_blocks: u64, } impl BlockRetrievalRequest { pub fn new(block_id: HashValue, num_blocks: u64) -> Self { Self { block_id, num_blocks, } } pub fn block_id(&self) -> HashValue { self.block_id } pub fn num_blocks(&self) -> u64 { self.num_blocks } } impl fmt::Display for BlockRetrievalRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[BlockRetrievalRequest starting from id {} with {} blocks]", self.block_id, self.num_blocks ) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum BlockRetrievalStatus { // Successfully fill in the request. Succeeded, // Can not find the block corresponding to block_id. IdNotFound, // Can not find enough blocks but find some. NotEnoughBlocks, } /// Carries the returned blocks and the retrieval status. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockRetrievalResponse { status: BlockRetrievalStatus, blocks: Vec<Block>, } impl BlockRetrievalResponse { pub fn new(status: BlockRetrievalStatus, blocks: Vec<Block>) -> Self { Self { status, blocks } } pub fn status(&self) -> BlockRetrievalStatus { self.status.clone() } pub fn blocks(&self) -> &Vec<Block> { &self.blocks } pub fn verify( &self, block_id: HashValue, num_blocks: u64, sig_verifier: &ValidatorVerifier, ) -> anyhow::Result<()> { ensure!( self.status!= BlockRetrievalStatus::Succeeded || self.blocks.len() as u64 == num_blocks, "not enough blocks returned, expect {}, get {}", num_blocks, self.blocks.len(), ); self.blocks .iter() .try_fold(block_id, |expected_id, block| { block.validate_signature(sig_verifier)?; block.verify_well_formed()?; ensure!( block.id() == expected_id, "blocks doesn't form a chain: expect {}, get {}",
.map(|_| ()) } } impl fmt::Display for BlockRetrievalResponse { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.status() { BlockRetrievalStatus::Succeeded => { write!( f, "[BlockRetrievalResponse: status: {:?}, num_blocks: {}, block_ids: ", self.status(), self.blocks().len(), )?; f.debug_list() .entries(self.blocks.iter().map(|b| b.id().short_str())) .finish()?; write!(f, "]") } _ => write!(f, "[BlockRetrievalResponse: status: {:?}]", self.status()), } } }
expected_id, block.id() ); Ok(block.parent_id()) })
random_line_split
spawn-types.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /* Make sure we can spawn tasks that take different types of parameters. This is based on a test case for #520 provided by Rob Arnold. */ use std::thread::Thread; use std::sync::mpsc::{channel, Sender}; type ctx = Sender<int>; fn iotask(_tx: &ctx, ip: String) { assert_eq!(ip, "localhost".to_string()); } pub fn main()
{ let (tx, _rx) = channel::<int>(); let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) ); t.join().ok().unwrap(); }
identifier_body
spawn-types.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /* Make sure we can spawn tasks that take different types of
use std::thread::Thread; use std::sync::mpsc::{channel, Sender}; type ctx = Sender<int>; fn iotask(_tx: &ctx, ip: String) { assert_eq!(ip, "localhost".to_string()); } pub fn main() { let (tx, _rx) = channel::<int>(); let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) ); t.join().ok().unwrap(); }
parameters. This is based on a test case for #520 provided by Rob Arnold. */
random_line_split
spawn-types.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /* Make sure we can spawn tasks that take different types of parameters. This is based on a test case for #520 provided by Rob Arnold. */ use std::thread::Thread; use std::sync::mpsc::{channel, Sender}; type ctx = Sender<int>; fn
(_tx: &ctx, ip: String) { assert_eq!(ip, "localhost".to_string()); } pub fn main() { let (tx, _rx) = channel::<int>(); let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) ); t.join().ok().unwrap(); }
iotask
identifier_name
enumerate_domains.rs
use std::{ io, os::raw::{ c_char, c_void, }, pin::Pin, task::{ Context, Poll, }, }; use crate::{ cstr, ffi, inner, interface::Interface, }; type CallbackStream = crate::stream::ServiceStream<inner::OwnedService, EnumerateResult>; /// Whether to enumerate domains which are browsed or domains for which /// registrations can be made. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Enumerate { /// enumerate domains which can be browsed BrowseDomains, /// enumerate domains to register services/records on RegistrationDomains, } impl From<Enumerate> for ffi::DNSServiceFlags { fn from(e: Enumerate) -> Self { match e { Enumerate::BrowseDomains => ffi::FLAGS_BROWSE_DOMAINS, Enumerate::RegistrationDomains => ffi::FLAGS_REGISTRATION_DOMAINS, } } } bitflags::bitflags! { /// Flags for [`EnumerateDomains`](struct.EnumerateDomains.html) #[derive(Default)] pub struct EnumeratedFlags: ffi::DNSServiceFlags { /// Indicates at least one more result is pending in the queue. If /// not set there still might be more results coming in the future. /// /// See [`kDNSServiceFlagsMoreComing`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsmorecoming). const MORE_COMING = ffi::FLAGS_MORE_COMING; /// Indicates the result is new. If not set indicates the result /// was removed. /// /// See [`kDNSServiceFlagsAdd`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsadd). const ADD = ffi::FLAGS_ADD; /// Indicates this is the default domain to search (always combined with `Add`). /// /// See [`kDNSServiceFlagsDefault`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsdefault). const DEFAULT = ffi::FLAGS_DEFAULT; } } /// Pending domain enumeration #[must_use = "streams do nothing unless polled"] pub struct EnumerateDomains { stream: crate::fused_err_stream::FusedErrorStream<CallbackStream>, } impl EnumerateDomains { pin_utils::unsafe_pinned!(stream: crate::fused_err_stream::FusedErrorStream<CallbackStream>); }
type Item = io::Result<EnumerateResult>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.stream().poll_next(cx) } } /// Domain enumeration result /// /// See [DNSServiceDomainEnumReply](https://developer.apple.com/documentation/dnssd/dnsservicedomainenumreply). #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct EnumerateResult { /// flags pub flags: EnumeratedFlags, /// interface domain was found on pub interface: Interface, /// domain name pub domain: String, } unsafe extern "C" fn enumerate_callback( _sd_ref: ffi::DNSServiceRef, flags: ffi::DNSServiceFlags, interface_index: u32, error_code: ffi::DNSServiceErrorType, reply_domain: *const c_char, context: *mut c_void, ) { CallbackStream::run_callback(context, error_code, || { let reply_domain = cstr::from_cstr(reply_domain)?; Ok(EnumerateResult { flags: EnumeratedFlags::from_bits_truncate(flags), interface: Interface::from_raw(interface_index), domain: reply_domain.to_string(), }) }); } /// Enumerate domains that are recommended for registration or browsing /// /// See [`DNSServiceEnumerateDomains`](https://developer.apple.com/documentation/dnssd/1804754-dnsserviceenumeratedomains). #[doc(alias = "DNSServiceEnumerateDomains")] pub fn enumerate_domains(enumerate: Enumerate, interface: Interface) -> EnumerateDomains { crate::init(); let stream = CallbackStream::new(move |sender| { inner::OwnedService::enumerate_domains( enumerate.into(), interface.into_raw(), Some(enumerate_callback), sender, ) }) .into(); EnumerateDomains { stream } }
impl futures_core::Stream for EnumerateDomains {
random_line_split
enumerate_domains.rs
use std::{ io, os::raw::{ c_char, c_void, }, pin::Pin, task::{ Context, Poll, }, }; use crate::{ cstr, ffi, inner, interface::Interface, }; type CallbackStream = crate::stream::ServiceStream<inner::OwnedService, EnumerateResult>; /// Whether to enumerate domains which are browsed or domains for which /// registrations can be made. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Enumerate { /// enumerate domains which can be browsed BrowseDomains, /// enumerate domains to register services/records on RegistrationDomains, } impl From<Enumerate> for ffi::DNSServiceFlags { fn from(e: Enumerate) -> Self
} bitflags::bitflags! { /// Flags for [`EnumerateDomains`](struct.EnumerateDomains.html) #[derive(Default)] pub struct EnumeratedFlags: ffi::DNSServiceFlags { /// Indicates at least one more result is pending in the queue. If /// not set there still might be more results coming in the future. /// /// See [`kDNSServiceFlagsMoreComing`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsmorecoming). const MORE_COMING = ffi::FLAGS_MORE_COMING; /// Indicates the result is new. If not set indicates the result /// was removed. /// /// See [`kDNSServiceFlagsAdd`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsadd). const ADD = ffi::FLAGS_ADD; /// Indicates this is the default domain to search (always combined with `Add`). /// /// See [`kDNSServiceFlagsDefault`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsdefault). const DEFAULT = ffi::FLAGS_DEFAULT; } } /// Pending domain enumeration #[must_use = "streams do nothing unless polled"] pub struct EnumerateDomains { stream: crate::fused_err_stream::FusedErrorStream<CallbackStream>, } impl EnumerateDomains { pin_utils::unsafe_pinned!(stream: crate::fused_err_stream::FusedErrorStream<CallbackStream>); } impl futures_core::Stream for EnumerateDomains { type Item = io::Result<EnumerateResult>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.stream().poll_next(cx) } } /// Domain enumeration result /// /// See [DNSServiceDomainEnumReply](https://developer.apple.com/documentation/dnssd/dnsservicedomainenumreply). #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct EnumerateResult { /// flags pub flags: EnumeratedFlags, /// interface domain was found on pub interface: Interface, /// domain name pub domain: String, } unsafe extern "C" fn enumerate_callback( _sd_ref: ffi::DNSServiceRef, flags: ffi::DNSServiceFlags, interface_index: u32, error_code: ffi::DNSServiceErrorType, reply_domain: *const c_char, context: *mut c_void, ) { CallbackStream::run_callback(context, error_code, || { let reply_domain = cstr::from_cstr(reply_domain)?; Ok(EnumerateResult { flags: EnumeratedFlags::from_bits_truncate(flags), interface: Interface::from_raw(interface_index), domain: reply_domain.to_string(), }) }); } /// Enumerate domains that are recommended for registration or browsing /// /// See [`DNSServiceEnumerateDomains`](https://developer.apple.com/documentation/dnssd/1804754-dnsserviceenumeratedomains). #[doc(alias = "DNSServiceEnumerateDomains")] pub fn enumerate_domains(enumerate: Enumerate, interface: Interface) -> EnumerateDomains { crate::init(); let stream = CallbackStream::new(move |sender| { inner::OwnedService::enumerate_domains( enumerate.into(), interface.into_raw(), Some(enumerate_callback), sender, ) }) .into(); EnumerateDomains { stream } }
{ match e { Enumerate::BrowseDomains => ffi::FLAGS_BROWSE_DOMAINS, Enumerate::RegistrationDomains => ffi::FLAGS_REGISTRATION_DOMAINS, } }
identifier_body
enumerate_domains.rs
use std::{ io, os::raw::{ c_char, c_void, }, pin::Pin, task::{ Context, Poll, }, }; use crate::{ cstr, ffi, inner, interface::Interface, }; type CallbackStream = crate::stream::ServiceStream<inner::OwnedService, EnumerateResult>; /// Whether to enumerate domains which are browsed or domains for which /// registrations can be made. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Enumerate { /// enumerate domains which can be browsed BrowseDomains, /// enumerate domains to register services/records on RegistrationDomains, } impl From<Enumerate> for ffi::DNSServiceFlags { fn from(e: Enumerate) -> Self { match e { Enumerate::BrowseDomains => ffi::FLAGS_BROWSE_DOMAINS, Enumerate::RegistrationDomains => ffi::FLAGS_REGISTRATION_DOMAINS, } } } bitflags::bitflags! { /// Flags for [`EnumerateDomains`](struct.EnumerateDomains.html) #[derive(Default)] pub struct EnumeratedFlags: ffi::DNSServiceFlags { /// Indicates at least one more result is pending in the queue. If /// not set there still might be more results coming in the future. /// /// See [`kDNSServiceFlagsMoreComing`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsmorecoming). const MORE_COMING = ffi::FLAGS_MORE_COMING; /// Indicates the result is new. If not set indicates the result /// was removed. /// /// See [`kDNSServiceFlagsAdd`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsadd). const ADD = ffi::FLAGS_ADD; /// Indicates this is the default domain to search (always combined with `Add`). /// /// See [`kDNSServiceFlagsDefault`](https://developer.apple.com/documentation/dnssd/1823436-anonymous/kdnsserviceflagsdefault). const DEFAULT = ffi::FLAGS_DEFAULT; } } /// Pending domain enumeration #[must_use = "streams do nothing unless polled"] pub struct EnumerateDomains { stream: crate::fused_err_stream::FusedErrorStream<CallbackStream>, } impl EnumerateDomains { pin_utils::unsafe_pinned!(stream: crate::fused_err_stream::FusedErrorStream<CallbackStream>); } impl futures_core::Stream for EnumerateDomains { type Item = io::Result<EnumerateResult>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.stream().poll_next(cx) } } /// Domain enumeration result /// /// See [DNSServiceDomainEnumReply](https://developer.apple.com/documentation/dnssd/dnsservicedomainenumreply). #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct EnumerateResult { /// flags pub flags: EnumeratedFlags, /// interface domain was found on pub interface: Interface, /// domain name pub domain: String, } unsafe extern "C" fn enumerate_callback( _sd_ref: ffi::DNSServiceRef, flags: ffi::DNSServiceFlags, interface_index: u32, error_code: ffi::DNSServiceErrorType, reply_domain: *const c_char, context: *mut c_void, ) { CallbackStream::run_callback(context, error_code, || { let reply_domain = cstr::from_cstr(reply_domain)?; Ok(EnumerateResult { flags: EnumeratedFlags::from_bits_truncate(flags), interface: Interface::from_raw(interface_index), domain: reply_domain.to_string(), }) }); } /// Enumerate domains that are recommended for registration or browsing /// /// See [`DNSServiceEnumerateDomains`](https://developer.apple.com/documentation/dnssd/1804754-dnsserviceenumeratedomains). #[doc(alias = "DNSServiceEnumerateDomains")] pub fn
(enumerate: Enumerate, interface: Interface) -> EnumerateDomains { crate::init(); let stream = CallbackStream::new(move |sender| { inner::OwnedService::enumerate_domains( enumerate.into(), interface.into_raw(), Some(enumerate_callback), sender, ) }) .into(); EnumerateDomains { stream } }
enumerate_domains
identifier_name
lib.rs
//! Time handling for games and other real-time simulations. //! //! Provides types and helpers for dealing with time in games. `game_time` allows for //! easy decoupling of internal "game" time and external "wall" time, as well as tracking //! frame rate. //! //! Additionally, different kinds of time steps may be used, while also setting a multiplier //! for speeding up/slowing down game time progression. //! //! # Usage //! Put this in your `Cargo.toml`: //! //! ```toml,ignore //! [dependencies] //! game_time = "0.2.0" //! ``` //! //! # Overview //! //! `game_time` consists of 4 main types. //! //! - [`GameClock`](clock/struct.GameClock.html) provides the basic time keeping for a simulation, //! tracking frames and returning a `GameTime` at the beginning of each. //! - [`GameTime`](clock/struct.GameTime.html) provides the time information for each frame. //! - [`FrameCount`](framerate/counter/struct.FrameCount.html) objects can be optionally used to track //! frame rate and other runtime statistics, utilizing swappable methods for computing the //! average fps. //! - [`FrameRunner`](runner/struct.FrameRunner.html) combines a `GameClock` and `FrameCount` and //! makes it easy to run the simulation at a given frame rate. //! //! For each frame, a [`TimeStep`](step/trait.TimeStep.html) is passed to `GameClock` in order //! to advance the frame. This allows the frame rate to be changed at any time, and allows different //! kinds of time steps (fixed, variable and a constant step are supported by default) to be used //! based on what is most useful. Together, these objects combine to form a convenient but //! flexible framework for time progression. //! //! # Examples //! //! Run a simulation with 50ms frames, without fps counting: //! //! ```rust //! use game_time::GameClock; //! use game_time::step; //! use game_time::FloatDuration; //! //! let mut clock = GameClock::new(); //! let end_time = FloatDuration::seconds(10.0); //! let mut sim_time = clock.last_frame_time().clone(); //! let step = step::ConstantStep::new(FloatDuration::milliseconds(50.0)); //!
//! sim_time = clock.tick(&step); //! println!("Frame #{} at time={:?}", sim_time.frame_number(), sim_time.total_game_time()); //! } //! ``` //! //! Run a simulation at 30fps, sleeping if necessary to maintain the framerate: //! //! ```rust //! use game_time::{GameClock, FrameCounter, FrameCount, FloatDuration}; //! use game_time::framerate::RunningAverageSampler; //! use game_time::step; //! //! let mut clock = GameClock::new(); //! let mut counter = FrameCounter::new(30.0, RunningAverageSampler::with_max_samples(60)); //! let end_time = FloatDuration::seconds(10.0); //! let mut sim_time = clock.last_frame_time().clone(); //! //! while sim_time.total_game_time() < end_time { //! sim_time = clock.tick(&step::FixedStep::new(&counter)); //! counter.tick(&sim_time); //! println!("Frame #{} at time={:?}", sim_time.frame_number(), sim_time.total_game_time()); //! } //! ``` //! extern crate chrono; extern crate time; extern crate float_duration; #[cfg(test)] #[macro_use] extern crate approx; pub mod clock; pub mod framerate; pub mod runner; pub mod step; pub use self::clock::{GameTime, GameClock}; pub use self::framerate::{FrameCounter, FrameCount, FrameRateSampler}; pub use self::runner::FrameRunner; pub use self::step::TimeStep; pub use float_duration::FloatDuration;
//! while sim_time.total_game_time() < end_time {
random_line_split
factorial.rs
#[macro_use] extern crate qmlrs; use std::fs::File; use std::io::prelude::*; struct
; impl Factorial { fn calculate(&self, x: i64) -> i64 { (1..x+1).fold(1, |t,c| t * c) } } Q_OBJECT! { Factorial: slot fn calculate(i64); // signal fn test(); } fn main() { let mut engine = qmlrs::Engine::new(); engine.set_property("factorial", Factorial); engine.load_local_file("examples/factorial_ui.qml"); engine.exec(); // test with string: let mut engine2 = qmlrs::Engine::new(); engine2.set_property("factorial", Factorial); let mut qml_file = File::open("examples/factorial_ui.qml").unwrap(); let mut qml_string = String::new(); qml_file.read_to_string(&mut qml_string).unwrap(); qml_string = qml_string.replace("Factorial", "Factorial (from string)"); engine2.load_data(&qml_string); engine2.exec(); }
Factorial
identifier_name
factorial.rs
#[macro_use] extern crate qmlrs; use std::fs::File; use std::io::prelude::*; struct Factorial;
Q_OBJECT! { Factorial: slot fn calculate(i64); // signal fn test(); } fn main() { let mut engine = qmlrs::Engine::new(); engine.set_property("factorial", Factorial); engine.load_local_file("examples/factorial_ui.qml"); engine.exec(); // test with string: let mut engine2 = qmlrs::Engine::new(); engine2.set_property("factorial", Factorial); let mut qml_file = File::open("examples/factorial_ui.qml").unwrap(); let mut qml_string = String::new(); qml_file.read_to_string(&mut qml_string).unwrap(); qml_string = qml_string.replace("Factorial", "Factorial (from string)"); engine2.load_data(&qml_string); engine2.exec(); }
impl Factorial { fn calculate(&self, x: i64) -> i64 { (1..x+1).fold(1, |t,c| t * c) } }
random_line_split
traversal.rs
(&self) -> bool { self.unstyled_children_only } } /// Enum to prevent duplicate logging. pub enum LogBehavior { /// We should log. MayLog, /// We shouldn't log. DontLog, } use self::LogBehavior::*; impl LogBehavior { fn allow(&self) -> bool { matches!(*self, MayLog) } } /// The kind of traversals we could perform. #[derive(Debug, Copy, Clone)] pub enum TraversalDriver { /// A potentially parallel traversal. Parallel, /// A sequential traversal. Sequential, } impl TraversalDriver { /// Returns whether this represents a parallel traversal or not. #[inline] pub fn is_parallel(&self) -> bool { matches!(*self, TraversalDriver::Parallel) } } /// A DOM Traversal trait, that is used to generically implement styling for /// Gecko and Servo. pub trait DomTraversal<E: TElement> : Sync { /// The thread-local context, used to store non-thread-safe stuff that needs /// to be used in the traversal, and of which we use one per worker, like /// the bloom filter, for example. type ThreadLocalContext: Send + BorrowMut<ThreadLocalStyleContext<E>>; /// Process `node` on the way down, before its children have been processed. fn process_preorder(&self, data: &mut PerLevelTraversalData, thread_local: &mut Self::ThreadLocalContext, node: E::ConcreteNode); /// Process `node` on the way up, after its children have been processed. /// /// This is only executed if `needs_postorder_traversal` returns true. fn process_postorder(&self, thread_local: &mut Self::ThreadLocalContext, node: E::ConcreteNode); /// Boolean that specifies whether a bottom up traversal should be /// performed. /// /// If it's false, then process_postorder has no effect at all. fn needs_postorder_traversal() -> bool { true } /// Must be invoked before traversing the root element to determine whether /// a traversal is needed. Returns a token that allows the caller to prove /// that the call happened. /// /// The traversal_flag is used in Gecko. /// If traversal_flag::UNSTYLED_CHILDREN_ONLY is specified, style newly- /// appended children without restyling the parent. /// If traversal_flag::ANIMATION_ONLY is specified, style only elements for /// animations. fn pre_traverse(root: E, stylist: &Stylist, traversal_flags: TraversalFlags) -> PreTraverseToken { if traversal_flags.for_unstyled_children_only() { return PreTraverseToken { traverse: true, unstyled_children_only: true, }; } // Expand the snapshot, if any. This is normally handled by the parent, so // we need a special case for the root. // // Expanding snapshots here may create a LATER_SIBLINGS restyle hint, which // we will drop on the floor. To prevent missed restyles, we assert against // restyling a root with later siblings. if let Some(mut data) = root.mutate_data() { if let Some(r) = data.get_restyle_mut() { debug_assert!(root.next_sibling_element().is_none()); let _later_siblings = r.compute_final_hint(root, stylist); } } PreTraverseToken { traverse: Self::node_needs_traversal(root.as_node(), traversal_flags.for_animation_only()), unstyled_children_only: false, } } /// Returns true if traversal should visit a text node. The style system never /// processes text nodes, but Servo overrides this to visit them for flow /// construction when necessary. fn text_node_needs_traversal(node: E::ConcreteNode) -> bool { debug_assert!(node.is_text_node()); false } /// Returns true if traversal is needed for the given node and subtree. fn node_needs_traversal(node: E::ConcreteNode, animation_only: bool) -> bool { // Non-incremental layout visits every node. if cfg!(feature = "servo") && opts::get().nonincremental_layout { return true; } match node.as_element() { None => Self::text_node_needs_traversal(node), Some(el) => { // In case of animation-only traversal we need to traverse // the element if the element has animation only dirty // descendants bit, animation-only restyle hint or recascade. if animation_only { if el.has_animation_only_dirty_descendants() { return true; } let data = match el.borrow_data() { Some(d) => d, None => return false, }; return data.get_restyle() .map_or(false, |r| r.hint.has_animation_hint() || r.recascade); } // If the dirty descendants bit is set, we need to traverse no // matter what. Skip examining the ElementData. if el.has_dirty_descendants() { return true; } // Check the element data. If it doesn't exist, we need to visit // the element. let data = match el.borrow_data() { Some(d) => d, None => return true, }; // If we don't have any style data, we need to visit the element. if!data.has_styles() { return true; } // Check the restyle data. if let Some(r) = data.get_restyle() { // If we have a restyle hint or need to recascade, we need to // visit the element. // // Note that this is different than checking has_current_styles(), // since that can return true even if we have a restyle hint // indicating that the element's descendants (but not necessarily // the element) need restyling. if!r.hint.is_empty() || r.recascade { return true; } } // Servo uses the post-order traversal for flow construction, so // we need to traverse any element with damage so that we can perform // fixup / reconstruction on our way back up the tree. if cfg!(feature = "servo") && data.get_restyle().map_or(false, |r| r.damage!= RestyleDamage::empty()) { return true; } false }, } } /// Returns true if traversal of this element's children is allowed. We use /// this to cull traversal of various subtrees. /// /// This may be called multiple times when processing an element, so we pass /// a parameter to keep the logs tidy. fn should_traverse_children(&self, thread_local: &mut ThreadLocalStyleContext<E>, parent: E, parent_data: &ElementData, log: LogBehavior) -> bool { // See the comment on `cascade_node` for why we allow this on Gecko. debug_assert!(cfg!(feature = "gecko") || parent_data.has_current_styles()); // If the parent computed display:none, we don't style the subtree. if parent_data.styles().is_display_none() { if log.allow() { debug!("Parent {:?} is display:none, culling traversal", parent); } return false; } // Gecko-only XBL handling. // // If we're computing initial styles and the parent has a Gecko XBL // binding, that binding may inject anonymous children and remap the // explicit children to an insertion point (or hide them entirely). It // may also specify a scoped stylesheet, which changes the rules that // apply within the subtree. These two effects can invalidate the result // of property inheritance and selector matching (respectively) within the // subtree. // // To avoid wasting work, we defer initial styling of XBL subtrees // until frame construction, which does an explicit traversal of the // unstyled children after shuffling the subtree. That explicit // traversal may in turn find other bound elements, which get handled // in the same way. // // We explicitly avoid handling restyles here (explicitly removing or // changing bindings), since that adds complexity and is rarer. If it // happens, we may just end up doing wasted work, since Gecko // recursively drops Servo ElementData when the XBL insertion parent of // an Element is changed. if cfg!(feature = "gecko") && thread_local.is_initial_style() && parent_data.styles().primary.values().has_moz_binding() { if log.allow() { debug!("Parent {:?} has XBL binding, deferring traversal", parent); } return false; } return true; } /// Helper for the traversal implementations to select the children that /// should be enqueued for processing. fn traverse_children<F>(&self, thread_local: &mut Self::ThreadLocalContext, parent: E, mut f: F) where F: FnMut(&mut Self::ThreadLocalContext, E::ConcreteNode) { // Check if we're allowed to traverse past this element. let should_traverse = self.should_traverse_children(thread_local.borrow_mut(), parent, &parent.borrow_data().unwrap(), MayLog); thread_local.borrow_mut().end_element(parent); if!should_traverse { return; } for kid in parent.as_node().children() { if Self::node_needs_traversal(kid, self.shared_context().animation_only_restyle) { let el = kid.as_element(); if el.as_ref().and_then(|el| el.borrow_data()) .map_or(false, |d| d.has_styles()) { unsafe { parent.set_dirty_descendants(); } } f(thread_local, kid); } } } /// Ensures the existence of the ElementData, and returns it. This can't live /// on TNode because of the trait-based separation between Servo's script /// and layout crates. /// /// This is only safe to call in top-down traversal before processing the /// children of |element|. unsafe fn ensure_element_data(element: &E) -> &AtomicRefCell<ElementData>; /// Clears the ElementData attached to this element, if any. /// /// This is only safe to call in top-down traversal before processing the /// children of |element|. unsafe fn clear_element_data(element: &E); /// Return the shared style context common to all worker threads. fn shared_context(&self) -> &SharedStyleContext; /// Creates a thread-local context. fn create_thread_local_context(&self) -> Self::ThreadLocalContext; /// Whether we're performing a parallel traversal. /// /// NB: We do this check on runtime. We could guarantee correctness in this /// regard via the type system via a `TraversalDriver` trait for this trait, /// that could be one of two concrete types. It's not clear whether the /// potential code size impact of that is worth it. fn is_parallel(&self) -> bool; } /// Helper for the function below. fn resolve_style_internal<E, F>(context: &mut StyleContext<E>, element: E, ensure_data: &F) -> Option<E> where E: TElement, F: Fn(E), { ensure_data(element); let mut data = element.mutate_data().unwrap(); let mut display_none_root = None; // If the Element isn't styled, we need to compute its style. if data.get_styles().is_none() { // Compute the parent style if necessary. let parent = element.parent_element(); if let Some(p) = parent { display_none_root = resolve_style_internal(context, p, ensure_data); } // Maintain the bloom filter. If it doesn't exist, we need to build it // from scratch. Otherwise we just need to push the parent. if context.thread_local.bloom_filter.is_empty() { context.thread_local.bloom_filter.rebuild(element); } else { context.thread_local.bloom_filter.push(parent.unwrap()); context.thread_local.bloom_filter.assert_complete(element); } // Compute our style. let match_results = element.match_element(context, &mut data); element.cascade_element(context, &mut data, match_results.primary_is_shareable()); // Conservatively mark us as having dirty descendants, since there might // be other unstyled siblings we miss when walking straight up the parent // chain. unsafe { element.set_dirty_descendants() }; } // If we're display:none and none of our ancestors are, we're the root // of a display:none subtree. if display_none_root.is_none() && data.styles().is_display_none() { display_none_root = Some(element); } return display_none_root } /// Manually resolve style by sequentially walking up the parent chain to the /// first styled Element, ignoring pending restyles. The resolved style is /// made available via a callback, and can be dropped by the time this function /// returns in the display:none subtree case. pub fn resolve_style<E, F, G, H>(context: &mut StyleContext<E>, element: E, ensure_data: &F, clear_data: &G, callback: H) where E: TElement, F: Fn(E), G: Fn(E), H: FnOnce(&ElementStyles) { // Clear the bloom filter, just in case the caller is reusing TLS. context.thread_local.bloom_filter.clear(); // Resolve styles up the tree. let display_none_root = resolve_style_internal(context, element, ensure_data); // Make them available for the scope of the callback. The callee may use the // argument, or perform any other processing that requires the styles to exist // on the Element. callback(element.borrow_data().unwrap().styles()); // Clear any styles in display:none subtrees or subtrees not in the document, // to leave the tree in a valid state. For display:none subtrees, we leave // the styles on the display:none root, but for subtrees not in the document, // we clear styles all the way up to the root of the disconnected subtree. let in_doc = element.as_node().is_in_doc(); if!in_doc || display_none_root.is_some() { let mut curr = element; loop { unsafe { curr.unset_dirty_descendants(); } if in_doc && curr == display_none_root.unwrap() { break; } clear_data(curr); curr = match curr.parent_element() { Some(parent) => parent, None => break, }; } } } /// Calculates the style for a single node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<E, D>(traversal: &D, traversal_data: &mut PerLevelTraversalData, context: &mut StyleContext<E>, element: E, mut data: &mut AtomicRefMut<ElementData>) where E: TElement, D: DomTraversal<E> { context.thread_local.begin_element(element, &data); context.thread_local.statistics.elements_traversed += 1; debug_assert!(data.get_restyle().map_or(true, |r| { r.snapshot.is_none() &&!r.has_sibling_invalidations() }), "Should've computed the final hint and handled later_siblings already"); let compute_self =!data.has_current_styles(); let mut inherited_style_changed = false; debug!("recalc_style_at: {:?} (compute_self={:?}, dirty_descendants={:?}, data={:?})", element, compute_self, element.has_dirty_descendants(), data); // Compute style for this element if necessary. if compute_self { compute_style(traversal, traversal_data, context, element, &mut data); // If we're restyling this element to display:none, throw away all style // data in the subtree, notify the caller to early-return. let display_none = data.styles().is_display_none(); if display_none { debug!("New element style is display:none - clearing data from descendants."); clear_descendant_data(element, &|e| unsafe { D::clear_element_data(&e) }); } // FIXME(bholley): Compute this accurately from the call to CalcStyleDifference. inherited_style_changed = true; } // Now that matching and cascading is done, clear the bits corresponding to // those operations and compute the propagated restyle hint. let empty_hint = StoredRestyleHint::empty(); let propagated_hint = match data.get_restyle_mut() { None => empty_hint, Some(r) => { r.recascade = false; if r.hint.has_animation_hint() { debug_assert!(context.shared.animation_only_restyle, "animation restyle hint should be handled during animation-only restyles"); // Drop animation restyle hint. let propagated_hint = r.hint.propagate(); r.hint.remove_animation_hint(); propagated_hint } else { mem::replace(&mut r.hint, empty_hint).propagate() } }, }; debug_assert!(data.has_current_styles() || context.shared.animation_only_restyle, "Should have computed style or haven't yet valid computed style in case of animation-only restyle"); trace!("propagated_hint={:?}, inherited_style_changed={:?}", propagated_hint, inherited_style_changed); // Preprocess children, propagating restyle hints and handling sibling relationships. if traversal.should_traverse_children(&mut context.thread_local, element, &data, DontLog) && ((!context.shared.animation_only_restyle && element.has_dirty_descendants()) || (context.shared.animation_only_restyle && element.has_animation_only_dirty_descendants()) || !propagated_hint.is_empty() || inherited_style_changed) { let damage_handled = data.get_restyle().map_or(RestyleDamage::empty(), |r| { r.damage_handled() | r.damage.handled_for_descendants() }); preprocess_children(traversal, element, propagated_hint, damage_handled, inherited_style_changed); } if context.shared.animation_only_restyle { unsafe { element.unset_animation_only_dirty_descendants(); } } // Make sure the dirty descendants bit is not set for the root of a // display:none subtree, even if the style didn't change (since, if // the style did change, we'd have already cleared it above). // // This keeps the tree in a valid state without requiring the DOM to // check display:none on the parent when inserting new children (which // can be moderately expensive). Instead, DOM implementations can // unconditionally set the dirty descendants bit on any styled parent, // and let the traversal sort it out. if data.styles().is_display_none() { unsafe { element.unset_dirty_descendants(); } } } fn compute_style<E, D>(_traversal: &D, traversal_data: &mut PerLevelTraversalData, context: &mut StyleContext<E>, element: E, mut data: &mut AtomicRefMut<ElementData>) where E: TElement, D: DomTraversal<E>, { use data::RestyleKind::*; use matching::StyleSharingResult::*; context.thread_local.statistics.elements_styled += 1; let shared_context
traverse_unstyled_children_only
identifier_name
traversal.rs
TraversalDriver::Parallel) } } /// A DOM Traversal trait, that is used to generically implement styling for /// Gecko and Servo. pub trait DomTraversal<E: TElement> : Sync { /// The thread-local context, used to store non-thread-safe stuff that needs /// to be used in the traversal, and of which we use one per worker, like /// the bloom filter, for example. type ThreadLocalContext: Send + BorrowMut<ThreadLocalStyleContext<E>>; /// Process `node` on the way down, before its children have been processed. fn process_preorder(&self, data: &mut PerLevelTraversalData, thread_local: &mut Self::ThreadLocalContext, node: E::ConcreteNode); /// Process `node` on the way up, after its children have been processed. /// /// This is only executed if `needs_postorder_traversal` returns true. fn process_postorder(&self, thread_local: &mut Self::ThreadLocalContext, node: E::ConcreteNode); /// Boolean that specifies whether a bottom up traversal should be /// performed. /// /// If it's false, then process_postorder has no effect at all. fn needs_postorder_traversal() -> bool { true } /// Must be invoked before traversing the root element to determine whether /// a traversal is needed. Returns a token that allows the caller to prove /// that the call happened. /// /// The traversal_flag is used in Gecko. /// If traversal_flag::UNSTYLED_CHILDREN_ONLY is specified, style newly- /// appended children without restyling the parent. /// If traversal_flag::ANIMATION_ONLY is specified, style only elements for /// animations. fn pre_traverse(root: E, stylist: &Stylist, traversal_flags: TraversalFlags) -> PreTraverseToken { if traversal_flags.for_unstyled_children_only() { return PreTraverseToken { traverse: true, unstyled_children_only: true, }; } // Expand the snapshot, if any. This is normally handled by the parent, so // we need a special case for the root. // // Expanding snapshots here may create a LATER_SIBLINGS restyle hint, which // we will drop on the floor. To prevent missed restyles, we assert against // restyling a root with later siblings. if let Some(mut data) = root.mutate_data() { if let Some(r) = data.get_restyle_mut() { debug_assert!(root.next_sibling_element().is_none()); let _later_siblings = r.compute_final_hint(root, stylist); } } PreTraverseToken { traverse: Self::node_needs_traversal(root.as_node(), traversal_flags.for_animation_only()), unstyled_children_only: false, } } /// Returns true if traversal should visit a text node. The style system never /// processes text nodes, but Servo overrides this to visit them for flow /// construction when necessary. fn text_node_needs_traversal(node: E::ConcreteNode) -> bool { debug_assert!(node.is_text_node()); false } /// Returns true if traversal is needed for the given node and subtree. fn node_needs_traversal(node: E::ConcreteNode, animation_only: bool) -> bool
}; return data.get_restyle() .map_or(false, |r| r.hint.has_animation_hint() || r.recascade); } // If the dirty descendants bit is set, we need to traverse no // matter what. Skip examining the ElementData. if el.has_dirty_descendants() { return true; } // Check the element data. If it doesn't exist, we need to visit // the element. let data = match el.borrow_data() { Some(d) => d, None => return true, }; // If we don't have any style data, we need to visit the element. if!data.has_styles() { return true; } // Check the restyle data. if let Some(r) = data.get_restyle() { // If we have a restyle hint or need to recascade, we need to // visit the element. // // Note that this is different than checking has_current_styles(), // since that can return true even if we have a restyle hint // indicating that the element's descendants (but not necessarily // the element) need restyling. if!r.hint.is_empty() || r.recascade { return true; } } // Servo uses the post-order traversal for flow construction, so // we need to traverse any element with damage so that we can perform // fixup / reconstruction on our way back up the tree. if cfg!(feature = "servo") && data.get_restyle().map_or(false, |r| r.damage!= RestyleDamage::empty()) { return true; } false }, } } /// Returns true if traversal of this element's children is allowed. We use /// this to cull traversal of various subtrees. /// /// This may be called multiple times when processing an element, so we pass /// a parameter to keep the logs tidy. fn should_traverse_children(&self, thread_local: &mut ThreadLocalStyleContext<E>, parent: E, parent_data: &ElementData, log: LogBehavior) -> bool { // See the comment on `cascade_node` for why we allow this on Gecko. debug_assert!(cfg!(feature = "gecko") || parent_data.has_current_styles()); // If the parent computed display:none, we don't style the subtree. if parent_data.styles().is_display_none() { if log.allow() { debug!("Parent {:?} is display:none, culling traversal", parent); } return false; } // Gecko-only XBL handling. // // If we're computing initial styles and the parent has a Gecko XBL // binding, that binding may inject anonymous children and remap the // explicit children to an insertion point (or hide them entirely). It // may also specify a scoped stylesheet, which changes the rules that // apply within the subtree. These two effects can invalidate the result // of property inheritance and selector matching (respectively) within the // subtree. // // To avoid wasting work, we defer initial styling of XBL subtrees // until frame construction, which does an explicit traversal of the // unstyled children after shuffling the subtree. That explicit // traversal may in turn find other bound elements, which get handled // in the same way. // // We explicitly avoid handling restyles here (explicitly removing or // changing bindings), since that adds complexity and is rarer. If it // happens, we may just end up doing wasted work, since Gecko // recursively drops Servo ElementData when the XBL insertion parent of // an Element is changed. if cfg!(feature = "gecko") && thread_local.is_initial_style() && parent_data.styles().primary.values().has_moz_binding() { if log.allow() { debug!("Parent {:?} has XBL binding, deferring traversal", parent); } return false; } return true; } /// Helper for the traversal implementations to select the children that /// should be enqueued for processing. fn traverse_children<F>(&self, thread_local: &mut Self::ThreadLocalContext, parent: E, mut f: F) where F: FnMut(&mut Self::ThreadLocalContext, E::ConcreteNode) { // Check if we're allowed to traverse past this element. let should_traverse = self.should_traverse_children(thread_local.borrow_mut(), parent, &parent.borrow_data().unwrap(), MayLog); thread_local.borrow_mut().end_element(parent); if!should_traverse { return; } for kid in parent.as_node().children() { if Self::node_needs_traversal(kid, self.shared_context().animation_only_restyle) { let el = kid.as_element(); if el.as_ref().and_then(|el| el.borrow_data()) .map_or(false, |d| d.has_styles()) { unsafe { parent.set_dirty_descendants(); } } f(thread_local, kid); } } } /// Ensures the existence of the ElementData, and returns it. This can't live /// on TNode because of the trait-based separation between Servo's script /// and layout crates. /// /// This is only safe to call in top-down traversal before processing the /// children of |element|. unsafe fn ensure_element_data(element: &E) -> &AtomicRefCell<ElementData>; /// Clears the ElementData attached to this element, if any. /// /// This is only safe to call in top-down traversal before processing the /// children of |element|. unsafe fn clear_element_data(element: &E); /// Return the shared style context common to all worker threads. fn shared_context(&self) -> &SharedStyleContext; /// Creates a thread-local context. fn create_thread_local_context(&self) -> Self::ThreadLocalContext; /// Whether we're performing a parallel traversal. /// /// NB: We do this check on runtime. We could guarantee correctness in this /// regard via the type system via a `TraversalDriver` trait for this trait, /// that could be one of two concrete types. It's not clear whether the /// potential code size impact of that is worth it. fn is_parallel(&self) -> bool; } /// Helper for the function below. fn resolve_style_internal<E, F>(context: &mut StyleContext<E>, element: E, ensure_data: &F) -> Option<E> where E: TElement, F: Fn(E), { ensure_data(element); let mut data = element.mutate_data().unwrap(); let mut display_none_root = None; // If the Element isn't styled, we need to compute its style. if data.get_styles().is_none() { // Compute the parent style if necessary. let parent = element.parent_element(); if let Some(p) = parent { display_none_root = resolve_style_internal(context, p, ensure_data); } // Maintain the bloom filter. If it doesn't exist, we need to build it // from scratch. Otherwise we just need to push the parent. if context.thread_local.bloom_filter.is_empty() { context.thread_local.bloom_filter.rebuild(element); } else { context.thread_local.bloom_filter.push(parent.unwrap()); context.thread_local.bloom_filter.assert_complete(element); } // Compute our style. let match_results = element.match_element(context, &mut data); element.cascade_element(context, &mut data, match_results.primary_is_shareable()); // Conservatively mark us as having dirty descendants, since there might // be other unstyled siblings we miss when walking straight up the parent // chain. unsafe { element.set_dirty_descendants() }; } // If we're display:none and none of our ancestors are, we're the root // of a display:none subtree. if display_none_root.is_none() && data.styles().is_display_none() { display_none_root = Some(element); } return display_none_root } /// Manually resolve style by sequentially walking up the parent chain to the /// first styled Element, ignoring pending restyles. The resolved style is /// made available via a callback, and can be dropped by the time this function /// returns in the display:none subtree case. pub fn resolve_style<E, F, G, H>(context: &mut StyleContext<E>, element: E, ensure_data: &F, clear_data: &G, callback: H) where E: TElement, F: Fn(E), G: Fn(E), H: FnOnce(&ElementStyles) { // Clear the bloom filter, just in case the caller is reusing TLS. context.thread_local.bloom_filter.clear(); // Resolve styles up the tree. let display_none_root = resolve_style_internal(context, element, ensure_data); // Make them available for the scope of the callback. The callee may use the // argument, or perform any other processing that requires the styles to exist // on the Element. callback(element.borrow_data().unwrap().styles()); // Clear any styles in display:none subtrees or subtrees not in the document, // to leave the tree in a valid state. For display:none subtrees, we leave // the styles on the display:none root, but for subtrees not in the document, // we clear styles all the way up to the root of the disconnected subtree. let in_doc = element.as_node().is_in_doc(); if!in_doc || display_none_root.is_some() { let mut curr = element; loop { unsafe { curr.unset_dirty_descendants(); } if in_doc && curr == display_none_root.unwrap() { break; } clear_data(curr); curr = match curr.parent_element() { Some(parent) => parent, None => break, }; } } } /// Calculates the style for a single node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<E, D>(traversal: &D, traversal_data: &mut PerLevelTraversalData, context: &mut StyleContext<E>, element: E, mut data: &mut AtomicRefMut<ElementData>) where E: TElement, D: DomTraversal<E> { context.thread_local.begin_element(element, &data); context.thread_local.statistics.elements_traversed += 1; debug_assert!(data.get_restyle().map_or(true, |r| { r.snapshot.is_none() &&!r.has_sibling_invalidations() }), "Should've computed the final hint and handled later_siblings already"); let compute_self =!data.has_current_styles(); let mut inherited_style_changed = false; debug!("recalc_style_at: {:?} (compute_self={:?}, dirty_descendants={:?}, data={:?})", element, compute_self, element.has_dirty_descendants(), data); // Compute style for this element if necessary. if compute_self { compute_style(traversal, traversal_data, context, element, &mut data); // If we're restyling this element to display:none, throw away all style // data in the subtree, notify the caller to early-return. let display_none = data.styles().is_display_none(); if display_none { debug!("New element style is display:none - clearing data from descendants."); clear_descendant_data(element, &|e| unsafe { D::clear_element_data(&e) }); } // FIXME(bholley): Compute this accurately from the call to CalcStyleDifference. inherited_style_changed = true; } // Now that matching and cascading is done, clear the bits corresponding to // those operations and compute the propagated restyle hint. let empty_hint = StoredRestyleHint::empty(); let propagated_hint = match data.get_restyle_mut() { None => empty_hint, Some(r) => { r.recascade = false; if r.hint.has_animation_hint() { debug_assert!(context.shared.animation_only_restyle, "animation restyle hint should be handled during animation-only restyles"); // Drop animation restyle hint. let propagated_hint = r.hint.propagate(); r.hint.remove_animation_hint(); propagated_hint } else { mem::replace(&mut r.hint, empty_hint).propagate() } }, }; debug_assert!(data.has_current_styles() || context.shared.animation_only_restyle, "Should have computed style or haven't yet valid computed style in case of animation-only restyle"); trace!("propagated_hint={:?}, inherited_style_changed={:?}", propagated_hint, inherited_style_changed); // Preprocess children, propagating restyle hints and handling sibling relationships. if traversal.should_traverse_children(&mut context.thread_local, element, &data, DontLog) && ((!context.shared.animation_only_restyle && element.has_dirty_descendants()) || (context.shared.animation_only_restyle && element.has_animation_only_dirty_descendants()) || !propagated_hint.is_empty() || inherited_style_changed) { let damage_handled = data.get_restyle().map_or(RestyleDamage::empty(), |r| { r.damage_handled() | r.damage.handled_for_descendants() }); preprocess_children(traversal, element, propagated_hint, damage_handled, inherited_style_changed); } if context.shared.animation_only_restyle { unsafe { element.unset_animation_only_dirty_descendants(); } } // Make sure the dirty descendants bit is not set for the root of a // display:none subtree, even if the style didn't change (since, if // the style did change, we'd have already cleared it above). // // This keeps the tree in a valid state without requiring the DOM to // check display:none on the parent when inserting new children (which // can be moderately expensive). Instead, DOM implementations can // unconditionally set the dirty descendants bit on any styled parent, // and let the traversal sort it out. if data.styles().is_display_none() { unsafe { element.unset_dirty_descendants(); } } } fn compute_style<E, D>(_traversal: &D, traversal_data: &mut PerLevelTraversalData, context: &mut StyleContext<E>, element: E, mut data: &mut AtomicRefMut<ElementData>) where E: TElement, D: DomTraversal<E>, { use data::RestyleKind::*; use matching::StyleSharingResult::*; context.thread_local.statistics.elements_styled += 1; let shared_context = context.shared; let kind = data.restyle_kind(); // First, try the style sharing cache. If we get a match we can skip the rest // of the work. if let MatchAndCascade = kind { let sharing_result = unsafe { let cache = &mut context.thread_local.style_sharing_candidate_cache; element.share_style_if_possible(cache, shared_context, &mut data) }; if let StyleWasShared(index) = sharing_result { context.thread_local.statistics.styles_shared += 1; context.thread_local.style_sharing_candidate_cache.touch(index);
{ // Non-incremental layout visits every node. if cfg!(feature = "servo") && opts::get().nonincremental_layout { return true; } match node.as_element() { None => Self::text_node_needs_traversal(node), Some(el) => { // In case of animation-only traversal we need to traverse // the element if the element has animation only dirty // descendants bit, animation-only restyle hint or recascade. if animation_only { if el.has_animation_only_dirty_descendants() { return true; } let data = match el.borrow_data() { Some(d) => d, None => return false,
identifier_body
traversal.rs
, TraversalDriver::Parallel) } } /// A DOM Traversal trait, that is used to generically implement styling for /// Gecko and Servo. pub trait DomTraversal<E: TElement> : Sync { /// The thread-local context, used to store non-thread-safe stuff that needs /// to be used in the traversal, and of which we use one per worker, like /// the bloom filter, for example. type ThreadLocalContext: Send + BorrowMut<ThreadLocalStyleContext<E>>; /// Process `node` on the way down, before its children have been processed. fn process_preorder(&self, data: &mut PerLevelTraversalData, thread_local: &mut Self::ThreadLocalContext, node: E::ConcreteNode); /// Process `node` on the way up, after its children have been processed. /// /// This is only executed if `needs_postorder_traversal` returns true. fn process_postorder(&self, thread_local: &mut Self::ThreadLocalContext, node: E::ConcreteNode); /// Boolean that specifies whether a bottom up traversal should be /// performed. /// /// If it's false, then process_postorder has no effect at all. fn needs_postorder_traversal() -> bool { true } /// Must be invoked before traversing the root element to determine whether /// a traversal is needed. Returns a token that allows the caller to prove /// that the call happened. /// /// The traversal_flag is used in Gecko. /// If traversal_flag::UNSTYLED_CHILDREN_ONLY is specified, style newly- /// appended children without restyling the parent. /// If traversal_flag::ANIMATION_ONLY is specified, style only elements for /// animations. fn pre_traverse(root: E, stylist: &Stylist, traversal_flags: TraversalFlags) -> PreTraverseToken { if traversal_flags.for_unstyled_children_only() { return PreTraverseToken { traverse: true, unstyled_children_only: true, }; } // Expand the snapshot, if any. This is normally handled by the parent, so // we need a special case for the root. // // Expanding snapshots here may create a LATER_SIBLINGS restyle hint, which // we will drop on the floor. To prevent missed restyles, we assert against // restyling a root with later siblings. if let Some(mut data) = root.mutate_data() { if let Some(r) = data.get_restyle_mut() { debug_assert!(root.next_sibling_element().is_none()); let _later_siblings = r.compute_final_hint(root, stylist); } } PreTraverseToken { traverse: Self::node_needs_traversal(root.as_node(), traversal_flags.for_animation_only()), unstyled_children_only: false, } } /// Returns true if traversal should visit a text node. The style system never /// processes text nodes, but Servo overrides this to visit them for flow /// construction when necessary. fn text_node_needs_traversal(node: E::ConcreteNode) -> bool { debug_assert!(node.is_text_node()); false } /// Returns true if traversal is needed for the given node and subtree. fn node_needs_traversal(node: E::ConcreteNode, animation_only: bool) -> bool { // Non-incremental layout visits every node. if cfg!(feature = "servo") && opts::get().nonincremental_layout { return true; } match node.as_element() { None => Self::text_node_needs_traversal(node), Some(el) => { // In case of animation-only traversal we need to traverse // the element if the element has animation only dirty // descendants bit, animation-only restyle hint or recascade. if animation_only { if el.has_animation_only_dirty_descendants() { return true; } let data = match el.borrow_data() { Some(d) => d, None => return false, }; return data.get_restyle() .map_or(false, |r| r.hint.has_animation_hint() || r.recascade); } // If the dirty descendants bit is set, we need to traverse no // matter what. Skip examining the ElementData. if el.has_dirty_descendants() { return true; } // Check the element data. If it doesn't exist, we need to visit // the element. let data = match el.borrow_data() { Some(d) => d, None => return true, }; // If we don't have any style data, we need to visit the element. if!data.has_styles() { return true; } // Check the restyle data. if let Some(r) = data.get_restyle() { // If we have a restyle hint or need to recascade, we need to // visit the element. // // Note that this is different than checking has_current_styles(), // since that can return true even if we have a restyle hint // indicating that the element's descendants (but not necessarily // the element) need restyling. if!r.hint.is_empty() || r.recascade { return true; } } // Servo uses the post-order traversal for flow construction, so // we need to traverse any element with damage so that we can perform // fixup / reconstruction on our way back up the tree. if cfg!(feature = "servo") && data.get_restyle().map_or(false, |r| r.damage!= RestyleDamage::empty()) { return true; } false }, } } /// Returns true if traversal of this element's children is allowed. We use /// this to cull traversal of various subtrees. /// /// This may be called multiple times when processing an element, so we pass /// a parameter to keep the logs tidy. fn should_traverse_children(&self, thread_local: &mut ThreadLocalStyleContext<E>, parent: E, parent_data: &ElementData, log: LogBehavior) -> bool { // See the comment on `cascade_node` for why we allow this on Gecko. debug_assert!(cfg!(feature = "gecko") || parent_data.has_current_styles()); // If the parent computed display:none, we don't style the subtree. if parent_data.styles().is_display_none() { if log.allow() { debug!("Parent {:?} is display:none, culling traversal", parent); } return false; } // Gecko-only XBL handling. // // If we're computing initial styles and the parent has a Gecko XBL // binding, that binding may inject anonymous children and remap the // explicit children to an insertion point (or hide them entirely). It // may also specify a scoped stylesheet, which changes the rules that // apply within the subtree. These two effects can invalidate the result // of property inheritance and selector matching (respectively) within the // subtree. // // To avoid wasting work, we defer initial styling of XBL subtrees // until frame construction, which does an explicit traversal of the // unstyled children after shuffling the subtree. That explicit // traversal may in turn find other bound elements, which get handled // in the same way. // // We explicitly avoid handling restyles here (explicitly removing or
// an Element is changed. if cfg!(feature = "gecko") && thread_local.is_initial_style() && parent_data.styles().primary.values().has_moz_binding() { if log.allow() { debug!("Parent {:?} has XBL binding, deferring traversal", parent); } return false; } return true; } /// Helper for the traversal implementations to select the children that /// should be enqueued for processing. fn traverse_children<F>(&self, thread_local: &mut Self::ThreadLocalContext, parent: E, mut f: F) where F: FnMut(&mut Self::ThreadLocalContext, E::ConcreteNode) { // Check if we're allowed to traverse past this element. let should_traverse = self.should_traverse_children(thread_local.borrow_mut(), parent, &parent.borrow_data().unwrap(), MayLog); thread_local.borrow_mut().end_element(parent); if!should_traverse { return; } for kid in parent.as_node().children() { if Self::node_needs_traversal(kid, self.shared_context().animation_only_restyle) { let el = kid.as_element(); if el.as_ref().and_then(|el| el.borrow_data()) .map_or(false, |d| d.has_styles()) { unsafe { parent.set_dirty_descendants(); } } f(thread_local, kid); } } } /// Ensures the existence of the ElementData, and returns it. This can't live /// on TNode because of the trait-based separation between Servo's script /// and layout crates. /// /// This is only safe to call in top-down traversal before processing the /// children of |element|. unsafe fn ensure_element_data(element: &E) -> &AtomicRefCell<ElementData>; /// Clears the ElementData attached to this element, if any. /// /// This is only safe to call in top-down traversal before processing the /// children of |element|. unsafe fn clear_element_data(element: &E); /// Return the shared style context common to all worker threads. fn shared_context(&self) -> &SharedStyleContext; /// Creates a thread-local context. fn create_thread_local_context(&self) -> Self::ThreadLocalContext; /// Whether we're performing a parallel traversal. /// /// NB: We do this check on runtime. We could guarantee correctness in this /// regard via the type system via a `TraversalDriver` trait for this trait, /// that could be one of two concrete types. It's not clear whether the /// potential code size impact of that is worth it. fn is_parallel(&self) -> bool; } /// Helper for the function below. fn resolve_style_internal<E, F>(context: &mut StyleContext<E>, element: E, ensure_data: &F) -> Option<E> where E: TElement, F: Fn(E), { ensure_data(element); let mut data = element.mutate_data().unwrap(); let mut display_none_root = None; // If the Element isn't styled, we need to compute its style. if data.get_styles().is_none() { // Compute the parent style if necessary. let parent = element.parent_element(); if let Some(p) = parent { display_none_root = resolve_style_internal(context, p, ensure_data); } // Maintain the bloom filter. If it doesn't exist, we need to build it // from scratch. Otherwise we just need to push the parent. if context.thread_local.bloom_filter.is_empty() { context.thread_local.bloom_filter.rebuild(element); } else { context.thread_local.bloom_filter.push(parent.unwrap()); context.thread_local.bloom_filter.assert_complete(element); } // Compute our style. let match_results = element.match_element(context, &mut data); element.cascade_element(context, &mut data, match_results.primary_is_shareable()); // Conservatively mark us as having dirty descendants, since there might // be other unstyled siblings we miss when walking straight up the parent // chain. unsafe { element.set_dirty_descendants() }; } // If we're display:none and none of our ancestors are, we're the root // of a display:none subtree. if display_none_root.is_none() && data.styles().is_display_none() { display_none_root = Some(element); } return display_none_root } /// Manually resolve style by sequentially walking up the parent chain to the /// first styled Element, ignoring pending restyles. The resolved style is /// made available via a callback, and can be dropped by the time this function /// returns in the display:none subtree case. pub fn resolve_style<E, F, G, H>(context: &mut StyleContext<E>, element: E, ensure_data: &F, clear_data: &G, callback: H) where E: TElement, F: Fn(E), G: Fn(E), H: FnOnce(&ElementStyles) { // Clear the bloom filter, just in case the caller is reusing TLS. context.thread_local.bloom_filter.clear(); // Resolve styles up the tree. let display_none_root = resolve_style_internal(context, element, ensure_data); // Make them available for the scope of the callback. The callee may use the // argument, or perform any other processing that requires the styles to exist // on the Element. callback(element.borrow_data().unwrap().styles()); // Clear any styles in display:none subtrees or subtrees not in the document, // to leave the tree in a valid state. For display:none subtrees, we leave // the styles on the display:none root, but for subtrees not in the document, // we clear styles all the way up to the root of the disconnected subtree. let in_doc = element.as_node().is_in_doc(); if!in_doc || display_none_root.is_some() { let mut curr = element; loop { unsafe { curr.unset_dirty_descendants(); } if in_doc && curr == display_none_root.unwrap() { break; } clear_data(curr); curr = match curr.parent_element() { Some(parent) => parent, None => break, }; } } } /// Calculates the style for a single node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<E, D>(traversal: &D, traversal_data: &mut PerLevelTraversalData, context: &mut StyleContext<E>, element: E, mut data: &mut AtomicRefMut<ElementData>) where E: TElement, D: DomTraversal<E> { context.thread_local.begin_element(element, &data); context.thread_local.statistics.elements_traversed += 1; debug_assert!(data.get_restyle().map_or(true, |r| { r.snapshot.is_none() &&!r.has_sibling_invalidations() }), "Should've computed the final hint and handled later_siblings already"); let compute_self =!data.has_current_styles(); let mut inherited_style_changed = false; debug!("recalc_style_at: {:?} (compute_self={:?}, dirty_descendants={:?}, data={:?})", element, compute_self, element.has_dirty_descendants(), data); // Compute style for this element if necessary. if compute_self { compute_style(traversal, traversal_data, context, element, &mut data); // If we're restyling this element to display:none, throw away all style // data in the subtree, notify the caller to early-return. let display_none = data.styles().is_display_none(); if display_none { debug!("New element style is display:none - clearing data from descendants."); clear_descendant_data(element, &|e| unsafe { D::clear_element_data(&e) }); } // FIXME(bholley): Compute this accurately from the call to CalcStyleDifference. inherited_style_changed = true; } // Now that matching and cascading is done, clear the bits corresponding to // those operations and compute the propagated restyle hint. let empty_hint = StoredRestyleHint::empty(); let propagated_hint = match data.get_restyle_mut() { None => empty_hint, Some(r) => { r.recascade = false; if r.hint.has_animation_hint() { debug_assert!(context.shared.animation_only_restyle, "animation restyle hint should be handled during animation-only restyles"); // Drop animation restyle hint. let propagated_hint = r.hint.propagate(); r.hint.remove_animation_hint(); propagated_hint } else { mem::replace(&mut r.hint, empty_hint).propagate() } }, }; debug_assert!(data.has_current_styles() || context.shared.animation_only_restyle, "Should have computed style or haven't yet valid computed style in case of animation-only restyle"); trace!("propagated_hint={:?}, inherited_style_changed={:?}", propagated_hint, inherited_style_changed); // Preprocess children, propagating restyle hints and handling sibling relationships. if traversal.should_traverse_children(&mut context.thread_local, element, &data, DontLog) && ((!context.shared.animation_only_restyle && element.has_dirty_descendants()) || (context.shared.animation_only_restyle && element.has_animation_only_dirty_descendants()) || !propagated_hint.is_empty() || inherited_style_changed) { let damage_handled = data.get_restyle().map_or(RestyleDamage::empty(), |r| { r.damage_handled() | r.damage.handled_for_descendants() }); preprocess_children(traversal, element, propagated_hint, damage_handled, inherited_style_changed); } if context.shared.animation_only_restyle { unsafe { element.unset_animation_only_dirty_descendants(); } } // Make sure the dirty descendants bit is not set for the root of a // display:none subtree, even if the style didn't change (since, if // the style did change, we'd have already cleared it above). // // This keeps the tree in a valid state without requiring the DOM to // check display:none on the parent when inserting new children (which // can be moderately expensive). Instead, DOM implementations can // unconditionally set the dirty descendants bit on any styled parent, // and let the traversal sort it out. if data.styles().is_display_none() { unsafe { element.unset_dirty_descendants(); } } } fn compute_style<E, D>(_traversal: &D, traversal_data: &mut PerLevelTraversalData, context: &mut StyleContext<E>, element: E, mut data: &mut AtomicRefMut<ElementData>) where E: TElement, D: DomTraversal<E>, { use data::RestyleKind::*; use matching::StyleSharingResult::*; context.thread_local.statistics.elements_styled += 1; let shared_context = context.shared; let kind = data.restyle_kind(); // First, try the style sharing cache. If we get a match we can skip the rest // of the work. if let MatchAndCascade = kind { let sharing_result = unsafe { let cache = &mut context.thread_local.style_sharing_candidate_cache; element.share_style_if_possible(cache, shared_context, &mut data) }; if let StyleWasShared(index) = sharing_result { context.thread_local.statistics.styles_shared += 1; context.thread_local.style_sharing_candidate_cache.touch(index);
// changing bindings), since that adds complexity and is rarer. If it // happens, we may just end up doing wasted work, since Gecko // recursively drops Servo ElementData when the XBL insertion parent of
random_line_split
opcode.rs
enum_from_primitive! { #[derive(Debug)] pub enum Opcode { // Control NoOp = 0x00, // Stop = 0x10, // Halt = 0x76, Special = 0xCB, // Flow Control Jump = 0xC3, JumpNonZero = 0xC2, JumpZero = 0xCA, JumpNonCarry = 0xD2, JumpCarry = 0xDA, JumpRelative = 0x18, JumpRelativeNonZero = 0x20, JumpRelativeZero = 0x28, JumpRelativeNonCarry = 0x30, JumpRelativeCarry = 0x38, Return = 0xC9, CallImmAddr = 0xCD, // 8-bit Load LoadAIntoC = 0x4f, LoadAIntoD = 0x57, LoadAIntoH = 0x67, LoadEIntoA = 0x7B, LoadImmIntoB = 0x06, LoadImmIntoC = 0x0E, LoadImmIntoD = 0x16, LoadImmIntoE = 0x1E, LoadImmIntoH = 0x26, LoadImmIntoL = 0x2E, LoadImmIntoA = 0x3E, LoadImmIntoAddrHl = 0x36, LoadAIntoAddrC = 0xE2, LoadAIntoAddrBc = 0x02, LoadAIntoAddrDe = 0x12, LoadAIntoAddrHl = 0x77, LoadAddrBcIntoA = 0x0A, LoadAddrDeIntoA = 0x1A, LoadAIntoImmAddr = 0xEA, LoadAIntoAddrHlAndInc = 0x22, LoadAddrHLIntoAAndInc = 0x2A, LoadAIntoAddrHlAndDec = 0x32, LoadAddrHlIntoAAndDec = 0x3A, LoadAIntoImmAddrIO = 0xE0, LoadImmAddrIOIntoA = 0xF0, // 16-bit Load LoadImmIntoBc = 0x01, LoadImmIntoDe = 0x11,
LoadSpIntoImmAddr = 0x08, PopBc = 0xC1, PushBc = 0xC5, // 8-bit Math IncrementB = 0x04, IncrementC = 0x0C, DecrementB = 0x05, DecrementC = 0x0D, DecrementA = 0x3D, SubtractL = 0x95, XorA = 0xAF, CompareImm = 0xFE, // 16-bit Math IncrementDe = 0x13, IncrementHl = 0x23, // 8-bit Shift/Rotate RotateLeftA = 0x17, } } enum_from_primitive! { #[derive(Debug)] pub enum SpecialOpcode { RotateLeftC = 0x11, Bit7H = 0x7C, } }
LoadImmIntoHl = 0x21, LoadImmIntoSp = 0x31,
random_line_split
errors.rs
use neon::prelude::*; pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.error(msg) } pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.type_error(msg) } pub fn
(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.range_error(msg) } pub fn throw_error(mut cx: FunctionContext) -> JsResult<JsUndefined> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.throw_error(msg) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber, _>(&mut cx) { Ok(cx.string(format!("{}", e))) } else { panic!() } }
new_range_error
identifier_name
errors.rs
use neon::prelude::*; pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.error(msg) } pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.type_error(msg) } pub fn new_range_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.range_error(msg) } pub fn throw_error(mut cx: FunctionContext) -> JsResult<JsUndefined>
pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber, _>(&mut cx) { Ok(cx.string(format!("{}", e))) } else { panic!() } }
{ let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.throw_error(msg) }
identifier_body
errors.rs
use neon::prelude::*; pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.error(msg) }
pub fn new_range_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.range_error(msg) } pub fn throw_error(mut cx: FunctionContext) -> JsResult<JsUndefined> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.throw_error(msg) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber, _>(&mut cx) { Ok(cx.string(format!("{}", e))) } else { panic!() } }
pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.type_error(msg) }
random_line_split
errors.rs
use neon::prelude::*; pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.error(msg) } pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.type_error(msg) } pub fn new_range_error(mut cx: FunctionContext) -> JsResult<JsError> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.range_error(msg) } pub fn throw_error(mut cx: FunctionContext) -> JsResult<JsUndefined> { let msg = cx.argument::<JsString>(0)?.value(&mut cx); cx.throw_error(msg) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> { let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber, _>(&mut cx)
else { panic!() } }
{ Ok(cx.string(format!("{}", e))) }
conditional_block
error.rs
//! This module contains enum Error. //! Error type represents all possible errors that can occur when dealing //! with the generic or any dedicated-exchange API use serde_json; use hyper; use data_encoding; use exchange::Exchange; error_chain!{ types { Error, ErrorKind, ResultExt, Result; } foreign_links { Json(serde_json::Error); ParseFloat(::std::num::ParseFloatError); ParseString(::std::string::FromUtf8Error); Hyper(hyper::Error); DataDecoding(data_encoding::DecodeError); Io(::std::io::Error); } errors { BadParse { description("ParsingError") display("The response could not be parsed.") } ServiceUnavailable(reason: String) { description("ServiceUnavailable") display("Host could not be reached: {}.", reason) } BadCredentials { description("BadCredentials") display("The informations provided do not allow authentication.") } RateLimitExceeded { description("RateLimitExceeded") display("API call rate limit exceeded.") } PairUnsupported { description("PairUnsupported") display("This pair is not supported.") } InvalidArguments { description("InvalidArguments") display("Arguments passed do not conform to the protocol.") } ExchangeSpecificError(reason: String) { description("ExchangeSpecificError") display("Exchange error: {}", reason) } TlsError { description("TlsError") display("Fail to initialize TLS client.") } InvalidFieldFormat(field: String) { description("InvalidFieldFormat") display("Fail to parse field \"{}\".", field) } InvalidFieldValue(field: String) { description("InvalidFieldValue") display("Invalid value for field \"{}\".", field) } MissingField(field: String) { description("MissingFiled") display("Missing field \"{}\".", field) } InsufficientFunds { description("InsufficientFunds") display("You haven't enough founds.") }
MissingPrice{ description("MissingPrice") display("No price specified.") } InvalidConfigType(expected: Exchange, find: Exchange){ description("InvalidConfigType") display("Invalid config: \nExpected: {:?}\nFind: {:?}", expected, find) } InvalidExchange(value: String) { description("InvalidExchange") display("Invalid exchange: \"{}\"", value) } InvalidNonce { description("InvalidNonce") display("Invalid nonce") } PermissionDenied { description("PermissionDenied") display("The operation cannot be done with the provided credentials") } } }
InsufficientOrderSize { description("InsufficientOrderSize") display("Your order is not big enough.") }
random_line_split
format.rs
#[macro_use] extern crate pretty_assertions; #[allow(unused)] mod support; use tokio::io::AsyncWrite; use languageserver_types::*; use crate::support::{did_change_event, expect_notification, expect_response, hover}; async fn
<W:?Sized>(stdin: &mut W, id: u64, uri: &str) where W: AsyncWrite + std::marker::Unpin, { let hover = support::method_call( "textDocument/formatting", id, DocumentFormattingParams { text_document: TextDocumentIdentifier { uri: support::test_url(uri), }, options: FormattingOptions { tab_size: 4, insert_spaces: true, properties: Default::default(), }, }, ); support::write_message(stdin, hover).await.unwrap(); } #[test] fn simple() { let text = r#" let x = 1 x + 2 "#; let expected = r#" let x = 1 x + 2 "#; support::send_rpc(move |stdin, stdout| { Box::pin(async move { support::did_open(stdin, "test", text).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; format(stdin, 2, "test").await; let edits: Vec<TextEdit> = expect_response(stdout).await; assert_eq!( edits, vec![TextEdit { range: Range { start: Position { line: 0, character: 0, }, end: Position { line: 4, character: 0, }, }, new_text: expected.to_string(), }] ); }) }); } #[test] fn empty_content_changes_do_not_lockup_server() { let text = r#" let x = 1 x + "abc" "#; support::send_rpc(move |stdin, stdout| { Box::pin(async move { // Insert a dummy file so that test is not the first file support::did_open(stdin, "dummy", r#""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa""#).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; support::did_open(stdin, "test", text).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; // Since nothing changed we don't update the version did_change_event(stdin, "test", 1, vec![]).await; hover( stdin, 4, "test", Position { line: 2, character: 7, }, ) .await; let hover: Hover = expect_response(&mut *stdout).await; assert_eq!( hover, Hover { contents: HoverContents::Scalar(MarkedString::String("String".into())), range: Some(Range { start: Position { line: 2, character: 4, }, end: Position { line: 2, character: 9, }, }), } ); }) }); }
format
identifier_name
format.rs
#[macro_use] extern crate pretty_assertions; #[allow(unused)] mod support; use tokio::io::AsyncWrite; use languageserver_types::*; use crate::support::{did_change_event, expect_notification, expect_response, hover}; async fn format<W:?Sized>(stdin: &mut W, id: u64, uri: &str) where W: AsyncWrite + std::marker::Unpin, { let hover = support::method_call(
}, options: FormattingOptions { tab_size: 4, insert_spaces: true, properties: Default::default(), }, }, ); support::write_message(stdin, hover).await.unwrap(); } #[test] fn simple() { let text = r#" let x = 1 x + 2 "#; let expected = r#" let x = 1 x + 2 "#; support::send_rpc(move |stdin, stdout| { Box::pin(async move { support::did_open(stdin, "test", text).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; format(stdin, 2, "test").await; let edits: Vec<TextEdit> = expect_response(stdout).await; assert_eq!( edits, vec![TextEdit { range: Range { start: Position { line: 0, character: 0, }, end: Position { line: 4, character: 0, }, }, new_text: expected.to_string(), }] ); }) }); } #[test] fn empty_content_changes_do_not_lockup_server() { let text = r#" let x = 1 x + "abc" "#; support::send_rpc(move |stdin, stdout| { Box::pin(async move { // Insert a dummy file so that test is not the first file support::did_open(stdin, "dummy", r#""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa""#).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; support::did_open(stdin, "test", text).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; // Since nothing changed we don't update the version did_change_event(stdin, "test", 1, vec![]).await; hover( stdin, 4, "test", Position { line: 2, character: 7, }, ) .await; let hover: Hover = expect_response(&mut *stdout).await; assert_eq!( hover, Hover { contents: HoverContents::Scalar(MarkedString::String("String".into())), range: Some(Range { start: Position { line: 2, character: 4, }, end: Position { line: 2, character: 9, }, }), } ); }) }); }
"textDocument/formatting", id, DocumentFormattingParams { text_document: TextDocumentIdentifier { uri: support::test_url(uri),
random_line_split
format.rs
#[macro_use] extern crate pretty_assertions; #[allow(unused)] mod support; use tokio::io::AsyncWrite; use languageserver_types::*; use crate::support::{did_change_event, expect_notification, expect_response, hover}; async fn format<W:?Sized>(stdin: &mut W, id: u64, uri: &str) where W: AsyncWrite + std::marker::Unpin,
#[test] fn simple() { let text = r#" let x = 1 x + 2 "#; let expected = r#" let x = 1 x + 2 "#; support::send_rpc(move |stdin, stdout| { Box::pin(async move { support::did_open(stdin, "test", text).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; format(stdin, 2, "test").await; let edits: Vec<TextEdit> = expect_response(stdout).await; assert_eq!( edits, vec![TextEdit { range: Range { start: Position { line: 0, character: 0, }, end: Position { line: 4, character: 0, }, }, new_text: expected.to_string(), }] ); }) }); } #[test] fn empty_content_changes_do_not_lockup_server() { let text = r#" let x = 1 x + "abc" "#; support::send_rpc(move |stdin, stdout| { Box::pin(async move { // Insert a dummy file so that test is not the first file support::did_open(stdin, "dummy", r#""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa""#).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; support::did_open(stdin, "test", text).await; let _: PublishDiagnosticsParams = expect_notification(&mut *stdout).await; // Since nothing changed we don't update the version did_change_event(stdin, "test", 1, vec![]).await; hover( stdin, 4, "test", Position { line: 2, character: 7, }, ) .await; let hover: Hover = expect_response(&mut *stdout).await; assert_eq!( hover, Hover { contents: HoverContents::Scalar(MarkedString::String("String".into())), range: Some(Range { start: Position { line: 2, character: 4, }, end: Position { line: 2, character: 9, }, }), } ); }) }); }
{ let hover = support::method_call( "textDocument/formatting", id, DocumentFormattingParams { text_document: TextDocumentIdentifier { uri: support::test_url(uri), }, options: FormattingOptions { tab_size: 4, insert_spaces: true, properties: Default::default(), }, }, ); support::write_message(stdin, hover).await.unwrap(); }
identifier_body
macro_rules.rs
#![allow(dead_code)] //! Used to test that certain lints don't trigger in imported external macros #[macro_export] macro_rules! foofoo { () => { loop {} }; } #[macro_export] macro_rules! must_use_unit { () => { #[must_use] fn foo() {} }; } #[macro_export] macro_rules! try_err { () => { pub fn try_err_fn() -> Result<i32, i32> { let err: i32 = 1; // To avoid warnings during rustfix if true { Err(err)? } else { Ok(2) } } }; } #[macro_export] macro_rules! string_add { () => { let y = "".to_owned();
} #[macro_export] macro_rules! take_external { ($s:expr) => { std::mem::replace($s, Default::default()) }; } #[macro_export] macro_rules! option_env_unwrap_external { ($env: expr) => { option_env!($env).unwrap() }; ($env: expr, $message: expr) => { option_env!($env).expect($message) }; } #[macro_export] macro_rules! ref_arg_binding { () => { let ref _y = 42; }; } #[macro_export] macro_rules! ref_arg_function { () => { fn fun_example(ref _x: usize) {} }; } #[macro_export] macro_rules! as_conv_with_arg { (0u32 as u64) => { () }; } #[macro_export] macro_rules! as_conv { () => { 0u32 as u64 }; } #[macro_export] macro_rules! large_enum_variant { () => { enum LargeEnumInMacro { A(i32), B([i32; 8000]), } }; } #[macro_export] macro_rules! field_reassign_with_default { () => { #[derive(Default)] struct A { pub i: i32, pub j: i64, } fn lint() { let mut a: A = Default::default(); a.i = 42; a; } }; } #[macro_export] macro_rules! default_numeric_fallback { () => { let x = 22; }; } #[macro_export] macro_rules! mut_mut { () => { let mut_mut_ty: &mut &mut u32 = &mut &mut 1u32; }; }
let z = y + "..."; };
random_line_split
int_macros.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
#![doc(hidden)] macro_rules! int_module { ($T:ty, $bits:expr) => ( // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of // calling the `mem::size_of` function. #[unstable] pub const BITS : uint = $bits; // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of // calling the `mem::size_of` function. #[unstable] pub const BYTES : uint = ($bits / 8); // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of // calling the `Bounded::min_value` function. #[stable] pub const MIN: $T = (-1 as $T) << (BITS - 1); // FIXME(#9837): Compute MIN like this so the high bits that shouldn't exist are 0. // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of // calling the `Bounded::max_value` function. #[stable] pub const MAX: $T =!MIN; ) }
// 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.
random_line_split
tests.rs
use std::ops::Deref; use std::str; use digest::Digest; use rustc_serialize as ser; use rustc_serialize::hex::{FromHex, ToHex}; #[derive(Debug, PartialEq, Eq)] pub struct
(Vec<u8>); impl Deref for Data { type Target = [u8]; fn deref(&self) -> &[u8] { &*self.0 } } impl ser::Decodable for Data { fn decode<D: ser::Decoder>(d: &mut D) -> Result<Data, D::Error> { let data = try!(d.read_str()); if data.starts_with("hex:") { Ok(Data(data[4..].from_hex().unwrap())) } else { Ok(Data(data.into())) } } } #[derive(RustcDecodable)] pub struct Test { input: Data, output: Data, } impl Test { pub fn test<T: Testable>(&self, tested: T) { tested.test(self); } } pub trait Testable: Sized { fn test(self, &Test); } impl<T> Testable for T where T: Digest + Sized { fn test(mut self, test: &Test) { self.update(&*test.input); let mut output = vec![0; T::output_bytes()]; self.result(&mut output[..]); assert!(&*test.output == &output[..], "Input: {:?} (str: \"{}\")\nExpected: {}\nGot: {}", test.input, str::from_utf8(&*test.input).unwrap_or("<non-UTF8>"), test.output.to_hex(), output.to_hex()); } }
Data
identifier_name
tests.rs
use std::ops::Deref; use std::str; use digest::Digest; use rustc_serialize as ser; use rustc_serialize::hex::{FromHex, ToHex}; #[derive(Debug, PartialEq, Eq)] pub struct Data(Vec<u8>); impl Deref for Data { type Target = [u8]; fn deref(&self) -> &[u8] { &*self.0 } } impl ser::Decodable for Data { fn decode<D: ser::Decoder>(d: &mut D) -> Result<Data, D::Error> { let data = try!(d.read_str()); if data.starts_with("hex:")
else { Ok(Data(data.into())) } } } #[derive(RustcDecodable)] pub struct Test { input: Data, output: Data, } impl Test { pub fn test<T: Testable>(&self, tested: T) { tested.test(self); } } pub trait Testable: Sized { fn test(self, &Test); } impl<T> Testable for T where T: Digest + Sized { fn test(mut self, test: &Test) { self.update(&*test.input); let mut output = vec![0; T::output_bytes()]; self.result(&mut output[..]); assert!(&*test.output == &output[..], "Input: {:?} (str: \"{}\")\nExpected: {}\nGot: {}", test.input, str::from_utf8(&*test.input).unwrap_or("<non-UTF8>"), test.output.to_hex(), output.to_hex()); } }
{ Ok(Data(data[4..].from_hex().unwrap())) }
conditional_block
tests.rs
use std::ops::Deref; use std::str; use digest::Digest; use rustc_serialize as ser; use rustc_serialize::hex::{FromHex, ToHex}; #[derive(Debug, PartialEq, Eq)] pub struct Data(Vec<u8>); impl Deref for Data { type Target = [u8]; fn deref(&self) -> &[u8] { &*self.0 } } impl ser::Decodable for Data { fn decode<D: ser::Decoder>(d: &mut D) -> Result<Data, D::Error> { let data = try!(d.read_str()); if data.starts_with("hex:") { Ok(Data(data[4..].from_hex().unwrap())) } else { Ok(Data(data.into())) } } } #[derive(RustcDecodable)] pub struct Test { input: Data, output: Data, } impl Test { pub fn test<T: Testable>(&self, tested: T) { tested.test(self); } }
pub trait Testable: Sized { fn test(self, &Test); } impl<T> Testable for T where T: Digest + Sized { fn test(mut self, test: &Test) { self.update(&*test.input); let mut output = vec![0; T::output_bytes()]; self.result(&mut output[..]); assert!(&*test.output == &output[..], "Input: {:?} (str: \"{}\")\nExpected: {}\nGot: {}", test.input, str::from_utf8(&*test.input).unwrap_or("<non-UTF8>"), test.output.to_hex(), output.to_hex()); } }
random_line_split
comparison_benches.rs
#![feature(test)] extern crate futures; extern crate test; extern crate tokio; extern crate trust_dns_client; extern crate trust_dns_proto; extern crate trust_dns_server; use std::env; use std::fs::{DirBuilder, File}; use std::mem; use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::Duration; use futures::Future; use test::Bencher; use tokio::net::TcpStream; use tokio::net::UdpSocket; use tokio::runtime::Runtime; use trust_dns_client::client::*; use trust_dns_client::op::*; use trust_dns_client::rr::dnssec::Signer; use trust_dns_client::rr::*; use trust_dns_client::tcp::*; use trust_dns_client::udp::*; use trust_dns_proto::error::*; use trust_dns_proto::xfer::*; use trust_dns_proto::{iocompat::AsyncIo02As03, TokioTime}; fn find_test_port() -> u16 { let server = std::net::UdpSocket::bind(("0.0.0.0", 0)).unwrap(); let server_addr = server.local_addr().unwrap(); server_addr.port() } struct NamedProcess { named: Child, } impl Drop for NamedProcess { fn drop(&mut self) { self.named.kill().expect("could not kill process"); self.named.wait().expect("waiting failed"); } } fn wrap_process(named: Child, server_port: u16) -> NamedProcess { let mut started = false; for _ in 0..20 { let mut io_loop = Runtime::new().unwrap(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); if response.is_ok() { started = true; break; } else { // wait for the server to start thread::sleep(Duration::from_millis(500)); } } assert!(started, "server did not startup..."); // return handle to child process NamedProcess { named } } /// Returns a NamedProcess (cleans the process up on drop), and a socket addr for connecting /// to the server. fn trust_dns_process() -> (NamedProcess, u16) { // find a random port to listen on let test_port = find_test_port(); let ws_root = env::var("WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let named_path = format!("{}/target/release/named", ws_root); let config_path = format!( "{}/tests/test-data/named_test_configs/example.toml", ws_root ); let zone_dir = format!("{}/tests/test-data/named_test_configs", ws_root); File::open(&named_path).expect(&named_path); File::open(&config_path).expect(&config_path); File::open(&zone_dir).expect(&zone_dir); let named = Command::new(&named_path) .stdout(Stdio::null()) .arg("-q") // TODO: need to rethink this one... .arg(&format!("--config={}", config_path)) .arg(&format!("--zonedir={}", zone_dir)) .arg(&format!("--port={}", test_port)) .spawn() .expect("failed to start named"); // let process = wrap_process(named, test_port); // return handle to child process (process, test_port) } /// Runs the bench tesk using the specified client fn bench<F, S, R>(b: &mut Bencher, stream: F) where F: Future<Output = Result<S, ProtoError>> +'static + Send + Unpin, S: DnsRequestSender<DnsResponseFuture = R>, R: Future<Output = Result<DnsResponse, ProtoError>> +'static + Send + Unpin, { let mut io_loop = Runtime::new().unwrap(); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); // validate the request let query = client.query(name.clone(), DNSClass::IN, RecordType::A); let response = io_loop.block_on(query).expect("Request failed"); assert_eq!(response.response_code(), ResponseCode::NoError); let record = &response.answers()[0]; if let RData::A(ref address) = *record.rdata() { assert_eq!(address, &Ipv4Addr::new(127, 0, 0, 1)); } else { unreachable!(); } b.iter(|| { let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); response.unwrap(); }); } #[bench] fn trust_dns_udp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn trust_dns_udp_bench_prof(b: &mut Bencher) { let server_port = 6363; let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); } #[bench] fn trust_dns_tcp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port)
.next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); } // downloaded from https://www.isc.org/downloads/file/bind-9-11-0-p1/ // cd bind-9-11-0-p1 //.configure // make // export TDNS_BIND_PATH=${PWD}/bin/named/named fn bind_process() -> (NamedProcess, u16) { let test_port = find_test_port(); let bind_path = env::var("TDNS_BIND_PATH").unwrap_or_else(|_| "".to_owned()); let server_path = env::var("TDNS_WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let bind_path = format!("{}/sbin/named", bind_path); // create the work directory let working_dir = format!("{}/../target/bind_pwd", server_path); if!Path::new(&working_dir).exists() { DirBuilder::new() .create(&working_dir) .expect("failed to create dir"); } let mut named = Command::new(bind_path) .current_dir(&working_dir) .stderr(Stdio::piped()) .arg("-c") .arg("../../server/benches/bind_conf/example.conf") //.arg("-d").arg("0") .arg("-D") .arg("Trust-DNS cmp bench") .arg("-g") .arg("-p") .arg(&format!("{}", test_port)) .spawn() .expect("failed to start named"); mem::replace(&mut named.stderr, None).unwrap(); let process = wrap_process(named, test_port); (process, test_port) } #[bench] #[ignore] fn bind_udp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn bind_tcp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); }
.to_socket_addrs() .unwrap()
random_line_split
comparison_benches.rs
#![feature(test)] extern crate futures; extern crate test; extern crate tokio; extern crate trust_dns_client; extern crate trust_dns_proto; extern crate trust_dns_server; use std::env; use std::fs::{DirBuilder, File}; use std::mem; use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::Duration; use futures::Future; use test::Bencher; use tokio::net::TcpStream; use tokio::net::UdpSocket; use tokio::runtime::Runtime; use trust_dns_client::client::*; use trust_dns_client::op::*; use trust_dns_client::rr::dnssec::Signer; use trust_dns_client::rr::*; use trust_dns_client::tcp::*; use trust_dns_client::udp::*; use trust_dns_proto::error::*; use trust_dns_proto::xfer::*; use trust_dns_proto::{iocompat::AsyncIo02As03, TokioTime}; fn find_test_port() -> u16 { let server = std::net::UdpSocket::bind(("0.0.0.0", 0)).unwrap(); let server_addr = server.local_addr().unwrap(); server_addr.port() } struct NamedProcess { named: Child, } impl Drop for NamedProcess { fn
(&mut self) { self.named.kill().expect("could not kill process"); self.named.wait().expect("waiting failed"); } } fn wrap_process(named: Child, server_port: u16) -> NamedProcess { let mut started = false; for _ in 0..20 { let mut io_loop = Runtime::new().unwrap(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); if response.is_ok() { started = true; break; } else { // wait for the server to start thread::sleep(Duration::from_millis(500)); } } assert!(started, "server did not startup..."); // return handle to child process NamedProcess { named } } /// Returns a NamedProcess (cleans the process up on drop), and a socket addr for connecting /// to the server. fn trust_dns_process() -> (NamedProcess, u16) { // find a random port to listen on let test_port = find_test_port(); let ws_root = env::var("WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let named_path = format!("{}/target/release/named", ws_root); let config_path = format!( "{}/tests/test-data/named_test_configs/example.toml", ws_root ); let zone_dir = format!("{}/tests/test-data/named_test_configs", ws_root); File::open(&named_path).expect(&named_path); File::open(&config_path).expect(&config_path); File::open(&zone_dir).expect(&zone_dir); let named = Command::new(&named_path) .stdout(Stdio::null()) .arg("-q") // TODO: need to rethink this one... .arg(&format!("--config={}", config_path)) .arg(&format!("--zonedir={}", zone_dir)) .arg(&format!("--port={}", test_port)) .spawn() .expect("failed to start named"); // let process = wrap_process(named, test_port); // return handle to child process (process, test_port) } /// Runs the bench tesk using the specified client fn bench<F, S, R>(b: &mut Bencher, stream: F) where F: Future<Output = Result<S, ProtoError>> +'static + Send + Unpin, S: DnsRequestSender<DnsResponseFuture = R>, R: Future<Output = Result<DnsResponse, ProtoError>> +'static + Send + Unpin, { let mut io_loop = Runtime::new().unwrap(); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); // validate the request let query = client.query(name.clone(), DNSClass::IN, RecordType::A); let response = io_loop.block_on(query).expect("Request failed"); assert_eq!(response.response_code(), ResponseCode::NoError); let record = &response.answers()[0]; if let RData::A(ref address) = *record.rdata() { assert_eq!(address, &Ipv4Addr::new(127, 0, 0, 1)); } else { unreachable!(); } b.iter(|| { let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); response.unwrap(); }); } #[bench] fn trust_dns_udp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn trust_dns_udp_bench_prof(b: &mut Bencher) { let server_port = 6363; let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); } #[bench] fn trust_dns_tcp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); } // downloaded from https://www.isc.org/downloads/file/bind-9-11-0-p1/ // cd bind-9-11-0-p1 //.configure // make // export TDNS_BIND_PATH=${PWD}/bin/named/named fn bind_process() -> (NamedProcess, u16) { let test_port = find_test_port(); let bind_path = env::var("TDNS_BIND_PATH").unwrap_or_else(|_| "".to_owned()); let server_path = env::var("TDNS_WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let bind_path = format!("{}/sbin/named", bind_path); // create the work directory let working_dir = format!("{}/../target/bind_pwd", server_path); if!Path::new(&working_dir).exists() { DirBuilder::new() .create(&working_dir) .expect("failed to create dir"); } let mut named = Command::new(bind_path) .current_dir(&working_dir) .stderr(Stdio::piped()) .arg("-c") .arg("../../server/benches/bind_conf/example.conf") //.arg("-d").arg("0") .arg("-D") .arg("Trust-DNS cmp bench") .arg("-g") .arg("-p") .arg(&format!("{}", test_port)) .spawn() .expect("failed to start named"); mem::replace(&mut named.stderr, None).unwrap(); let process = wrap_process(named, test_port); (process, test_port) } #[bench] #[ignore] fn bind_udp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn bind_tcp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); }
drop
identifier_name
comparison_benches.rs
#![feature(test)] extern crate futures; extern crate test; extern crate tokio; extern crate trust_dns_client; extern crate trust_dns_proto; extern crate trust_dns_server; use std::env; use std::fs::{DirBuilder, File}; use std::mem; use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::Duration; use futures::Future; use test::Bencher; use tokio::net::TcpStream; use tokio::net::UdpSocket; use tokio::runtime::Runtime; use trust_dns_client::client::*; use trust_dns_client::op::*; use trust_dns_client::rr::dnssec::Signer; use trust_dns_client::rr::*; use trust_dns_client::tcp::*; use trust_dns_client::udp::*; use trust_dns_proto::error::*; use trust_dns_proto::xfer::*; use trust_dns_proto::{iocompat::AsyncIo02As03, TokioTime}; fn find_test_port() -> u16 { let server = std::net::UdpSocket::bind(("0.0.0.0", 0)).unwrap(); let server_addr = server.local_addr().unwrap(); server_addr.port() } struct NamedProcess { named: Child, } impl Drop for NamedProcess { fn drop(&mut self) { self.named.kill().expect("could not kill process"); self.named.wait().expect("waiting failed"); } } fn wrap_process(named: Child, server_port: u16) -> NamedProcess { let mut started = false; for _ in 0..20 { let mut io_loop = Runtime::new().unwrap(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); if response.is_ok() { started = true; break; } else { // wait for the server to start thread::sleep(Duration::from_millis(500)); } } assert!(started, "server did not startup..."); // return handle to child process NamedProcess { named } } /// Returns a NamedProcess (cleans the process up on drop), and a socket addr for connecting /// to the server. fn trust_dns_process() -> (NamedProcess, u16)
.arg(&format!("--zonedir={}", zone_dir)) .arg(&format!("--port={}", test_port)) .spawn() .expect("failed to start named"); // let process = wrap_process(named, test_port); // return handle to child process (process, test_port) } /// Runs the bench tesk using the specified client fn bench<F, S, R>(b: &mut Bencher, stream: F) where F: Future<Output = Result<S, ProtoError>> +'static + Send + Unpin, S: DnsRequestSender<DnsResponseFuture = R>, R: Future<Output = Result<DnsResponse, ProtoError>> +'static + Send + Unpin, { let mut io_loop = Runtime::new().unwrap(); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); // validate the request let query = client.query(name.clone(), DNSClass::IN, RecordType::A); let response = io_loop.block_on(query).expect("Request failed"); assert_eq!(response.response_code(), ResponseCode::NoError); let record = &response.answers()[0]; if let RData::A(ref address) = *record.rdata() { assert_eq!(address, &Ipv4Addr::new(127, 0, 0, 1)); } else { unreachable!(); } b.iter(|| { let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); response.unwrap(); }); } #[bench] fn trust_dns_udp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn trust_dns_udp_bench_prof(b: &mut Bencher) { let server_port = 6363; let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); } #[bench] fn trust_dns_tcp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); } // downloaded from https://www.isc.org/downloads/file/bind-9-11-0-p1/ // cd bind-9-11-0-p1 //.configure // make // export TDNS_BIND_PATH=${PWD}/bin/named/named fn bind_process() -> (NamedProcess, u16) { let test_port = find_test_port(); let bind_path = env::var("TDNS_BIND_PATH").unwrap_or_else(|_| "".to_owned()); let server_path = env::var("TDNS_WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let bind_path = format!("{}/sbin/named", bind_path); // create the work directory let working_dir = format!("{}/../target/bind_pwd", server_path); if!Path::new(&working_dir).exists() { DirBuilder::new() .create(&working_dir) .expect("failed to create dir"); } let mut named = Command::new(bind_path) .current_dir(&working_dir) .stderr(Stdio::piped()) .arg("-c") .arg("../../server/benches/bind_conf/example.conf") //.arg("-d").arg("0") .arg("-D") .arg("Trust-DNS cmp bench") .arg("-g") .arg("-p") .arg(&format!("{}", test_port)) .spawn() .expect("failed to start named"); mem::replace(&mut named.stderr, None).unwrap(); let process = wrap_process(named, test_port); (process, test_port) } #[bench] #[ignore] fn bind_udp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn bind_tcp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); }
{ // find a random port to listen on let test_port = find_test_port(); let ws_root = env::var("WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let named_path = format!("{}/target/release/named", ws_root); let config_path = format!( "{}/tests/test-data/named_test_configs/example.toml", ws_root ); let zone_dir = format!("{}/tests/test-data/named_test_configs", ws_root); File::open(&named_path).expect(&named_path); File::open(&config_path).expect(&config_path); File::open(&zone_dir).expect(&zone_dir); let named = Command::new(&named_path) .stdout(Stdio::null()) .arg("-q") // TODO: need to rethink this one... .arg(&format!("--config={}", config_path))
identifier_body
comparison_benches.rs
#![feature(test)] extern crate futures; extern crate test; extern crate tokio; extern crate trust_dns_client; extern crate trust_dns_proto; extern crate trust_dns_server; use std::env; use std::fs::{DirBuilder, File}; use std::mem; use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::Duration; use futures::Future; use test::Bencher; use tokio::net::TcpStream; use tokio::net::UdpSocket; use tokio::runtime::Runtime; use trust_dns_client::client::*; use trust_dns_client::op::*; use trust_dns_client::rr::dnssec::Signer; use trust_dns_client::rr::*; use trust_dns_client::tcp::*; use trust_dns_client::udp::*; use trust_dns_proto::error::*; use trust_dns_proto::xfer::*; use trust_dns_proto::{iocompat::AsyncIo02As03, TokioTime}; fn find_test_port() -> u16 { let server = std::net::UdpSocket::bind(("0.0.0.0", 0)).unwrap(); let server_addr = server.local_addr().unwrap(); server_addr.port() } struct NamedProcess { named: Child, } impl Drop for NamedProcess { fn drop(&mut self) { self.named.kill().expect("could not kill process"); self.named.wait().expect("waiting failed"); } } fn wrap_process(named: Child, server_port: u16) -> NamedProcess { let mut started = false; for _ in 0..20 { let mut io_loop = Runtime::new().unwrap(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); if response.is_ok() { started = true; break; } else { // wait for the server to start thread::sleep(Duration::from_millis(500)); } } assert!(started, "server did not startup..."); // return handle to child process NamedProcess { named } } /// Returns a NamedProcess (cleans the process up on drop), and a socket addr for connecting /// to the server. fn trust_dns_process() -> (NamedProcess, u16) { // find a random port to listen on let test_port = find_test_port(); let ws_root = env::var("WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let named_path = format!("{}/target/release/named", ws_root); let config_path = format!( "{}/tests/test-data/named_test_configs/example.toml", ws_root ); let zone_dir = format!("{}/tests/test-data/named_test_configs", ws_root); File::open(&named_path).expect(&named_path); File::open(&config_path).expect(&config_path); File::open(&zone_dir).expect(&zone_dir); let named = Command::new(&named_path) .stdout(Stdio::null()) .arg("-q") // TODO: need to rethink this one... .arg(&format!("--config={}", config_path)) .arg(&format!("--zonedir={}", zone_dir)) .arg(&format!("--port={}", test_port)) .spawn() .expect("failed to start named"); // let process = wrap_process(named, test_port); // return handle to child process (process, test_port) } /// Runs the bench tesk using the specified client fn bench<F, S, R>(b: &mut Bencher, stream: F) where F: Future<Output = Result<S, ProtoError>> +'static + Send + Unpin, S: DnsRequestSender<DnsResponseFuture = R>, R: Future<Output = Result<DnsResponse, ProtoError>> +'static + Send + Unpin, { let mut io_loop = Runtime::new().unwrap(); let client = AsyncClient::connect(stream); let (mut client, bg) = io_loop.block_on(client).expect("failed to create client"); io_loop.spawn(bg); let name = domain::Name::from_str("www.example.com.").unwrap(); // validate the request let query = client.query(name.clone(), DNSClass::IN, RecordType::A); let response = io_loop.block_on(query).expect("Request failed"); assert_eq!(response.response_code(), ResponseCode::NoError); let record = &response.answers()[0]; if let RData::A(ref address) = *record.rdata()
else { unreachable!(); } b.iter(|| { let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A)); response.unwrap(); }); } #[bench] fn trust_dns_udp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn trust_dns_udp_bench_prof(b: &mut Bencher) { let server_port = 6363; let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); } #[bench] fn trust_dns_tcp_bench(b: &mut Bencher) { let (named, server_port) = trust_dns_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); } // downloaded from https://www.isc.org/downloads/file/bind-9-11-0-p1/ // cd bind-9-11-0-p1 //.configure // make // export TDNS_BIND_PATH=${PWD}/bin/named/named fn bind_process() -> (NamedProcess, u16) { let test_port = find_test_port(); let bind_path = env::var("TDNS_BIND_PATH").unwrap_or_else(|_| "".to_owned()); let server_path = env::var("TDNS_WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned()); let bind_path = format!("{}/sbin/named", bind_path); // create the work directory let working_dir = format!("{}/../target/bind_pwd", server_path); if!Path::new(&working_dir).exists() { DirBuilder::new() .create(&working_dir) .expect("failed to create dir"); } let mut named = Command::new(bind_path) .current_dir(&working_dir) .stderr(Stdio::piped()) .arg("-c") .arg("../../server/benches/bind_conf/example.conf") //.arg("-d").arg("0") .arg("-D") .arg("Trust-DNS cmp bench") .arg("-g") .arg("-p") .arg(&format!("{}", test_port)) .spawn() .expect("failed to start named"); mem::replace(&mut named.stderr, None).unwrap(); let process = wrap_process(named, test_port); (process, test_port) } #[bench] #[ignore] fn bind_udp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let stream = UdpClientStream::<UdpSocket>::new(addr); bench(b, stream); // cleaning up the named process drop(named); } #[bench] #[ignore] fn bind_tcp_bench(b: &mut Bencher) { let (named, server_port) = bind_process(); let addr: SocketAddr = ("127.0.0.1", server_port) .to_socket_addrs() .unwrap() .next() .unwrap(); let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr); let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>); bench(b, mp); // cleaning up the named process drop(named); }
{ assert_eq!(address, &Ipv4Addr::new(127, 0, 0, 1)); }
conditional_block
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType}; use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableJS, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase}; use dom::globalscope::GlobalScope; use dom::node::Node; use dom::virtualmethods::vtable_for; use dom::window::Window; use script_thread::Runnable; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; use time; #[dom_struct] pub struct Event { reflector_: Reflector, current_target: MutNullableJS<EventTarget>, target: MutNullableJS<EventTarget>, type_: DOMRefCell<Atom>, phase: Cell<EventPhase>, canceled: Cell<EventDefault>, stop_propagation: Cell<bool>, stop_immediate: Cell<bool>, cancelable: Cell<bool>, bubbles: Cell<bool>, trusted: Cell<bool>, dispatching: Cell<bool>, initialized: Cell<bool>, timestamp: u64, } impl Event { pub fn new_inherited() -> Event { Event { reflector_: Reflector::new(), current_target: Default::default(), target: Default::default(), type_: DOMRefCell::new(atom!("")), phase: Cell::new(EventPhase::None), canceled: Cell::new(EventDefault::Allowed), stop_propagation: Cell::new(false), stop_immediate: Cell::new(false), cancelable: Cell::new(false), bubbles: Cell::new(false), trusted: Cell::new(false), dispatching: Cell::new(false), initialized: Cell::new(false), timestamp: time::get_time().sec as u64, } } pub fn new_uninitialized(global: &GlobalScope) -> Root<Event> { reflect_dom_object(box Event::new_inherited(), global, EventBinding::Wrap) } pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable) -> Root<Event> { let event = Event::new_uninitialized(global); event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); event } pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &EventBinding::EventInit) -> Fallible<Root<Event>> { let bubbles = EventBubbles::from(init.bubbles); let cancelable = EventCancelable::from(init.cancelable); Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) } pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) { if self.dispatching.get() { return; } self.initialized.set(true); self.stop_propagation.set(false); self.stop_immediate.set(false); self.canceled.set(EventDefault::Allowed); self.trusted.set(false); self.target.set(None); *self.type_.borrow_mut() = type_; self.bubbles.set(bubbles); self.cancelable.set(cancelable); } // https://dom.spec.whatwg.org/#concept-event-dispatch pub fn dispatch(&self, target: &EventTarget, target_override: Option<&EventTarget>) -> EventStatus { assert!(!self.dispatching()); assert!(self.initialized()); assert_eq!(self.phase.get(), EventPhase::None); assert!(self.GetCurrentTarget().is_none()); // Step 1. self.dispatching.set(true); // Step 2. self.target.set(Some(target_override.unwrap_or(target))); if self.stop_propagation.get() { // If the event's stop propagation flag is set, we can skip everything because // it prevents the calls of the invoke algorithm in the spec. // Step 10-12. self.clear_dispatching_flags(); // Step 14. return self.status(); } // Step 3. The "invoke" algorithm is only used on `target` separately, // so we don't put it in the path. rooted_vec!(let mut event_path); // Step 4. if let Some(target_node) = target.downcast::<Node>() { for ancestor in target_node.ancestors() { event_path.push(JS::from_ref(ancestor.upcast::<EventTarget>())); } let top_most_ancestor_or_target = Root::from_ref(event_path.r().last().cloned().unwrap_or(target)); if let Some(document) = Root::downcast::<Document>(top_most_ancestor_or_target) { if self.type_()!= atom!("load") && document.browsing_context().is_some() { event_path.push(JS::from_ref(document.window().upcast())); } } } // Steps 5-9. In a separate function to short-circuit various things easily. dispatch_to_listeners(self, target, event_path.r()); // Default action. if let Some(target) = self.GetTarget() { if let Some(node) = target.downcast::<Node>() { let vtable = vtable_for(&node); vtable.handle_event(self); } } // Step 10-12. self.clear_dispatching_flags(); // Step 14. self.status() } pub fn status(&self) -> EventStatus { match self.DefaultPrevented() { true => EventStatus::Canceled, false => EventStatus::NotCanceled } } #[inline] pub fn dispatching(&self) -> bool { self.dispatching.get() } #[inline] // https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12. fn clear_dispatching_flags(&self) { assert!(self.dispatching.get()); self.dispatching.set(false); self.stop_propagation.set(false); self.stop_immediate.set(false); self.phase.set(EventPhase::None); self.current_target.set(None); } #[inline] pub fn initialized(&self) -> bool { self.initialized.get() } #[inline] pub fn type_(&self) -> Atom { self.type_.borrow().clone() } #[inline] pub fn mark_as_handled(&self) { self.canceled.set(EventDefault::Handled); } #[inline] pub fn get_cancel_state(&self) -> EventDefault { self.canceled.get() } pub fn set_trusted(&self, trusted: bool) { self.trusted.set(trusted); } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub fn fire(&self, target: &EventTarget) -> EventStatus { self.set_trusted(true); target.dispatch_event(self) } } impl EventMethods for Event { // https://dom.spec.whatwg.org/#dom-event-eventphase fn EventPhase(&self) -> u16 { self.phase.get() as u16 } // https://dom.spec.whatwg.org/#dom-event-type fn Type(&self) -> DOMString { DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString } // https://dom.spec.whatwg.org/#dom-event-target fn GetTarget(&self) -> Option<Root<EventTarget>> { self.target.get() } // https://dom.spec.whatwg.org/#dom-event-currenttarget fn GetCurrentTarget(&self) -> Option<Root<EventTarget>> { self.current_target.get() } // https://dom.spec.whatwg.org/#dom-event-defaultprevented fn DefaultPrevented(&self) -> bool { self.canceled.get() == EventDefault::Prevented } // https://dom.spec.whatwg.org/#dom-event-preventdefault fn PreventDefault(&self) { if self.cancelable.get() { self.canceled.set(EventDefault::Prevented) } } // https://dom.spec.whatwg.org/#dom-event-stoppropagation fn StopPropagation(&self) { self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation fn StopImmediatePropagation(&self) { self.stop_immediate.set(true); self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-bubbles fn Bubbles(&self) -> bool { self.bubbles.get() } // https://dom.spec.whatwg.org/#dom-event-cancelable fn Cancelable(&self) -> bool { self.cancelable.get() } // https://dom.spec.whatwg.org/#dom-event-timestamp fn TimeStamp(&self) -> u64 { self.timestamp } // https://dom.spec.whatwg.org/#dom-event-initevent fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) { self.init_event(Atom::from(type_), bubbles, cancelable) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.trusted.get() } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventBubbles { Bubbles, DoesNotBubble } impl From<bool> for EventBubbles { fn from(boolean: bool) -> Self { match boolean { true => EventBubbles::Bubbles, false => EventBubbles::DoesNotBubble } } } impl From<EventBubbles> for bool { fn from(bubbles: EventBubbles) -> Self { match bubbles { EventBubbles::Bubbles => true, EventBubbles::DoesNotBubble => false } } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventCancelable { Cancelable, NotCancelable } impl From<bool> for EventCancelable { fn from(boolean: bool) -> Self { match boolean { true => EventCancelable::Cancelable, false => EventCancelable::NotCancelable } } } impl From<EventCancelable> for bool { fn from(bubbles: EventCancelable) -> Self { match bubbles { EventCancelable::Cancelable => true, EventCancelable::NotCancelable => false } } } #[derive(JSTraceable, Copy, Clone, Debug, PartialEq, Eq)] #[repr(u16)] #[derive(HeapSizeOf)] pub enum EventPhase { None = EventConstants::NONE, Capturing = EventConstants::CAPTURING_PHASE, AtTarget = EventConstants::AT_TARGET, Bubbling = EventConstants::BUBBLING_PHASE, } /// An enum to indicate whether the default action of an event is allowed. /// /// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled /// states, we also need something to stop the event from being handled again (without cancelling /// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will /// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum /// helps us to prevent such events from being [sent to the constellation][msg] where it will be /// handled once again for page scrolling (which is definitely not what we'd want). /// /// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent /// #[derive(JSTraceable, HeapSizeOf, Copy, Clone, PartialEq)] pub enum EventDefault { /// The default action of the event is allowed (constructor's default) Allowed, /// The default action has been prevented by calling `PreventDefault` Prevented, /// The event has been handled somewhere in the DOM, and it should be prevented from being /// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented` Handled, } #[derive(PartialEq)] pub enum EventStatus { Canceled, NotCanceled } // https://dom.spec.whatwg.org/#concept-event-fire pub struct EventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, pub bubbles: EventBubbles, pub cancelable: EventCancelable, } impl Runnable for EventRunnable { fn name(&self) -> &'static str { "EventRunnable" } fn handler(self: Box<EventRunnable>) { let target = self.target.root(); let bubbles = self.bubbles; let cancelable = self.cancelable; target.fire_event_with_params(self.name, bubbles, cancelable); } } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub struct SimpleEventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, } impl Runnable for SimpleEventRunnable { fn name(&self) -> &'static str { "SimpleEventRunnable" } fn handler(self: Box<SimpleEventRunnable>) { let target = self.target.root(); target.fire_event(self.name); } } // See dispatch_event. // https://dom.spec.whatwg.org/#concept-event-dispatch fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) { assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); let window = match Root::downcast::<Window>(target.global()) { Some(window) => { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { Some(window) } else { None } }, _ => None, }; // Step 5. event.phase.set(EventPhase::Capturing); // Step 6. for object in event_path.iter().rev() { invoke(window.r(), object, event, Some(ListenerPhase::Capturing)); if event.stop_propagation.get() { return; } } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); // Step 7. event.phase.set(EventPhase::AtTarget); // Step 8. invoke(window.r(), target, event, None); if event.stop_propagation.get() { return; } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); if!event.bubbles.get() { return; } // Step 9.1. event.phase.set(EventPhase::Bubbling); // Step 9.2. for object in event_path { invoke(window.r(), object, event, Some(ListenerPhase::Bubbling)); if event.stop_propagation.get() { return; } } } // https://dom.spec.whatwg.org/#concept-event-listener-invoke fn invoke(window: Option<&Window>, object: &EventTarget, event: &Event, specific_listener_phase: Option<ListenerPhase>) { // Step 1. assert!(!event.stop_propagation.get()); // Steps 2-3. let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase); // Step 4. event.current_target.set(Some(object)); // Step 5. inner_invoke(window, object, event, &listeners); // TODO: step 6. } // https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke fn inner_invoke(window: Option<&Window>, object: &EventTarget, event: &Event, listeners: &[CompiledEventListener]) -> bool { // Step 1. let mut found = false; // Step 2. for listener in listeners { // Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the // relevant ones for this invoke call during the dispatch algorithm. // Step 2.2. found = true; // TODO: step 2.5. // Step 2.6. let marker = TimelineMarker::start("DOMEvent".to_owned()); listener.call_or_handle_event(object, event, ExceptionHandling::Report); if let Some(window) = window
if event.stop_immediate.get() { return found; } // TODO: step 2.7. } // Step 3. found }
{ window.emit_timeline_marker(marker.end()); }
conditional_block
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType}; use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableJS, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase}; use dom::globalscope::GlobalScope; use dom::node::Node; use dom::virtualmethods::vtable_for; use dom::window::Window; use script_thread::Runnable; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; use time; #[dom_struct] pub struct Event { reflector_: Reflector, current_target: MutNullableJS<EventTarget>, target: MutNullableJS<EventTarget>, type_: DOMRefCell<Atom>, phase: Cell<EventPhase>, canceled: Cell<EventDefault>, stop_propagation: Cell<bool>, stop_immediate: Cell<bool>, cancelable: Cell<bool>, bubbles: Cell<bool>, trusted: Cell<bool>, dispatching: Cell<bool>, initialized: Cell<bool>, timestamp: u64, } impl Event { pub fn new_inherited() -> Event { Event { reflector_: Reflector::new(), current_target: Default::default(), target: Default::default(), type_: DOMRefCell::new(atom!("")), phase: Cell::new(EventPhase::None), canceled: Cell::new(EventDefault::Allowed), stop_propagation: Cell::new(false), stop_immediate: Cell::new(false), cancelable: Cell::new(false), bubbles: Cell::new(false), trusted: Cell::new(false), dispatching: Cell::new(false), initialized: Cell::new(false), timestamp: time::get_time().sec as u64, } } pub fn new_uninitialized(global: &GlobalScope) -> Root<Event> { reflect_dom_object(box Event::new_inherited(), global, EventBinding::Wrap) } pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable) -> Root<Event> { let event = Event::new_uninitialized(global); event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); event } pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &EventBinding::EventInit) -> Fallible<Root<Event>> { let bubbles = EventBubbles::from(init.bubbles); let cancelable = EventCancelable::from(init.cancelable); Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) } pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) { if self.dispatching.get() { return; } self.initialized.set(true); self.stop_propagation.set(false); self.stop_immediate.set(false); self.canceled.set(EventDefault::Allowed); self.trusted.set(false); self.target.set(None); *self.type_.borrow_mut() = type_; self.bubbles.set(bubbles); self.cancelable.set(cancelable); } // https://dom.spec.whatwg.org/#concept-event-dispatch pub fn dispatch(&self, target: &EventTarget, target_override: Option<&EventTarget>) -> EventStatus { assert!(!self.dispatching()); assert!(self.initialized()); assert_eq!(self.phase.get(), EventPhase::None); assert!(self.GetCurrentTarget().is_none()); // Step 1. self.dispatching.set(true); // Step 2. self.target.set(Some(target_override.unwrap_or(target))); if self.stop_propagation.get() { // If the event's stop propagation flag is set, we can skip everything because // it prevents the calls of the invoke algorithm in the spec. // Step 10-12. self.clear_dispatching_flags(); // Step 14. return self.status(); } // Step 3. The "invoke" algorithm is only used on `target` separately, // so we don't put it in the path. rooted_vec!(let mut event_path); // Step 4. if let Some(target_node) = target.downcast::<Node>() { for ancestor in target_node.ancestors() { event_path.push(JS::from_ref(ancestor.upcast::<EventTarget>())); } let top_most_ancestor_or_target = Root::from_ref(event_path.r().last().cloned().unwrap_or(target)); if let Some(document) = Root::downcast::<Document>(top_most_ancestor_or_target) { if self.type_()!= atom!("load") && document.browsing_context().is_some() { event_path.push(JS::from_ref(document.window().upcast())); } } } // Steps 5-9. In a separate function to short-circuit various things easily. dispatch_to_listeners(self, target, event_path.r()); // Default action. if let Some(target) = self.GetTarget() { if let Some(node) = target.downcast::<Node>() { let vtable = vtable_for(&node); vtable.handle_event(self); } } // Step 10-12. self.clear_dispatching_flags(); // Step 14. self.status() } pub fn status(&self) -> EventStatus { match self.DefaultPrevented() { true => EventStatus::Canceled, false => EventStatus::NotCanceled } } #[inline] pub fn dispatching(&self) -> bool { self.dispatching.get() } #[inline] // https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12. fn clear_dispatching_flags(&self) { assert!(self.dispatching.get()); self.dispatching.set(false); self.stop_propagation.set(false); self.stop_immediate.set(false); self.phase.set(EventPhase::None); self.current_target.set(None); } #[inline] pub fn initialized(&self) -> bool { self.initialized.get() } #[inline] pub fn type_(&self) -> Atom { self.type_.borrow().clone() } #[inline] pub fn mark_as_handled(&self) { self.canceled.set(EventDefault::Handled); } #[inline] pub fn get_cancel_state(&self) -> EventDefault { self.canceled.get() } pub fn set_trusted(&self, trusted: bool) { self.trusted.set(trusted); } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub fn fire(&self, target: &EventTarget) -> EventStatus { self.set_trusted(true); target.dispatch_event(self) } } impl EventMethods for Event { // https://dom.spec.whatwg.org/#dom-event-eventphase fn EventPhase(&self) -> u16 { self.phase.get() as u16 } // https://dom.spec.whatwg.org/#dom-event-type fn Type(&self) -> DOMString { DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString } // https://dom.spec.whatwg.org/#dom-event-target fn GetTarget(&self) -> Option<Root<EventTarget>> { self.target.get() } // https://dom.spec.whatwg.org/#dom-event-currenttarget fn GetCurrentTarget(&self) -> Option<Root<EventTarget>> { self.current_target.get() } // https://dom.spec.whatwg.org/#dom-event-defaultprevented fn DefaultPrevented(&self) -> bool { self.canceled.get() == EventDefault::Prevented } // https://dom.spec.whatwg.org/#dom-event-preventdefault fn PreventDefault(&self) { if self.cancelable.get() { self.canceled.set(EventDefault::Prevented) } } // https://dom.spec.whatwg.org/#dom-event-stoppropagation fn StopPropagation(&self) { self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation fn StopImmediatePropagation(&self) { self.stop_immediate.set(true); self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-bubbles fn Bubbles(&self) -> bool { self.bubbles.get() } // https://dom.spec.whatwg.org/#dom-event-cancelable fn Cancelable(&self) -> bool { self.cancelable.get() } // https://dom.spec.whatwg.org/#dom-event-timestamp fn TimeStamp(&self) -> u64 { self.timestamp } // https://dom.spec.whatwg.org/#dom-event-initevent fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) { self.init_event(Atom::from(type_), bubbles, cancelable) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.trusted.get() } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventBubbles { Bubbles, DoesNotBubble } impl From<bool> for EventBubbles { fn from(boolean: bool) -> Self { match boolean { true => EventBubbles::Bubbles, false => EventBubbles::DoesNotBubble } } } impl From<EventBubbles> for bool { fn from(bubbles: EventBubbles) -> Self { match bubbles { EventBubbles::Bubbles => true, EventBubbles::DoesNotBubble => false } } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventCancelable { Cancelable, NotCancelable } impl From<bool> for EventCancelable { fn from(boolean: bool) -> Self { match boolean { true => EventCancelable::Cancelable, false => EventCancelable::NotCancelable } } } impl From<EventCancelable> for bool { fn from(bubbles: EventCancelable) -> Self { match bubbles { EventCancelable::Cancelable => true, EventCancelable::NotCancelable => false } } } #[derive(JSTraceable, Copy, Clone, Debug, PartialEq, Eq)] #[repr(u16)] #[derive(HeapSizeOf)] pub enum EventPhase { None = EventConstants::NONE, Capturing = EventConstants::CAPTURING_PHASE, AtTarget = EventConstants::AT_TARGET, Bubbling = EventConstants::BUBBLING_PHASE, } /// An enum to indicate whether the default action of an event is allowed. /// /// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled /// states, we also need something to stop the event from being handled again (without cancelling /// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will /// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum /// helps us to prevent such events from being [sent to the constellation][msg] where it will be /// handled once again for page scrolling (which is definitely not what we'd want). /// /// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent /// #[derive(JSTraceable, HeapSizeOf, Copy, Clone, PartialEq)] pub enum EventDefault { /// The default action of the event is allowed (constructor's default) Allowed, /// The default action has been prevented by calling `PreventDefault` Prevented, /// The event has been handled somewhere in the DOM, and it should be prevented from being /// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented` Handled, } #[derive(PartialEq)] pub enum EventStatus { Canceled, NotCanceled } // https://dom.spec.whatwg.org/#concept-event-fire pub struct EventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, pub bubbles: EventBubbles, pub cancelable: EventCancelable, } impl Runnable for EventRunnable { fn name(&self) -> &'static str { "EventRunnable" } fn handler(self: Box<EventRunnable>)
} // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub struct SimpleEventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, } impl Runnable for SimpleEventRunnable { fn name(&self) -> &'static str { "SimpleEventRunnable" } fn handler(self: Box<SimpleEventRunnable>) { let target = self.target.root(); target.fire_event(self.name); } } // See dispatch_event. // https://dom.spec.whatwg.org/#concept-event-dispatch fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) { assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); let window = match Root::downcast::<Window>(target.global()) { Some(window) => { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { Some(window) } else { None } }, _ => None, }; // Step 5. event.phase.set(EventPhase::Capturing); // Step 6. for object in event_path.iter().rev() { invoke(window.r(), object, event, Some(ListenerPhase::Capturing)); if event.stop_propagation.get() { return; } } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); // Step 7. event.phase.set(EventPhase::AtTarget); // Step 8. invoke(window.r(), target, event, None); if event.stop_propagation.get() { return; } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); if!event.bubbles.get() { return; } // Step 9.1. event.phase.set(EventPhase::Bubbling); // Step 9.2. for object in event_path { invoke(window.r(), object, event, Some(ListenerPhase::Bubbling)); if event.stop_propagation.get() { return; } } } // https://dom.spec.whatwg.org/#concept-event-listener-invoke fn invoke(window: Option<&Window>, object: &EventTarget, event: &Event, specific_listener_phase: Option<ListenerPhase>) { // Step 1. assert!(!event.stop_propagation.get()); // Steps 2-3. let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase); // Step 4. event.current_target.set(Some(object)); // Step 5. inner_invoke(window, object, event, &listeners); // TODO: step 6. } // https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke fn inner_invoke(window: Option<&Window>, object: &EventTarget, event: &Event, listeners: &[CompiledEventListener]) -> bool { // Step 1. let mut found = false; // Step 2. for listener in listeners { // Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the // relevant ones for this invoke call during the dispatch algorithm. // Step 2.2. found = true; // TODO: step 2.5. // Step 2.6. let marker = TimelineMarker::start("DOMEvent".to_owned()); listener.call_or_handle_event(object, event, ExceptionHandling::Report); if let Some(window) = window { window.emit_timeline_marker(marker.end()); } if event.stop_immediate.get() { return found; } // TODO: step 2.7. } // Step 3. found }
{ let target = self.target.root(); let bubbles = self.bubbles; let cancelable = self.cancelable; target.fire_event_with_params(self.name, bubbles, cancelable); }
identifier_body
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType}; use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableJS, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase}; use dom::globalscope::GlobalScope; use dom::node::Node; use dom::virtualmethods::vtable_for; use dom::window::Window; use script_thread::Runnable; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; use time; #[dom_struct] pub struct Event { reflector_: Reflector, current_target: MutNullableJS<EventTarget>, target: MutNullableJS<EventTarget>, type_: DOMRefCell<Atom>, phase: Cell<EventPhase>, canceled: Cell<EventDefault>, stop_propagation: Cell<bool>, stop_immediate: Cell<bool>, cancelable: Cell<bool>, bubbles: Cell<bool>, trusted: Cell<bool>, dispatching: Cell<bool>, initialized: Cell<bool>, timestamp: u64, } impl Event { pub fn new_inherited() -> Event { Event { reflector_: Reflector::new(), current_target: Default::default(), target: Default::default(), type_: DOMRefCell::new(atom!("")), phase: Cell::new(EventPhase::None), canceled: Cell::new(EventDefault::Allowed), stop_propagation: Cell::new(false), stop_immediate: Cell::new(false), cancelable: Cell::new(false), bubbles: Cell::new(false), trusted: Cell::new(false), dispatching: Cell::new(false), initialized: Cell::new(false), timestamp: time::get_time().sec as u64, } } pub fn new_uninitialized(global: &GlobalScope) -> Root<Event> { reflect_dom_object(box Event::new_inherited(), global, EventBinding::Wrap) } pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable) -> Root<Event> { let event = Event::new_uninitialized(global); event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); event } pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &EventBinding::EventInit) -> Fallible<Root<Event>> { let bubbles = EventBubbles::from(init.bubbles); let cancelable = EventCancelable::from(init.cancelable); Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) } pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) { if self.dispatching.get() { return; } self.initialized.set(true); self.stop_propagation.set(false); self.stop_immediate.set(false); self.canceled.set(EventDefault::Allowed); self.trusted.set(false); self.target.set(None); *self.type_.borrow_mut() = type_; self.bubbles.set(bubbles); self.cancelable.set(cancelable); } // https://dom.spec.whatwg.org/#concept-event-dispatch pub fn dispatch(&self, target: &EventTarget, target_override: Option<&EventTarget>) -> EventStatus { assert!(!self.dispatching()); assert!(self.initialized()); assert_eq!(self.phase.get(), EventPhase::None); assert!(self.GetCurrentTarget().is_none()); // Step 1. self.dispatching.set(true); // Step 2. self.target.set(Some(target_override.unwrap_or(target))); if self.stop_propagation.get() { // If the event's stop propagation flag is set, we can skip everything because // it prevents the calls of the invoke algorithm in the spec. // Step 10-12. self.clear_dispatching_flags(); // Step 14. return self.status(); } // Step 3. The "invoke" algorithm is only used on `target` separately, // so we don't put it in the path. rooted_vec!(let mut event_path); // Step 4. if let Some(target_node) = target.downcast::<Node>() { for ancestor in target_node.ancestors() { event_path.push(JS::from_ref(ancestor.upcast::<EventTarget>())); } let top_most_ancestor_or_target = Root::from_ref(event_path.r().last().cloned().unwrap_or(target)); if let Some(document) = Root::downcast::<Document>(top_most_ancestor_or_target) { if self.type_()!= atom!("load") && document.browsing_context().is_some() { event_path.push(JS::from_ref(document.window().upcast())); } } } // Steps 5-9. In a separate function to short-circuit various things easily. dispatch_to_listeners(self, target, event_path.r()); // Default action. if let Some(target) = self.GetTarget() { if let Some(node) = target.downcast::<Node>() { let vtable = vtable_for(&node); vtable.handle_event(self); } } // Step 10-12. self.clear_dispatching_flags(); // Step 14. self.status() } pub fn status(&self) -> EventStatus { match self.DefaultPrevented() { true => EventStatus::Canceled, false => EventStatus::NotCanceled } } #[inline] pub fn dispatching(&self) -> bool { self.dispatching.get() } #[inline] // https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12. fn clear_dispatching_flags(&self) { assert!(self.dispatching.get()); self.dispatching.set(false); self.stop_propagation.set(false); self.stop_immediate.set(false); self.phase.set(EventPhase::None); self.current_target.set(None); } #[inline] pub fn initialized(&self) -> bool { self.initialized.get() } #[inline] pub fn type_(&self) -> Atom { self.type_.borrow().clone() } #[inline] pub fn mark_as_handled(&self) { self.canceled.set(EventDefault::Handled); } #[inline] pub fn get_cancel_state(&self) -> EventDefault { self.canceled.get() } pub fn set_trusted(&self, trusted: bool) { self.trusted.set(trusted); } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub fn fire(&self, target: &EventTarget) -> EventStatus { self.set_trusted(true); target.dispatch_event(self) } } impl EventMethods for Event { // https://dom.spec.whatwg.org/#dom-event-eventphase fn EventPhase(&self) -> u16 { self.phase.get() as u16 } // https://dom.spec.whatwg.org/#dom-event-type fn Type(&self) -> DOMString { DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString } // https://dom.spec.whatwg.org/#dom-event-target fn GetTarget(&self) -> Option<Root<EventTarget>> { self.target.get() } // https://dom.spec.whatwg.org/#dom-event-currenttarget fn GetCurrentTarget(&self) -> Option<Root<EventTarget>> { self.current_target.get() } // https://dom.spec.whatwg.org/#dom-event-defaultprevented fn DefaultPrevented(&self) -> bool { self.canceled.get() == EventDefault::Prevented } // https://dom.spec.whatwg.org/#dom-event-preventdefault fn PreventDefault(&self) { if self.cancelable.get() { self.canceled.set(EventDefault::Prevented) } } // https://dom.spec.whatwg.org/#dom-event-stoppropagation fn StopPropagation(&self) { self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation fn StopImmediatePropagation(&self) { self.stop_immediate.set(true); self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-bubbles fn Bubbles(&self) -> bool { self.bubbles.get() } // https://dom.spec.whatwg.org/#dom-event-cancelable fn Cancelable(&self) -> bool { self.cancelable.get() } // https://dom.spec.whatwg.org/#dom-event-timestamp fn TimeStamp(&self) -> u64 { self.timestamp } // https://dom.spec.whatwg.org/#dom-event-initevent fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) { self.init_event(Atom::from(type_), bubbles, cancelable) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.trusted.get() } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventBubbles { Bubbles, DoesNotBubble } impl From<bool> for EventBubbles { fn from(boolean: bool) -> Self { match boolean { true => EventBubbles::Bubbles, false => EventBubbles::DoesNotBubble } } } impl From<EventBubbles> for bool { fn from(bubbles: EventBubbles) -> Self { match bubbles { EventBubbles::Bubbles => true, EventBubbles::DoesNotBubble => false } } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventCancelable { Cancelable, NotCancelable } impl From<bool> for EventCancelable { fn from(boolean: bool) -> Self { match boolean { true => EventCancelable::Cancelable, false => EventCancelable::NotCancelable } } } impl From<EventCancelable> for bool { fn
(bubbles: EventCancelable) -> Self { match bubbles { EventCancelable::Cancelable => true, EventCancelable::NotCancelable => false } } } #[derive(JSTraceable, Copy, Clone, Debug, PartialEq, Eq)] #[repr(u16)] #[derive(HeapSizeOf)] pub enum EventPhase { None = EventConstants::NONE, Capturing = EventConstants::CAPTURING_PHASE, AtTarget = EventConstants::AT_TARGET, Bubbling = EventConstants::BUBBLING_PHASE, } /// An enum to indicate whether the default action of an event is allowed. /// /// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled /// states, we also need something to stop the event from being handled again (without cancelling /// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will /// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum /// helps us to prevent such events from being [sent to the constellation][msg] where it will be /// handled once again for page scrolling (which is definitely not what we'd want). /// /// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent /// #[derive(JSTraceable, HeapSizeOf, Copy, Clone, PartialEq)] pub enum EventDefault { /// The default action of the event is allowed (constructor's default) Allowed, /// The default action has been prevented by calling `PreventDefault` Prevented, /// The event has been handled somewhere in the DOM, and it should be prevented from being /// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented` Handled, } #[derive(PartialEq)] pub enum EventStatus { Canceled, NotCanceled } // https://dom.spec.whatwg.org/#concept-event-fire pub struct EventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, pub bubbles: EventBubbles, pub cancelable: EventCancelable, } impl Runnable for EventRunnable { fn name(&self) -> &'static str { "EventRunnable" } fn handler(self: Box<EventRunnable>) { let target = self.target.root(); let bubbles = self.bubbles; let cancelable = self.cancelable; target.fire_event_with_params(self.name, bubbles, cancelable); } } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub struct SimpleEventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, } impl Runnable for SimpleEventRunnable { fn name(&self) -> &'static str { "SimpleEventRunnable" } fn handler(self: Box<SimpleEventRunnable>) { let target = self.target.root(); target.fire_event(self.name); } } // See dispatch_event. // https://dom.spec.whatwg.org/#concept-event-dispatch fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) { assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); let window = match Root::downcast::<Window>(target.global()) { Some(window) => { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { Some(window) } else { None } }, _ => None, }; // Step 5. event.phase.set(EventPhase::Capturing); // Step 6. for object in event_path.iter().rev() { invoke(window.r(), object, event, Some(ListenerPhase::Capturing)); if event.stop_propagation.get() { return; } } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); // Step 7. event.phase.set(EventPhase::AtTarget); // Step 8. invoke(window.r(), target, event, None); if event.stop_propagation.get() { return; } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); if!event.bubbles.get() { return; } // Step 9.1. event.phase.set(EventPhase::Bubbling); // Step 9.2. for object in event_path { invoke(window.r(), object, event, Some(ListenerPhase::Bubbling)); if event.stop_propagation.get() { return; } } } // https://dom.spec.whatwg.org/#concept-event-listener-invoke fn invoke(window: Option<&Window>, object: &EventTarget, event: &Event, specific_listener_phase: Option<ListenerPhase>) { // Step 1. assert!(!event.stop_propagation.get()); // Steps 2-3. let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase); // Step 4. event.current_target.set(Some(object)); // Step 5. inner_invoke(window, object, event, &listeners); // TODO: step 6. } // https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke fn inner_invoke(window: Option<&Window>, object: &EventTarget, event: &Event, listeners: &[CompiledEventListener]) -> bool { // Step 1. let mut found = false; // Step 2. for listener in listeners { // Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the // relevant ones for this invoke call during the dispatch algorithm. // Step 2.2. found = true; // TODO: step 2.5. // Step 2.6. let marker = TimelineMarker::start("DOMEvent".to_owned()); listener.call_or_handle_event(object, event, ExceptionHandling::Report); if let Some(window) = window { window.emit_timeline_marker(marker.end()); } if event.stop_immediate.get() { return found; } // TODO: step 2.7. } // Step 3. found }
from
identifier_name
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType}; use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableJS, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase}; use dom::globalscope::GlobalScope; use dom::node::Node; use dom::virtualmethods::vtable_for; use dom::window::Window; use script_thread::Runnable; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; use time; #[dom_struct] pub struct Event { reflector_: Reflector, current_target: MutNullableJS<EventTarget>, target: MutNullableJS<EventTarget>, type_: DOMRefCell<Atom>, phase: Cell<EventPhase>, canceled: Cell<EventDefault>, stop_propagation: Cell<bool>, stop_immediate: Cell<bool>, cancelable: Cell<bool>, bubbles: Cell<bool>, trusted: Cell<bool>, dispatching: Cell<bool>, initialized: Cell<bool>, timestamp: u64, } impl Event { pub fn new_inherited() -> Event { Event { reflector_: Reflector::new(), current_target: Default::default(), target: Default::default(), type_: DOMRefCell::new(atom!("")), phase: Cell::new(EventPhase::None), canceled: Cell::new(EventDefault::Allowed), stop_propagation: Cell::new(false), stop_immediate: Cell::new(false), cancelable: Cell::new(false), bubbles: Cell::new(false), trusted: Cell::new(false), dispatching: Cell::new(false), initialized: Cell::new(false), timestamp: time::get_time().sec as u64, } } pub fn new_uninitialized(global: &GlobalScope) -> Root<Event> { reflect_dom_object(box Event::new_inherited(), global, EventBinding::Wrap) } pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable) -> Root<Event> { let event = Event::new_uninitialized(global); event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); event } pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &EventBinding::EventInit) -> Fallible<Root<Event>> { let bubbles = EventBubbles::from(init.bubbles); let cancelable = EventCancelable::from(init.cancelable); Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) } pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) { if self.dispatching.get() { return; } self.initialized.set(true); self.stop_propagation.set(false); self.stop_immediate.set(false); self.canceled.set(EventDefault::Allowed); self.trusted.set(false); self.target.set(None); *self.type_.borrow_mut() = type_; self.bubbles.set(bubbles); self.cancelable.set(cancelable); } // https://dom.spec.whatwg.org/#concept-event-dispatch pub fn dispatch(&self, target: &EventTarget, target_override: Option<&EventTarget>) -> EventStatus { assert!(!self.dispatching()); assert!(self.initialized()); assert_eq!(self.phase.get(), EventPhase::None); assert!(self.GetCurrentTarget().is_none()); // Step 1. self.dispatching.set(true); // Step 2. self.target.set(Some(target_override.unwrap_or(target))); if self.stop_propagation.get() { // If the event's stop propagation flag is set, we can skip everything because // it prevents the calls of the invoke algorithm in the spec. // Step 10-12. self.clear_dispatching_flags(); // Step 14. return self.status(); } // Step 3. The "invoke" algorithm is only used on `target` separately, // so we don't put it in the path. rooted_vec!(let mut event_path); // Step 4. if let Some(target_node) = target.downcast::<Node>() { for ancestor in target_node.ancestors() { event_path.push(JS::from_ref(ancestor.upcast::<EventTarget>())); } let top_most_ancestor_or_target = Root::from_ref(event_path.r().last().cloned().unwrap_or(target)); if let Some(document) = Root::downcast::<Document>(top_most_ancestor_or_target) { if self.type_()!= atom!("load") && document.browsing_context().is_some() { event_path.push(JS::from_ref(document.window().upcast())); } } } // Steps 5-9. In a separate function to short-circuit various things easily. dispatch_to_listeners(self, target, event_path.r()); // Default action. if let Some(target) = self.GetTarget() { if let Some(node) = target.downcast::<Node>() { let vtable = vtable_for(&node); vtable.handle_event(self); } } // Step 10-12. self.clear_dispatching_flags(); // Step 14. self.status() } pub fn status(&self) -> EventStatus { match self.DefaultPrevented() { true => EventStatus::Canceled, false => EventStatus::NotCanceled } } #[inline]
#[inline] // https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12. fn clear_dispatching_flags(&self) { assert!(self.dispatching.get()); self.dispatching.set(false); self.stop_propagation.set(false); self.stop_immediate.set(false); self.phase.set(EventPhase::None); self.current_target.set(None); } #[inline] pub fn initialized(&self) -> bool { self.initialized.get() } #[inline] pub fn type_(&self) -> Atom { self.type_.borrow().clone() } #[inline] pub fn mark_as_handled(&self) { self.canceled.set(EventDefault::Handled); } #[inline] pub fn get_cancel_state(&self) -> EventDefault { self.canceled.get() } pub fn set_trusted(&self, trusted: bool) { self.trusted.set(trusted); } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub fn fire(&self, target: &EventTarget) -> EventStatus { self.set_trusted(true); target.dispatch_event(self) } } impl EventMethods for Event { // https://dom.spec.whatwg.org/#dom-event-eventphase fn EventPhase(&self) -> u16 { self.phase.get() as u16 } // https://dom.spec.whatwg.org/#dom-event-type fn Type(&self) -> DOMString { DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString } // https://dom.spec.whatwg.org/#dom-event-target fn GetTarget(&self) -> Option<Root<EventTarget>> { self.target.get() } // https://dom.spec.whatwg.org/#dom-event-currenttarget fn GetCurrentTarget(&self) -> Option<Root<EventTarget>> { self.current_target.get() } // https://dom.spec.whatwg.org/#dom-event-defaultprevented fn DefaultPrevented(&self) -> bool { self.canceled.get() == EventDefault::Prevented } // https://dom.spec.whatwg.org/#dom-event-preventdefault fn PreventDefault(&self) { if self.cancelable.get() { self.canceled.set(EventDefault::Prevented) } } // https://dom.spec.whatwg.org/#dom-event-stoppropagation fn StopPropagation(&self) { self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation fn StopImmediatePropagation(&self) { self.stop_immediate.set(true); self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-bubbles fn Bubbles(&self) -> bool { self.bubbles.get() } // https://dom.spec.whatwg.org/#dom-event-cancelable fn Cancelable(&self) -> bool { self.cancelable.get() } // https://dom.spec.whatwg.org/#dom-event-timestamp fn TimeStamp(&self) -> u64 { self.timestamp } // https://dom.spec.whatwg.org/#dom-event-initevent fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) { self.init_event(Atom::from(type_), bubbles, cancelable) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.trusted.get() } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventBubbles { Bubbles, DoesNotBubble } impl From<bool> for EventBubbles { fn from(boolean: bool) -> Self { match boolean { true => EventBubbles::Bubbles, false => EventBubbles::DoesNotBubble } } } impl From<EventBubbles> for bool { fn from(bubbles: EventBubbles) -> Self { match bubbles { EventBubbles::Bubbles => true, EventBubbles::DoesNotBubble => false } } } #[derive(PartialEq, HeapSizeOf, Copy, Clone)] pub enum EventCancelable { Cancelable, NotCancelable } impl From<bool> for EventCancelable { fn from(boolean: bool) -> Self { match boolean { true => EventCancelable::Cancelable, false => EventCancelable::NotCancelable } } } impl From<EventCancelable> for bool { fn from(bubbles: EventCancelable) -> Self { match bubbles { EventCancelable::Cancelable => true, EventCancelable::NotCancelable => false } } } #[derive(JSTraceable, Copy, Clone, Debug, PartialEq, Eq)] #[repr(u16)] #[derive(HeapSizeOf)] pub enum EventPhase { None = EventConstants::NONE, Capturing = EventConstants::CAPTURING_PHASE, AtTarget = EventConstants::AT_TARGET, Bubbling = EventConstants::BUBBLING_PHASE, } /// An enum to indicate whether the default action of an event is allowed. /// /// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled /// states, we also need something to stop the event from being handled again (without cancelling /// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will /// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum /// helps us to prevent such events from being [sent to the constellation][msg] where it will be /// handled once again for page scrolling (which is definitely not what we'd want). /// /// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent /// #[derive(JSTraceable, HeapSizeOf, Copy, Clone, PartialEq)] pub enum EventDefault { /// The default action of the event is allowed (constructor's default) Allowed, /// The default action has been prevented by calling `PreventDefault` Prevented, /// The event has been handled somewhere in the DOM, and it should be prevented from being /// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented` Handled, } #[derive(PartialEq)] pub enum EventStatus { Canceled, NotCanceled } // https://dom.spec.whatwg.org/#concept-event-fire pub struct EventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, pub bubbles: EventBubbles, pub cancelable: EventCancelable, } impl Runnable for EventRunnable { fn name(&self) -> &'static str { "EventRunnable" } fn handler(self: Box<EventRunnable>) { let target = self.target.root(); let bubbles = self.bubbles; let cancelable = self.cancelable; target.fire_event_with_params(self.name, bubbles, cancelable); } } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event pub struct SimpleEventRunnable { pub target: Trusted<EventTarget>, pub name: Atom, } impl Runnable for SimpleEventRunnable { fn name(&self) -> &'static str { "SimpleEventRunnable" } fn handler(self: Box<SimpleEventRunnable>) { let target = self.target.root(); target.fire_event(self.name); } } // See dispatch_event. // https://dom.spec.whatwg.org/#concept-event-dispatch fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) { assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); let window = match Root::downcast::<Window>(target.global()) { Some(window) => { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { Some(window) } else { None } }, _ => None, }; // Step 5. event.phase.set(EventPhase::Capturing); // Step 6. for object in event_path.iter().rev() { invoke(window.r(), object, event, Some(ListenerPhase::Capturing)); if event.stop_propagation.get() { return; } } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); // Step 7. event.phase.set(EventPhase::AtTarget); // Step 8. invoke(window.r(), target, event, None); if event.stop_propagation.get() { return; } assert!(!event.stop_propagation.get()); assert!(!event.stop_immediate.get()); if!event.bubbles.get() { return; } // Step 9.1. event.phase.set(EventPhase::Bubbling); // Step 9.2. for object in event_path { invoke(window.r(), object, event, Some(ListenerPhase::Bubbling)); if event.stop_propagation.get() { return; } } } // https://dom.spec.whatwg.org/#concept-event-listener-invoke fn invoke(window: Option<&Window>, object: &EventTarget, event: &Event, specific_listener_phase: Option<ListenerPhase>) { // Step 1. assert!(!event.stop_propagation.get()); // Steps 2-3. let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase); // Step 4. event.current_target.set(Some(object)); // Step 5. inner_invoke(window, object, event, &listeners); // TODO: step 6. } // https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke fn inner_invoke(window: Option<&Window>, object: &EventTarget, event: &Event, listeners: &[CompiledEventListener]) -> bool { // Step 1. let mut found = false; // Step 2. for listener in listeners { // Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the // relevant ones for this invoke call during the dispatch algorithm. // Step 2.2. found = true; // TODO: step 2.5. // Step 2.6. let marker = TimelineMarker::start("DOMEvent".to_owned()); listener.call_or_handle_event(object, event, ExceptionHandling::Report); if let Some(window) = window { window.emit_timeline_marker(marker.end()); } if event.stop_immediate.get() { return found; } // TODO: step 2.7. } // Step 3. found }
pub fn dispatching(&self) -> bool { self.dispatching.get() }
random_line_split
vector.rs
// Copyright 2014 Michael Yang. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #[cfg(not(feature = "default"))] use libc::c_int; #[cfg(feature = "default")] pub use rblas::vector::Vector; #[cfg(not(feature = "default"))] /// Methods that allow a type to be used in BLAS functions as a vector. pub trait Vector<T> { /// The stride within the vector. For example, if `inc` returns 7, every /// 7th element is used. Defaults to 1.
/// An unsafe pointer to a contiguous block of memory. fn as_ptr(&self) -> *const T; /// An unsafe mutable pointer to a contiguous block of memory. fn as_mut_ptr(&mut self) -> *mut T; }
fn inc(&self) -> c_int { 1 } /// The number of elements in the vector. fn len(&self) -> c_int;
random_line_split
vector.rs
// Copyright 2014 Michael Yang. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #[cfg(not(feature = "default"))] use libc::c_int; #[cfg(feature = "default")] pub use rblas::vector::Vector; #[cfg(not(feature = "default"))] /// Methods that allow a type to be used in BLAS functions as a vector. pub trait Vector<T> { /// The stride within the vector. For example, if `inc` returns 7, every /// 7th element is used. Defaults to 1. fn
(&self) -> c_int { 1 } /// The number of elements in the vector. fn len(&self) -> c_int; /// An unsafe pointer to a contiguous block of memory. fn as_ptr(&self) -> *const T; /// An unsafe mutable pointer to a contiguous block of memory. fn as_mut_ptr(&mut self) -> *mut T; }
inc
identifier_name
vector.rs
// Copyright 2014 Michael Yang. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #[cfg(not(feature = "default"))] use libc::c_int; #[cfg(feature = "default")] pub use rblas::vector::Vector; #[cfg(not(feature = "default"))] /// Methods that allow a type to be used in BLAS functions as a vector. pub trait Vector<T> { /// The stride within the vector. For example, if `inc` returns 7, every /// 7th element is used. Defaults to 1. fn inc(&self) -> c_int
/// The number of elements in the vector. fn len(&self) -> c_int; /// An unsafe pointer to a contiguous block of memory. fn as_ptr(&self) -> *const T; /// An unsafe mutable pointer to a contiguous block of memory. fn as_mut_ptr(&mut self) -> *mut T; }
{ 1 }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(box_syntax)] #![feature(core_intrinsics)] #![feature(custom_derive)] #![feature(fnbox)] #![feature(optin_builtin_traits)] #![feature(plugin)] #![feature(panic_handler)] #![feature(reflect_marker)] #![feature(step_by)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![deny(unsafe_code)] extern crate app_units; extern crate backtrace; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; extern crate deque; extern crate euclid; extern crate getopts; extern crate heapsize; extern crate ipc_channel; #[cfg(feature = "non-geckolib")] extern crate js; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static; extern crate libc; #[macro_use] extern crate log; extern crate num; extern crate num_cpus; extern crate rand; extern crate rustc_serialize; extern crate serde; extern crate smallvec; extern crate string_cache; extern crate url; use std::sync::Arc; pub mod cache; #[allow(unsafe_code)] pub mod debug_utils; pub mod geometry; #[allow(unsafe_code)] pub mod ipc; pub mod linked_list; #[cfg(feature = "non-geckolib")] #[allow(unsafe_code)] pub mod non_geckolib; #[allow(unsafe_code)] pub mod opts; pub mod panicking; #[allow(unsafe_code)] pub mod prefs; pub mod print_tree; #[allow(unsafe_code)] pub mod resource_files; #[allow(unsafe_code)] pub mod str; pub mod thread; pub mod thread_state; pub mod tid; pub mod time; pub mod vec; #[allow(unsafe_code)] pub mod workqueue; #[allow(unsafe_code)] pub fn breakpoint() { unsafe { ::std::intrinsics::breakpoint() }; } // Workaround for lack of `ptr_eq` on Arcs... #[inline] pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool
{ let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(box_syntax)] #![feature(core_intrinsics)] #![feature(custom_derive)] #![feature(fnbox)] #![feature(optin_builtin_traits)] #![feature(plugin)] #![feature(panic_handler)] #![feature(reflect_marker)] #![feature(step_by)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![deny(unsafe_code)] extern crate app_units; extern crate backtrace; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; extern crate deque; extern crate euclid; extern crate getopts; extern crate heapsize; extern crate ipc_channel; #[cfg(feature = "non-geckolib")] extern crate js; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static; extern crate libc; #[macro_use] extern crate log; extern crate num; extern crate num_cpus; extern crate rand; extern crate rustc_serialize; extern crate serde; extern crate smallvec; extern crate string_cache; extern crate url; use std::sync::Arc; pub mod cache; #[allow(unsafe_code)] pub mod debug_utils; pub mod geometry; #[allow(unsafe_code)] pub mod ipc; pub mod linked_list; #[cfg(feature = "non-geckolib")] #[allow(unsafe_code)] pub mod non_geckolib; #[allow(unsafe_code)] pub mod opts; pub mod panicking; #[allow(unsafe_code)] pub mod prefs; pub mod print_tree; #[allow(unsafe_code)] pub mod resource_files; #[allow(unsafe_code)] pub mod str; pub mod thread; pub mod thread_state; pub mod tid; pub mod time; pub mod vec; #[allow(unsafe_code)] pub mod workqueue; #[allow(unsafe_code)] pub fn
() { unsafe { ::std::intrinsics::breakpoint() }; } // Workaround for lack of `ptr_eq` on Arcs... #[inline] pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
breakpoint
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(box_syntax)] #![feature(core_intrinsics)] #![feature(custom_derive)] #![feature(fnbox)] #![feature(optin_builtin_traits)] #![feature(plugin)] #![feature(panic_handler)] #![feature(reflect_marker)] #![feature(step_by)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![deny(unsafe_code)] extern crate app_units; extern crate backtrace; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; extern crate deque; extern crate euclid; extern crate getopts; extern crate heapsize; extern crate ipc_channel; #[cfg(feature = "non-geckolib")] extern crate js; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static;
extern crate log; extern crate num; extern crate num_cpus; extern crate rand; extern crate rustc_serialize; extern crate serde; extern crate smallvec; extern crate string_cache; extern crate url; use std::sync::Arc; pub mod cache; #[allow(unsafe_code)] pub mod debug_utils; pub mod geometry; #[allow(unsafe_code)] pub mod ipc; pub mod linked_list; #[cfg(feature = "non-geckolib")] #[allow(unsafe_code)] pub mod non_geckolib; #[allow(unsafe_code)] pub mod opts; pub mod panicking; #[allow(unsafe_code)] pub mod prefs; pub mod print_tree; #[allow(unsafe_code)] pub mod resource_files; #[allow(unsafe_code)] pub mod str; pub mod thread; pub mod thread_state; pub mod tid; pub mod time; pub mod vec; #[allow(unsafe_code)] pub mod workqueue; #[allow(unsafe_code)] pub fn breakpoint() { unsafe { ::std::intrinsics::breakpoint() }; } // Workaround for lack of `ptr_eq` on Arcs... #[inline] pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
extern crate libc; #[macro_use]
random_line_split
length.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser, ParserInput}; use parsing::parse; use style::context::QuirksMode; use style::parser::{Parse, ParserContext}; use style::stylesheets::{CssRuleType, Origin}; use style::values::Either; use style::values::specified::{LengthOrPercentageOrNumber, Number}; use style::values::specified::length::{AbsoluteLength, Length, NoCalcLength}; use style_traits::{ParsingMode, ToCss}; #[test] fn test_calc() { assert!(parse(Length::parse, "calc(1px+ 2px)").is_err()); assert!(parse(Length::parse, "calc(calc(1px) + calc(1px + 4px))").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px )").is_ok()); assert!(parse(Length::parse, "calc(1px + 2px )").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px)").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px / ( 1 + 2 - 1))").is_ok()); } #[test] fn test_length_literals() { assert_roundtrip_with_context!(Length::parse, "0.33px", "0.33px"); assert_roundtrip_with_context!(Length::parse, "0.33in", "0.33in"); assert_roundtrip_with_context!(Length::parse, "0.33cm", "0.33cm"); assert_roundtrip_with_context!(Length::parse, "0.33mm", "0.33mm"); assert_roundtrip_with_context!(Length::parse, "0.33q", "0.33q"); assert_roundtrip_with_context!(Length::parse, "0.33pt", "0.33pt"); assert_roundtrip_with_context!(Length::parse, "0.33pc", "0.33pc"); } #[test] fn test_parsing_modes()
#[test] fn test_zero_percentage_length_or_number() { assert_eq!(parse(LengthOrPercentageOrNumber::parse, "0"), Ok(Either::First(Number::new(0.)))); }
{ // In default length mode, non-zero lengths must have a unit. assert!(parse(Length::parse, "1").is_err()); // In SVG length mode, non-zero lengths are assumed to be px. let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Some(CssRuleType::Style), ParsingMode::ALLOW_UNITLESS_LENGTH, QuirksMode::NoQuirks); let mut input = ParserInput::new("1"); let mut parser = Parser::new(&mut input); let result = Length::parse(&context, &mut parser); assert!(result.is_ok()); assert_eq!(result.unwrap(), Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(1.)))); }
identifier_body
length.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser, ParserInput}; use parsing::parse; use style::context::QuirksMode;
use style::values::specified::length::{AbsoluteLength, Length, NoCalcLength}; use style_traits::{ParsingMode, ToCss}; #[test] fn test_calc() { assert!(parse(Length::parse, "calc(1px+ 2px)").is_err()); assert!(parse(Length::parse, "calc(calc(1px) + calc(1px + 4px))").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px )").is_ok()); assert!(parse(Length::parse, "calc(1px + 2px )").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px)").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px / ( 1 + 2 - 1))").is_ok()); } #[test] fn test_length_literals() { assert_roundtrip_with_context!(Length::parse, "0.33px", "0.33px"); assert_roundtrip_with_context!(Length::parse, "0.33in", "0.33in"); assert_roundtrip_with_context!(Length::parse, "0.33cm", "0.33cm"); assert_roundtrip_with_context!(Length::parse, "0.33mm", "0.33mm"); assert_roundtrip_with_context!(Length::parse, "0.33q", "0.33q"); assert_roundtrip_with_context!(Length::parse, "0.33pt", "0.33pt"); assert_roundtrip_with_context!(Length::parse, "0.33pc", "0.33pc"); } #[test] fn test_parsing_modes() { // In default length mode, non-zero lengths must have a unit. assert!(parse(Length::parse, "1").is_err()); // In SVG length mode, non-zero lengths are assumed to be px. let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Some(CssRuleType::Style), ParsingMode::ALLOW_UNITLESS_LENGTH, QuirksMode::NoQuirks); let mut input = ParserInput::new("1"); let mut parser = Parser::new(&mut input); let result = Length::parse(&context, &mut parser); assert!(result.is_ok()); assert_eq!(result.unwrap(), Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(1.)))); } #[test] fn test_zero_percentage_length_or_number() { assert_eq!(parse(LengthOrPercentageOrNumber::parse, "0"), Ok(Either::First(Number::new(0.)))); }
use style::parser::{Parse, ParserContext}; use style::stylesheets::{CssRuleType, Origin}; use style::values::Either; use style::values::specified::{LengthOrPercentageOrNumber, Number};
random_line_split
length.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser, ParserInput}; use parsing::parse; use style::context::QuirksMode; use style::parser::{Parse, ParserContext}; use style::stylesheets::{CssRuleType, Origin}; use style::values::Either; use style::values::specified::{LengthOrPercentageOrNumber, Number}; use style::values::specified::length::{AbsoluteLength, Length, NoCalcLength}; use style_traits::{ParsingMode, ToCss}; #[test] fn test_calc() { assert!(parse(Length::parse, "calc(1px+ 2px)").is_err()); assert!(parse(Length::parse, "calc(calc(1px) + calc(1px + 4px))").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px )").is_ok()); assert!(parse(Length::parse, "calc(1px + 2px )").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px)").is_ok()); assert!(parse(Length::parse, "calc( 1px + 2px / ( 1 + 2 - 1))").is_ok()); } #[test] fn test_length_literals() { assert_roundtrip_with_context!(Length::parse, "0.33px", "0.33px"); assert_roundtrip_with_context!(Length::parse, "0.33in", "0.33in"); assert_roundtrip_with_context!(Length::parse, "0.33cm", "0.33cm"); assert_roundtrip_with_context!(Length::parse, "0.33mm", "0.33mm"); assert_roundtrip_with_context!(Length::parse, "0.33q", "0.33q"); assert_roundtrip_with_context!(Length::parse, "0.33pt", "0.33pt"); assert_roundtrip_with_context!(Length::parse, "0.33pc", "0.33pc"); } #[test] fn test_parsing_modes() { // In default length mode, non-zero lengths must have a unit. assert!(parse(Length::parse, "1").is_err()); // In SVG length mode, non-zero lengths are assumed to be px. let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Some(CssRuleType::Style), ParsingMode::ALLOW_UNITLESS_LENGTH, QuirksMode::NoQuirks); let mut input = ParserInput::new("1"); let mut parser = Parser::new(&mut input); let result = Length::parse(&context, &mut parser); assert!(result.is_ok()); assert_eq!(result.unwrap(), Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(1.)))); } #[test] fn
() { assert_eq!(parse(LengthOrPercentageOrNumber::parse, "0"), Ok(Either::First(Number::new(0.)))); }
test_zero_percentage_length_or_number
identifier_name
regions-variance-invariant-use-covariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a type which is invariant with respect to its region // parameter used in a covariant way yields an error. // // Note: see variance-regions-*.rs for the tests that check that the // variance inference works in the first place. struct Invariant<'a> { f: &'a mut &'a int } fn use_<'b>(c: Invariant<'b>) { // For this assignment to be legal, Invariant<'b> <: Invariant<'static>. // Since 'b <='static, this would be true if Invariant were covariant // with respect to its parameter 'a. let _: Invariant<'static> = c; //~ ERROR mismatched types } fn main() { }
random_line_split
regions-variance-invariant-use-covariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a type which is invariant with respect to its region // parameter used in a covariant way yields an error. // // Note: see variance-regions-*.rs for the tests that check that the // variance inference works in the first place. struct Invariant<'a> { f: &'a mut &'a int } fn use_<'b>(c: Invariant<'b>) { // For this assignment to be legal, Invariant<'b> <: Invariant<'static>. // Since 'b <='static, this would be true if Invariant were covariant // with respect to its parameter 'a. let _: Invariant<'static> = c; //~ ERROR mismatched types } fn
() { }
main
identifier_name
input.rs
use std::thread; use std::sync::{Arc, Mutex}; use rustbox; use rustbox::{RustBox, Key, Mouse, EventResult}; use rustbox::Event::{KeyEvent, MouseEvent, ResizeEvent}; /** * Spawns a thread which loops, polling for keyboard and mouse input using rustbox. * (Rustbox is only used for this purpose, not for any terminal output). * * Note how data is not passed using a channel's sender, but by mutating the passed-in argument, * which is shared with the main thread. This value acts as a flag. * * TODO: Should not be a flag so much as a queue... (eg, fast mousewheel operations lag) * TODO: The use of app-specific 'Commands' as an extra abstraction has proven to be not all that useful; should flatten or smth */ pub fn launch_thread(wrapped_command: Arc<Mutex<Command>>) -> thread::JoinHandle<()> { thread::spawn(move || { let rustbox = match RustBox::init( rustbox::InitOptions { input_mode: rustbox::InputMode::EscMouse, buffer_stderr: false }) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; { // immediately set the command to tell app the terminal's character dimensions let mut locked_command = wrapped_command.lock().unwrap(); *locked_command = Command::Size(rustbox.width(), rustbox.height()); } loop { let event = rustbox.poll_event(false); // rem, this BLOCKS // TODO: use this instead, and rip out the thread nonsense // let event = rustbox.peek_event(Duration::from_millis(5000), false); let mut locked_command = wrapped_command.lock().unwrap(); *locked_command = Command::from_rustbox_event(event); match *locked_command { Command::Quit => { break; } _ => {} } } }) } #[derive(Debug)] pub enum Command { ChangeFractalSet, PositionVelocity(f64,f64), PositionTween(i32, i32), Zoom(f64), ZoomContinuous(f64), RotationalVelocity(f64), Size(usize, usize), Coord(usize), AutoExposure, Help, Stop, Reset, Quit, None, // TODO: use 'Option' pattern instead of 'none'? } impl Command { pub fn from_rustbox_event(event_result: EventResult) -> Command { let event = event_result.unwrap(); match event { KeyEvent(key) => {
Key::Right => Command::PositionVelocity(1.0, 0.0), Key::Up => Command::PositionVelocity(0.0, -1.0), Key::Down => Command::PositionVelocity(0.0, 1.0), Key::Char('a') | Key::Char('=') => Command::Zoom(-1.0), Key::Char('A') | Key::Char('+') => Command::ZoomContinuous(-0.5), Key::Char('z') | Key::Char('-') => Command::Zoom(1.0), Key::Char('Z') | Key::Char('_') => Command::ZoomContinuous(0.5), Key::Char('[') | Key::Char('{') => Command::RotationalVelocity(1.0), Key::Char(']') | Key::Char('}') => Command::RotationalVelocity(-1.0), Key::Char('/') | Key::Char('?') | Key::Char('h') | Key::Char('H') => Command::Help, Key::Char('1') => Command::Coord(0), Key::Char('2') => Command::Coord(1), Key::Char('3') => Command::Coord(2), Key::Char('4') => Command::Coord(3), Key::Char('5') => Command::Coord(4), Key::Char('6') => Command::Coord(5), Key::Char('7') => Command::Coord(6), Key::Char('8') => Command::Coord(7), Key::Char('9') => Command::Coord(8), Key::Char('0') => Command::Coord(9), Key::Char('e') | Key::Char('E') => Command::AutoExposure, Key::Char(' ') => Command::Stop, Key::Char('r') | Key::Char('R') => Command::Reset, Key::Esc | Key::Ctrl('c') => Command::Quit, _ => Command::None, } } MouseEvent(mouse, x, y) => { match mouse { Mouse::WheelUp => Command::Zoom(-0.3), Mouse::WheelDown => Command::Zoom(0.3), Mouse::Left => Command::PositionTween(x, y), _ => Command::None } }, ResizeEvent(w, h) => { Command::Size(w as usize, h as usize) }, _ => { Command::None } } } }
match key { Key::Char('f') | Key::Char('F') => Command::ChangeFractalSet, Key::Left => Command::PositionVelocity(-1.0, 0.0),
random_line_split
input.rs
use std::thread; use std::sync::{Arc, Mutex}; use rustbox; use rustbox::{RustBox, Key, Mouse, EventResult}; use rustbox::Event::{KeyEvent, MouseEvent, ResizeEvent}; /** * Spawns a thread which loops, polling for keyboard and mouse input using rustbox. * (Rustbox is only used for this purpose, not for any terminal output). * * Note how data is not passed using a channel's sender, but by mutating the passed-in argument, * which is shared with the main thread. This value acts as a flag. * * TODO: Should not be a flag so much as a queue... (eg, fast mousewheel operations lag) * TODO: The use of app-specific 'Commands' as an extra abstraction has proven to be not all that useful; should flatten or smth */ pub fn launch_thread(wrapped_command: Arc<Mutex<Command>>) -> thread::JoinHandle<()> { thread::spawn(move || { let rustbox = match RustBox::init( rustbox::InitOptions { input_mode: rustbox::InputMode::EscMouse, buffer_stderr: false }) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; { // immediately set the command to tell app the terminal's character dimensions let mut locked_command = wrapped_command.lock().unwrap(); *locked_command = Command::Size(rustbox.width(), rustbox.height()); } loop { let event = rustbox.poll_event(false); // rem, this BLOCKS // TODO: use this instead, and rip out the thread nonsense // let event = rustbox.peek_event(Duration::from_millis(5000), false); let mut locked_command = wrapped_command.lock().unwrap(); *locked_command = Command::from_rustbox_event(event); match *locked_command { Command::Quit => { break; } _ => {} } } }) } #[derive(Debug)] pub enum
{ ChangeFractalSet, PositionVelocity(f64,f64), PositionTween(i32, i32), Zoom(f64), ZoomContinuous(f64), RotationalVelocity(f64), Size(usize, usize), Coord(usize), AutoExposure, Help, Stop, Reset, Quit, None, // TODO: use 'Option' pattern instead of 'none'? } impl Command { pub fn from_rustbox_event(event_result: EventResult) -> Command { let event = event_result.unwrap(); match event { KeyEvent(key) => { match key { Key::Char('f') | Key::Char('F') => Command::ChangeFractalSet, Key::Left => Command::PositionVelocity(-1.0, 0.0), Key::Right => Command::PositionVelocity(1.0, 0.0), Key::Up => Command::PositionVelocity(0.0, -1.0), Key::Down => Command::PositionVelocity(0.0, 1.0), Key::Char('a') | Key::Char('=') => Command::Zoom(-1.0), Key::Char('A') | Key::Char('+') => Command::ZoomContinuous(-0.5), Key::Char('z') | Key::Char('-') => Command::Zoom(1.0), Key::Char('Z') | Key::Char('_') => Command::ZoomContinuous(0.5), Key::Char('[') | Key::Char('{') => Command::RotationalVelocity(1.0), Key::Char(']') | Key::Char('}') => Command::RotationalVelocity(-1.0), Key::Char('/') | Key::Char('?') | Key::Char('h') | Key::Char('H') => Command::Help, Key::Char('1') => Command::Coord(0), Key::Char('2') => Command::Coord(1), Key::Char('3') => Command::Coord(2), Key::Char('4') => Command::Coord(3), Key::Char('5') => Command::Coord(4), Key::Char('6') => Command::Coord(5), Key::Char('7') => Command::Coord(6), Key::Char('8') => Command::Coord(7), Key::Char('9') => Command::Coord(8), Key::Char('0') => Command::Coord(9), Key::Char('e') | Key::Char('E') => Command::AutoExposure, Key::Char(' ') => Command::Stop, Key::Char('r') | Key::Char('R') => Command::Reset, Key::Esc | Key::Ctrl('c') => Command::Quit, _ => Command::None, } } MouseEvent(mouse, x, y) => { match mouse { Mouse::WheelUp => Command::Zoom(-0.3), Mouse::WheelDown => Command::Zoom(0.3), Mouse::Left => Command::PositionTween(x, y), _ => Command::None } }, ResizeEvent(w, h) => { Command::Size(w as usize, h as usize) }, _ => { Command::None } } } }
Command
identifier_name
input.rs
use std::thread; use std::sync::{Arc, Mutex}; use rustbox; use rustbox::{RustBox, Key, Mouse, EventResult}; use rustbox::Event::{KeyEvent, MouseEvent, ResizeEvent}; /** * Spawns a thread which loops, polling for keyboard and mouse input using rustbox. * (Rustbox is only used for this purpose, not for any terminal output). * * Note how data is not passed using a channel's sender, but by mutating the passed-in argument, * which is shared with the main thread. This value acts as a flag. * * TODO: Should not be a flag so much as a queue... (eg, fast mousewheel operations lag) * TODO: The use of app-specific 'Commands' as an extra abstraction has proven to be not all that useful; should flatten or smth */ pub fn launch_thread(wrapped_command: Arc<Mutex<Command>>) -> thread::JoinHandle<()> { thread::spawn(move || { let rustbox = match RustBox::init( rustbox::InitOptions { input_mode: rustbox::InputMode::EscMouse, buffer_stderr: false }) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; { // immediately set the command to tell app the terminal's character dimensions let mut locked_command = wrapped_command.lock().unwrap(); *locked_command = Command::Size(rustbox.width(), rustbox.height()); } loop { let event = rustbox.poll_event(false); // rem, this BLOCKS // TODO: use this instead, and rip out the thread nonsense // let event = rustbox.peek_event(Duration::from_millis(5000), false); let mut locked_command = wrapped_command.lock().unwrap(); *locked_command = Command::from_rustbox_event(event); match *locked_command { Command::Quit => { break; } _ => {} } } }) } #[derive(Debug)] pub enum Command { ChangeFractalSet, PositionVelocity(f64,f64), PositionTween(i32, i32), Zoom(f64), ZoomContinuous(f64), RotationalVelocity(f64), Size(usize, usize), Coord(usize), AutoExposure, Help, Stop, Reset, Quit, None, // TODO: use 'Option' pattern instead of 'none'? } impl Command { pub fn from_rustbox_event(event_result: EventResult) -> Command
Key::Char('[') | Key::Char('{') => Command::RotationalVelocity(1.0), Key::Char(']') | Key::Char('}') => Command::RotationalVelocity(-1.0), Key::Char('/') | Key::Char('?') | Key::Char('h') | Key::Char('H') => Command::Help, Key::Char('1') => Command::Coord(0), Key::Char('2') => Command::Coord(1), Key::Char('3') => Command::Coord(2), Key::Char('4') => Command::Coord(3), Key::Char('5') => Command::Coord(4), Key::Char('6') => Command::Coord(5), Key::Char('7') => Command::Coord(6), Key::Char('8') => Command::Coord(7), Key::Char('9') => Command::Coord(8), Key::Char('0') => Command::Coord(9), Key::Char('e') | Key::Char('E') => Command::AutoExposure, Key::Char(' ') => Command::Stop, Key::Char('r') | Key::Char('R') => Command::Reset, Key::Esc | Key::Ctrl('c') => Command::Quit, _ => Command::None, } } MouseEvent(mouse, x, y) => { match mouse { Mouse::WheelUp => Command::Zoom(-0.3), Mouse::WheelDown => Command::Zoom(0.3), Mouse::Left => Command::PositionTween(x, y), _ => Command::None } }, ResizeEvent(w, h) => { Command::Size(w as usize, h as usize) }, _ => { Command::None } } } }
{ let event = event_result.unwrap(); match event { KeyEvent(key) => { match key { Key::Char('f') | Key::Char('F') => Command::ChangeFractalSet, Key::Left => Command::PositionVelocity(-1.0, 0.0), Key::Right => Command::PositionVelocity(1.0, 0.0), Key::Up => Command::PositionVelocity(0.0, -1.0), Key::Down => Command::PositionVelocity(0.0, 1.0), Key::Char('a') | Key::Char('=') => Command::Zoom(-1.0), Key::Char('A') | Key::Char('+') => Command::ZoomContinuous(-0.5), Key::Char('z') | Key::Char('-') => Command::Zoom(1.0), Key::Char('Z') | Key::Char('_') => Command::ZoomContinuous(0.5),
identifier_body
borrowck-loan-blocks-move-cc.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] use std::thread::Thread; fn
<F>(v: &isize, f: F) where F: FnOnce(&isize) { f(v); } fn box_imm() { let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move `v` into closure }); } fn box_imm_explicit() { let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move }); } fn main() { }
borrow
identifier_name
borrowck-loan-blocks-move-cc.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] use std::thread::Thread; fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) { f(v); } fn box_imm() { let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move `v` into closure }); } fn box_imm_explicit()
fn main() { }
{ let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move }); }
identifier_body
borrowck-loan-blocks-move-cc.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] use std::thread::Thread; fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) { f(v); } fn box_imm() { let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move `v` into closure }); } fn box_imm_explicit() {
}); } fn main() { }
let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move
random_line_split
level.rs
use crate::time::driver::TimerHandle; use crate::time::driver::{EntryList, TimerShared}; use std::{fmt, ptr::NonNull}; /// Wheel for a single level in the timer. This wheel contains 64 slots. pub(crate) struct Level { level: usize, /// Bit field tracking which slots currently contain entries. /// /// Using a bit field to track slots that contain entries allows avoiding a /// scan to find entries. This field is updated when entries are added or /// removed from a slot. /// /// The least-significant bit represents slot zero. occupied: u64, /// Slots. We access these via the EntryInner `current_list` as well, so this needs to be an UnsafeCell. slot: [EntryList; LEVEL_MULT], } /// Indicates when a slot must be processed next. #[derive(Debug)] pub(crate) struct Expiration { /// The level containing the slot. pub(crate) level: usize, /// The slot index. pub(crate) slot: usize, /// The instant at which the slot needs to be processed. pub(crate) deadline: u64, } /// Level multiplier. /// /// Being a power of 2 is very important. const LEVEL_MULT: usize = 64; impl Level { pub(crate) fn new(level: usize) -> Level { // A value has to be Copy in order to use syntax like: // let stack = Stack::default(); // ... // slots: [stack; 64], // // Alternatively, since Stack is Default one can // use syntax like: // let slots: [Stack; 64] = Default::default(); // // However, that is only supported for arrays of size // 32 or fewer. So in our case we have to explicitly // invoke the constructor for each array element. let ctor = EntryList::default; Level { level, occupied: 0, slot: [ ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ], } } /// Finds the slot that needs to be processed next and returns the slot and /// `Instant` at which this slot must be processed. pub(crate) fn next_expiration(&self, now: u64) -> Option<Expiration> { // Use the `occupied` bit field to get the index of the next slot that // needs to be processed. let slot = match self.next_occupied_slot(now) { Some(slot) => slot, None => return None, }; // From the slot index, calculate the `Instant` at which it needs to be // processed. This value *must* be in the future with respect to `now`. let level_range = level_range(self.level); let slot_range = slot_range(self.level); // Compute the start date of the current level by masking the low bits // of `now` (`level_range` is a power of 2). let level_start = now &!(level_range - 1); let mut deadline = level_start + slot as u64 * slot_range; if deadline <= now { // A timer is in a slot "prior" to the current time. This can occur // because we do not have an infinite hierarchy of timer levels, and // eventually a timer scheduled for a very distant time might end up // being placed in a slot that is beyond the end of all of the // arrays. // // To deal with this, we first limit timers to being scheduled no // more than MAX_DURATION ticks in the future; that is, they're at // most one rotation of the top level away. Then, we force timers // that logically would go into the top+1 level, to instead go into // the top level's slots. // // What this means is that the top level's slots act as a // pseudo-ring buffer, and we rotate around them indefinitely. If we // compute a deadline before now, and it's the top level, it // therefore means we're actually looking at a slot in the future. debug_assert_eq!(self.level, super::NUM_LEVELS - 1); deadline += level_range; } debug_assert!( deadline >= now, "deadline={:016X}; now={:016X}; level={}; lr={:016X}, sr={:016X}, slot={}; occupied={:b}", deadline, now, self.level, level_range, slot_range, slot, self.occupied ); Some(Expiration { level: self.level, slot, deadline, }) } fn next_occupied_slot(&self, now: u64) -> Option<usize> { if self.occupied == 0 { return None; } // Get the slot for now using Maths let now_slot = (now / slot_range(self.level)) as usize; let occupied = self.occupied.rotate_right(now_slot as u32); let zeros = occupied.trailing_zeros() as usize; let slot = (zeros + now_slot) % 64; Some(slot) } pub(crate) unsafe fn add_entry(&mut self, item: TimerHandle) { let slot = slot_for(item.cached_when(), self.level); self.slot[slot].push_front(item); self.occupied |= occupied_bit(slot); } pub(crate) unsafe fn remove_entry(&mut self, item: NonNull<TimerShared>) { let slot = slot_for(unsafe { item.as_ref().cached_when() }, self.level); unsafe { self.slot[slot].remove(item) }; if self.slot[slot].is_empty() { // The bit is currently set debug_assert!(self.occupied & occupied_bit(slot)!= 0); // Unset the bit self.occupied ^= occupied_bit(slot); } } pub(crate) fn take_slot(&mut self, slot: usize) -> EntryList { self.occupied &=!occupied_bit(slot); std::mem::take(&mut self.slot[slot]) } } impl fmt::Debug for Level { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Level") .field("occupied", &self.occupied) .finish() } } fn occupied_bit(slot: usize) -> u64
fn slot_range(level: usize) -> u64 { LEVEL_MULT.pow(level as u32) as u64 } fn level_range(level: usize) -> u64 { LEVEL_MULT as u64 * slot_range(level) } /// Converts a duration (milliseconds) and a level to a slot position. fn slot_for(duration: u64, level: usize) -> usize { ((duration >> (level * 6)) % LEVEL_MULT as u64) as usize } #[cfg(all(test, not(loom)))] mod test { use super::*; #[test] fn test_slot_for() { for pos in 0..64 { assert_eq!(pos as usize, slot_for(pos, 0)); } for level in 1..5 { for pos in level..64 { let a = pos * 64_usize.pow(level as u32); assert_eq!(pos as usize, slot_for(a as u64, level)); } } } }
{ 1 << slot }
identifier_body
level.rs
use crate::time::driver::TimerHandle; use crate::time::driver::{EntryList, TimerShared}; use std::{fmt, ptr::NonNull}; /// Wheel for a single level in the timer. This wheel contains 64 slots. pub(crate) struct Level { level: usize, /// Bit field tracking which slots currently contain entries. /// /// Using a bit field to track slots that contain entries allows avoiding a /// scan to find entries. This field is updated when entries are added or /// removed from a slot. /// /// The least-significant bit represents slot zero. occupied: u64, /// Slots. We access these via the EntryInner `current_list` as well, so this needs to be an UnsafeCell. slot: [EntryList; LEVEL_MULT], } /// Indicates when a slot must be processed next. #[derive(Debug)] pub(crate) struct Expiration { /// The level containing the slot. pub(crate) level: usize, /// The slot index. pub(crate) slot: usize, /// The instant at which the slot needs to be processed. pub(crate) deadline: u64, } /// Level multiplier. /// /// Being a power of 2 is very important. const LEVEL_MULT: usize = 64; impl Level { pub(crate) fn
(level: usize) -> Level { // A value has to be Copy in order to use syntax like: // let stack = Stack::default(); // ... // slots: [stack; 64], // // Alternatively, since Stack is Default one can // use syntax like: // let slots: [Stack; 64] = Default::default(); // // However, that is only supported for arrays of size // 32 or fewer. So in our case we have to explicitly // invoke the constructor for each array element. let ctor = EntryList::default; Level { level, occupied: 0, slot: [ ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ], } } /// Finds the slot that needs to be processed next and returns the slot and /// `Instant` at which this slot must be processed. pub(crate) fn next_expiration(&self, now: u64) -> Option<Expiration> { // Use the `occupied` bit field to get the index of the next slot that // needs to be processed. let slot = match self.next_occupied_slot(now) { Some(slot) => slot, None => return None, }; // From the slot index, calculate the `Instant` at which it needs to be // processed. This value *must* be in the future with respect to `now`. let level_range = level_range(self.level); let slot_range = slot_range(self.level); // Compute the start date of the current level by masking the low bits // of `now` (`level_range` is a power of 2). let level_start = now &!(level_range - 1); let mut deadline = level_start + slot as u64 * slot_range; if deadline <= now { // A timer is in a slot "prior" to the current time. This can occur // because we do not have an infinite hierarchy of timer levels, and // eventually a timer scheduled for a very distant time might end up // being placed in a slot that is beyond the end of all of the // arrays. // // To deal with this, we first limit timers to being scheduled no // more than MAX_DURATION ticks in the future; that is, they're at // most one rotation of the top level away. Then, we force timers // that logically would go into the top+1 level, to instead go into // the top level's slots. // // What this means is that the top level's slots act as a // pseudo-ring buffer, and we rotate around them indefinitely. If we // compute a deadline before now, and it's the top level, it // therefore means we're actually looking at a slot in the future. debug_assert_eq!(self.level, super::NUM_LEVELS - 1); deadline += level_range; } debug_assert!( deadline >= now, "deadline={:016X}; now={:016X}; level={}; lr={:016X}, sr={:016X}, slot={}; occupied={:b}", deadline, now, self.level, level_range, slot_range, slot, self.occupied ); Some(Expiration { level: self.level, slot, deadline, }) } fn next_occupied_slot(&self, now: u64) -> Option<usize> { if self.occupied == 0 { return None; } // Get the slot for now using Maths let now_slot = (now / slot_range(self.level)) as usize; let occupied = self.occupied.rotate_right(now_slot as u32); let zeros = occupied.trailing_zeros() as usize; let slot = (zeros + now_slot) % 64; Some(slot) } pub(crate) unsafe fn add_entry(&mut self, item: TimerHandle) { let slot = slot_for(item.cached_when(), self.level); self.slot[slot].push_front(item); self.occupied |= occupied_bit(slot); } pub(crate) unsafe fn remove_entry(&mut self, item: NonNull<TimerShared>) { let slot = slot_for(unsafe { item.as_ref().cached_when() }, self.level); unsafe { self.slot[slot].remove(item) }; if self.slot[slot].is_empty() { // The bit is currently set debug_assert!(self.occupied & occupied_bit(slot)!= 0); // Unset the bit self.occupied ^= occupied_bit(slot); } } pub(crate) fn take_slot(&mut self, slot: usize) -> EntryList { self.occupied &=!occupied_bit(slot); std::mem::take(&mut self.slot[slot]) } } impl fmt::Debug for Level { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Level") .field("occupied", &self.occupied) .finish() } } fn occupied_bit(slot: usize) -> u64 { 1 << slot } fn slot_range(level: usize) -> u64 { LEVEL_MULT.pow(level as u32) as u64 } fn level_range(level: usize) -> u64 { LEVEL_MULT as u64 * slot_range(level) } /// Converts a duration (milliseconds) and a level to a slot position. fn slot_for(duration: u64, level: usize) -> usize { ((duration >> (level * 6)) % LEVEL_MULT as u64) as usize } #[cfg(all(test, not(loom)))] mod test { use super::*; #[test] fn test_slot_for() { for pos in 0..64 { assert_eq!(pos as usize, slot_for(pos, 0)); } for level in 1..5 { for pos in level..64 { let a = pos * 64_usize.pow(level as u32); assert_eq!(pos as usize, slot_for(a as u64, level)); } } } }
new
identifier_name
level.rs
use crate::time::driver::TimerHandle; use crate::time::driver::{EntryList, TimerShared}; use std::{fmt, ptr::NonNull}; /// Wheel for a single level in the timer. This wheel contains 64 slots. pub(crate) struct Level { level: usize, /// Bit field tracking which slots currently contain entries. /// /// Using a bit field to track slots that contain entries allows avoiding a /// scan to find entries. This field is updated when entries are added or /// removed from a slot. /// /// The least-significant bit represents slot zero. occupied: u64, /// Slots. We access these via the EntryInner `current_list` as well, so this needs to be an UnsafeCell. slot: [EntryList; LEVEL_MULT], } /// Indicates when a slot must be processed next. #[derive(Debug)] pub(crate) struct Expiration { /// The level containing the slot. pub(crate) level: usize, /// The slot index. pub(crate) slot: usize, /// The instant at which the slot needs to be processed. pub(crate) deadline: u64, } /// Level multiplier. /// /// Being a power of 2 is very important. const LEVEL_MULT: usize = 64; impl Level { pub(crate) fn new(level: usize) -> Level { // A value has to be Copy in order to use syntax like: // let stack = Stack::default(); // ... // slots: [stack; 64], // // Alternatively, since Stack is Default one can // use syntax like: // let slots: [Stack; 64] = Default::default(); // // However, that is only supported for arrays of size // 32 or fewer. So in our case we have to explicitly // invoke the constructor for each array element. let ctor = EntryList::default; Level { level, occupied: 0, slot: [ ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ctor(), ], } } /// Finds the slot that needs to be processed next and returns the slot and /// `Instant` at which this slot must be processed. pub(crate) fn next_expiration(&self, now: u64) -> Option<Expiration> { // Use the `occupied` bit field to get the index of the next slot that // needs to be processed. let slot = match self.next_occupied_slot(now) { Some(slot) => slot, None => return None, }; // From the slot index, calculate the `Instant` at which it needs to be // processed. This value *must* be in the future with respect to `now`. let level_range = level_range(self.level); let slot_range = slot_range(self.level); // Compute the start date of the current level by masking the low bits // of `now` (`level_range` is a power of 2). let level_start = now &!(level_range - 1); let mut deadline = level_start + slot as u64 * slot_range; if deadline <= now { // A timer is in a slot "prior" to the current time. This can occur // because we do not have an infinite hierarchy of timer levels, and // eventually a timer scheduled for a very distant time might end up // being placed in a slot that is beyond the end of all of the // arrays. // // To deal with this, we first limit timers to being scheduled no // more than MAX_DURATION ticks in the future; that is, they're at // most one rotation of the top level away. Then, we force timers // that logically would go into the top+1 level, to instead go into // the top level's slots. // // What this means is that the top level's slots act as a // pseudo-ring buffer, and we rotate around them indefinitely. If we // compute a deadline before now, and it's the top level, it // therefore means we're actually looking at a slot in the future. debug_assert_eq!(self.level, super::NUM_LEVELS - 1); deadline += level_range; } debug_assert!( deadline >= now, "deadline={:016X}; now={:016X}; level={}; lr={:016X}, sr={:016X}, slot={}; occupied={:b}", deadline, now, self.level, level_range, slot_range, slot, self.occupied ); Some(Expiration { level: self.level, slot, deadline, }) } fn next_occupied_slot(&self, now: u64) -> Option<usize> { if self.occupied == 0 { return None; } // Get the slot for now using Maths let now_slot = (now / slot_range(self.level)) as usize; let occupied = self.occupied.rotate_right(now_slot as u32); let zeros = occupied.trailing_zeros() as usize; let slot = (zeros + now_slot) % 64; Some(slot) } pub(crate) unsafe fn add_entry(&mut self, item: TimerHandle) { let slot = slot_for(item.cached_when(), self.level); self.slot[slot].push_front(item); self.occupied |= occupied_bit(slot); } pub(crate) unsafe fn remove_entry(&mut self, item: NonNull<TimerShared>) { let slot = slot_for(unsafe { item.as_ref().cached_when() }, self.level); unsafe { self.slot[slot].remove(item) }; if self.slot[slot].is_empty() { // The bit is currently set debug_assert!(self.occupied & occupied_bit(slot)!= 0); // Unset the bit self.occupied ^= occupied_bit(slot); } } pub(crate) fn take_slot(&mut self, slot: usize) -> EntryList { self.occupied &=!occupied_bit(slot); std::mem::take(&mut self.slot[slot]) } } impl fmt::Debug for Level { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Level") .field("occupied", &self.occupied) .finish() } } fn occupied_bit(slot: usize) -> u64 { 1 << slot } fn slot_range(level: usize) -> u64 { LEVEL_MULT.pow(level as u32) as u64 } fn level_range(level: usize) -> u64 { LEVEL_MULT as u64 * slot_range(level) } /// Converts a duration (milliseconds) and a level to a slot position. fn slot_for(duration: u64, level: usize) -> usize { ((duration >> (level * 6)) % LEVEL_MULT as u64) as usize } #[cfg(all(test, not(loom)))] mod test { use super::*; #[test] fn test_slot_for() { for pos in 0..64 { assert_eq!(pos as usize, slot_for(pos, 0)); } for level in 1..5 { for pos in level..64 {
} } } }
let a = pos * 64_usize.pow(level as u32); assert_eq!(pos as usize, slot_for(a as u64, level));
random_line_split
fmt.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. //! Implementation of the `{:?}` format qualifier //! //! This module contains the `Poly` trait which is used to implement the `{:?}` //! format expression in formatting macros. This trait is defined for all types //! automatically, so it is likely not necessary to use this module manually use std::fmt; use repr; /// Format trait for the `?` character pub trait Poly { /// Formats the value using the given formatter. #[experimental] fn fmt(&self, &mut fmt::Formatter) -> fmt::Result; } #[doc(hidden)] pub fn secret_poly<T: Poly>(x: &T, fmt: &mut fmt::Formatter) -> fmt::Result
impl<T> Poly for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match (f.width, f.precision) { (None, None) => { match repr::write_repr(f, self) { Ok(()) => Ok(()), Err(..) => Err(fmt::WriteError), } } // If we have a specified width for formatting, then we have to make // this allocation of a new string _ => { let s = repr::repr_to_str(self); f.pad(s.as_slice()) } } } }
{ // FIXME #11938 - UFCS would make us able call the this method // directly Poly::fmt(x, fmt). x.fmt(fmt) }
identifier_body
fmt.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. //! Implementation of the `{:?}` format qualifier //! //! This module contains the `Poly` trait which is used to implement the `{:?}` //! format expression in formatting macros. This trait is defined for all types //! automatically, so it is likely not necessary to use this module manually use std::fmt; use repr; /// Format trait for the `?` character pub trait Poly { /// Formats the value using the given formatter. #[experimental] fn fmt(&self, &mut fmt::Formatter) -> fmt::Result; } #[doc(hidden)] pub fn
<T: Poly>(x: &T, fmt: &mut fmt::Formatter) -> fmt::Result { // FIXME #11938 - UFCS would make us able call the this method // directly Poly::fmt(x, fmt). x.fmt(fmt) } impl<T> Poly for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match (f.width, f.precision) { (None, None) => { match repr::write_repr(f, self) { Ok(()) => Ok(()), Err(..) => Err(fmt::WriteError), } } // If we have a specified width for formatting, then we have to make // this allocation of a new string _ => { let s = repr::repr_to_str(self); f.pad(s.as_slice()) } } } }
secret_poly
identifier_name
fmt.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. //! Implementation of the `{:?}` format qualifier
use std::fmt; use repr; /// Format trait for the `?` character pub trait Poly { /// Formats the value using the given formatter. #[experimental] fn fmt(&self, &mut fmt::Formatter) -> fmt::Result; } #[doc(hidden)] pub fn secret_poly<T: Poly>(x: &T, fmt: &mut fmt::Formatter) -> fmt::Result { // FIXME #11938 - UFCS would make us able call the this method // directly Poly::fmt(x, fmt). x.fmt(fmt) } impl<T> Poly for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match (f.width, f.precision) { (None, None) => { match repr::write_repr(f, self) { Ok(()) => Ok(()), Err(..) => Err(fmt::WriteError), } } // If we have a specified width for formatting, then we have to make // this allocation of a new string _ => { let s = repr::repr_to_str(self); f.pad(s.as_slice()) } } } }
//! //! This module contains the `Poly` trait which is used to implement the `{:?}` //! format expression in formatting macros. This trait is defined for all types //! automatically, so it is likely not necessary to use this module manually
random_line_split
inner_perfect_unshuffle.rs
use word::{Word, ReverseBitGroups, OuterPerfectUnshuffle}; /// Inner Perfect Unshuffle of `x`. /// /// See also: /// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm). /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// let n = 0b1011_1110_1001_0011_0111_1001_0100_1111u32; /// // AaBb CcDd EeFf GgHh IiJj KkLl MmNn OoPp /// let s = 0b0110_0101_1101_1011_1111_1001_0110_0011u32; /// // abcd efgh ijkl mnop ABCD EFGH IJKL MNOP, /// /// assert_eq!(n.inner_perfect_unshuffle(), s); /// assert_eq!(inner_perfect_unshuffle(n), s); /// ``` #[inline] pub fn inner_perfect_unshuffle<T: Word>(x: T) -> T { let hwb = T::bit_size().to_u8() / 2u8; x.outer_perfect_unshuffle().reverse_bit_groups(hwb, 1u8) } /// Method version of [`inner_perfect_unshuffle`](fn.inner_perfect_unshuffle.html). pub trait InnerPerfectUnshuffle { #[inline] fn inner_perfect_unshuffle(self) -> Self; } impl<T: Word> InnerPerfectUnshuffle for T { #[inline] fn inner_perfect_unshuffle(self) -> Self
}
{ inner_perfect_unshuffle(self) }
identifier_body
inner_perfect_unshuffle.rs
use word::{Word, ReverseBitGroups, OuterPerfectUnshuffle}; /// Inner Perfect Unshuffle of `x`. /// /// See also: /// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm). /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// let n = 0b1011_1110_1001_0011_0111_1001_0100_1111u32; /// // AaBb CcDd EeFf GgHh IiJj KkLl MmNn OoPp /// let s = 0b0110_0101_1101_1011_1111_1001_0110_0011u32; /// // abcd efgh ijkl mnop ABCD EFGH IJKL MNOP, /// /// assert_eq!(n.inner_perfect_unshuffle(), s); /// assert_eq!(inner_perfect_unshuffle(n), s); /// ```
let hwb = T::bit_size().to_u8() / 2u8; x.outer_perfect_unshuffle().reverse_bit_groups(hwb, 1u8) } /// Method version of [`inner_perfect_unshuffle`](fn.inner_perfect_unshuffle.html). pub trait InnerPerfectUnshuffle { #[inline] fn inner_perfect_unshuffle(self) -> Self; } impl<T: Word> InnerPerfectUnshuffle for T { #[inline] fn inner_perfect_unshuffle(self) -> Self { inner_perfect_unshuffle(self) } }
#[inline] pub fn inner_perfect_unshuffle<T: Word>(x: T) -> T {
random_line_split
inner_perfect_unshuffle.rs
use word::{Word, ReverseBitGroups, OuterPerfectUnshuffle}; /// Inner Perfect Unshuffle of `x`. /// /// See also: /// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm). /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// let n = 0b1011_1110_1001_0011_0111_1001_0100_1111u32; /// // AaBb CcDd EeFf GgHh IiJj KkLl MmNn OoPp /// let s = 0b0110_0101_1101_1011_1111_1001_0110_0011u32; /// // abcd efgh ijkl mnop ABCD EFGH IJKL MNOP, /// /// assert_eq!(n.inner_perfect_unshuffle(), s); /// assert_eq!(inner_perfect_unshuffle(n), s); /// ``` #[inline] pub fn inner_perfect_unshuffle<T: Word>(x: T) -> T { let hwb = T::bit_size().to_u8() / 2u8; x.outer_perfect_unshuffle().reverse_bit_groups(hwb, 1u8) } /// Method version of [`inner_perfect_unshuffle`](fn.inner_perfect_unshuffle.html). pub trait InnerPerfectUnshuffle { #[inline] fn inner_perfect_unshuffle(self) -> Self; } impl<T: Word> InnerPerfectUnshuffle for T { #[inline] fn
(self) -> Self { inner_perfect_unshuffle(self) } }
inner_perfect_unshuffle
identifier_name
lib.rs
//! Double is a fully-featured mocking library for mocking `trait` //! implementations. //! //! The `Mock` struct tracks function call arguments and specifies return //! values or function overrides. //! //! # Examples //! //! ``` //! #[macro_use] //! extern crate double; //! //! // Code under test //! trait BalanceSheet {
//! balance_sheet.profit(revenue, costs) * 2 //! } //! //! // Test which uses a mock BalanceSheet //! mock_trait!( //! MockBalanceSheet, //! profit(u32, u32) -> i32); //! impl BalanceSheet for MockBalanceSheet { //! mock_method!(profit(&self, revenue: u32, costs: u32) -> i32); //! } //! //! fn test_doubling_a_sheets_profit() { //! // GIVEN: //! let sheet = MockBalanceSheet::default(); //! sheet.profit.return_value(250); //! // WHEN: //! let profit = double_profit(500, 250, &sheet); //! // THEN: //! // mock return 250, which was double //! assert_eq!(500, profit); //! // assert that the revenue and costs were correctly passed to the mock //! sheet.profit.has_calls_exactly_in_order(vec!((500, 250))); //! } //! //! // Executing test //! fn main() { //! test_doubling_a_sheets_profit(); //! } //! ``` pub use crate::mock::Mock; pub mod macros; pub mod matcher; pub mod mock;
//! fn profit(&self, revenue: u32, costs: u32) -> i32; //! } //! //! fn double_profit(revenue: u32, costs: u32, balance_sheet: &BalanceSheet) -> i32 {
random_line_split
issue-24086.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(dead_code)] #![allow(unused_mut)] #![allow(unused_variables)] pub struct Registry<'a> { listener: &'a mut (), } pub struct Listener<'a> { pub announce: Option<Box<FnMut(&mut Registry) + 'a>>, pub remove: Option<Box<FnMut(&mut Registry) + 'a>>, } impl<'a> Drop for Registry<'a> { fn drop(&mut self) {} } fn
() { let mut registry_listener = Listener { announce: None, remove: None, }; }
main
identifier_name
issue-24086.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(dead_code)] #![allow(unused_mut)] #![allow(unused_variables)] pub struct Registry<'a> { listener: &'a mut (), } pub struct Listener<'a> { pub announce: Option<Box<FnMut(&mut Registry) + 'a>>, pub remove: Option<Box<FnMut(&mut Registry) + 'a>>, } impl<'a> Drop for Registry<'a> { fn drop(&mut self) {} } fn main() {
remove: None, }; }
let mut registry_listener = Listener { announce: None,
random_line_split
tutorial4.rs
use std::process::exit; use std::sync::mpsc; use std::thread::sleep; use std::time::Duration; extern crate unbound; mod util; fn
() { let ctx = unbound::Context::new().unwrap(); let mut i = 0; let (tx, rx) = mpsc::channel(); let mycallback = move |_: unbound::AsyncID, result: unbound::Result<unbound::Answer>| match result { Err(err) => println!("resolve error: {}", err), Ok(ans) => { for ip in ans.data().map(util::data_to_ipv4) { println!("The address of {} is {}", ans.qname(), ip); } tx.send(true).unwrap(); } }; match ctx.resolve_async("www.nlnetlabs.nl", 1, 1, mycallback) { Err(err) => { println!("resolve error: {}", err); exit(1) } Ok(_id) => (), } while rx.try_recv() == Err(mpsc::TryRecvError::Empty) { sleep(Duration::new(1, 0) / 10); i += 1; println!("time passed ({})..", i); if let Err(err) = ctx.process() { println!("resolve error: {}", err); exit(1) } } println!("done") }
main
identifier_name
tutorial4.rs
use std::process::exit; use std::sync::mpsc; use std::thread::sleep; use std::time::Duration; extern crate unbound; mod util; fn main()
} Ok(_id) => (), } while rx.try_recv() == Err(mpsc::TryRecvError::Empty) { sleep(Duration::new(1, 0) / 10); i += 1; println!("time passed ({})..", i); if let Err(err) = ctx.process() { println!("resolve error: {}", err); exit(1) } } println!("done") }
{ let ctx = unbound::Context::new().unwrap(); let mut i = 0; let (tx, rx) = mpsc::channel(); let mycallback = move |_: unbound::AsyncID, result: unbound::Result<unbound::Answer>| match result { Err(err) => println!("resolve error: {}", err), Ok(ans) => { for ip in ans.data().map(util::data_to_ipv4) { println!("The address of {} is {}", ans.qname(), ip); } tx.send(true).unwrap(); } }; match ctx.resolve_async("www.nlnetlabs.nl", 1, 1, mycallback) { Err(err) => { println!("resolve error: {}", err); exit(1)
identifier_body
tutorial4.rs
use std::process::exit; use std::sync::mpsc; use std::thread::sleep; use std::time::Duration; extern crate unbound; mod util; fn main() { let ctx = unbound::Context::new().unwrap(); let mut i = 0; let (tx, rx) = mpsc::channel(); let mycallback = move |_: unbound::AsyncID, result: unbound::Result<unbound::Answer>| match result { Err(err) => println!("resolve error: {}", err), Ok(ans) => { for ip in ans.data().map(util::data_to_ipv4) { println!("The address of {} is {}", ans.qname(), ip); }
tx.send(true).unwrap(); } }; match ctx.resolve_async("www.nlnetlabs.nl", 1, 1, mycallback) { Err(err) => { println!("resolve error: {}", err); exit(1) } Ok(_id) => (), } while rx.try_recv() == Err(mpsc::TryRecvError::Empty) { sleep(Duration::new(1, 0) / 10); i += 1; println!("time passed ({})..", i); if let Err(err) = ctx.process() { println!("resolve error: {}", err); exit(1) } } println!("done") }
random_line_split
tutorial4.rs
use std::process::exit; use std::sync::mpsc; use std::thread::sleep; use std::time::Duration; extern crate unbound; mod util; fn main() { let ctx = unbound::Context::new().unwrap(); let mut i = 0; let (tx, rx) = mpsc::channel(); let mycallback = move |_: unbound::AsyncID, result: unbound::Result<unbound::Answer>| match result { Err(err) => println!("resolve error: {}", err), Ok(ans) =>
}; match ctx.resolve_async("www.nlnetlabs.nl", 1, 1, mycallback) { Err(err) => { println!("resolve error: {}", err); exit(1) } Ok(_id) => (), } while rx.try_recv() == Err(mpsc::TryRecvError::Empty) { sleep(Duration::new(1, 0) / 10); i += 1; println!("time passed ({})..", i); if let Err(err) = ctx.process() { println!("resolve error: {}", err); exit(1) } } println!("done") }
{ for ip in ans.data().map(util::data_to_ipv4) { println!("The address of {} is {}", ans.qname(), ip); } tx.send(true).unwrap(); }
conditional_block
mod.rs
//! Provides common neural network layers. //! //! For now the layers in common should be discribed as layers that are typical //! layers for building neural networks but are not activation or loss layers. #[macro_export] macro_rules! impl_ilayer_common { () => ( fn exact_num_output_blobs(&self) -> Option<usize> { Some(1) } fn exact_num_input_blobs(&self) -> Option<usize> { Some(1) } ) } pub use self::convolution::{Convolution, ConvolutionConfig}; pub use self::linear::{Linear, LinearConfig}; pub use self::log_softmax::LogSoftmax; pub use self::pooling::{Pooling, PoolingConfig, PoolingMode}; pub use self::softmax::Softmax; pub use self::dropout::{Dropout,DropoutConfig}; pub mod convolution; pub mod linear; pub mod log_softmax; pub mod pooling; pub mod softmax; pub mod dropout; /// Provides common utilities for Layers that utilize a filter with stride and padding. /// /// This is used by the Convolution and Pooling layers. pub trait FilterLayer { /// Computes the shape of the spatial dimensions. fn calculate_spatial_output_dims(input_dims: &[usize], filter_dims: &[usize], padding: &[usize], stride: &[usize]) -> Vec<usize> { let mut output_dims = Vec::with_capacity(input_dims.len()); for (i, _) in input_dims.iter().enumerate() { output_dims.push(((input_dims[i] + (2 * padding[i]) - filter_dims[i]) / stride[i]) + 1); } output_dims } /// Calculate output shape based on the shape of filter, padding, stride and input. fn calculate_output_shape(&self, input_shape: &[usize]) -> Vec<usize>; /// Calculates the number of spatial dimensions for the pooling operation.
/// and the number of spatial dimensions. /// /// The spatial dimensions only make up part of the whole filter shape. The other parts are the /// number of input and output feature maps. fn spatial_filter_dims(&self, num_spatial_dims: usize) -> Vec<usize> { let mut spatial_dims = Vec::with_capacity(num_spatial_dims); let filter_shape = self.filter_shape(); if filter_shape.len() == 1 { for i in 0..num_spatial_dims { spatial_dims.push(filter_shape[0]); } } else if filter_shape.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one filter dimension per spatial dimension"); } else { panic!("Must either specify one filter_shape or one filter_shape per spatial dimension. Supplied {:?}", filter_shape.len()); } spatial_dims } /// Retrievs the stride for the convolution based on `self.stride` /// and the number of spatial dimensions. fn stride_dims(&self, num_spatial_dims: usize) -> Vec<usize> { let mut stride_dims = Vec::with_capacity(num_spatial_dims); let stride = self.stride(); if stride.len() == 1 { for i in 0..num_spatial_dims { stride_dims.push(stride[0]); } } else if stride.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one stride per spatial dimension"); } else { panic!("Must either specify one stride or one stride per spatial dimension. Supplied {:?}", stride.len()); } stride_dims } /// Retrievs the padding for the convolution based on `self.padding` /// and the number of spatial dimensions. fn padding_dims(&self, num_spatial_dims: usize) -> Vec<usize> { let mut padding_dims = Vec::with_capacity(num_spatial_dims); let padding = self.padding(); if padding.len() == 1 { for i in 0..num_spatial_dims { padding_dims.push(padding[0]); } } else if padding.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one padding per spatial dimension"); } else { panic!("Must either specify one padding or one padding per spatial dimension. Supplied {:?}", padding.len()); } padding_dims } /// The filter_shape that will be used by `spatial_filter_dims`. fn filter_shape(&self) -> &[usize]; /// The stride that will be used by `stride_dims`. fn stride(&self) -> &[usize]; /// The padding that will be used by `padding_dims`. fn padding(&self) -> &[usize]; }
fn num_spatial_dims(&self, input_shape: &[usize]) -> usize; /// Retrievs the spatial dimensions for the filter based on `self.filter_shape()`
random_line_split
mod.rs
//! Provides common neural network layers. //! //! For now the layers in common should be discribed as layers that are typical //! layers for building neural networks but are not activation or loss layers. #[macro_export] macro_rules! impl_ilayer_common { () => ( fn exact_num_output_blobs(&self) -> Option<usize> { Some(1) } fn exact_num_input_blobs(&self) -> Option<usize> { Some(1) } ) } pub use self::convolution::{Convolution, ConvolutionConfig}; pub use self::linear::{Linear, LinearConfig}; pub use self::log_softmax::LogSoftmax; pub use self::pooling::{Pooling, PoolingConfig, PoolingMode}; pub use self::softmax::Softmax; pub use self::dropout::{Dropout,DropoutConfig}; pub mod convolution; pub mod linear; pub mod log_softmax; pub mod pooling; pub mod softmax; pub mod dropout; /// Provides common utilities for Layers that utilize a filter with stride and padding. /// /// This is used by the Convolution and Pooling layers. pub trait FilterLayer { /// Computes the shape of the spatial dimensions. fn calculate_spatial_output_dims(input_dims: &[usize], filter_dims: &[usize], padding: &[usize], stride: &[usize]) -> Vec<usize> { let mut output_dims = Vec::with_capacity(input_dims.len()); for (i, _) in input_dims.iter().enumerate() { output_dims.push(((input_dims[i] + (2 * padding[i]) - filter_dims[i]) / stride[i]) + 1); } output_dims } /// Calculate output shape based on the shape of filter, padding, stride and input. fn calculate_output_shape(&self, input_shape: &[usize]) -> Vec<usize>; /// Calculates the number of spatial dimensions for the pooling operation. fn num_spatial_dims(&self, input_shape: &[usize]) -> usize; /// Retrievs the spatial dimensions for the filter based on `self.filter_shape()` /// and the number of spatial dimensions. /// /// The spatial dimensions only make up part of the whole filter shape. The other parts are the /// number of input and output feature maps. fn spatial_filter_dims(&self, num_spatial_dims: usize) -> Vec<usize> { let mut spatial_dims = Vec::with_capacity(num_spatial_dims); let filter_shape = self.filter_shape(); if filter_shape.len() == 1 { for i in 0..num_spatial_dims { spatial_dims.push(filter_shape[0]); } } else if filter_shape.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one filter dimension per spatial dimension"); } else { panic!("Must either specify one filter_shape or one filter_shape per spatial dimension. Supplied {:?}", filter_shape.len()); } spatial_dims } /// Retrievs the stride for the convolution based on `self.stride` /// and the number of spatial dimensions. fn stride_dims(&self, num_spatial_dims: usize) -> Vec<usize>
/// Retrievs the padding for the convolution based on `self.padding` /// and the number of spatial dimensions. fn padding_dims(&self, num_spatial_dims: usize) -> Vec<usize> { let mut padding_dims = Vec::with_capacity(num_spatial_dims); let padding = self.padding(); if padding.len() == 1 { for i in 0..num_spatial_dims { padding_dims.push(padding[0]); } } else if padding.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one padding per spatial dimension"); } else { panic!("Must either specify one padding or one padding per spatial dimension. Supplied {:?}", padding.len()); } padding_dims } /// The filter_shape that will be used by `spatial_filter_dims`. fn filter_shape(&self) -> &[usize]; /// The stride that will be used by `stride_dims`. fn stride(&self) -> &[usize]; /// The padding that will be used by `padding_dims`. fn padding(&self) -> &[usize]; }
{ let mut stride_dims = Vec::with_capacity(num_spatial_dims); let stride = self.stride(); if stride.len() == 1 { for i in 0..num_spatial_dims { stride_dims.push(stride[0]); } } else if stride.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one stride per spatial dimension"); } else { panic!("Must either specify one stride or one stride per spatial dimension. Supplied {:?}", stride.len()); } stride_dims }
identifier_body
mod.rs
//! Provides common neural network layers. //! //! For now the layers in common should be discribed as layers that are typical //! layers for building neural networks but are not activation or loss layers. #[macro_export] macro_rules! impl_ilayer_common { () => ( fn exact_num_output_blobs(&self) -> Option<usize> { Some(1) } fn exact_num_input_blobs(&self) -> Option<usize> { Some(1) } ) } pub use self::convolution::{Convolution, ConvolutionConfig}; pub use self::linear::{Linear, LinearConfig}; pub use self::log_softmax::LogSoftmax; pub use self::pooling::{Pooling, PoolingConfig, PoolingMode}; pub use self::softmax::Softmax; pub use self::dropout::{Dropout,DropoutConfig}; pub mod convolution; pub mod linear; pub mod log_softmax; pub mod pooling; pub mod softmax; pub mod dropout; /// Provides common utilities for Layers that utilize a filter with stride and padding. /// /// This is used by the Convolution and Pooling layers. pub trait FilterLayer { /// Computes the shape of the spatial dimensions. fn calculate_spatial_output_dims(input_dims: &[usize], filter_dims: &[usize], padding: &[usize], stride: &[usize]) -> Vec<usize> { let mut output_dims = Vec::with_capacity(input_dims.len()); for (i, _) in input_dims.iter().enumerate() { output_dims.push(((input_dims[i] + (2 * padding[i]) - filter_dims[i]) / stride[i]) + 1); } output_dims } /// Calculate output shape based on the shape of filter, padding, stride and input. fn calculate_output_shape(&self, input_shape: &[usize]) -> Vec<usize>; /// Calculates the number of spatial dimensions for the pooling operation. fn num_spatial_dims(&self, input_shape: &[usize]) -> usize; /// Retrievs the spatial dimensions for the filter based on `self.filter_shape()` /// and the number of spatial dimensions. /// /// The spatial dimensions only make up part of the whole filter shape. The other parts are the /// number of input and output feature maps. fn spatial_filter_dims(&self, num_spatial_dims: usize) -> Vec<usize> { let mut spatial_dims = Vec::with_capacity(num_spatial_dims); let filter_shape = self.filter_shape(); if filter_shape.len() == 1 { for i in 0..num_spatial_dims { spatial_dims.push(filter_shape[0]); } } else if filter_shape.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one filter dimension per spatial dimension"); } else { panic!("Must either specify one filter_shape or one filter_shape per spatial dimension. Supplied {:?}", filter_shape.len()); } spatial_dims } /// Retrievs the stride for the convolution based on `self.stride` /// and the number of spatial dimensions. fn stride_dims(&self, num_spatial_dims: usize) -> Vec<usize> { let mut stride_dims = Vec::with_capacity(num_spatial_dims); let stride = self.stride(); if stride.len() == 1 { for i in 0..num_spatial_dims { stride_dims.push(stride[0]); } } else if stride.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one stride per spatial dimension"); } else { panic!("Must either specify one stride or one stride per spatial dimension. Supplied {:?}", stride.len()); } stride_dims } /// Retrievs the padding for the convolution based on `self.padding` /// and the number of spatial dimensions. fn
(&self, num_spatial_dims: usize) -> Vec<usize> { let mut padding_dims = Vec::with_capacity(num_spatial_dims); let padding = self.padding(); if padding.len() == 1 { for i in 0..num_spatial_dims { padding_dims.push(padding[0]); } } else if padding.len() == num_spatial_dims { panic!("unimplemented: You can not yet specify one padding per spatial dimension"); } else { panic!("Must either specify one padding or one padding per spatial dimension. Supplied {:?}", padding.len()); } padding_dims } /// The filter_shape that will be used by `spatial_filter_dims`. fn filter_shape(&self) -> &[usize]; /// The stride that will be used by `stride_dims`. fn stride(&self) -> &[usize]; /// The padding that will be used by `padding_dims`. fn padding(&self) -> &[usize]; }
padding_dims
identifier_name
plugin.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::PluginBinding::PluginMethods; use dom::bindings::js::Root; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; use dom::mimetype::MimeType; #[dom_struct] pub struct Plugin { reflector_: Reflector, } impl PluginMethods for Plugin { // https://html.spec.whatwg.org/multipage/#dom-plugin-name fn Name(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-description fn Description(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-filename fn Filename(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-length fn Length(&self) -> u32 { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-item fn Item(&self, _index: u32) -> Option<Root<MimeType>> { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-nameditem fn NamedItem(&self, _name: DOMString) -> Option<Root<MimeType>> { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-item fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> Option<Root<MimeType>> { unreachable!() }
fn NamedGetter(&self, _name: DOMString, _found: &mut bool) -> Option<Root<MimeType>> { unreachable!() } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { unreachable!() } }
// check-tidy: no specs after this line
random_line_split
plugin.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::PluginBinding::PluginMethods; use dom::bindings::js::Root; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; use dom::mimetype::MimeType; #[dom_struct] pub struct Plugin { reflector_: Reflector, } impl PluginMethods for Plugin { // https://html.spec.whatwg.org/multipage/#dom-plugin-name fn Name(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-description fn Description(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-filename fn Filename(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-length fn Length(&self) -> u32
// https://html.spec.whatwg.org/multipage/#dom-plugin-item fn Item(&self, _index: u32) -> Option<Root<MimeType>> { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-nameditem fn NamedItem(&self, _name: DOMString) -> Option<Root<MimeType>> { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-item fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> Option<Root<MimeType>> { unreachable!() } // check-tidy: no specs after this line fn NamedGetter(&self, _name: DOMString, _found: &mut bool) -> Option<Root<MimeType>> { unreachable!() } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { unreachable!() } }
{ unreachable!() }
identifier_body
plugin.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::PluginBinding::PluginMethods; use dom::bindings::js::Root; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; use dom::mimetype::MimeType; #[dom_struct] pub struct Plugin { reflector_: Reflector, } impl PluginMethods for Plugin { // https://html.spec.whatwg.org/multipage/#dom-plugin-name fn Name(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-description fn Description(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-filename fn Filename(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-length fn Length(&self) -> u32 { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-item fn Item(&self, _index: u32) -> Option<Root<MimeType>> { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-nameditem fn NamedItem(&self, _name: DOMString) -> Option<Root<MimeType>> { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-plugin-item fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> Option<Root<MimeType>> { unreachable!() } // check-tidy: no specs after this line fn
(&self, _name: DOMString, _found: &mut bool) -> Option<Root<MimeType>> { unreachable!() } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { unreachable!() } }
NamedGetter
identifier_name
list-tables.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_dynamodb::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; use tokio_stream::StreamExt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // List your tables. // snippet-start:[dynamodb.rust.list-tables] async fn list_tables(client: &Client) -> Result<(), Error> { let paginator = client.list_tables().into_paginator().items().send(); let table_names = paginator.collect::<Result<Vec<_>, _>>().await?; println!("Tables:"); for name in &table_names { println!(" {}", name); } println!("Found {} tables", table_names.len()); Ok(()) } // snippet-end:[dynamodb.rust.list-tables] /// Lists your DynamoDB tables. /// # Arguments
/// * `[-r REGION]` - The region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { region, verbose } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose { println!("DynamoDB client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); list_tables(&client).await }
///
random_line_split
list-tables.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_dynamodb::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; use tokio_stream::StreamExt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // List your tables. // snippet-start:[dynamodb.rust.list-tables] async fn list_tables(client: &Client) -> Result<(), Error> { let paginator = client.list_tables().into_paginator().items().send(); let table_names = paginator.collect::<Result<Vec<_>, _>>().await?; println!("Tables:"); for name in &table_names { println!(" {}", name); } println!("Found {} tables", table_names.len()); Ok(()) } // snippet-end:[dynamodb.rust.list-tables] /// Lists your DynamoDB tables. /// # Arguments /// /// * `[-r REGION]` - The region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn
() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { region, verbose } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose { println!("DynamoDB client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); list_tables(&client).await }
main
identifier_name
list-tables.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_dynamodb::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; use tokio_stream::StreamExt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // List your tables. // snippet-start:[dynamodb.rust.list-tables] async fn list_tables(client: &Client) -> Result<(), Error> { let paginator = client.list_tables().into_paginator().items().send(); let table_names = paginator.collect::<Result<Vec<_>, _>>().await?; println!("Tables:"); for name in &table_names { println!(" {}", name); } println!("Found {} tables", table_names.len()); Ok(()) } // snippet-end:[dynamodb.rust.list-tables] /// Lists your DynamoDB tables. /// # Arguments /// /// * `[-r REGION]` - The region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { region, verbose } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose
let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); list_tables(&client).await }
{ println!("DynamoDB client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!(); }
conditional_block
which.rs
use getopts::{getopts,optflag}; use std; use std::path::Path; use common; pub fn main(args: &[~str]) { let opts = ~[ optflag("a", "", "List all instances of executables found (instead of just the first one of each)."), optflag("s", "", "No output."), ]; let usage = "which [-as] program..."; let matches = match getopts(args.tail(), opts) { Err(f) => { common::err_write_line(f.to_err_msg()); common::print_usage(usage, opts); std::os::set_exit_status(1); return; } Ok(m) => { m } }; let silent = matches.opt_present("s"); let showall = matches.opt_present("a"); let pathenv = match std::os::getenv("PATH") { Some(s) => s, None => { std::os::set_exit_status(1); return; } }; let paths: ~[Path] = pathenv.split(':').map(|x| { Path::new(x) }).collect(); let mut stdout = std::io::stdout(); match matches.free.as_slice() { [] => { common::print_usage(usage, opts); std::os::set_exit_status(1); return; } [..cmds] => { for cmd in cmds.iter() { let mut found = false; for path in paths.iter() { let mut p = path.clone(); p.push(cmd.as_slice()); if check_path(&p) { found = true; if!silent { let _ = stdout.write(p.as_vec()); //TODO should handle return value? let _ = stdout.write_char('\n'); //TODO should handle return value? } if!showall { break; } } } if!found { std::os::set_exit_status(1); } } } } } fn check_path(p: &Path) -> bool { if! p.exists() { return false; } match p.stat() { Ok(filestat) =>
_ => {} } return false; }
{ if filestat.kind == std::io::TypeFile && filestat.perm & 0111 != 0 { return true; } }
conditional_block
which.rs
use getopts::{getopts,optflag}; use std; use std::path::Path; use common; pub fn main(args: &[~str]) { let opts = ~[ optflag("a", "", "List all instances of executables found (instead of just the first one of each)."), optflag("s", "", "No output."), ]; let usage = "which [-as] program..."; let matches = match getopts(args.tail(), opts) { Err(f) => { common::err_write_line(f.to_err_msg()); common::print_usage(usage, opts); std::os::set_exit_status(1); return; } Ok(m) => { m } }; let silent = matches.opt_present("s"); let showall = matches.opt_present("a"); let pathenv = match std::os::getenv("PATH") { Some(s) => s, None => { std::os::set_exit_status(1); return; } }; let paths: ~[Path] = pathenv.split(':').map(|x| { Path::new(x) }).collect(); let mut stdout = std::io::stdout(); match matches.free.as_slice() { [] => { common::print_usage(usage, opts); std::os::set_exit_status(1); return; } [..cmds] => { for cmd in cmds.iter() { let mut found = false; for path in paths.iter() { let mut p = path.clone(); p.push(cmd.as_slice()); if check_path(&p) { found = true; if!silent { let _ = stdout.write(p.as_vec()); //TODO should handle return value? let _ = stdout.write_char('\n'); //TODO should handle return value? } if!showall { break; } } } if!found { std::os::set_exit_status(1); } } } } } fn
(p: &Path) -> bool { if! p.exists() { return false; } match p.stat() { Ok(filestat) => { if filestat.kind == std::io::TypeFile && filestat.perm & 0111!= 0 { return true; } } _ => {} } return false; }
check_path
identifier_name
which.rs
use getopts::{getopts,optflag}; use std; use std::path::Path; use common; pub fn main(args: &[~str])
Some(s) => s, None => { std::os::set_exit_status(1); return; } }; let paths: ~[Path] = pathenv.split(':').map(|x| { Path::new(x) }).collect(); let mut stdout = std::io::stdout(); match matches.free.as_slice() { [] => { common::print_usage(usage, opts); std::os::set_exit_status(1); return; } [..cmds] => { for cmd in cmds.iter() { let mut found = false; for path in paths.iter() { let mut p = path.clone(); p.push(cmd.as_slice()); if check_path(&p) { found = true; if!silent { let _ = stdout.write(p.as_vec()); //TODO should handle return value? let _ = stdout.write_char('\n'); //TODO should handle return value? } if!showall { break; } } } if!found { std::os::set_exit_status(1); } } } } } fn check_path(p: &Path) -> bool { if! p.exists() { return false; } match p.stat() { Ok(filestat) => { if filestat.kind == std::io::TypeFile && filestat.perm & 0111!= 0 { return true; } } _ => {} } return false; }
{ let opts = ~[ optflag("a", "", "List all instances of executables found (instead of just the first one of each)."), optflag("s", "", "No output."), ]; let usage = "which [-as] program ..."; let matches = match getopts(args.tail(), opts) { Err(f) => { common::err_write_line(f.to_err_msg()); common::print_usage(usage, opts); std::os::set_exit_status(1); return; } Ok(m) => { m } }; let silent = matches.opt_present("s"); let showall = matches.opt_present("a"); let pathenv = match std::os::getenv("PATH") {
identifier_body
which.rs
use getopts::{getopts,optflag}; use std; use std::path::Path; use common; pub fn main(args: &[~str]) { let opts = ~[ optflag("a", "", "List all instances of executables found (instead of just the first one of each)."), optflag("s", "", "No output."), ]; let usage = "which [-as] program..."; let matches = match getopts(args.tail(), opts) { Err(f) => { common::err_write_line(f.to_err_msg()); common::print_usage(usage, opts); std::os::set_exit_status(1); return; } Ok(m) => { m } }; let silent = matches.opt_present("s"); let showall = matches.opt_present("a"); let pathenv = match std::os::getenv("PATH") { Some(s) => s, None => { std::os::set_exit_status(1); return; } };
[] => { common::print_usage(usage, opts); std::os::set_exit_status(1); return; } [..cmds] => { for cmd in cmds.iter() { let mut found = false; for path in paths.iter() { let mut p = path.clone(); p.push(cmd.as_slice()); if check_path(&p) { found = true; if!silent { let _ = stdout.write(p.as_vec()); //TODO should handle return value? let _ = stdout.write_char('\n'); //TODO should handle return value? } if!showall { break; } } } if!found { std::os::set_exit_status(1); } } } } } fn check_path(p: &Path) -> bool { if! p.exists() { return false; } match p.stat() { Ok(filestat) => { if filestat.kind == std::io::TypeFile && filestat.perm & 0111!= 0 { return true; } } _ => {} } return false; }
let paths: ~[Path] = pathenv.split(':').map(|x| { Path::new(x) }).collect(); let mut stdout = std::io::stdout(); match matches.free.as_slice() {
random_line_split
qmlengine.rs
use qvariant::*; use types::*; use qurl::*; extern "C" { fn dos_qguiapplication_create(); fn dos_qguiapplication_exec(); fn dos_qguiapplication_quit(); fn dos_qguiapplication_delete(); fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine; fn dos_qqmlapplicationengine_load(vptr: DosQmlApplicationEngine, filename: DosCStr); fn dos_qqmlapplicationengine_load_url(vptr: DosQmlApplicationEngine, url: DosQUrl); fn dos_qqmlapplicationengine_load_data(vptr: DosQmlApplicationEngine, data: DosCStr); fn dos_qqmlapplicationengine_add_import_path(vptr: DosQmlApplicationEngine, path: DosCStr); fn dos_qqmlapplicationengine_context(vptr: DosQmlApplicationEngine) -> DosQQmlContext; fn dos_qqmlapplicationengine_delete(vptr: DosQmlApplicationEngine); fn dos_qqmlcontext_setcontextproperty(vptr: DosQQmlContext, name: DosCStr, value: DosQVariant); } /// Provides an entry point for building QML applications from Rust pub struct QmlEngine { ptr: DosQmlApplicationEngine, stored: Vec<QVariant>, } impl QmlEngine { /// Creates a QML context of a non-headless application pub fn
() -> Self { unsafe { dos_qguiapplication_create(); QmlEngine { ptr: dos_qqmlapplicationengine_create(), stored: Vec::new(), } } } /// Loads a file as a qml file pub fn load_file(&mut self, path: &str) { let path_raw = ::std::env::current_dir().unwrap().join(path); let path = if cfg!(windows) { format!("file:///{}", path_raw.display()) } else { format!("file://{}", path_raw.display()) }; unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(&path)) } } /// Loads qml from a specified url (`file://`, `qrc://`, `http://`) pub fn load_url(&mut self, uri: &str) { unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(uri)) } } /// Adds a path to the QML import path /// On an "import ModuleName" call QML will additionally search this path for the matching module. pub fn add_import_path(&mut self, path: &str) { unsafe { dos_qqmlapplicationengine_add_import_path(self.ptr, stoptr(path)) } } /// Loads a string as a qml file pub fn load_data(&mut self, data: &str) { unsafe { dos_qqmlapplicationengine_load_data(self.ptr, stoptr(data)) } } /// Launches the application pub fn exec(&mut self) { unsafe { dos_qguiapplication_exec(); } } /// Closes the application pub fn quit(&mut self) { unsafe { dos_qguiapplication_quit(); } } /// Sets a property for this QML context /// /// This variant stores qvariant, so it is removed, only when this QmlEngine is removed. pub fn set_and_store_property<T: Into<QVariant>>(&mut self, name: &str, value: T) { let val = value.into(); unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(&val)); } self.stored.push(val); } /// Sets a property for this QML context pub fn set_property(&mut self, name: &str, value: &QVariant) { unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(value)); } } } use utils::*; impl Default for QmlEngine { fn default() -> Self { Self::new() } } impl Drop for QmlEngine { fn drop(&mut self) { unsafe { dos_qguiapplication_quit(); dos_qqmlapplicationengine_delete(self.ptr); dos_qguiapplication_delete(); } } }
new
identifier_name
qmlengine.rs
use qvariant::*; use types::*; use qurl::*; extern "C" { fn dos_qguiapplication_create(); fn dos_qguiapplication_exec(); fn dos_qguiapplication_quit(); fn dos_qguiapplication_delete(); fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine; fn dos_qqmlapplicationengine_load(vptr: DosQmlApplicationEngine, filename: DosCStr); fn dos_qqmlapplicationengine_load_url(vptr: DosQmlApplicationEngine, url: DosQUrl); fn dos_qqmlapplicationengine_load_data(vptr: DosQmlApplicationEngine, data: DosCStr); fn dos_qqmlapplicationengine_add_import_path(vptr: DosQmlApplicationEngine, path: DosCStr); fn dos_qqmlapplicationengine_context(vptr: DosQmlApplicationEngine) -> DosQQmlContext; fn dos_qqmlapplicationengine_delete(vptr: DosQmlApplicationEngine); fn dos_qqmlcontext_setcontextproperty(vptr: DosQQmlContext, name: DosCStr,
/// Provides an entry point for building QML applications from Rust pub struct QmlEngine { ptr: DosQmlApplicationEngine, stored: Vec<QVariant>, } impl QmlEngine { /// Creates a QML context of a non-headless application pub fn new() -> Self { unsafe { dos_qguiapplication_create(); QmlEngine { ptr: dos_qqmlapplicationengine_create(), stored: Vec::new(), } } } /// Loads a file as a qml file pub fn load_file(&mut self, path: &str) { let path_raw = ::std::env::current_dir().unwrap().join(path); let path = if cfg!(windows) { format!("file:///{}", path_raw.display()) } else { format!("file://{}", path_raw.display()) }; unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(&path)) } } /// Loads qml from a specified url (`file://`, `qrc://`, `http://`) pub fn load_url(&mut self, uri: &str) { unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(uri)) } } /// Adds a path to the QML import path /// On an "import ModuleName" call QML will additionally search this path for the matching module. pub fn add_import_path(&mut self, path: &str) { unsafe { dos_qqmlapplicationengine_add_import_path(self.ptr, stoptr(path)) } } /// Loads a string as a qml file pub fn load_data(&mut self, data: &str) { unsafe { dos_qqmlapplicationengine_load_data(self.ptr, stoptr(data)) } } /// Launches the application pub fn exec(&mut self) { unsafe { dos_qguiapplication_exec(); } } /// Closes the application pub fn quit(&mut self) { unsafe { dos_qguiapplication_quit(); } } /// Sets a property for this QML context /// /// This variant stores qvariant, so it is removed, only when this QmlEngine is removed. pub fn set_and_store_property<T: Into<QVariant>>(&mut self, name: &str, value: T) { let val = value.into(); unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(&val)); } self.stored.push(val); } /// Sets a property for this QML context pub fn set_property(&mut self, name: &str, value: &QVariant) { unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(value)); } } } use utils::*; impl Default for QmlEngine { fn default() -> Self { Self::new() } } impl Drop for QmlEngine { fn drop(&mut self) { unsafe { dos_qguiapplication_quit(); dos_qqmlapplicationengine_delete(self.ptr); dos_qguiapplication_delete(); } } }
value: DosQVariant); }
random_line_split
qmlengine.rs
use qvariant::*; use types::*; use qurl::*; extern "C" { fn dos_qguiapplication_create(); fn dos_qguiapplication_exec(); fn dos_qguiapplication_quit(); fn dos_qguiapplication_delete(); fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine; fn dos_qqmlapplicationengine_load(vptr: DosQmlApplicationEngine, filename: DosCStr); fn dos_qqmlapplicationengine_load_url(vptr: DosQmlApplicationEngine, url: DosQUrl); fn dos_qqmlapplicationengine_load_data(vptr: DosQmlApplicationEngine, data: DosCStr); fn dos_qqmlapplicationengine_add_import_path(vptr: DosQmlApplicationEngine, path: DosCStr); fn dos_qqmlapplicationengine_context(vptr: DosQmlApplicationEngine) -> DosQQmlContext; fn dos_qqmlapplicationengine_delete(vptr: DosQmlApplicationEngine); fn dos_qqmlcontext_setcontextproperty(vptr: DosQQmlContext, name: DosCStr, value: DosQVariant); } /// Provides an entry point for building QML applications from Rust pub struct QmlEngine { ptr: DosQmlApplicationEngine, stored: Vec<QVariant>, } impl QmlEngine { /// Creates a QML context of a non-headless application pub fn new() -> Self { unsafe { dos_qguiapplication_create(); QmlEngine { ptr: dos_qqmlapplicationengine_create(), stored: Vec::new(), } } } /// Loads a file as a qml file pub fn load_file(&mut self, path: &str) { let path_raw = ::std::env::current_dir().unwrap().join(path); let path = if cfg!(windows) { format!("file:///{}", path_raw.display()) } else
; unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(&path)) } } /// Loads qml from a specified url (`file://`, `qrc://`, `http://`) pub fn load_url(&mut self, uri: &str) { unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(uri)) } } /// Adds a path to the QML import path /// On an "import ModuleName" call QML will additionally search this path for the matching module. pub fn add_import_path(&mut self, path: &str) { unsafe { dos_qqmlapplicationengine_add_import_path(self.ptr, stoptr(path)) } } /// Loads a string as a qml file pub fn load_data(&mut self, data: &str) { unsafe { dos_qqmlapplicationengine_load_data(self.ptr, stoptr(data)) } } /// Launches the application pub fn exec(&mut self) { unsafe { dos_qguiapplication_exec(); } } /// Closes the application pub fn quit(&mut self) { unsafe { dos_qguiapplication_quit(); } } /// Sets a property for this QML context /// /// This variant stores qvariant, so it is removed, only when this QmlEngine is removed. pub fn set_and_store_property<T: Into<QVariant>>(&mut self, name: &str, value: T) { let val = value.into(); unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(&val)); } self.stored.push(val); } /// Sets a property for this QML context pub fn set_property(&mut self, name: &str, value: &QVariant) { unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(value)); } } } use utils::*; impl Default for QmlEngine { fn default() -> Self { Self::new() } } impl Drop for QmlEngine { fn drop(&mut self) { unsafe { dos_qguiapplication_quit(); dos_qqmlapplicationengine_delete(self.ptr); dos_qguiapplication_delete(); } } }
{ format!("file://{}", path_raw.display()) }
conditional_block
qmlengine.rs
use qvariant::*; use types::*; use qurl::*; extern "C" { fn dos_qguiapplication_create(); fn dos_qguiapplication_exec(); fn dos_qguiapplication_quit(); fn dos_qguiapplication_delete(); fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine; fn dos_qqmlapplicationengine_load(vptr: DosQmlApplicationEngine, filename: DosCStr); fn dos_qqmlapplicationengine_load_url(vptr: DosQmlApplicationEngine, url: DosQUrl); fn dos_qqmlapplicationengine_load_data(vptr: DosQmlApplicationEngine, data: DosCStr); fn dos_qqmlapplicationengine_add_import_path(vptr: DosQmlApplicationEngine, path: DosCStr); fn dos_qqmlapplicationengine_context(vptr: DosQmlApplicationEngine) -> DosQQmlContext; fn dos_qqmlapplicationengine_delete(vptr: DosQmlApplicationEngine); fn dos_qqmlcontext_setcontextproperty(vptr: DosQQmlContext, name: DosCStr, value: DosQVariant); } /// Provides an entry point for building QML applications from Rust pub struct QmlEngine { ptr: DosQmlApplicationEngine, stored: Vec<QVariant>, } impl QmlEngine { /// Creates a QML context of a non-headless application pub fn new() -> Self { unsafe { dos_qguiapplication_create(); QmlEngine { ptr: dos_qqmlapplicationengine_create(), stored: Vec::new(), } } } /// Loads a file as a qml file pub fn load_file(&mut self, path: &str) { let path_raw = ::std::env::current_dir().unwrap().join(path); let path = if cfg!(windows) { format!("file:///{}", path_raw.display()) } else { format!("file://{}", path_raw.display()) }; unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(&path)) } } /// Loads qml from a specified url (`file://`, `qrc://`, `http://`) pub fn load_url(&mut self, uri: &str) { unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(uri)) } } /// Adds a path to the QML import path /// On an "import ModuleName" call QML will additionally search this path for the matching module. pub fn add_import_path(&mut self, path: &str) { unsafe { dos_qqmlapplicationengine_add_import_path(self.ptr, stoptr(path)) } } /// Loads a string as a qml file pub fn load_data(&mut self, data: &str) { unsafe { dos_qqmlapplicationengine_load_data(self.ptr, stoptr(data)) } } /// Launches the application pub fn exec(&mut self) { unsafe { dos_qguiapplication_exec(); } } /// Closes the application pub fn quit(&mut self) { unsafe { dos_qguiapplication_quit(); } } /// Sets a property for this QML context /// /// This variant stores qvariant, so it is removed, only when this QmlEngine is removed. pub fn set_and_store_property<T: Into<QVariant>>(&mut self, name: &str, value: T) { let val = value.into(); unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(&val)); } self.stored.push(val); } /// Sets a property for this QML context pub fn set_property(&mut self, name: &str, value: &QVariant)
} use utils::*; impl Default for QmlEngine { fn default() -> Self { Self::new() } } impl Drop for QmlEngine { fn drop(&mut self) { unsafe { dos_qguiapplication_quit(); dos_qqmlapplicationengine_delete(self.ptr); dos_qguiapplication_delete(); } } }
{ unsafe { let context = dos_qqmlapplicationengine_context(self.ptr); dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(value)); } }
identifier_body
store.rs
use std::path::PathBuf; use std::env; use std::ffi; use std::fmt; use std::convert; use std::error; use std::io; use std::fs::File; use std::fs; use std::io::prelude::*; use std::result; use tree; use gpgme; use ::vcs; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ); pub static PASS_ENTRY_EXTENSION: &'static str = "gpg"; pub static PASS_GPGID_FILE: &'static str = ".gpg-id"; #[derive(Debug)] pub enum PassStoreError { GPG(gpgme::Error), Io(io::Error), Other(String), } pub type Result<T> = result::Result<T, PassStoreError>; impl From<gpgme::Error> for PassStoreError { fn from(err: gpgme::Error) -> PassStoreError { PassStoreError::GPG(err) } } impl From<io::Error> for PassStoreError { fn from(err: io::Error) -> PassStoreError { PassStoreError::Io(err) } } impl fmt::Display for PassStoreError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PassStoreError::GPG(ref err) => write!(f, "GPG error: {}", err), PassStoreError::Io(ref err) => write!(f, "IO error: {}", err), PassStoreError::Other(ref err) => write!(f, "Other error: {}", err), } } } impl error::Error for PassStoreError { fn description(&self) -> &str { match *self { PassStoreError::GPG(_) => "gpg error", PassStoreError::Io(ref err) => err.description(), PassStoreError::Other(ref err) => err, } } fn cause(&self) -> Option<&error::Error> { match *self { PassStoreError::GPG(ref err) => Some(err), PassStoreError::Io(ref err) => Some(err), PassStoreError::Other(ref _err) => None, } } } pub type PassTree = tree::Tree<PassEntry>; pub type PassTreePath = tree::Path<PassEntry>; /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). #[derive(Debug)] pub struct PassStore { passhome: PathBuf, entries: PassTree, gpgid: String, verbose: bool, } /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). /// /// On construction of the store, base directory is be walked. All found /// gpg-files will be treated as store entries, which are represented by /// `PassEntry`. impl PassStore { /// Constructs a new `PassStore` with the default store location. pub fn new() -> Result<PassStore> { let def_path = PassStore::get_default_location(); let mut store = PassStore { entries: PassTree::default(), passhome: def_path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Constructs a new `PassStore` using the provided location. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassStore; /// /// let p = PathBuf::from("/home/bar/.store"); /// /// let store = PassStore::from(&p); /// /// ``` pub fn from(path: &PathBuf) -> Result<PassStore> { let mut store = PassStore { entries: PassTree::default(), passhome: path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Set the verbose printouts for the store. pub fn set_verbose(&mut self, verbose: bool) { self.verbose = verbose } /// Returns the absolute_path of a given `PassEntry`. pub fn absolute_path(&self, entry: &str) -> PathBuf { self.passhome.clone().join(PathBuf::from(entry)) } fn fill(&mut self) -> Result<()> { let t = self.passhome.clone(); self.entries = try!(self.parse(&t)); self.entries.set_root(true); self.entries.name_mut().name = String::from("Password Store"); Ok(()) } fn parse(&mut self, path: &PathBuf) -> Result<PassTree> { let entry = PassEntry::new(&path, &self.passhome); let mut current = PassTree::new(entry); if path.is_dir() { let rd = match fs::read_dir(path) { Err(_) => { let s = format!("Unable to read dir: {:?}", path); return Err(PassStoreError::Other(s)) }, Ok(r) => r }; for entry in rd { let entry = match entry { Ok(e) => e, Err(_) => continue }; let p = entry.path(); if p.ends_with(".git") { continue; } let gpgid_fname = ffi::OsStr::new(PASS_GPGID_FILE); if p.file_name() == Some(gpgid_fname) { self.gpgid = match get_gpgid_from_file(&p) { Ok(id) => id, Err(_) => panic!("Unable to open file: {}", PASS_GPGID_FILE) }; continue; } let ending = ffi::OsStr::new(PASS_ENTRY_EXTENSION); if p.is_file() && p.extension()!= Some(ending) { continue; } let sub = try!(self.parse(&p)); current.add(sub); } } Ok(current) } /// Initializes the directory structure for the password store. Fails if the /// directory exists and has files or folders or if no secret key can be /// found for the specified `gpgid`. pub fn init(&mut self, gpgid: &str) -> Result<()> { let ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); if self.passhome.is_dir() { if let Ok(r) = fs::read_dir(self.passhome.clone()) { if r.count() > 0 { let s = format!("Directory exists and not empty: {:?} ", self.passhome); return Err(PassStoreError::Other(s)); } } } match ctx.find_secret_key(gpgid) { Ok(key) => { if! key.has_secret() { let s = format!("Secret key for {:?} is not available, \ wouldn't be able to decrypt passwords.", key.id().unwrap()); return Err(PassStoreError::Other(s)) } self.gpgid = String::from(key.fingerprint().unwrap()); }, Err(_) => { let s = format!("Secret key {} not found.", gpgid); return Err(PassStoreError::Other(s)) } } let gpgid_fname = String::from(PASS_GPGID_FILE); let gpgid_path = self.passhome.clone().join(PathBuf::from(gpgid_fname)); if let Err(_) = fs::create_dir_all(&self.passhome) { let s = format!("Failed to create directory: {:?}", self.passhome); return Err(PassStoreError::Other(s)) } if let Err(_) = write_gpgid_to_file(&gpgid_path, &self.gpgid) { let s = format!("Unable to write to file: {:?}", gpgid_path); return Err(PassStoreError::Other(s)) } Ok(()) } /// Internal to get the default location of a store fn get_default_location() -> PathBuf { let mut passhome = env::home_dir().unwrap(); passhome.push(".password-store"); passhome } /// Returns the location of the `PassStore` as `String`. pub fn get_location(&self) -> String { self.passhome.to_str().unwrap_or("").to_string() } /// Find and returns a Vector of `PassEntry`s by its name. pub fn find<S>(&self, query: S) -> Vec<PassTreePath> where S: Into<String>
/// Get a `PassTreePath` from the give parameter `pass`. Returns an pub fn get<S>(&self, pass: S) -> Option<PassTreePath> where S: Into<String> { let pass = pass.into(); if pass.is_empty() { return Some(PassTreePath::from(vec![])); } self.entries .into_iter() .find(|x| x.to_string() == pass) } /// Reads and returns the content of the given `PassEntry`. The for the /// gpg-file related to the `PassEntry` encrypt. pub fn read(&self, entry: &PassTreePath) -> Option<String> { let p = String::from(format!("{}.{}", entry.to_string(), PASS_ENTRY_EXTENSION)); let p = self.passhome.clone().join(PathBuf::from(p)); if self.verbose { println!("Read path: {}", p.to_str().unwrap()); } let mut input = match gpgme::Data::load(p.to_str().unwrap()) { Ok(input) => input, Err(x) => { println_stderr!("Unable to load ({:?}): {}", p, x); return None; } }; let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let mut output = gpgme::Data::new().unwrap(); match ctx.decrypt(&mut input, &mut output) { Ok(..) => (), Err(x) => { println_stderr!("Unable to decrypt {:?}: {}", p, x); return None; } } let mut result = String::new(); let _ = output.seek(io::SeekFrom::Start(0)); let _ = output.read_to_string(&mut result); Some(result) } /// Inserts a new entry into the store. This creates a new encrypted /// gpg-file and add it to version control system, provided via `vcs`. pub fn insert<D>(&mut self, vcs: &Box<vcs::VersionControl>, entry: &str, data: D) -> Result<()> where D: Into<Vec<u8>> { let mut path = self.passhome.clone().join(entry); path.set_extension(PASS_ENTRY_EXTENSION); let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let key = try!(ctx.find_key(&*self.gpgid)); let mut input = try!(gpgme::Data::from_bytes(data.into())); let mut output = try!(gpgme::Data::new()); let flags = gpgme::ENCRYPT_NO_ENCRYPT_TO | gpgme::ENCRYPT_NO_COMPRESS; try!(ctx.encrypt_with_flags(Some(&key), &mut input, &mut output, flags)); try!(output.seek(io::SeekFrom::Start(0))); if self.verbose { println!("Going to write file: {}", path.to_str().unwrap_or("")); } let mut outfile = try!(File::create(&path)); try!(io::copy(&mut output, &mut outfile)); try!(vcs.add(path.to_str().unwrap())); try!(vcs.commit(&format!("Add given password {} to store.", entry))); Ok(()) } /// Removes a given `PassEntry` from the store. Therefore the related /// gpg-file will be removed from the file-system and the internal entry /// list. Further the `vcs` will use to commit that change. /// /// Note that the `entry` passed into the function shall be a copy of the /// original reference. pub fn remove(&mut self, vcs: &Box<vcs::VersionControl>, entry: &PassTreePath) -> Result<()> { if self.verbose { println!("Remove {}", entry); } self.entries.remove(entry); let mut p = self.absolute_path(&entry.to_string()); p.set_extension(PASS_ENTRY_EXTENSION); println!("{:?}", p); try!(fs::remove_file(&p)); try!(vcs.remove(p.to_str().unwrap())); try!(vcs.commit(&format!("Remove {} from store.", entry.to_string()))); Ok(()) } /// Gets all entries from the store as a `Tree` structure. pub fn entries<'a>(&'a self) -> &'a PassTree { &self.entries } /// Prints a give `path` as a tree. Note, if the `path` does not point /// to any entry in the store, nothing will be printed! pub fn print_tree(&self, path: &PassTreePath) { if let Some(t) = self.entries.get_entry_from_path(path) { let printer = tree::TreePrinter::new(); printer.print(&t); } else { println_stderr!("Unable to get entry for path '{}'", path); } } /// Executes over all entries in the store with the given search parameters. /// Take note that `grep_args` can include all grep parameters which are /// relevant for a piped grep execution. However, the last parameter shall /// always be the grep command. pub fn grep(&self, searcher: &str, grep_args: &Vec<&str>) -> Result<String> { use std::process::{Command, Stdio}; use std::io::{Write}; if self.verbose { println!("Use searcher: {}", searcher); } let mut result = String::new(); for entry in &self.entries { if!entry.is_leaf() { continue; } if self.verbose { println!("Current entry: {}", &entry); } let content = self.read(&entry); if content.is_none() { continue } let content = content.unwrap(); let grep = match Command::new(searcher) .arg("--color=always") .args(grep_args.as_slice()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Ok(x) => x, Err(why) => { println_stderr!("unable to spawn {}: {}", searcher, why); continue; } }; if let Err(why) = grep.stdin.unwrap().write_all(content.as_bytes()) { println_stderr!("Could not write to grep stdin {}: {}", searcher, why); } let mut grep_out = String::new(); match grep.stdout.unwrap().read_to_string(&mut grep_out) { Err(why) => println_stderr!("Unable to read from {} stdout: {}", searcher, why), _ => () } if!grep_out.is_empty() { result.push_str(&format!("{}:\n{}\n", entry, &grep_out)); } } Ok(result) } } /// Represents an entry in a `PassStore` relative to the stores location. #[derive(Debug, Clone, Default, PartialEq)] pub struct PassEntry { name: String, } impl PassEntry { /// Constructs a new `PassEntry`. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassEntry; /// /// let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); /// let store_path = PathBuf::from("/home/bar/.store"); /// /// let entry = PassEntry::new(&entry_path, &store_path); /// /// assert_eq!("foobar", &format!("{}",entry)); /// ``` /// pub fn new(path: &PathBuf, passhome: &PathBuf) -> PassEntry { let path = ::util::strip_path(path, passhome); // contains the full path! //let name = path.to_str().unwrap().to_string(); let name = match path.components().last() { Some(last) => last.as_os_str().to_str().unwrap().to_string(), None => String::from(""), }; PassEntry { name: name, } } } impl fmt::Display for PassEntry { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.name.ends_with(".gpg") { write!(f, "{}", &self.name[..self.name.len()-4]) } else { write!(f, "{}", &self.name) } } } impl convert::Into<String> for PassEntry { fn into(self) -> String { self.name } } fn get_gpgid_from_file(path: &PathBuf) -> Result<String> { let f = try!(fs::File::open(path)); let mut reader = io::BufReader::new(f); let mut buffer = String::new(); reader.read_line(&mut buffer).unwrap(); Ok(buffer.trim().to_string()) } fn write_gpgid_to_file(path: &PathBuf, gpgid: &String) -> Result<()> { let mut file = File::create(path)?; file.write_all(&gpgid.clone().into_bytes())?; file.write_all(b"\n")?; Ok(()) } #[cfg(test)] mod test { mod entry { use std::path::PathBuf; use ::store::PassEntry; #[test] fn test_new() { let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); let store_path = PathBuf::from("/home/bar/.store"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar", &format!("{}", entry)); // test entry with url as name let entry_path = PathBuf::from("/home/bar/.store/foobar.com.gpg"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar.com", &format!("{}",entry)); } } }
{ let query = query.into(); self.entries .into_iter() .filter(|x| x.to_string().contains(&query) ) .collect() }
identifier_body
store.rs
use std::path::PathBuf; use std::env; use std::ffi; use std::fmt; use std::convert; use std::error; use std::io; use std::fs::File; use std::fs; use std::io::prelude::*; use std::result; use tree; use gpgme; use ::vcs; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ); pub static PASS_ENTRY_EXTENSION: &'static str = "gpg"; pub static PASS_GPGID_FILE: &'static str = ".gpg-id"; #[derive(Debug)] pub enum PassStoreError { GPG(gpgme::Error), Io(io::Error), Other(String), } pub type Result<T> = result::Result<T, PassStoreError>; impl From<gpgme::Error> for PassStoreError { fn from(err: gpgme::Error) -> PassStoreError { PassStoreError::GPG(err) } } impl From<io::Error> for PassStoreError { fn from(err: io::Error) -> PassStoreError { PassStoreError::Io(err) } } impl fmt::Display for PassStoreError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PassStoreError::GPG(ref err) => write!(f, "GPG error: {}", err), PassStoreError::Io(ref err) => write!(f, "IO error: {}", err), PassStoreError::Other(ref err) => write!(f, "Other error: {}", err), } } } impl error::Error for PassStoreError { fn description(&self) -> &str { match *self { PassStoreError::GPG(_) => "gpg error", PassStoreError::Io(ref err) => err.description(), PassStoreError::Other(ref err) => err, } } fn cause(&self) -> Option<&error::Error> { match *self { PassStoreError::GPG(ref err) => Some(err), PassStoreError::Io(ref err) => Some(err), PassStoreError::Other(ref _err) => None, } } } pub type PassTree = tree::Tree<PassEntry>; pub type PassTreePath = tree::Path<PassEntry>; /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). #[derive(Debug)] pub struct PassStore { passhome: PathBuf, entries: PassTree, gpgid: String, verbose: bool, } /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). /// /// On construction of the store, base directory is be walked. All found /// gpg-files will be treated as store entries, which are represented by /// `PassEntry`. impl PassStore { /// Constructs a new `PassStore` with the default store location. pub fn new() -> Result<PassStore> { let def_path = PassStore::get_default_location(); let mut store = PassStore { entries: PassTree::default(), passhome: def_path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Constructs a new `PassStore` using the provided location. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassStore; /// /// let p = PathBuf::from("/home/bar/.store"); /// /// let store = PassStore::from(&p); /// /// ``` pub fn from(path: &PathBuf) -> Result<PassStore> { let mut store = PassStore { entries: PassTree::default(), passhome: path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Set the verbose printouts for the store. pub fn set_verbose(&mut self, verbose: bool) { self.verbose = verbose } /// Returns the absolute_path of a given `PassEntry`. pub fn absolute_path(&self, entry: &str) -> PathBuf { self.passhome.clone().join(PathBuf::from(entry)) } fn fill(&mut self) -> Result<()> { let t = self.passhome.clone(); self.entries = try!(self.parse(&t)); self.entries.set_root(true); self.entries.name_mut().name = String::from("Password Store"); Ok(()) } fn parse(&mut self, path: &PathBuf) -> Result<PassTree> { let entry = PassEntry::new(&path, &self.passhome); let mut current = PassTree::new(entry); if path.is_dir() { let rd = match fs::read_dir(path) { Err(_) => { let s = format!("Unable to read dir: {:?}", path); return Err(PassStoreError::Other(s)) }, Ok(r) => r }; for entry in rd { let entry = match entry { Ok(e) => e, Err(_) => continue }; let p = entry.path(); if p.ends_with(".git") { continue; } let gpgid_fname = ffi::OsStr::new(PASS_GPGID_FILE); if p.file_name() == Some(gpgid_fname) { self.gpgid = match get_gpgid_from_file(&p) { Ok(id) => id, Err(_) => panic!("Unable to open file: {}", PASS_GPGID_FILE) }; continue; } let ending = ffi::OsStr::new(PASS_ENTRY_EXTENSION); if p.is_file() && p.extension()!= Some(ending) { continue; } let sub = try!(self.parse(&p)); current.add(sub); } } Ok(current) } /// Initializes the directory structure for the password store. Fails if the /// directory exists and has files or folders or if no secret key can be /// found for the specified `gpgid`. pub fn init(&mut self, gpgid: &str) -> Result<()> { let ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); if self.passhome.is_dir() { if let Ok(r) = fs::read_dir(self.passhome.clone()) { if r.count() > 0 { let s = format!("Directory exists and not empty: {:?} ", self.passhome); return Err(PassStoreError::Other(s)); } } } match ctx.find_secret_key(gpgid) { Ok(key) => { if! key.has_secret() { let s = format!("Secret key for {:?} is not available, \ wouldn't be able to decrypt passwords.", key.id().unwrap()); return Err(PassStoreError::Other(s)) } self.gpgid = String::from(key.fingerprint().unwrap()); }, Err(_) => { let s = format!("Secret key {} not found.", gpgid); return Err(PassStoreError::Other(s)) } } let gpgid_fname = String::from(PASS_GPGID_FILE); let gpgid_path = self.passhome.clone().join(PathBuf::from(gpgid_fname)); if let Err(_) = fs::create_dir_all(&self.passhome) { let s = format!("Failed to create directory: {:?}", self.passhome); return Err(PassStoreError::Other(s)) } if let Err(_) = write_gpgid_to_file(&gpgid_path, &self.gpgid) { let s = format!("Unable to write to file: {:?}", gpgid_path); return Err(PassStoreError::Other(s)) } Ok(()) } /// Internal to get the default location of a store fn get_default_location() -> PathBuf { let mut passhome = env::home_dir().unwrap(); passhome.push(".password-store"); passhome } /// Returns the location of the `PassStore` as `String`. pub fn get_location(&self) -> String { self.passhome.to_str().unwrap_or("").to_string() } /// Find and returns a Vector of `PassEntry`s by its name. pub fn find<S>(&self, query: S) -> Vec<PassTreePath> where S: Into<String> { let query = query.into(); self.entries .into_iter() .filter(|x| x.to_string().contains(&query) ) .collect() } /// Get a `PassTreePath` from the give parameter `pass`. Returns an pub fn get<S>(&self, pass: S) -> Option<PassTreePath> where S: Into<String> { let pass = pass.into(); if pass.is_empty() { return Some(PassTreePath::from(vec![])); } self.entries .into_iter() .find(|x| x.to_string() == pass) } /// Reads and returns the content of the given `PassEntry`. The for the /// gpg-file related to the `PassEntry` encrypt. pub fn read(&self, entry: &PassTreePath) -> Option<String> { let p = String::from(format!("{}.{}", entry.to_string(), PASS_ENTRY_EXTENSION)); let p = self.passhome.clone().join(PathBuf::from(p)); if self.verbose { println!("Read path: {}", p.to_str().unwrap()); } let mut input = match gpgme::Data::load(p.to_str().unwrap()) { Ok(input) => input, Err(x) =>
}; let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let mut output = gpgme::Data::new().unwrap(); match ctx.decrypt(&mut input, &mut output) { Ok(..) => (), Err(x) => { println_stderr!("Unable to decrypt {:?}: {}", p, x); return None; } } let mut result = String::new(); let _ = output.seek(io::SeekFrom::Start(0)); let _ = output.read_to_string(&mut result); Some(result) } /// Inserts a new entry into the store. This creates a new encrypted /// gpg-file and add it to version control system, provided via `vcs`. pub fn insert<D>(&mut self, vcs: &Box<vcs::VersionControl>, entry: &str, data: D) -> Result<()> where D: Into<Vec<u8>> { let mut path = self.passhome.clone().join(entry); path.set_extension(PASS_ENTRY_EXTENSION); let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let key = try!(ctx.find_key(&*self.gpgid)); let mut input = try!(gpgme::Data::from_bytes(data.into())); let mut output = try!(gpgme::Data::new()); let flags = gpgme::ENCRYPT_NO_ENCRYPT_TO | gpgme::ENCRYPT_NO_COMPRESS; try!(ctx.encrypt_with_flags(Some(&key), &mut input, &mut output, flags)); try!(output.seek(io::SeekFrom::Start(0))); if self.verbose { println!("Going to write file: {}", path.to_str().unwrap_or("")); } let mut outfile = try!(File::create(&path)); try!(io::copy(&mut output, &mut outfile)); try!(vcs.add(path.to_str().unwrap())); try!(vcs.commit(&format!("Add given password {} to store.", entry))); Ok(()) } /// Removes a given `PassEntry` from the store. Therefore the related /// gpg-file will be removed from the file-system and the internal entry /// list. Further the `vcs` will use to commit that change. /// /// Note that the `entry` passed into the function shall be a copy of the /// original reference. pub fn remove(&mut self, vcs: &Box<vcs::VersionControl>, entry: &PassTreePath) -> Result<()> { if self.verbose { println!("Remove {}", entry); } self.entries.remove(entry); let mut p = self.absolute_path(&entry.to_string()); p.set_extension(PASS_ENTRY_EXTENSION); println!("{:?}", p); try!(fs::remove_file(&p)); try!(vcs.remove(p.to_str().unwrap())); try!(vcs.commit(&format!("Remove {} from store.", entry.to_string()))); Ok(()) } /// Gets all entries from the store as a `Tree` structure. pub fn entries<'a>(&'a self) -> &'a PassTree { &self.entries } /// Prints a give `path` as a tree. Note, if the `path` does not point /// to any entry in the store, nothing will be printed! pub fn print_tree(&self, path: &PassTreePath) { if let Some(t) = self.entries.get_entry_from_path(path) { let printer = tree::TreePrinter::new(); printer.print(&t); } else { println_stderr!("Unable to get entry for path '{}'", path); } } /// Executes over all entries in the store with the given search parameters. /// Take note that `grep_args` can include all grep parameters which are /// relevant for a piped grep execution. However, the last parameter shall /// always be the grep command. pub fn grep(&self, searcher: &str, grep_args: &Vec<&str>) -> Result<String> { use std::process::{Command, Stdio}; use std::io::{Write}; if self.verbose { println!("Use searcher: {}", searcher); } let mut result = String::new(); for entry in &self.entries { if!entry.is_leaf() { continue; } if self.verbose { println!("Current entry: {}", &entry); } let content = self.read(&entry); if content.is_none() { continue } let content = content.unwrap(); let grep = match Command::new(searcher) .arg("--color=always") .args(grep_args.as_slice()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Ok(x) => x, Err(why) => { println_stderr!("unable to spawn {}: {}", searcher, why); continue; } }; if let Err(why) = grep.stdin.unwrap().write_all(content.as_bytes()) { println_stderr!("Could not write to grep stdin {}: {}", searcher, why); } let mut grep_out = String::new(); match grep.stdout.unwrap().read_to_string(&mut grep_out) { Err(why) => println_stderr!("Unable to read from {} stdout: {}", searcher, why), _ => () } if!grep_out.is_empty() { result.push_str(&format!("{}:\n{}\n", entry, &grep_out)); } } Ok(result) } } /// Represents an entry in a `PassStore` relative to the stores location. #[derive(Debug, Clone, Default, PartialEq)] pub struct PassEntry { name: String, } impl PassEntry { /// Constructs a new `PassEntry`. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassEntry; /// /// let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); /// let store_path = PathBuf::from("/home/bar/.store"); /// /// let entry = PassEntry::new(&entry_path, &store_path); /// /// assert_eq!("foobar", &format!("{}",entry)); /// ``` /// pub fn new(path: &PathBuf, passhome: &PathBuf) -> PassEntry { let path = ::util::strip_path(path, passhome); // contains the full path! //let name = path.to_str().unwrap().to_string(); let name = match path.components().last() { Some(last) => last.as_os_str().to_str().unwrap().to_string(), None => String::from(""), }; PassEntry { name: name, } } } impl fmt::Display for PassEntry { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.name.ends_with(".gpg") { write!(f, "{}", &self.name[..self.name.len()-4]) } else { write!(f, "{}", &self.name) } } } impl convert::Into<String> for PassEntry { fn into(self) -> String { self.name } } fn get_gpgid_from_file(path: &PathBuf) -> Result<String> { let f = try!(fs::File::open(path)); let mut reader = io::BufReader::new(f); let mut buffer = String::new(); reader.read_line(&mut buffer).unwrap(); Ok(buffer.trim().to_string()) } fn write_gpgid_to_file(path: &PathBuf, gpgid: &String) -> Result<()> { let mut file = File::create(path)?; file.write_all(&gpgid.clone().into_bytes())?; file.write_all(b"\n")?; Ok(()) } #[cfg(test)] mod test { mod entry { use std::path::PathBuf; use ::store::PassEntry; #[test] fn test_new() { let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); let store_path = PathBuf::from("/home/bar/.store"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar", &format!("{}", entry)); // test entry with url as name let entry_path = PathBuf::from("/home/bar/.store/foobar.com.gpg"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar.com", &format!("{}",entry)); } } }
{ println_stderr!("Unable to load ({:?}): {}", p, x); return None; }
conditional_block
store.rs
use std::path::PathBuf; use std::env; use std::ffi; use std::fmt; use std::convert; use std::error; use std::io; use std::fs::File; use std::fs; use std::io::prelude::*; use std::result; use tree; use gpgme; use ::vcs; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ); pub static PASS_ENTRY_EXTENSION: &'static str = "gpg"; pub static PASS_GPGID_FILE: &'static str = ".gpg-id"; #[derive(Debug)] pub enum PassStoreError { GPG(gpgme::Error), Io(io::Error), Other(String), } pub type Result<T> = result::Result<T, PassStoreError>; impl From<gpgme::Error> for PassStoreError { fn from(err: gpgme::Error) -> PassStoreError { PassStoreError::GPG(err) } } impl From<io::Error> for PassStoreError { fn from(err: io::Error) -> PassStoreError { PassStoreError::Io(err) } } impl fmt::Display for PassStoreError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PassStoreError::GPG(ref err) => write!(f, "GPG error: {}", err), PassStoreError::Io(ref err) => write!(f, "IO error: {}", err), PassStoreError::Other(ref err) => write!(f, "Other error: {}", err), } } } impl error::Error for PassStoreError { fn description(&self) -> &str { match *self { PassStoreError::GPG(_) => "gpg error", PassStoreError::Io(ref err) => err.description(), PassStoreError::Other(ref err) => err, } } fn cause(&self) -> Option<&error::Error> { match *self { PassStoreError::GPG(ref err) => Some(err), PassStoreError::Io(ref err) => Some(err), PassStoreError::Other(ref _err) => None, } } } pub type PassTree = tree::Tree<PassEntry>; pub type PassTreePath = tree::Path<PassEntry>; /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). #[derive(Debug)] pub struct PassStore { passhome: PathBuf, entries: PassTree, gpgid: String, verbose: bool, } /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). /// /// On construction of the store, base directory is be walked. All found /// gpg-files will be treated as store entries, which are represented by /// `PassEntry`. impl PassStore { /// Constructs a new `PassStore` with the default store location. pub fn new() -> Result<PassStore> { let def_path = PassStore::get_default_location(); let mut store = PassStore { entries: PassTree::default(), passhome: def_path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Constructs a new `PassStore` using the provided location. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassStore; /// /// let p = PathBuf::from("/home/bar/.store"); /// /// let store = PassStore::from(&p); /// /// ``` pub fn from(path: &PathBuf) -> Result<PassStore> { let mut store = PassStore { entries: PassTree::default(), passhome: path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Set the verbose printouts for the store. pub fn set_verbose(&mut self, verbose: bool) { self.verbose = verbose } /// Returns the absolute_path of a given `PassEntry`. pub fn absolute_path(&self, entry: &str) -> PathBuf { self.passhome.clone().join(PathBuf::from(entry)) } fn fill(&mut self) -> Result<()> { let t = self.passhome.clone(); self.entries = try!(self.parse(&t)); self.entries.set_root(true); self.entries.name_mut().name = String::from("Password Store"); Ok(()) } fn parse(&mut self, path: &PathBuf) -> Result<PassTree> { let entry = PassEntry::new(&path, &self.passhome); let mut current = PassTree::new(entry); if path.is_dir() { let rd = match fs::read_dir(path) { Err(_) => { let s = format!("Unable to read dir: {:?}", path); return Err(PassStoreError::Other(s)) }, Ok(r) => r }; for entry in rd { let entry = match entry { Ok(e) => e, Err(_) => continue }; let p = entry.path(); if p.ends_with(".git") { continue; } let gpgid_fname = ffi::OsStr::new(PASS_GPGID_FILE); if p.file_name() == Some(gpgid_fname) { self.gpgid = match get_gpgid_from_file(&p) { Ok(id) => id, Err(_) => panic!("Unable to open file: {}", PASS_GPGID_FILE) }; continue; } let ending = ffi::OsStr::new(PASS_ENTRY_EXTENSION); if p.is_file() && p.extension()!= Some(ending) { continue; } let sub = try!(self.parse(&p)); current.add(sub); } } Ok(current) } /// Initializes the directory structure for the password store. Fails if the /// directory exists and has files or folders or if no secret key can be /// found for the specified `gpgid`. pub fn init(&mut self, gpgid: &str) -> Result<()> { let ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); if self.passhome.is_dir() { if let Ok(r) = fs::read_dir(self.passhome.clone()) { if r.count() > 0 { let s = format!("Directory exists and not empty: {:?} ", self.passhome); return Err(PassStoreError::Other(s)); } } } match ctx.find_secret_key(gpgid) { Ok(key) => { if! key.has_secret() { let s = format!("Secret key for {:?} is not available, \ wouldn't be able to decrypt passwords.", key.id().unwrap()); return Err(PassStoreError::Other(s)) } self.gpgid = String::from(key.fingerprint().unwrap()); }, Err(_) => { let s = format!("Secret key {} not found.", gpgid); return Err(PassStoreError::Other(s)) } } let gpgid_fname = String::from(PASS_GPGID_FILE); let gpgid_path = self.passhome.clone().join(PathBuf::from(gpgid_fname)); if let Err(_) = fs::create_dir_all(&self.passhome) { let s = format!("Failed to create directory: {:?}", self.passhome); return Err(PassStoreError::Other(s)) } if let Err(_) = write_gpgid_to_file(&gpgid_path, &self.gpgid) { let s = format!("Unable to write to file: {:?}", gpgid_path); return Err(PassStoreError::Other(s)) } Ok(()) } /// Internal to get the default location of a store fn get_default_location() -> PathBuf { let mut passhome = env::home_dir().unwrap(); passhome.push(".password-store"); passhome } /// Returns the location of the `PassStore` as `String`. pub fn
(&self) -> String { self.passhome.to_str().unwrap_or("").to_string() } /// Find and returns a Vector of `PassEntry`s by its name. pub fn find<S>(&self, query: S) -> Vec<PassTreePath> where S: Into<String> { let query = query.into(); self.entries .into_iter() .filter(|x| x.to_string().contains(&query) ) .collect() } /// Get a `PassTreePath` from the give parameter `pass`. Returns an pub fn get<S>(&self, pass: S) -> Option<PassTreePath> where S: Into<String> { let pass = pass.into(); if pass.is_empty() { return Some(PassTreePath::from(vec![])); } self.entries .into_iter() .find(|x| x.to_string() == pass) } /// Reads and returns the content of the given `PassEntry`. The for the /// gpg-file related to the `PassEntry` encrypt. pub fn read(&self, entry: &PassTreePath) -> Option<String> { let p = String::from(format!("{}.{}", entry.to_string(), PASS_ENTRY_EXTENSION)); let p = self.passhome.clone().join(PathBuf::from(p)); if self.verbose { println!("Read path: {}", p.to_str().unwrap()); } let mut input = match gpgme::Data::load(p.to_str().unwrap()) { Ok(input) => input, Err(x) => { println_stderr!("Unable to load ({:?}): {}", p, x); return None; } }; let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let mut output = gpgme::Data::new().unwrap(); match ctx.decrypt(&mut input, &mut output) { Ok(..) => (), Err(x) => { println_stderr!("Unable to decrypt {:?}: {}", p, x); return None; } } let mut result = String::new(); let _ = output.seek(io::SeekFrom::Start(0)); let _ = output.read_to_string(&mut result); Some(result) } /// Inserts a new entry into the store. This creates a new encrypted /// gpg-file and add it to version control system, provided via `vcs`. pub fn insert<D>(&mut self, vcs: &Box<vcs::VersionControl>, entry: &str, data: D) -> Result<()> where D: Into<Vec<u8>> { let mut path = self.passhome.clone().join(entry); path.set_extension(PASS_ENTRY_EXTENSION); let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let key = try!(ctx.find_key(&*self.gpgid)); let mut input = try!(gpgme::Data::from_bytes(data.into())); let mut output = try!(gpgme::Data::new()); let flags = gpgme::ENCRYPT_NO_ENCRYPT_TO | gpgme::ENCRYPT_NO_COMPRESS; try!(ctx.encrypt_with_flags(Some(&key), &mut input, &mut output, flags)); try!(output.seek(io::SeekFrom::Start(0))); if self.verbose { println!("Going to write file: {}", path.to_str().unwrap_or("")); } let mut outfile = try!(File::create(&path)); try!(io::copy(&mut output, &mut outfile)); try!(vcs.add(path.to_str().unwrap())); try!(vcs.commit(&format!("Add given password {} to store.", entry))); Ok(()) } /// Removes a given `PassEntry` from the store. Therefore the related /// gpg-file will be removed from the file-system and the internal entry /// list. Further the `vcs` will use to commit that change. /// /// Note that the `entry` passed into the function shall be a copy of the /// original reference. pub fn remove(&mut self, vcs: &Box<vcs::VersionControl>, entry: &PassTreePath) -> Result<()> { if self.verbose { println!("Remove {}", entry); } self.entries.remove(entry); let mut p = self.absolute_path(&entry.to_string()); p.set_extension(PASS_ENTRY_EXTENSION); println!("{:?}", p); try!(fs::remove_file(&p)); try!(vcs.remove(p.to_str().unwrap())); try!(vcs.commit(&format!("Remove {} from store.", entry.to_string()))); Ok(()) } /// Gets all entries from the store as a `Tree` structure. pub fn entries<'a>(&'a self) -> &'a PassTree { &self.entries } /// Prints a give `path` as a tree. Note, if the `path` does not point /// to any entry in the store, nothing will be printed! pub fn print_tree(&self, path: &PassTreePath) { if let Some(t) = self.entries.get_entry_from_path(path) { let printer = tree::TreePrinter::new(); printer.print(&t); } else { println_stderr!("Unable to get entry for path '{}'", path); } } /// Executes over all entries in the store with the given search parameters. /// Take note that `grep_args` can include all grep parameters which are /// relevant for a piped grep execution. However, the last parameter shall /// always be the grep command. pub fn grep(&self, searcher: &str, grep_args: &Vec<&str>) -> Result<String> { use std::process::{Command, Stdio}; use std::io::{Write}; if self.verbose { println!("Use searcher: {}", searcher); } let mut result = String::new(); for entry in &self.entries { if!entry.is_leaf() { continue; } if self.verbose { println!("Current entry: {}", &entry); } let content = self.read(&entry); if content.is_none() { continue } let content = content.unwrap(); let grep = match Command::new(searcher) .arg("--color=always") .args(grep_args.as_slice()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Ok(x) => x, Err(why) => { println_stderr!("unable to spawn {}: {}", searcher, why); continue; } }; if let Err(why) = grep.stdin.unwrap().write_all(content.as_bytes()) { println_stderr!("Could not write to grep stdin {}: {}", searcher, why); } let mut grep_out = String::new(); match grep.stdout.unwrap().read_to_string(&mut grep_out) { Err(why) => println_stderr!("Unable to read from {} stdout: {}", searcher, why), _ => () } if!grep_out.is_empty() { result.push_str(&format!("{}:\n{}\n", entry, &grep_out)); } } Ok(result) } } /// Represents an entry in a `PassStore` relative to the stores location. #[derive(Debug, Clone, Default, PartialEq)] pub struct PassEntry { name: String, } impl PassEntry { /// Constructs a new `PassEntry`. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassEntry; /// /// let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); /// let store_path = PathBuf::from("/home/bar/.store"); /// /// let entry = PassEntry::new(&entry_path, &store_path); /// /// assert_eq!("foobar", &format!("{}",entry)); /// ``` /// pub fn new(path: &PathBuf, passhome: &PathBuf) -> PassEntry { let path = ::util::strip_path(path, passhome); // contains the full path! //let name = path.to_str().unwrap().to_string(); let name = match path.components().last() { Some(last) => last.as_os_str().to_str().unwrap().to_string(), None => String::from(""), }; PassEntry { name: name, } } } impl fmt::Display for PassEntry { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.name.ends_with(".gpg") { write!(f, "{}", &self.name[..self.name.len()-4]) } else { write!(f, "{}", &self.name) } } } impl convert::Into<String> for PassEntry { fn into(self) -> String { self.name } } fn get_gpgid_from_file(path: &PathBuf) -> Result<String> { let f = try!(fs::File::open(path)); let mut reader = io::BufReader::new(f); let mut buffer = String::new(); reader.read_line(&mut buffer).unwrap(); Ok(buffer.trim().to_string()) } fn write_gpgid_to_file(path: &PathBuf, gpgid: &String) -> Result<()> { let mut file = File::create(path)?; file.write_all(&gpgid.clone().into_bytes())?; file.write_all(b"\n")?; Ok(()) } #[cfg(test)] mod test { mod entry { use std::path::PathBuf; use ::store::PassEntry; #[test] fn test_new() { let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); let store_path = PathBuf::from("/home/bar/.store"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar", &format!("{}", entry)); // test entry with url as name let entry_path = PathBuf::from("/home/bar/.store/foobar.com.gpg"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar.com", &format!("{}",entry)); } } }
get_location
identifier_name
store.rs
use std::path::PathBuf; use std::env; use std::ffi; use std::fmt; use std::convert; use std::error; use std::io; use std::fs::File; use std::fs; use std::io::prelude::*; use std::result; use tree; use gpgme; use ::vcs; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ); pub static PASS_ENTRY_EXTENSION: &'static str = "gpg"; pub static PASS_GPGID_FILE: &'static str = ".gpg-id"; #[derive(Debug)] pub enum PassStoreError { GPG(gpgme::Error), Io(io::Error), Other(String), } pub type Result<T> = result::Result<T, PassStoreError>; impl From<gpgme::Error> for PassStoreError { fn from(err: gpgme::Error) -> PassStoreError { PassStoreError::GPG(err) } } impl From<io::Error> for PassStoreError { fn from(err: io::Error) -> PassStoreError { PassStoreError::Io(err) } } impl fmt::Display for PassStoreError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PassStoreError::GPG(ref err) => write!(f, "GPG error: {}", err), PassStoreError::Io(ref err) => write!(f, "IO error: {}", err), PassStoreError::Other(ref err) => write!(f, "Other error: {}", err), } } } impl error::Error for PassStoreError { fn description(&self) -> &str { match *self { PassStoreError::GPG(_) => "gpg error", PassStoreError::Io(ref err) => err.description(), PassStoreError::Other(ref err) => err, } } fn cause(&self) -> Option<&error::Error> { match *self { PassStoreError::GPG(ref err) => Some(err), PassStoreError::Io(ref err) => Some(err), PassStoreError::Other(ref _err) => None, } } } pub type PassTree = tree::Tree<PassEntry>; pub type PassTreePath = tree::Path<PassEntry>; /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). #[derive(Debug)] pub struct PassStore { passhome: PathBuf, entries: PassTree, gpgid: String, verbose: bool, } /// Represents the underlying directory structure of a password store. /// The folder structure is inherit from pass(1). /// /// On construction of the store, base directory is be walked. All found /// gpg-files will be treated as store entries, which are represented by /// `PassEntry`. impl PassStore { /// Constructs a new `PassStore` with the default store location. pub fn new() -> Result<PassStore> { let def_path = PassStore::get_default_location(); let mut store = PassStore { entries: PassTree::default(), passhome: def_path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Constructs a new `PassStore` using the provided location. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassStore; /// /// let p = PathBuf::from("/home/bar/.store"); /// /// let store = PassStore::from(&p); /// /// ``` pub fn from(path: &PathBuf) -> Result<PassStore> { let mut store = PassStore { entries: PassTree::default(), passhome: path.clone(), gpgid: String::new(), verbose: false, }; try!(store.fill()); Ok(store) } /// Set the verbose printouts for the store. pub fn set_verbose(&mut self, verbose: bool) { self.verbose = verbose } /// Returns the absolute_path of a given `PassEntry`. pub fn absolute_path(&self, entry: &str) -> PathBuf { self.passhome.clone().join(PathBuf::from(entry)) } fn fill(&mut self) -> Result<()> { let t = self.passhome.clone(); self.entries = try!(self.parse(&t)); self.entries.set_root(true); self.entries.name_mut().name = String::from("Password Store"); Ok(()) } fn parse(&mut self, path: &PathBuf) -> Result<PassTree> { let entry = PassEntry::new(&path, &self.passhome); let mut current = PassTree::new(entry); if path.is_dir() { let rd = match fs::read_dir(path) { Err(_) => { let s = format!("Unable to read dir: {:?}", path); return Err(PassStoreError::Other(s)) }, Ok(r) => r }; for entry in rd { let entry = match entry { Ok(e) => e, Err(_) => continue }; let p = entry.path(); if p.ends_with(".git") { continue; } let gpgid_fname = ffi::OsStr::new(PASS_GPGID_FILE); if p.file_name() == Some(gpgid_fname) { self.gpgid = match get_gpgid_from_file(&p) { Ok(id) => id, Err(_) => panic!("Unable to open file: {}", PASS_GPGID_FILE) }; continue; } let ending = ffi::OsStr::new(PASS_ENTRY_EXTENSION); if p.is_file() && p.extension()!= Some(ending) { continue; } let sub = try!(self.parse(&p)); current.add(sub); } } Ok(current) } /// Initializes the directory structure for the password store. Fails if the /// directory exists and has files or folders or if no secret key can be /// found for the specified `gpgid`. pub fn init(&mut self, gpgid: &str) -> Result<()> { let ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); if self.passhome.is_dir() { if let Ok(r) = fs::read_dir(self.passhome.clone()) { if r.count() > 0 { let s = format!("Directory exists and not empty: {:?} ", self.passhome); return Err(PassStoreError::Other(s)); } } } match ctx.find_secret_key(gpgid) { Ok(key) => { if! key.has_secret() { let s = format!("Secret key for {:?} is not available, \ wouldn't be able to decrypt passwords.", key.id().unwrap()); return Err(PassStoreError::Other(s)) } self.gpgid = String::from(key.fingerprint().unwrap()); }, Err(_) => { let s = format!("Secret key {} not found.", gpgid); return Err(PassStoreError::Other(s)) } } let gpgid_fname = String::from(PASS_GPGID_FILE); let gpgid_path = self.passhome.clone().join(PathBuf::from(gpgid_fname)); if let Err(_) = fs::create_dir_all(&self.passhome) { let s = format!("Failed to create directory: {:?}", self.passhome); return Err(PassStoreError::Other(s)) } if let Err(_) = write_gpgid_to_file(&gpgid_path, &self.gpgid) { let s = format!("Unable to write to file: {:?}", gpgid_path); return Err(PassStoreError::Other(s)) } Ok(()) } /// Internal to get the default location of a store fn get_default_location() -> PathBuf { let mut passhome = env::home_dir().unwrap(); passhome.push(".password-store"); passhome } /// Returns the location of the `PassStore` as `String`. pub fn get_location(&self) -> String { self.passhome.to_str().unwrap_or("").to_string() } /// Find and returns a Vector of `PassEntry`s by its name. pub fn find<S>(&self, query: S) -> Vec<PassTreePath> where S: Into<String> { let query = query.into(); self.entries .into_iter() .filter(|x| x.to_string().contains(&query) ) .collect() } /// Get a `PassTreePath` from the give parameter `pass`. Returns an pub fn get<S>(&self, pass: S) -> Option<PassTreePath> where S: Into<String> { let pass = pass.into(); if pass.is_empty() { return Some(PassTreePath::from(vec![])); } self.entries .into_iter() .find(|x| x.to_string() == pass) } /// Reads and returns the content of the given `PassEntry`. The for the /// gpg-file related to the `PassEntry` encrypt. pub fn read(&self, entry: &PassTreePath) -> Option<String> { let p = String::from(format!("{}.{}", entry.to_string(), PASS_ENTRY_EXTENSION)); let p = self.passhome.clone().join(PathBuf::from(p)); if self.verbose { println!("Read path: {}", p.to_str().unwrap()); } let mut input = match gpgme::Data::load(p.to_str().unwrap()) { Ok(input) => input, Err(x) => { println_stderr!("Unable to load ({:?}): {}", p, x); return None; } }; let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let mut output = gpgme::Data::new().unwrap(); match ctx.decrypt(&mut input, &mut output) { Ok(..) => (), Err(x) => { println_stderr!("Unable to decrypt {:?}: {}", p, x); return None; } } let mut result = String::new(); let _ = output.seek(io::SeekFrom::Start(0)); let _ = output.read_to_string(&mut result); Some(result) } /// Inserts a new entry into the store. This creates a new encrypted /// gpg-file and add it to version control system, provided via `vcs`. pub fn insert<D>(&mut self, vcs: &Box<vcs::VersionControl>, entry: &str, data: D) -> Result<()> where D: Into<Vec<u8>> { let mut path = self.passhome.clone().join(entry); path.set_extension(PASS_ENTRY_EXTENSION); let mut ctx = gpgme::Context::from_protocol( gpgme::Protocol::OpenPgp).unwrap(); let key = try!(ctx.find_key(&*self.gpgid)); let mut input = try!(gpgme::Data::from_bytes(data.into())); let mut output = try!(gpgme::Data::new()); let flags = gpgme::ENCRYPT_NO_ENCRYPT_TO | gpgme::ENCRYPT_NO_COMPRESS; try!(ctx.encrypt_with_flags(Some(&key), &mut input, &mut output, flags)); try!(output.seek(io::SeekFrom::Start(0))); if self.verbose { println!("Going to write file: {}", path.to_str().unwrap_or("")); } let mut outfile = try!(File::create(&path)); try!(io::copy(&mut output, &mut outfile)); try!(vcs.add(path.to_str().unwrap())); try!(vcs.commit(&format!("Add given password {} to store.", entry))); Ok(()) } /// Removes a given `PassEntry` from the store. Therefore the related /// gpg-file will be removed from the file-system and the internal entry /// list. Further the `vcs` will use to commit that change. /// /// Note that the `entry` passed into the function shall be a copy of the /// original reference. pub fn remove(&mut self, vcs: &Box<vcs::VersionControl>, entry: &PassTreePath) -> Result<()> { if self.verbose { println!("Remove {}", entry); } self.entries.remove(entry); let mut p = self.absolute_path(&entry.to_string()); p.set_extension(PASS_ENTRY_EXTENSION); println!("{:?}", p); try!(fs::remove_file(&p)); try!(vcs.remove(p.to_str().unwrap())); try!(vcs.commit(&format!("Remove {} from store.", entry.to_string()))); Ok(()) } /// Gets all entries from the store as a `Tree` structure. pub fn entries<'a>(&'a self) -> &'a PassTree { &self.entries } /// Prints a give `path` as a tree. Note, if the `path` does not point /// to any entry in the store, nothing will be printed! pub fn print_tree(&self, path: &PassTreePath) { if let Some(t) = self.entries.get_entry_from_path(path) { let printer = tree::TreePrinter::new(); printer.print(&t); } else { println_stderr!("Unable to get entry for path '{}'", path); } } /// Executes over all entries in the store with the given search parameters. /// Take note that `grep_args` can include all grep parameters which are /// relevant for a piped grep execution. However, the last parameter shall /// always be the grep command. pub fn grep(&self, searcher: &str, grep_args: &Vec<&str>) -> Result<String> { use std::process::{Command, Stdio}; use std::io::{Write}; if self.verbose { println!("Use searcher: {}", searcher); } let mut result = String::new(); for entry in &self.entries { if!entry.is_leaf() { continue; } if self.verbose { println!("Current entry: {}", &entry); } let content = self.read(&entry); if content.is_none() { continue } let content = content.unwrap(); let grep = match Command::new(searcher) .arg("--color=always") .args(grep_args.as_slice()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Ok(x) => x, Err(why) => { println_stderr!("unable to spawn {}: {}", searcher, why); continue; } }; if let Err(why) = grep.stdin.unwrap().write_all(content.as_bytes()) { println_stderr!("Could not write to grep stdin {}: {}", searcher, why); } let mut grep_out = String::new(); match grep.stdout.unwrap().read_to_string(&mut grep_out) { Err(why) => println_stderr!("Unable to read from {} stdout: {}", searcher, why), _ => () } if!grep_out.is_empty() { result.push_str(&format!("{}:\n{}\n", entry, &grep_out)); } } Ok(result) } } /// Represents an entry in a `PassStore` relative to the stores location.
impl PassEntry { /// Constructs a new `PassEntry`. /// /// # Examples /// /// ``` /// use std::path::PathBuf; /// use rasslib::store::PassEntry; /// /// let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); /// let store_path = PathBuf::from("/home/bar/.store"); /// /// let entry = PassEntry::new(&entry_path, &store_path); /// /// assert_eq!("foobar", &format!("{}",entry)); /// ``` /// pub fn new(path: &PathBuf, passhome: &PathBuf) -> PassEntry { let path = ::util::strip_path(path, passhome); // contains the full path! //let name = path.to_str().unwrap().to_string(); let name = match path.components().last() { Some(last) => last.as_os_str().to_str().unwrap().to_string(), None => String::from(""), }; PassEntry { name: name, } } } impl fmt::Display for PassEntry { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.name.ends_with(".gpg") { write!(f, "{}", &self.name[..self.name.len()-4]) } else { write!(f, "{}", &self.name) } } } impl convert::Into<String> for PassEntry { fn into(self) -> String { self.name } } fn get_gpgid_from_file(path: &PathBuf) -> Result<String> { let f = try!(fs::File::open(path)); let mut reader = io::BufReader::new(f); let mut buffer = String::new(); reader.read_line(&mut buffer).unwrap(); Ok(buffer.trim().to_string()) } fn write_gpgid_to_file(path: &PathBuf, gpgid: &String) -> Result<()> { let mut file = File::create(path)?; file.write_all(&gpgid.clone().into_bytes())?; file.write_all(b"\n")?; Ok(()) } #[cfg(test)] mod test { mod entry { use std::path::PathBuf; use ::store::PassEntry; #[test] fn test_new() { let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg"); let store_path = PathBuf::from("/home/bar/.store"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar", &format!("{}", entry)); // test entry with url as name let entry_path = PathBuf::from("/home/bar/.store/foobar.com.gpg"); let entry = PassEntry::new(&entry_path, &store_path); assert_eq!("foobar.com", &format!("{}",entry)); } } }
#[derive(Debug, Clone, Default, PartialEq)] pub struct PassEntry { name: String, }
random_line_split
htmlolistelement.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::HTMLOListElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOListElementDerived; use dom::bindings::js::JS; use dom::bindings::error::ErrorResult; use dom::document::Document; use dom::element::HTMLOListElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLOListElement { htmlelement: HTMLElement, } impl HTMLOListElementDerived for EventTarget { fn is_htmlolistelement(&self) -> bool { match self.type_id { NodeTargetTypeId(ElementNodeTypeId(HTMLOListElementTypeId)) => true, _ => false } } } impl HTMLOListElement { pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLOListElement { HTMLOListElement { htmlelement: HTMLElement::new_inherited(HTMLOListElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLOListElement> { let element = HTMLOListElement::new_inherited(localName, document.clone()); Node::reflect_node(~element, document, HTMLOListElementBinding::Wrap) } } impl HTMLOListElement { pub fn Reversed(&self) -> bool { false } pub fn SetReversed(&self, _reversed: bool) -> ErrorResult { Ok(()) } pub fn Start(&self) -> i32 { 0 } pub fn SetStart(&mut self, _start: i32) -> ErrorResult { Ok(()) } pub fn Type(&self) -> DOMString {
} pub fn Compact(&self) -> bool { false } pub fn SetCompact(&self, _compact: bool) -> ErrorResult { Ok(()) } }
~"" } pub fn SetType(&mut self, _type: DOMString) -> ErrorResult { Ok(())
random_line_split
htmlolistelement.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::HTMLOListElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOListElementDerived; use dom::bindings::js::JS; use dom::bindings::error::ErrorResult; use dom::document::Document; use dom::element::HTMLOListElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLOListElement { htmlelement: HTMLElement, } impl HTMLOListElementDerived for EventTarget { fn is_htmlolistelement(&self) -> bool { match self.type_id { NodeTargetTypeId(ElementNodeTypeId(HTMLOListElementTypeId)) => true, _ => false } } } impl HTMLOListElement { pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLOListElement { HTMLOListElement { htmlelement: HTMLElement::new_inherited(HTMLOListElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLOListElement> { let element = HTMLOListElement::new_inherited(localName, document.clone()); Node::reflect_node(~element, document, HTMLOListElementBinding::Wrap) } } impl HTMLOListElement { pub fn Reversed(&self) -> bool { false } pub fn SetReversed(&self, _reversed: bool) -> ErrorResult { Ok(()) } pub fn Start(&self) -> i32 { 0 } pub fn
(&mut self, _start: i32) -> ErrorResult { Ok(()) } pub fn Type(&self) -> DOMString { ~"" } pub fn SetType(&mut self, _type: DOMString) -> ErrorResult { Ok(()) } pub fn Compact(&self) -> bool { false } pub fn SetCompact(&self, _compact: bool) -> ErrorResult { Ok(()) } }
SetStart
identifier_name
htmlolistelement.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::HTMLOListElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOListElementDerived; use dom::bindings::js::JS; use dom::bindings::error::ErrorResult; use dom::document::Document; use dom::element::HTMLOListElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLOListElement { htmlelement: HTMLElement, } impl HTMLOListElementDerived for EventTarget { fn is_htmlolistelement(&self) -> bool { match self.type_id { NodeTargetTypeId(ElementNodeTypeId(HTMLOListElementTypeId)) => true, _ => false } } } impl HTMLOListElement { pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLOListElement { HTMLOListElement { htmlelement: HTMLElement::new_inherited(HTMLOListElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLOListElement> { let element = HTMLOListElement::new_inherited(localName, document.clone()); Node::reflect_node(~element, document, HTMLOListElementBinding::Wrap) } } impl HTMLOListElement { pub fn Reversed(&self) -> bool
pub fn SetReversed(&self, _reversed: bool) -> ErrorResult { Ok(()) } pub fn Start(&self) -> i32 { 0 } pub fn SetStart(&mut self, _start: i32) -> ErrorResult { Ok(()) } pub fn Type(&self) -> DOMString { ~"" } pub fn SetType(&mut self, _type: DOMString) -> ErrorResult { Ok(()) } pub fn Compact(&self) -> bool { false } pub fn SetCompact(&self, _compact: bool) -> ErrorResult { Ok(()) } }
{ false }
identifier_body
file_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 http://mozilla.org/MPL/2.0/. */ use about_loader; use mime_classifier::MimeClassifier; use mime_guess::guess_mime_type; use msg::constellation_msg::PipelineId; use net_traits::{LoadConsumer, LoadData, LoadOrigin, Metadata, NetworkError, ReferrerPolicy}; use net_traits::ProgressMsg::{Done, Payload}; use resource_thread::{CancellationListener, ProgressSender}; use resource_thread::{send_error, start_sending_sniffed_opt}; use std::borrow::ToOwned; use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::Arc; use url::Url; use util::thread::spawn_named; static READ_SIZE: usize = 8192; enum ReadStatus { Partial(Vec<u8>), EOF, } enum LoadResult { Cancelled, Finished, } struct FileLoadOrigin; impl LoadOrigin for FileLoadOrigin { fn referrer_url(&self) -> Option<Url> { None } fn referrer_policy(&self) -> Option<ReferrerPolicy>
fn pipeline_id(&self) -> Option<PipelineId> { None } } fn read_block(reader: &mut File) -> Result<ReadStatus, String> { let mut buf = vec![0; READ_SIZE]; match reader.read(&mut buf) { Ok(0) => Ok(ReadStatus::EOF), Ok(n) => { buf.truncate(n); Ok(ReadStatus::Partial(buf)) } Err(e) => Err(e.description().to_owned()), } } fn read_all(reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener) -> Result<LoadResult, String> { while!cancel_listener.is_cancelled() { match try!(read_block(reader)) { ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(), ReadStatus::EOF => return Ok(LoadResult::Finished), } } let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); Ok(LoadResult::Cancelled) } fn get_progress_chan(load_data: LoadData, file_path: &Path, senders: LoadConsumer, classifier: Arc<MimeClassifier>, buf: &[u8]) -> Result<ProgressSender, ()> { let mut metadata = Metadata::default(load_data.url); let mime_type = guess_mime_type(file_path); metadata.set_content_type(Some(&mime_type)); return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context); } pub fn factory(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MimeClassifier>, cancel_listener: CancellationListener) { assert!(load_data.url.scheme() == "file"); spawn_named("file_loader".to_owned(), move || { let file_path = match load_data.url.to_file_path() { Ok(file_path) => file_path, Err(_) => { send_error(load_data.url, NetworkError::Internal("Could not parse path".to_owned()), senders); return; }, }; let mut file = File::open(&file_path); let reader = match file { Ok(ref mut reader) => reader, Err(_) => { // this should be one of the three errors listed in // http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open // but, we'll go for a "file not found!" let url = Url::parse("about:not-found").unwrap(); let load_data_404 = LoadData::new(load_data.context, url, &FileLoadOrigin); about_loader::factory(load_data_404, senders, classifier, cancel_listener); return; } }; if cancel_listener.is_cancelled() { if let Ok(progress_chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); } return; } match read_block(reader) { Ok(ReadStatus::Partial(buf)) => { let progress_chan = get_progress_chan(load_data, &file_path, senders, classifier, &buf).ok().unwrap(); progress_chan.send(Payload(buf)).unwrap(); let read_result = read_all(reader, &progress_chan, &cancel_listener); if let Ok(load_result) = read_result { match load_result { LoadResult::Cancelled => return, LoadResult::Finished => progress_chan.send(Done(Ok(()))).unwrap(), } } } Ok(ReadStatus::EOF) => { if let Ok(chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = chan.send(Done(Ok(()))); } } Err(e) => { send_error(load_data.url, NetworkError::Internal(e), senders); } } }); }
{ None }
identifier_body
file_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 http://mozilla.org/MPL/2.0/. */ use about_loader; use mime_classifier::MimeClassifier; use mime_guess::guess_mime_type; use msg::constellation_msg::PipelineId; use net_traits::{LoadConsumer, LoadData, LoadOrigin, Metadata, NetworkError, ReferrerPolicy}; use net_traits::ProgressMsg::{Done, Payload}; use resource_thread::{CancellationListener, ProgressSender}; use resource_thread::{send_error, start_sending_sniffed_opt}; use std::borrow::ToOwned; use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::Arc; use url::Url; use util::thread::spawn_named; static READ_SIZE: usize = 8192; enum ReadStatus { Partial(Vec<u8>), EOF, } enum LoadResult { Cancelled, Finished, } struct FileLoadOrigin; impl LoadOrigin for FileLoadOrigin { fn referrer_url(&self) -> Option<Url> { None } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn pipeline_id(&self) -> Option<PipelineId> { None } } fn read_block(reader: &mut File) -> Result<ReadStatus, String> { let mut buf = vec![0; READ_SIZE]; match reader.read(&mut buf) { Ok(0) => Ok(ReadStatus::EOF), Ok(n) => { buf.truncate(n); Ok(ReadStatus::Partial(buf)) } Err(e) => Err(e.description().to_owned()), } } fn read_all(reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener) -> Result<LoadResult, String> { while!cancel_listener.is_cancelled() { match try!(read_block(reader)) { ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(), ReadStatus::EOF => return Ok(LoadResult::Finished), } } let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); Ok(LoadResult::Cancelled) } fn get_progress_chan(load_data: LoadData, file_path: &Path, senders: LoadConsumer, classifier: Arc<MimeClassifier>, buf: &[u8]) -> Result<ProgressSender, ()> { let mut metadata = Metadata::default(load_data.url); let mime_type = guess_mime_type(file_path); metadata.set_content_type(Some(&mime_type)); return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context); } pub fn
(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MimeClassifier>, cancel_listener: CancellationListener) { assert!(load_data.url.scheme() == "file"); spawn_named("file_loader".to_owned(), move || { let file_path = match load_data.url.to_file_path() { Ok(file_path) => file_path, Err(_) => { send_error(load_data.url, NetworkError::Internal("Could not parse path".to_owned()), senders); return; }, }; let mut file = File::open(&file_path); let reader = match file { Ok(ref mut reader) => reader, Err(_) => { // this should be one of the three errors listed in // http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open // but, we'll go for a "file not found!" let url = Url::parse("about:not-found").unwrap(); let load_data_404 = LoadData::new(load_data.context, url, &FileLoadOrigin); about_loader::factory(load_data_404, senders, classifier, cancel_listener); return; } }; if cancel_listener.is_cancelled() { if let Ok(progress_chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); } return; } match read_block(reader) { Ok(ReadStatus::Partial(buf)) => { let progress_chan = get_progress_chan(load_data, &file_path, senders, classifier, &buf).ok().unwrap(); progress_chan.send(Payload(buf)).unwrap(); let read_result = read_all(reader, &progress_chan, &cancel_listener); if let Ok(load_result) = read_result { match load_result { LoadResult::Cancelled => return, LoadResult::Finished => progress_chan.send(Done(Ok(()))).unwrap(), } } } Ok(ReadStatus::EOF) => { if let Ok(chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = chan.send(Done(Ok(()))); } } Err(e) => { send_error(load_data.url, NetworkError::Internal(e), senders); } } }); }
factory
identifier_name
file_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 http://mozilla.org/MPL/2.0/. */ use about_loader; use mime_classifier::MimeClassifier; use mime_guess::guess_mime_type; use msg::constellation_msg::PipelineId; use net_traits::{LoadConsumer, LoadData, LoadOrigin, Metadata, NetworkError, ReferrerPolicy}; use net_traits::ProgressMsg::{Done, Payload}; use resource_thread::{CancellationListener, ProgressSender}; use resource_thread::{send_error, start_sending_sniffed_opt}; use std::borrow::ToOwned; use std::error::Error; use std::fs::File;
use url::Url; use util::thread::spawn_named; static READ_SIZE: usize = 8192; enum ReadStatus { Partial(Vec<u8>), EOF, } enum LoadResult { Cancelled, Finished, } struct FileLoadOrigin; impl LoadOrigin for FileLoadOrigin { fn referrer_url(&self) -> Option<Url> { None } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn pipeline_id(&self) -> Option<PipelineId> { None } } fn read_block(reader: &mut File) -> Result<ReadStatus, String> { let mut buf = vec![0; READ_SIZE]; match reader.read(&mut buf) { Ok(0) => Ok(ReadStatus::EOF), Ok(n) => { buf.truncate(n); Ok(ReadStatus::Partial(buf)) } Err(e) => Err(e.description().to_owned()), } } fn read_all(reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener) -> Result<LoadResult, String> { while!cancel_listener.is_cancelled() { match try!(read_block(reader)) { ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(), ReadStatus::EOF => return Ok(LoadResult::Finished), } } let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); Ok(LoadResult::Cancelled) } fn get_progress_chan(load_data: LoadData, file_path: &Path, senders: LoadConsumer, classifier: Arc<MimeClassifier>, buf: &[u8]) -> Result<ProgressSender, ()> { let mut metadata = Metadata::default(load_data.url); let mime_type = guess_mime_type(file_path); metadata.set_content_type(Some(&mime_type)); return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context); } pub fn factory(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MimeClassifier>, cancel_listener: CancellationListener) { assert!(load_data.url.scheme() == "file"); spawn_named("file_loader".to_owned(), move || { let file_path = match load_data.url.to_file_path() { Ok(file_path) => file_path, Err(_) => { send_error(load_data.url, NetworkError::Internal("Could not parse path".to_owned()), senders); return; }, }; let mut file = File::open(&file_path); let reader = match file { Ok(ref mut reader) => reader, Err(_) => { // this should be one of the three errors listed in // http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open // but, we'll go for a "file not found!" let url = Url::parse("about:not-found").unwrap(); let load_data_404 = LoadData::new(load_data.context, url, &FileLoadOrigin); about_loader::factory(load_data_404, senders, classifier, cancel_listener); return; } }; if cancel_listener.is_cancelled() { if let Ok(progress_chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); } return; } match read_block(reader) { Ok(ReadStatus::Partial(buf)) => { let progress_chan = get_progress_chan(load_data, &file_path, senders, classifier, &buf).ok().unwrap(); progress_chan.send(Payload(buf)).unwrap(); let read_result = read_all(reader, &progress_chan, &cancel_listener); if let Ok(load_result) = read_result { match load_result { LoadResult::Cancelled => return, LoadResult::Finished => progress_chan.send(Done(Ok(()))).unwrap(), } } } Ok(ReadStatus::EOF) => { if let Ok(chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = chan.send(Done(Ok(()))); } } Err(e) => { send_error(load_data.url, NetworkError::Internal(e), senders); } } }); }
use std::io::Read; use std::path::Path; use std::sync::Arc;
random_line_split
file_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 http://mozilla.org/MPL/2.0/. */ use about_loader; use mime_classifier::MimeClassifier; use mime_guess::guess_mime_type; use msg::constellation_msg::PipelineId; use net_traits::{LoadConsumer, LoadData, LoadOrigin, Metadata, NetworkError, ReferrerPolicy}; use net_traits::ProgressMsg::{Done, Payload}; use resource_thread::{CancellationListener, ProgressSender}; use resource_thread::{send_error, start_sending_sniffed_opt}; use std::borrow::ToOwned; use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::Arc; use url::Url; use util::thread::spawn_named; static READ_SIZE: usize = 8192; enum ReadStatus { Partial(Vec<u8>), EOF, } enum LoadResult { Cancelled, Finished, } struct FileLoadOrigin; impl LoadOrigin for FileLoadOrigin { fn referrer_url(&self) -> Option<Url> { None } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn pipeline_id(&self) -> Option<PipelineId> { None } } fn read_block(reader: &mut File) -> Result<ReadStatus, String> { let mut buf = vec![0; READ_SIZE]; match reader.read(&mut buf) { Ok(0) => Ok(ReadStatus::EOF), Ok(n) => { buf.truncate(n); Ok(ReadStatus::Partial(buf)) } Err(e) => Err(e.description().to_owned()), } } fn read_all(reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener) -> Result<LoadResult, String> { while!cancel_listener.is_cancelled() { match try!(read_block(reader)) { ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(), ReadStatus::EOF => return Ok(LoadResult::Finished), } } let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); Ok(LoadResult::Cancelled) } fn get_progress_chan(load_data: LoadData, file_path: &Path, senders: LoadConsumer, classifier: Arc<MimeClassifier>, buf: &[u8]) -> Result<ProgressSender, ()> { let mut metadata = Metadata::default(load_data.url); let mime_type = guess_mime_type(file_path); metadata.set_content_type(Some(&mime_type)); return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context); } pub fn factory(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MimeClassifier>, cancel_listener: CancellationListener) { assert!(load_data.url.scheme() == "file"); spawn_named("file_loader".to_owned(), move || { let file_path = match load_data.url.to_file_path() { Ok(file_path) => file_path, Err(_) =>
, }; let mut file = File::open(&file_path); let reader = match file { Ok(ref mut reader) => reader, Err(_) => { // this should be one of the three errors listed in // http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open // but, we'll go for a "file not found!" let url = Url::parse("about:not-found").unwrap(); let load_data_404 = LoadData::new(load_data.context, url, &FileLoadOrigin); about_loader::factory(load_data_404, senders, classifier, cancel_listener); return; } }; if cancel_listener.is_cancelled() { if let Ok(progress_chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled))); } return; } match read_block(reader) { Ok(ReadStatus::Partial(buf)) => { let progress_chan = get_progress_chan(load_data, &file_path, senders, classifier, &buf).ok().unwrap(); progress_chan.send(Payload(buf)).unwrap(); let read_result = read_all(reader, &progress_chan, &cancel_listener); if let Ok(load_result) = read_result { match load_result { LoadResult::Cancelled => return, LoadResult::Finished => progress_chan.send(Done(Ok(()))).unwrap(), } } } Ok(ReadStatus::EOF) => { if let Ok(chan) = get_progress_chan(load_data, &file_path, senders, classifier, &[]) { let _ = chan.send(Done(Ok(()))); } } Err(e) => { send_error(load_data.url, NetworkError::Internal(e), senders); } } }); }
{ send_error(load_data.url, NetworkError::Internal("Could not parse path".to_owned()), senders); return; }
conditional_block
process.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use ascii::*; use collections::HashMap; use collections; use env::split_paths; use env; use ffi::{OsString, OsStr}; use fmt; use fs; use io::{self, Error}; use libc::{self, c_void}; use mem; use os::windows::ffi::OsStrExt; use path::Path; use ptr; use sync::StaticMutex; use sys::c; use sys::fs::{OpenOptions, File}; use sys::handle::{Handle, RawHandle}; use sys::pipe::AnonPipe; use sys::stdio; use sys::{self, cvt}; use sys_common::{AsInner, FromInner}; //////////////////////////////////////////////////////////////////////////////// // Command //////////////////////////////////////////////////////////////////////////////// fn mk_key(s: &OsStr) -> OsString { FromInner::from_inner(sys::os_str::Buf { inner: s.as_inner().inner.to_ascii_uppercase() }) } #[derive(Clone)] pub struct Command { pub program: OsString, pub args: Vec<OsString>, pub env: Option<HashMap<OsString, OsString>>, pub cwd: Option<OsString>, pub detach: bool, // not currently exposed in std::process } impl Command { pub fn new(program: &OsStr) -> Command { Command { program: program.to_os_string(), args: Vec::new(), env: None, cwd: None, detach: false, } } pub fn arg(&mut self, arg: &OsStr) { self.args.push(arg.to_os_string()) } pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) { self.args.extend(args.map(OsStr::to_os_string)) } fn init_env_map(&mut self){ if self.env.is_none() { self.env = Some(env::vars_os().map(|(key, val)| { (mk_key(&key), val) }).collect()); } } pub fn env(&mut self, key: &OsStr, val: &OsStr) { self.init_env_map(); self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string()); } pub fn env_remove(&mut self, key: &OsStr) { self.init_env_map(); self.env.as_mut().unwrap().remove(&mk_key(key)); } pub fn
(&mut self) { self.env = Some(HashMap::new()) } pub fn cwd(&mut self, dir: &OsStr) { self.cwd = Some(dir.to_os_string()) } } //////////////////////////////////////////////////////////////////////////////// // Processes //////////////////////////////////////////////////////////////////////////////// /// A value representing a child process. /// /// The lifetime of this value is linked to the lifetime of the actual /// process - the Process destructor calls self.finish() which waits /// for the process to terminate. pub struct Process { handle: Handle, } pub enum Stdio { Inherit, Piped(AnonPipe), None, Handle(RawHandle), } impl Process { pub fn spawn(cfg: &Command, in_handle: Stdio, out_handle: Stdio, err_handle: Stdio) -> io::Result<Process> { use libc::{TRUE, STARTF_USESTDHANDLES}; use libc::{DWORD, STARTUPINFO, CreateProcessW}; // To have the spawning semantics of unix/windows stay the same, we need // to read the *child's* PATH if one is provided. See #15149 for more // details. let program = cfg.env.as_ref().and_then(|env| { for (key, v) in env { if OsStr::new("PATH")!= &**key { continue } // Split the value and test each path to see if the // program exists. for path in split_paths(&v) { let path = path.join(cfg.program.to_str().unwrap()) .with_extension(env::consts::EXE_EXTENSION); if fs::metadata(&path).is_ok() { return Some(path.into_os_string()) } } break } None }); let mut si = zeroed_startupinfo(); si.cb = mem::size_of::<STARTUPINFO>() as DWORD; si.dwFlags = STARTF_USESTDHANDLES; let stdin = try!(in_handle.to_handle(c::STD_INPUT_HANDLE)); let stdout = try!(out_handle.to_handle(c::STD_OUTPUT_HANDLE)); let stderr = try!(err_handle.to_handle(c::STD_ERROR_HANDLE)); si.hStdInput = stdin.raw(); si.hStdOutput = stdout.raw(); si.hStdError = stderr.raw(); let program = program.as_ref().unwrap_or(&cfg.program); let mut cmd_str = make_command_line(program, &cfg.args); cmd_str.push(0); // add null terminator // stolen from the libuv code. let mut flags = libc::CREATE_UNICODE_ENVIRONMENT; if cfg.detach { flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP; } let (envp, _data) = make_envp(cfg.env.as_ref()); let (dirp, _data) = make_dirp(cfg.cwd.as_ref()); let mut pi = zeroed_process_information(); try!(unsafe { // `CreateProcess` is racy! // http://support.microsoft.com/kb/315939 static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new(); let _lock = CREATE_PROCESS_LOCK.lock(); cvt(CreateProcessW(ptr::null(), cmd_str.as_mut_ptr(), ptr::null_mut(), ptr::null_mut(), TRUE, flags, envp, dirp, &mut si, &mut pi)) }); // We close the thread handle because we don't care about keeping // the thread id valid, and we aren't keeping the thread handle // around to be able to close it later. drop(Handle::new(pi.hThread)); Ok(Process { handle: Handle::new(pi.hProcess) }) } pub unsafe fn kill(&self) -> io::Result<()> { try!(cvt(libc::TerminateProcess(self.handle.raw(), 1))); Ok(()) } pub fn id(&self) -> u32 { unsafe { c::GetProcessId(self.handle.raw()) as u32 } } pub fn wait(&self) -> io::Result<ExitStatus> { use libc::{STILL_ACTIVE, INFINITE, WAIT_OBJECT_0}; use libc::{GetExitCodeProcess, WaitForSingleObject}; unsafe { loop { let mut status = 0; try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status))); if status!= STILL_ACTIVE { return Ok(ExitStatus(status as i32)); } match WaitForSingleObject(self.handle.raw(), INFINITE) { WAIT_OBJECT_0 => {} _ => return Err(Error::last_os_error()), } } } } pub fn handle(&self) -> &Handle { &self.handle } } #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct ExitStatus(i32); impl ExitStatus { pub fn success(&self) -> bool { self.0 == 0 } pub fn code(&self) -> Option<i32> { Some(self.0) } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "exit code: {}", self.0) } } fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO { libc::types::os::arch::extra::STARTUPINFO { cb: 0, lpReserved: ptr::null_mut(), lpDesktop: ptr::null_mut(), lpTitle: ptr::null_mut(), dwX: 0, dwY: 0, dwXSize: 0, dwYSize: 0, dwXCountChars: 0, dwYCountCharts: 0, dwFillAttribute: 0, dwFlags: 0, wShowWindow: 0, cbReserved2: 0, lpReserved2: ptr::null_mut(), hStdInput: libc::INVALID_HANDLE_VALUE, hStdOutput: libc::INVALID_HANDLE_VALUE, hStdError: libc::INVALID_HANDLE_VALUE, } } fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION { libc::types::os::arch::extra::PROCESS_INFORMATION { hProcess: ptr::null_mut(), hThread: ptr::null_mut(), dwProcessId: 0, dwThreadId: 0 } } // Produces a wide string *without terminating null* fn make_command_line(prog: &OsStr, args: &[OsString]) -> Vec<u16> { // Encode the command and arguments in a command line string such // that the spawned process may recover them using CommandLineToArgvW. let mut cmd: Vec<u16> = Vec::new(); append_arg(&mut cmd, prog); for arg in args { cmd.push(''as u16); append_arg(&mut cmd, arg); } return cmd; fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) { // If an argument has 0 characters then we need to quote it to ensure // that it actually gets passed through on the command line or otherwise // it will be dropped entirely when parsed on the other end. let arg_bytes = &arg.as_inner().inner.as_inner(); let quote = arg_bytes.iter().any(|c| *c == b''|| *c == b'\t') || arg_bytes.is_empty(); if quote { cmd.push('"' as u16); } let mut iter = arg.encode_wide(); let mut backslashes: usize = 0; while let Some(x) = iter.next() { if x == '\\' as u16 { backslashes += 1; } else { if x == '"' as u16 { // Add n+1 backslashes to total 2n+1 before internal '"'. for _ in 0..(backslashes+1) { cmd.push('\\' as u16); } } backslashes = 0; } cmd.push(x); } if quote { // Add n backslashes to total 2n before ending '"'. for _ in 0..backslashes { cmd.push('\\' as u16); } cmd.push('"' as u16); } } } fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>) -> (*mut c_void, Vec<u16>) { // On Windows we pass an "environment block" which is not a char**, but // rather a concatenation of null-terminated k=v\0 sequences, with a final // \0 to terminate. match env { Some(env) => { let mut blk = Vec::new(); for pair in env { blk.extend(pair.0.encode_wide()); blk.push('=' as u16); blk.extend(pair.1.encode_wide()); blk.push(0); } blk.push(0); (blk.as_mut_ptr() as *mut c_void, blk) } _ => (ptr::null_mut(), Vec::new()) } } fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) { match d { Some(dir) => { let mut dir_str: Vec<u16> = dir.encode_wide().collect(); dir_str.push(0); (dir_str.as_ptr(), dir_str) }, None => (ptr::null(), Vec::new()) } } impl Stdio { pub fn clone_if_copy(&self) -> Stdio { match *self { Stdio::Inherit => Stdio::Inherit, Stdio::None => Stdio::None, Stdio::Handle(handle) => Stdio::Handle(handle), Stdio::Piped(_) => unreachable!(), } } fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> { use libc::DUPLICATE_SAME_ACCESS; match *self { Stdio::Inherit => { stdio::get(stdio_id).and_then(|io| { io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS) }) } Stdio::Handle(ref handle) => { handle.duplicate(0, true, DUPLICATE_SAME_ACCESS) } Stdio::Piped(ref pipe) => { pipe.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS) } // Similarly to unix, we don't actually leave holes for the // stdio file descriptors, but rather open up /dev/null // equivalents. These equivalents are drawn from libuv's // windows process spawning. Stdio::None => { let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>(); let mut sa = libc::SECURITY_ATTRIBUTES { nLength: size as libc::DWORD, lpSecurityDescriptor: ptr::null_mut(), bInheritHandle: 1, }; let mut opts = OpenOptions::new(); opts.read(stdio_id == c::STD_INPUT_HANDLE); opts.write(stdio_id!= c::STD_INPUT_HANDLE); opts.security_attributes(&mut sa); File::open(Path::new("NUL"), &opts).map(|file| { file.into_handle() }) } } } } #[cfg(test)] mod tests { use prelude::v1::*; use str; use ffi::{OsStr, OsString}; use super::make_command_line; #[test] fn test_make_command_line() { fn test_wrapper(prog: &str, args: &[&str]) -> String { String::from_utf16( &make_command_line(OsStr::new(prog), &args.iter() .map(|a| OsString::from(a)) .collect::<Vec<OsString>>())).unwrap() } assert_eq!( test_wrapper("prog", &["aaa", "bbb", "ccc"]), "prog aaa bbb ccc" ); assert_eq!( test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]), "\"C:\\Program Files\\blah\\blah.exe\" aaa" ); assert_eq!( test_wrapper("C:\\Program Files\\test", &["aa\"bb"]), "\"C:\\Program Files\\test\" aa\\\"bb" ); assert_eq!( test_wrapper("echo", &["a b c"]), "echo \"a b c\"" ); assert_eq!( test_wrapper("echo", &["\" \\\" \\", "\\"]), "echo \"\\\" \\\\\\\" \\\\\" \\" ); assert_eq!( test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]), "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}" ); } }
env_clear
identifier_name