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 |
---|---|---|---|---|
adv3.rs | #![allow(warnings)]
// Goal #1: Eliminate the borrow check error in the `remove` method.
pub struct Map<K: Eq, V> {
elements: Vec<(K, V)>,
}
impl<K: Eq, V> Map<K, V> { | pub fn new() -> Self {
Map { elements: vec![] }
}
pub fn insert(&mut self, key: K, value: V) {
self.elements.push((key, value));
}
pub fn get(&self, key: &K) -> Option<&V> {
self.elements.iter().rev().find(|pair| pair.0 == *key).map(|pair| &pair.1)
}
pub fn remove(&mut self, key: &K) {
let mut i : Option<usize> = None;
for (index, pair) in self.elements.iter().enumerate() {
if pair.0 == *key {
i = Some(index);
break;
}
}
match i {
Some(index) => {self.elements.remove(index);},
None => {},
}
}
} | random_line_split |
|
fault.rs | use std::panic::catch_unwind;
use std::error::Error;
use std::fmt;
use std::io::{Write, stderr, Error as IoError, ErrorKind};
pub fn catch_fault() {
let result = catch_unwind(|| {
panic!("holy crap!");
});
println!("\n{:?}\n", result);
}
pub fn get_something() -> Result<(), String> {
Err("holy crap".to_string())
}
| let _ = writeln!(stderr(), "error: {}", err);
while let Some(cause) = err.cause() {
let _ = writeln!(stderr(), "caused by: {}", cause);
err = cause;
}
}
pub fn demo_print_std_err() {
#[derive(Debug)]
struct SuperErrorSideKick;
impl fmt::Display for SuperErrorSideKick {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SuperErrorSideKick is here!")
}
}
impl Error for SuperErrorSideKick {
fn description(&self) -> &str {
"I'm SuperError side kick"
}
}
#[derive(Debug)]
struct SuperError;
impl fmt::Display for SuperError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SuperError is here!")
}
}
impl Error for SuperError {
fn description(&self) -> &str {
"I'm the superhero of errors"
}
fn cause(&self) -> Option<&Error> {
Some(&SuperErrorSideKick{})
}
}
let mut err = SuperError{};
println!("{:?}", err.cause());
print_error(&err);
}
pub fn err_propagation() -> Result<(), IoError> {
Err(IoError::new(ErrorKind::Other, "oh no!"))
}
pub fn demo_err_propagation() -> Result<(), IoError> {
let result = err_propagation()?;
println!("propagation in middle.");
Ok(())
} | pub fn print_error(mut err: &Error) { | random_line_split |
fault.rs | use std::panic::catch_unwind;
use std::error::Error;
use std::fmt;
use std::io::{Write, stderr, Error as IoError, ErrorKind};
pub fn catch_fault() {
let result = catch_unwind(|| {
panic!("holy crap!");
});
println!("\n{:?}\n", result);
}
pub fn get_something() -> Result<(), String> {
Err("holy crap".to_string())
}
pub fn print_error(mut err: &Error) {
let _ = writeln!(stderr(), "error: {}", err);
while let Some(cause) = err.cause() {
let _ = writeln!(stderr(), "caused by: {}", cause);
err = cause;
}
}
pub fn demo_print_std_err() {
#[derive(Debug)]
struct SuperErrorSideKick;
impl fmt::Display for SuperErrorSideKick {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SuperErrorSideKick is here!")
}
}
impl Error for SuperErrorSideKick {
fn description(&self) -> &str |
}
#[derive(Debug)]
struct SuperError;
impl fmt::Display for SuperError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SuperError is here!")
}
}
impl Error for SuperError {
fn description(&self) -> &str {
"I'm the superhero of errors"
}
fn cause(&self) -> Option<&Error> {
Some(&SuperErrorSideKick{})
}
}
let mut err = SuperError{};
println!("{:?}", err.cause());
print_error(&err);
}
pub fn err_propagation() -> Result<(), IoError> {
Err(IoError::new(ErrorKind::Other, "oh no!"))
}
pub fn demo_err_propagation() -> Result<(), IoError> {
let result = err_propagation()?;
println!("propagation in middle.");
Ok(())
} | {
"I'm SuperError side kick"
} | identifier_body |
fault.rs | use std::panic::catch_unwind;
use std::error::Error;
use std::fmt;
use std::io::{Write, stderr, Error as IoError, ErrorKind};
pub fn catch_fault() {
let result = catch_unwind(|| {
panic!("holy crap!");
});
println!("\n{:?}\n", result);
}
pub fn get_something() -> Result<(), String> {
Err("holy crap".to_string())
}
pub fn print_error(mut err: &Error) {
let _ = writeln!(stderr(), "error: {}", err);
while let Some(cause) = err.cause() {
let _ = writeln!(stderr(), "caused by: {}", cause);
err = cause;
}
}
pub fn demo_print_std_err() {
#[derive(Debug)]
struct SuperErrorSideKick;
impl fmt::Display for SuperErrorSideKick {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SuperErrorSideKick is here!")
}
}
impl Error for SuperErrorSideKick {
fn description(&self) -> &str {
"I'm SuperError side kick"
}
}
#[derive(Debug)]
struct SuperError;
impl fmt::Display for SuperError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SuperError is here!")
}
}
impl Error for SuperError {
fn | (&self) -> &str {
"I'm the superhero of errors"
}
fn cause(&self) -> Option<&Error> {
Some(&SuperErrorSideKick{})
}
}
let mut err = SuperError{};
println!("{:?}", err.cause());
print_error(&err);
}
pub fn err_propagation() -> Result<(), IoError> {
Err(IoError::new(ErrorKind::Other, "oh no!"))
}
pub fn demo_err_propagation() -> Result<(), IoError> {
let result = err_propagation()?;
println!("propagation in middle.");
Ok(())
} | description | identifier_name |
extcolorbufferhalffloat.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use canvas_traits::webgl::WebGLVersion;
use crate::dom::bindings::codegen::Bindings::EXTColorBufferHalfFloatBinding;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::webgl_extensions::ext::oestexturehalffloat::OESTextureHalfFloat;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use dom_struct::dom_struct;
#[dom_struct]
pub struct EXTColorBufferHalfFloat {
reflector_: Reflector, |
impl EXTColorBufferHalfFloat {
fn new_inherited() -> EXTColorBufferHalfFloat {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for EXTColorBufferHalfFloat {
type Extension = EXTColorBufferHalfFloat;
fn new(ctx: &WebGLRenderingContext) -> DomRoot<EXTColorBufferHalfFloat> {
reflect_dom_object(
Box::new(EXTColorBufferHalfFloat::new_inherited()),
&*ctx.global(),
EXTColorBufferHalfFloatBinding::Wrap,
)
}
fn spec() -> WebGLExtensionSpec {
WebGLExtensionSpec::Specific(WebGLVersion::WebGL1)
}
fn is_supported(ext: &WebGLExtensions) -> bool {
OESTextureHalfFloat::is_supported(ext)
}
fn enable(_ext: &WebGLExtensions) {}
fn name() -> &'static str {
"EXT_color_buffer_half_float"
}
} | } | random_line_split |
extcolorbufferhalffloat.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use canvas_traits::webgl::WebGLVersion;
use crate::dom::bindings::codegen::Bindings::EXTColorBufferHalfFloatBinding;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::webgl_extensions::ext::oestexturehalffloat::OESTextureHalfFloat;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use dom_struct::dom_struct;
#[dom_struct]
pub struct | {
reflector_: Reflector,
}
impl EXTColorBufferHalfFloat {
fn new_inherited() -> EXTColorBufferHalfFloat {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for EXTColorBufferHalfFloat {
type Extension = EXTColorBufferHalfFloat;
fn new(ctx: &WebGLRenderingContext) -> DomRoot<EXTColorBufferHalfFloat> {
reflect_dom_object(
Box::new(EXTColorBufferHalfFloat::new_inherited()),
&*ctx.global(),
EXTColorBufferHalfFloatBinding::Wrap,
)
}
fn spec() -> WebGLExtensionSpec {
WebGLExtensionSpec::Specific(WebGLVersion::WebGL1)
}
fn is_supported(ext: &WebGLExtensions) -> bool {
OESTextureHalfFloat::is_supported(ext)
}
fn enable(_ext: &WebGLExtensions) {}
fn name() -> &'static str {
"EXT_color_buffer_half_float"
}
}
| EXTColorBufferHalfFloat | identifier_name |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
);
/// Convert a String to C-compatible string
///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn rust_string_to_c(s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null() |
drop(CString::from_raw(s));
}
| {
return;
} | conditional_block |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
);
/// Convert a String to C-compatible string
///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn | (s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
}
| rust_string_to_c | identifier_name |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
); | ///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn rust_string_to_c(s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
} |
/// Convert a String to C-compatible string | random_line_split |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
);
/// Convert a String to C-compatible string
///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn rust_string_to_c(s: String) -> *mut c_char |
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
}
| {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
} | identifier_body |
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClientStreamBuilder,
};
use crate::config::TlsClientConfig;
#[allow(clippy::type_complexity)]
pub(crate) fn new_https_stream<R>(
socket_addr: SocketAddr,
dns_name: String,
client_config: Option<TlsClientConfig>,
) -> DnsExchangeConnect<HttpsClientConnect<R::Tcp>, HttpsClientStream, HttpsClientResponse, TokioTime>
where
R: RuntimeProvider,
{
let client_config = client_config.map_or_else(
|| CLIENT_CONFIG.clone(),
|TlsClientConfig(client_config)| client_config,
);
let https_builder = HttpsClientStreamBuilder::with_client_config(client_config);
DnsExchange::connect(https_builder.build::<R::Tcp>(socket_addr, dns_name))
}
#[cfg(test)]
mod tests {
extern crate env_logger;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use tokio::runtime::Runtime;
use crate::config::{ResolverConfig, ResolverOpts};
use crate::TokioAsyncResolver;
fn https_test(config: ResolverConfig) {
//env_logger::try_init().ok();
let mut io_loop = Runtime::new().unwrap();
let resolver =
TokioAsyncResolver::new(config, ResolverOpts::default(), io_loop.handle().clone())
.expect("failed to create resolver");
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
}
}
// check if there is another connection created
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
}
}
}
#[test]
fn test_cloudflare_https() |
}
| {
https_test(ResolverConfig::cloudflare_https())
} | identifier_body |
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClientStreamBuilder,
};
use crate::config::TlsClientConfig;
#[allow(clippy::type_complexity)]
pub(crate) fn new_https_stream<R>(
socket_addr: SocketAddr,
dns_name: String,
client_config: Option<TlsClientConfig>,
) -> DnsExchangeConnect<HttpsClientConnect<R::Tcp>, HttpsClientStream, HttpsClientResponse, TokioTime>
where
R: RuntimeProvider,
{
let client_config = client_config.map_or_else(
|| CLIENT_CONFIG.clone(),
|TlsClientConfig(client_config)| client_config,
);
let https_builder = HttpsClientStreamBuilder::with_client_config(client_config);
DnsExchange::connect(https_builder.build::<R::Tcp>(socket_addr, dns_name))
}
#[cfg(test)]
mod tests {
extern crate env_logger;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use tokio::runtime::Runtime;
use crate::config::{ResolverConfig, ResolverOpts};
use crate::TokioAsyncResolver;
fn https_test(config: ResolverConfig) {
//env_logger::try_init().ok();
let mut io_loop = Runtime::new().unwrap();
let resolver =
TokioAsyncResolver::new(config, ResolverOpts::default(), io_loop.handle().clone())
.expect("failed to create resolver");
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
}
}
// check if there is another connection created
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
}
}
}
#[test]
fn | () {
https_test(ResolverConfig::cloudflare_https())
}
}
| test_cloudflare_https | identifier_name |
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClientStreamBuilder,
};
use crate::config::TlsClientConfig;
#[allow(clippy::type_complexity)]
pub(crate) fn new_https_stream<R>(
socket_addr: SocketAddr,
dns_name: String,
client_config: Option<TlsClientConfig>,
) -> DnsExchangeConnect<HttpsClientConnect<R::Tcp>, HttpsClientStream, HttpsClientResponse, TokioTime>
where
R: RuntimeProvider,
{
let client_config = client_config.map_or_else(
|| CLIENT_CONFIG.clone(),
|TlsClientConfig(client_config)| client_config,
);
let https_builder = HttpsClientStreamBuilder::with_client_config(client_config);
DnsExchange::connect(https_builder.build::<R::Tcp>(socket_addr, dns_name))
}
#[cfg(test)]
mod tests {
extern crate env_logger;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use tokio::runtime::Runtime;
use crate::config::{ResolverConfig, ResolverOpts};
use crate::TokioAsyncResolver;
fn https_test(config: ResolverConfig) {
//env_logger::try_init().ok();
let mut io_loop = Runtime::new().unwrap();
| let resolver =
TokioAsyncResolver::new(config, ResolverOpts::default(), io_loop.handle().clone())
.expect("failed to create resolver");
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
}
}
// check if there is another connection created
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
}
}
}
#[test]
fn test_cloudflare_https() {
https_test(ResolverConfig::cloudflare_https())
}
} | random_line_split |
|
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClientStreamBuilder,
};
use crate::config::TlsClientConfig;
#[allow(clippy::type_complexity)]
pub(crate) fn new_https_stream<R>(
socket_addr: SocketAddr,
dns_name: String,
client_config: Option<TlsClientConfig>,
) -> DnsExchangeConnect<HttpsClientConnect<R::Tcp>, HttpsClientStream, HttpsClientResponse, TokioTime>
where
R: RuntimeProvider,
{
let client_config = client_config.map_or_else(
|| CLIENT_CONFIG.clone(),
|TlsClientConfig(client_config)| client_config,
);
let https_builder = HttpsClientStreamBuilder::with_client_config(client_config);
DnsExchange::connect(https_builder.build::<R::Tcp>(socket_addr, dns_name))
}
#[cfg(test)]
mod tests {
extern crate env_logger;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use tokio::runtime::Runtime;
use crate::config::{ResolverConfig, ResolverOpts};
use crate::TokioAsyncResolver;
fn https_test(config: ResolverConfig) {
//env_logger::try_init().ok();
let mut io_loop = Runtime::new().unwrap();
let resolver =
TokioAsyncResolver::new(config, ResolverOpts::default(), io_loop.handle().clone())
.expect("failed to create resolver");
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else |
}
// check if there is another connection created
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_ipv4() {
assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
} else {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
}
}
}
#[test]
fn test_cloudflare_https() {
https_test(ResolverConfig::cloudflare_https())
}
}
| {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
} | conditional_block |
htmldatalistelement.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::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods;
use dom::bindings::codegen::InheritTypes::{HTMLDataListElementDerived, HTMLOptionElementDerived};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::js::{JSRef, Rootable, Temporary};
use dom::document::Document;
use dom::element::Element;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlcollection::{HTMLCollection, CollectionFilter};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLDataListElement {
htmlelement: HTMLElement
}
impl HTMLDataListElementDerived for EventTarget {
fn is_htmldatalistelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement)))
}
}
impl HTMLDataListElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataListElement {
HTMLDataListElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLDataListElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLDataListElement> {
let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
}
}
impl<'a> HTMLDataListElementMethods for JSRef<'a, HTMLDataListElement> {
fn Options(self) -> Temporary<HTMLCollection> { | }
}
let node: JSRef<Node> = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node).root();
HTMLCollection::create(window.r(), node, filter)
}
} | #[jstraceable]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: JSRef<Element>, _root: JSRef<Node>) -> bool {
elem.is_htmloptionelement() | random_line_split |
htmldatalistelement.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::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods;
use dom::bindings::codegen::InheritTypes::{HTMLDataListElementDerived, HTMLOptionElementDerived};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::js::{JSRef, Rootable, Temporary};
use dom::document::Document;
use dom::element::Element;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlcollection::{HTMLCollection, CollectionFilter};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLDataListElement {
htmlelement: HTMLElement
}
impl HTMLDataListElementDerived for EventTarget {
fn | (&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement)))
}
}
impl HTMLDataListElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataListElement {
HTMLDataListElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLDataListElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLDataListElement> {
let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
}
}
impl<'a> HTMLDataListElementMethods for JSRef<'a, HTMLDataListElement> {
fn Options(self) -> Temporary<HTMLCollection> {
#[jstraceable]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: JSRef<Element>, _root: JSRef<Node>) -> bool {
elem.is_htmloptionelement()
}
}
let node: JSRef<Node> = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node).root();
HTMLCollection::create(window.r(), node, filter)
}
}
| is_htmldatalistelement | identifier_name |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/jleahred/...) for
//! more context information
//!
#[macro_use]
pub mod expr; |
#[cfg(test)]
mod test;
use result::*;
use rules::*;
use status::Status;
fn from_status_error_2_result_error(e: status::Error) -> Error {
Error {
pos: e.status.pos.clone(),
expected: e.expected,
line: e
.status
.text2parse
.lines()
.into_iter()
.skip(e.status.pos.row)
.take(1)
.collect(),
}
}
// --------------------------------------------------------------------------------
/// Parse a string with for a given set of rules
pub fn parse<'a, CustI>(text: &'a str, rules: &SetOfRules<CustI>) -> Result<'a> {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
}
// --------------------------------------------------------------------------------
// todo:
impl<'a> Status<'a> {
fn check_finalization(&self) -> Result<'a> {
if self.pos.n == self.text2parse.len() {
Ok(())
} else {
match &self.deeper_error {
None => Err(Error {
pos: self.pos.clone(),
expected: im::vector!["not consumed full input...".to_owned()],
line: self
.text2parse
.lines()
.into_iter()
.skip(self.pos.row)
.take(1)
.collect(),
}),
Some(e) => Err(from_status_error_2_result_error(*e.clone())),
}
}
}
} | pub mod result;
#[macro_use]
pub mod rules;
pub(crate) mod status; | random_line_split |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/jleahred/...) for
//! more context information
//!
#[macro_use]
pub mod expr;
pub mod result;
#[macro_use]
pub mod rules;
pub(crate) mod status;
#[cfg(test)]
mod test;
use result::*;
use rules::*;
use status::Status;
fn from_status_error_2_result_error(e: status::Error) -> Error {
Error {
pos: e.status.pos.clone(),
expected: e.expected,
line: e
.status
.text2parse
.lines()
.into_iter()
.skip(e.status.pos.row)
.take(1)
.collect(),
}
}
// --------------------------------------------------------------------------------
/// Parse a string with for a given set of rules
pub fn | <'a, CustI>(text: &'a str, rules: &SetOfRules<CustI>) -> Result<'a> {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
}
// --------------------------------------------------------------------------------
// todo:
impl<'a> Status<'a> {
fn check_finalization(&self) -> Result<'a> {
if self.pos.n == self.text2parse.len() {
Ok(())
} else {
match &self.deeper_error {
None => Err(Error {
pos: self.pos.clone(),
expected: im::vector!["not consumed full input...".to_owned()],
line: self
.text2parse
.lines()
.into_iter()
.skip(self.pos.row)
.take(1)
.collect(),
}),
Some(e) => Err(from_status_error_2_result_error(*e.clone())),
}
}
}
}
| parse | identifier_name |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/jleahred/...) for
//! more context information
//!
#[macro_use]
pub mod expr;
pub mod result;
#[macro_use]
pub mod rules;
pub(crate) mod status;
#[cfg(test)]
mod test;
use result::*;
use rules::*;
use status::Status;
fn from_status_error_2_result_error(e: status::Error) -> Error {
Error {
pos: e.status.pos.clone(),
expected: e.expected,
line: e
.status
.text2parse
.lines()
.into_iter()
.skip(e.status.pos.row)
.take(1)
.collect(),
}
}
// --------------------------------------------------------------------------------
/// Parse a string with for a given set of rules
pub fn parse<'a, CustI>(text: &'a str, rules: &SetOfRules<CustI>) -> Result<'a> |
// --------------------------------------------------------------------------------
// todo:
impl<'a> Status<'a> {
fn check_finalization(&self) -> Result<'a> {
if self.pos.n == self.text2parse.len() {
Ok(())
} else {
match &self.deeper_error {
None => Err(Error {
pos: self.pos.clone(),
expected: im::vector!["not consumed full input...".to_owned()],
line: self
.text2parse
.lines()
.into_iter()
.skip(self.pos.row)
.take(1)
.collect(),
}),
Some(e) => Err(from_status_error_2_result_error(*e.clone())),
}
}
}
}
| {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
} | identifier_body |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/jleahred/...) for
//! more context information
//!
#[macro_use]
pub mod expr;
pub mod result;
#[macro_use]
pub mod rules;
pub(crate) mod status;
#[cfg(test)]
mod test;
use result::*;
use rules::*;
use status::Status;
fn from_status_error_2_result_error(e: status::Error) -> Error {
Error {
pos: e.status.pos.clone(),
expected: e.expected,
line: e
.status
.text2parse
.lines()
.into_iter()
.skip(e.status.pos.row)
.take(1)
.collect(),
}
}
// --------------------------------------------------------------------------------
/// Parse a string with for a given set of rules
pub fn parse<'a, CustI>(text: &'a str, rules: &SetOfRules<CustI>) -> Result<'a> {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
}
// --------------------------------------------------------------------------------
// todo:
impl<'a> Status<'a> {
fn check_finalization(&self) -> Result<'a> {
if self.pos.n == self.text2parse.len() | else {
match &self.deeper_error {
None => Err(Error {
pos: self.pos.clone(),
expected: im::vector!["not consumed full input...".to_owned()],
line: self
.text2parse
.lines()
.into_iter()
.skip(self.pos.row)
.take(1)
.collect(),
}),
Some(e) => Err(from_status_error_2_result_error(*e.clone())),
}
}
}
}
| {
Ok(())
} | conditional_block |
fragments.rs | tcx>, tcx: &ty::ctxt<'tcx>) -> String {
let repr = |mpi| move_data.path_loan_path(mpi).repr(tcx);
match *self {
Just(mpi) => repr(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", repr(mpi)),
}
}
fn loan_path_user_string<'tcx>(&self,
move_data: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>) -> String {
let user_string = |mpi| move_data.path_loan_path(mpi).user_string(tcx);
match *self {
Just(mpi) => user_string(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", user_string(mpi)),
}
}
}
pub struct FragmentSets {
/// During move_data construction, `moved_leaf_paths` tracks paths
/// that have been used directly by being moved out of. When
/// move_data construction has been completed, `moved_leaf_paths`
/// tracks such paths that are *leaf fragments* (e.g. `a.j` if we
/// never move out any child like `a.j.x`); any parent paths
/// (e.g. `a` for the `a.j` example) are moved over to
/// `parents_of_fragments`.
moved_leaf_paths: Vec<MovePathIndex>,
/// `assigned_leaf_paths` tracks paths that have been used
/// directly by being overwritten, but is otherwise much like
/// `moved_leaf_paths`.
assigned_leaf_paths: Vec<MovePathIndex>,
/// `parents_of_fragments` tracks paths that are definitely
/// parents of paths that have been moved.
///
/// FIXME(pnkfelix) probably do not want/need
/// `parents_of_fragments` at all, if we can avoid it.
///
/// Update: I do not see a way to to avoid it. Maybe just remove
/// above fixme, or at least document why doing this may be hard.
parents_of_fragments: Vec<MovePathIndex>,
/// During move_data construction (specifically the
/// fixup_fragment_sets call), `unmoved_fragments` tracks paths
/// that have been "left behind" after a sibling has been moved or
/// assigned. When move_data construction has been completed,
/// `unmoved_fragments` tracks paths that were *only* results of
/// being left-behind, and never directly moved themselves.
unmoved_fragments: Vec<Fragment>,
}
impl FragmentSets {
pub fn new() -> FragmentSets {
FragmentSets {
unmoved_fragments: Vec::new(),
moved_leaf_paths: Vec::new(),
assigned_leaf_paths: Vec::new(),
parents_of_fragments: Vec::new(),
}
}
pub fn add_move(&mut self, path_index: MovePathIndex) {
self.moved_leaf_paths.push(path_index);
}
pub fn add_assignment(&mut self, path_index: MovePathIndex) {
self.assigned_leaf_paths.push(path_index);
}
}
pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
sp: Span,
id: ast::NodeId) {
let span_err = tcx.map.attrs(id).iter()
.any(|a| a.check_name("rustc_move_fragments"));
let print = tcx.sess.opts.debugging_opts.print_move_fragments;
if!span_err &&!print { return; }
let instrument_all_paths = |kind, vec_rc: &Vec<MovePathIndex>| {
for (i, mpi) in vec_rc.iter().enumerate() {
let render = || this.path_loan_path(*mpi).user_string(tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render()));
}
if print {
println!("id:{} {}[{}] `{}`", id, kind, i, render());
}
}
};
let instrument_all_fragments = |kind, vec_rc: &Vec<Fragment>| {
for (i, f) in vec_rc.iter().enumerate() {
let render = || f.loan_path_user_string(this, tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render()));
}
if print {
println!("id:{} {}[{}] `{}`", id, kind, i, render());
}
}
};
let fragments = this.fragments.borrow();
instrument_all_paths("moved_leaf_path", &fragments.moved_leaf_paths);
instrument_all_fragments("unmoved_fragment", &fragments.unmoved_fragments);
instrument_all_paths("parent_of_fragments", &fragments.parents_of_fragments);
instrument_all_paths("assigned_leaf_path", &fragments.assigned_leaf_paths);
}
/// Normalizes the fragment sets in `this`; i.e., removes duplicate entries, constructs the set of
/// parents, and constructs the left-over fragments.
///
/// Note: "left-over fragments" means paths that were not directly referenced in moves nor
/// assignments, but must nonetheless be tracked as potential drop obligations.
pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) {
let mut fragments = this.fragments.borrow_mut();
// Swap out contents of fragments so that we can modify the fields
// without borrowing the common fragments.
let mut unmoved = mem::replace(&mut fragments.unmoved_fragments, vec![]);
let mut parents = mem::replace(&mut fragments.parents_of_fragments, vec![]);
let mut moved = mem::replace(&mut fragments.moved_leaf_paths, vec![]);
let mut assigned = mem::replace(&mut fragments.assigned_leaf_paths, vec![]);
let path_lps = |mpis: &[MovePathIndex]| -> Vec<String> {
mpis.iter().map(|mpi| this.path_loan_path(*mpi).repr(tcx)).collect()
};
let frag_lps = |fs: &[Fragment]| -> Vec<String> {
fs.iter().map(|f| f.loan_path_repr(this, tcx)).collect()
};
// First, filter out duplicates
moved.sort();
moved.dedup();
debug!("fragments 1 moved: {:?}", path_lps(&moved[..]));
assigned.sort();
assigned.dedup();
debug!("fragments 1 assigned: {:?}", path_lps(&assigned[..]));
// Second, build parents from the moved and assigned.
for m in &moved {
let mut p = this.path_parent(*m);
while p!= InvalidMovePathIndex {
parents.push(p);
p = this.path_parent(p);
}
}
for a in &assigned {
let mut p = this.path_parent(*a);
while p!= InvalidMovePathIndex {
parents.push(p);
p = this.path_parent(p);
}
}
parents.sort();
parents.dedup();
debug!("fragments 2 parents: {:?}", path_lps(&parents[..]));
// Third, filter the moved and assigned fragments down to just the non-parents
moved.retain(|f| non_member(*f, &parents[..]));
debug!("fragments 3 moved: {:?}", path_lps(&moved[..]));
assigned.retain(|f| non_member(*f, &parents[..]));
debug!("fragments 3 assigned: {:?}", path_lps(&assigned[..]));
// Fourth, build the leftover from the moved, assigned, and parents.
for m in &moved {
let lp = this.path_loan_path(*m);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
for a in &assigned {
let lp = this.path_loan_path(*a);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
for p in &parents {
let lp = this.path_loan_path(*p);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
unmoved.sort();
unmoved.dedup();
debug!("fragments 4 unmoved: {:?}", frag_lps(&unmoved[..]));
// Fifth, filter the leftover fragments down to its core.
unmoved.retain(|f| match *f {
AllButOneFrom(_) => true,
Just(mpi) => non_member(mpi, &parents[..]) &&
non_member(mpi, &moved[..]) &&
non_member(mpi, &assigned[..])
});
debug!("fragments 5 unmoved: {:?}", frag_lps(&unmoved[..]));
// Swap contents back in.
fragments.unmoved_fragments = unmoved;
fragments.parents_of_fragments = parents;
fragments.moved_leaf_paths = moved;
fragments.assigned_leaf_paths = assigned;
return;
fn non_member(elem: MovePathIndex, set: &[MovePathIndex]) -> bool {
match set.binary_search(&elem) {
Ok(_) => false,
Err(_) => true,
}
}
}
/// Adds all of the precisely-tracked siblings of `lp` as potential move paths of interest. For
/// example, if `lp` represents `s.x.j`, then adds moves paths for `s.x.i` and `s.x.k`, the
/// siblings of `s.x.j`.
fn add_fragment_siblings<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
lp: Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>) {
match lp.kind {
LpVar(_) | LpUpvar(..) => {} // Local variables have no siblings.
// Consuming a downcast is like consuming the original value, so propage inward.
LpDowncast(ref loan_parent, _) => {
add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
}
// *LV for Unique consumes the contents of the box (at
// least when it is non-copy...), so propagate inward.
LpExtend(ref loan_parent, _, LpDeref(mc::Unique)) => {
add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
}
// *LV for unsafe and borrowed pointers do not consume their loan path, so stop here.
LpExtend(_, _, LpDeref(mc::UnsafePtr(..))) |
LpExtend(_, _, LpDeref(mc::Implicit(..))) |
LpExtend(_, _, LpDeref(mc::BorrowedPtr(..))) => {}
// FIXME (pnkfelix): LV[j] should be tracked, at least in the
// sense of we will track the remaining drop obligation of the
// rest of the array.
//
// Well, either that or LV[j] should be made illegal.
// But even then, we will need to deal with destructuring
// bind.
//
// Anyway, for now: LV[j] is not tracked precisely
LpExtend(_, _, LpInterior(InteriorElement(..))) => {
let mp = this.move_path(tcx, lp.clone());
gathered_fragments.push(AllButOneFrom(mp));
}
// field access LV.x and tuple access LV#k are the cases
// we are interested in
LpExtend(ref loan_parent, mc,
LpInterior(InteriorField(ref field_name))) => {
let enum_variant_info = match loan_parent.kind {
LpDowncast(ref loan_parent_2, variant_def_id) =>
Some((variant_def_id, loan_parent_2.clone())),
LpExtend(..) | LpVar(..) | LpUpvar(..) =>
None,
};
add_fragment_siblings_for_extension(
this,
tcx,
gathered_fragments,
loan_parent, mc, field_name, &lp, origin_id, enum_variant_info);
}
}
}
/// We have determined that `origin_lp` destructures to LpExtend(parent, original_field_name).
/// Based on this, add move paths for all of the siblings of `origin_lp`.
fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
parent_lp: &Rc<LoanPath<'tcx>>,
mc: mc::MutabilityCategory,
origin_field_name: &mc::FieldName,
origin_lp: &Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>,
enum_variant_info: Option<(ast::DefId,
Rc<LoanPath<'tcx>>)>) {
let parent_ty = parent_lp.to_type();
let mut add_fragment_sibling_local = |field_name, variant_did| {
add_fragment_sibling_core(
this, tcx, gathered_fragments, parent_lp.clone(), mc, field_name, origin_lp,
variant_did);
};
match (&parent_ty.sty, enum_variant_info) {
(&ty::ty_tup(ref v), None) => {
let tuple_idx = match *origin_field_name {
mc::PositionalField(tuple_idx) => tuple_idx,
mc::NamedField(_) =>
panic!("tuple type {} should not have named fields.",
parent_ty.repr(tcx)),
};
let tuple_len = v.len();
for i in 0..tuple_len {
if i == tuple_idx { continue }
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
(&ty::ty_struct(def_id, ref _substs), None) => {
let fields = ty::lookup_struct_fields(tcx, def_id);
match *origin_field_name {
mc::NamedField(ast_name) => {
for f in &fields {
if f.name == ast_name {
continue;
}
let field_name = mc::NamedField(f.name);
add_fragment_sibling_local(field_name, None);
}
}
mc::PositionalField(tuple_idx) => {
for (i, _f) in fields.iter().enumerate() {
if i == tuple_idx {
continue
}
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
}
}
(&ty::ty_enum(enum_def_id, substs), ref enum_variant_info) => {
let variant_info = {
let mut variants = ty::substd_enum_variants(tcx, enum_def_id, substs);
match *enum_variant_info {
Some((variant_def_id, ref _lp2)) =>
variants.iter()
.find(|variant| variant.id == variant_def_id)
.expect("enum_variant_with_id(): no variant exists with that ID")
.clone(),
None => {
assert_eq!(variants.len(), 1);
variants.pop().unwrap()
}
}
};
match *origin_field_name {
mc::NamedField(ast_name) => {
let variant_arg_names = variant_info.arg_names.as_ref().unwrap();
for variant_arg_ident in variant_arg_names {
if variant_arg_ident.name == ast_name {
continue;
}
let field_name = mc::NamedField(variant_arg_ident.name);
add_fragment_sibling_local(field_name, Some(variant_info.id));
}
}
mc::PositionalField(tuple_idx) => {
let variant_arg_types = &variant_info.args;
for (i, _variant_arg_ty) in variant_arg_types.iter().enumerate() {
if tuple_idx == i {
continue;
}
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
}
}
ref sty_and_variant_info => {
let msg = format!("type {} ({:?}) is not fragmentable",
parent_ty.repr(tcx), sty_and_variant_info);
let opt_span = origin_id.and_then(|id|tcx.map.opt_span(id));
tcx.sess.opt_span_bug(opt_span, &msg[..])
}
}
}
/// Adds the single sibling `LpExtend(parent, new_field_name)` of `origin_lp` (the original
/// loan-path).
fn add_fragment_sibling_core<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
parent: Rc<LoanPath<'tcx>>,
mc: mc::MutabilityCategory,
new_field_name: mc::FieldName,
origin_lp: &Rc<LoanPath<'tcx>>,
enum_variant_did: Option<ast::DefId>) -> MovePathIndex | {
let opt_variant_did = match parent.kind {
LpDowncast(_, variant_did) => Some(variant_did),
LpVar(..) | LpUpvar(..) | LpExtend(..) => enum_variant_did,
};
let loan_path_elem = LpInterior(InteriorField(new_field_name));
let new_lp_type = match new_field_name {
mc::NamedField(ast_name) =>
ty::named_element_ty(tcx, parent.to_type(), ast_name, opt_variant_did),
mc::PositionalField(idx) =>
ty::positional_element_ty(tcx, parent.to_type(), idx, opt_variant_did),
};
let new_lp_variant = LpExtend(parent, mc, loan_path_elem);
let new_lp = LoanPath::new(new_lp_variant, new_lp_type.unwrap());
debug!("add_fragment_sibling_core(new_lp={}, origin_lp={})",
new_lp.repr(tcx), origin_lp.repr(tcx));
let mp = this.move_path(tcx, Rc::new(new_lp));
// Do not worry about checking for duplicates here; we will sort | identifier_body |
|
fragments.rs | Eq, PartialOrd, Ord)]
enum Fragment {
// This represents the path described by the move path index
Just(MovePathIndex),
// This represents the collection of all but one of the elements
// from an array at the path described by the move path index.
// Note that attached MovePathIndex should have mem_categorization
// of InteriorElement (i.e. array dereference `&foo[..]`).
AllButOneFrom(MovePathIndex),
}
impl Fragment {
fn loan_path_repr<'tcx>(&self, move_data: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) -> String {
let repr = |mpi| move_data.path_loan_path(mpi).repr(tcx);
match *self {
Just(mpi) => repr(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", repr(mpi)),
}
}
fn loan_path_user_string<'tcx>(&self,
move_data: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>) -> String {
let user_string = |mpi| move_data.path_loan_path(mpi).user_string(tcx);
match *self {
Just(mpi) => user_string(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", user_string(mpi)),
}
}
}
pub struct FragmentSets {
/// During move_data construction, `moved_leaf_paths` tracks paths
/// that have been used directly by being moved out of. When
/// move_data construction has been completed, `moved_leaf_paths`
/// tracks such paths that are *leaf fragments* (e.g. `a.j` if we
/// never move out any child like `a.j.x`); any parent paths
/// (e.g. `a` for the `a.j` example) are moved over to
/// `parents_of_fragments`.
moved_leaf_paths: Vec<MovePathIndex>,
/// `assigned_leaf_paths` tracks paths that have been used
/// directly by being overwritten, but is otherwise much like
/// `moved_leaf_paths`.
assigned_leaf_paths: Vec<MovePathIndex>,
/// `parents_of_fragments` tracks paths that are definitely
/// parents of paths that have been moved.
///
/// FIXME(pnkfelix) probably do not want/need
/// `parents_of_fragments` at all, if we can avoid it.
///
/// Update: I do not see a way to to avoid it. Maybe just remove
/// above fixme, or at least document why doing this may be hard.
parents_of_fragments: Vec<MovePathIndex>,
/// During move_data construction (specifically the
/// fixup_fragment_sets call), `unmoved_fragments` tracks paths
/// that have been "left behind" after a sibling has been moved or
/// assigned. When move_data construction has been completed,
/// `unmoved_fragments` tracks paths that were *only* results of
/// being left-behind, and never directly moved themselves.
unmoved_fragments: Vec<Fragment>,
}
impl FragmentSets {
pub fn new() -> FragmentSets {
FragmentSets {
unmoved_fragments: Vec::new(),
moved_leaf_paths: Vec::new(),
assigned_leaf_paths: Vec::new(),
parents_of_fragments: Vec::new(),
}
}
pub fn add_move(&mut self, path_index: MovePathIndex) {
self.moved_leaf_paths.push(path_index);
}
pub fn add_assignment(&mut self, path_index: MovePathIndex) {
self.assigned_leaf_paths.push(path_index);
}
}
pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
sp: Span,
id: ast::NodeId) {
let span_err = tcx.map.attrs(id).iter()
.any(|a| a.check_name("rustc_move_fragments"));
let print = tcx.sess.opts.debugging_opts.print_move_fragments;
if!span_err &&!print { return; }
let instrument_all_paths = |kind, vec_rc: &Vec<MovePathIndex>| {
for (i, mpi) in vec_rc.iter().enumerate() {
let render = || this.path_loan_path(*mpi).user_string(tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render()));
}
if print {
println!("id:{} {}[{}] `{}`", id, kind, i, render());
}
}
};
let instrument_all_fragments = |kind, vec_rc: &Vec<Fragment>| {
for (i, f) in vec_rc.iter().enumerate() {
let render = || f.loan_path_user_string(this, tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render()));
}
if print {
println!("id:{} {}[{}] `{}`", id, kind, i, render());
}
}
};
let fragments = this.fragments.borrow();
instrument_all_paths("moved_leaf_path", &fragments.moved_leaf_paths);
instrument_all_fragments("unmoved_fragment", &fragments.unmoved_fragments);
instrument_all_paths("parent_of_fragments", &fragments.parents_of_fragments);
instrument_all_paths("assigned_leaf_path", &fragments.assigned_leaf_paths);
}
/// Normalizes the fragment sets in `this`; i.e., removes duplicate entries, constructs the set of
/// parents, and constructs the left-over fragments.
///
/// Note: "left-over fragments" means paths that were not directly referenced in moves nor
/// assignments, but must nonetheless be tracked as potential drop obligations.
pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) {
let mut fragments = this.fragments.borrow_mut();
// Swap out contents of fragments so that we can modify the fields
// without borrowing the common fragments.
let mut unmoved = mem::replace(&mut fragments.unmoved_fragments, vec![]);
let mut parents = mem::replace(&mut fragments.parents_of_fragments, vec![]);
let mut moved = mem::replace(&mut fragments.moved_leaf_paths, vec![]);
let mut assigned = mem::replace(&mut fragments.assigned_leaf_paths, vec![]);
let path_lps = |mpis: &[MovePathIndex]| -> Vec<String> {
mpis.iter().map(|mpi| this.path_loan_path(*mpi).repr(tcx)).collect()
};
let frag_lps = |fs: &[Fragment]| -> Vec<String> {
fs.iter().map(|f| f.loan_path_repr(this, tcx)).collect()
};
// First, filter out duplicates
moved.sort();
moved.dedup();
debug!("fragments 1 moved: {:?}", path_lps(&moved[..]));
assigned.sort();
assigned.dedup();
debug!("fragments 1 assigned: {:?}", path_lps(&assigned[..]));
// Second, build parents from the moved and assigned.
for m in &moved {
let mut p = this.path_parent(*m);
while p!= InvalidMovePathIndex {
parents.push(p);
p = this.path_parent(p);
}
}
for a in &assigned {
let mut p = this.path_parent(*a);
while p!= InvalidMovePathIndex {
parents.push(p);
p = this.path_parent(p);
}
}
parents.sort();
parents.dedup();
debug!("fragments 2 parents: {:?}", path_lps(&parents[..]));
// Third, filter the moved and assigned fragments down to just the non-parents
moved.retain(|f| non_member(*f, &parents[..]));
debug!("fragments 3 moved: {:?}", path_lps(&moved[..]));
assigned.retain(|f| non_member(*f, &parents[..]));
debug!("fragments 3 assigned: {:?}", path_lps(&assigned[..]));
// Fourth, build the leftover from the moved, assigned, and parents.
for m in &moved {
let lp = this.path_loan_path(*m);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
for a in &assigned {
let lp = this.path_loan_path(*a);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
for p in &parents {
let lp = this.path_loan_path(*p);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
unmoved.sort();
unmoved.dedup();
debug!("fragments 4 unmoved: {:?}", frag_lps(&unmoved[..]));
// Fifth, filter the leftover fragments down to its core.
unmoved.retain(|f| match *f {
AllButOneFrom(_) => true,
Just(mpi) => non_member(mpi, &parents[..]) &&
non_member(mpi, &moved[..]) &&
non_member(mpi, &assigned[..])
});
debug!("fragments 5 unmoved: {:?}", frag_lps(&unmoved[..]));
// Swap contents back in.
fragments.unmoved_fragments = unmoved;
fragments.parents_of_fragments = parents;
fragments.moved_leaf_paths = moved;
fragments.assigned_leaf_paths = assigned;
return;
fn non_member(elem: MovePathIndex, set: &[MovePathIndex]) -> bool {
match set.binary_search(&elem) {
Ok(_) => false,
Err(_) => true,
}
}
}
/// Adds all of the precisely-tracked siblings of `lp` as potential move paths of interest. For
/// example, if `lp` represents `s.x.j`, then adds moves paths for `s.x.i` and `s.x.k`, the
/// siblings of `s.x.j`.
fn add_fragment_siblings<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
lp: Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>) {
match lp.kind {
LpVar(_) | LpUpvar(..) => {} // Local variables have no siblings.
// Consuming a downcast is like consuming the original value, so propage inward.
LpDowncast(ref loan_parent, _) => {
add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
}
// *LV for Unique consumes the contents of the box (at
// least when it is non-copy...), so propagate inward.
LpExtend(ref loan_parent, _, LpDeref(mc::Unique)) => {
add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
}
// *LV for unsafe and borrowed pointers do not consume their loan path, so stop here.
LpExtend(_, _, LpDeref(mc::UnsafePtr(..))) |
LpExtend(_, _, LpDeref(mc::Implicit(..))) |
LpExtend(_, _, LpDeref(mc::BorrowedPtr(..))) => {}
// FIXME (pnkfelix): LV[j] should be tracked, at least in the
// sense of we will track the remaining drop obligation of the
// rest of the array.
//
// Well, either that or LV[j] should be made illegal.
// But even then, we will need to deal with destructuring
// bind.
//
// Anyway, for now: LV[j] is not tracked precisely
LpExtend(_, _, LpInterior(InteriorElement(..))) => {
let mp = this.move_path(tcx, lp.clone());
gathered_fragments.push(AllButOneFrom(mp));
}
// field access LV.x and tuple access LV#k are the cases
// we are interested in
LpExtend(ref loan_parent, mc,
LpInterior(InteriorField(ref field_name))) => {
let enum_variant_info = match loan_parent.kind {
LpDowncast(ref loan_parent_2, variant_def_id) =>
Some((variant_def_id, loan_parent_2.clone())),
LpExtend(..) | LpVar(..) | LpUpvar(..) =>
None,
};
add_fragment_siblings_for_extension(
this,
tcx,
gathered_fragments,
loan_parent, mc, field_name, &lp, origin_id, enum_variant_info);
}
}
}
/// We have determined that `origin_lp` destructures to LpExtend(parent, original_field_name).
/// Based on this, add move paths for all of the siblings of `origin_lp`.
fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
parent_lp: &Rc<LoanPath<'tcx>>,
mc: mc::MutabilityCategory,
origin_field_name: &mc::FieldName,
origin_lp: &Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>,
enum_variant_info: Option<(ast::DefId,
Rc<LoanPath<'tcx>>)>) {
let parent_ty = parent_lp.to_type();
let mut add_fragment_sibling_local = |field_name, variant_did| {
add_fragment_sibling_core(
this, tcx, gathered_fragments, parent_lp.clone(), mc, field_name, origin_lp,
variant_did);
};
match (&parent_ty.sty, enum_variant_info) {
(&ty::ty_tup(ref v), None) => {
let tuple_idx = match *origin_field_name {
mc::PositionalField(tuple_idx) => tuple_idx,
mc::NamedField(_) =>
panic!("tuple type {} should not have named fields.",
parent_ty.repr(tcx)),
};
let tuple_len = v.len();
for i in 0..tuple_len {
if i == tuple_idx { continue }
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
(&ty::ty_struct(def_id, ref _substs), None) => {
let fields = ty::lookup_struct_fields(tcx, def_id);
match *origin_field_name {
mc::NamedField(ast_name) => {
for f in &fields {
if f.name == ast_name {
continue;
}
let field_name = mc::NamedField(f.name);
add_fragment_sibling_local(field_name, None);
}
}
mc::PositionalField(tuple_idx) => {
for (i, _f) in fields.iter().enumerate() {
if i == tuple_idx {
continue
}
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
}
}
(&ty::ty_enum(enum_def_id, substs), ref enum_variant_info) => {
let variant_info = {
let mut variants = ty::substd_enum_variants(tcx, enum_def_id, substs);
match *enum_variant_info {
Some((variant_def_id, ref _lp2)) =>
variants.iter()
.find(|variant| variant.id == variant_def_id)
.expect("enum_variant_with_id(): no variant exists with that ID")
.clone(),
None => {
assert_eq!(variants.len(), 1);
variants.pop().unwrap()
}
}
};
match *origin_field_name {
mc::NamedField(ast_name) => {
let variant_arg_names = variant_info.arg_names.as_ref().unwrap();
for variant_arg_ident in variant_arg_names {
if variant_arg_ident.name == ast_name {
continue;
}
let field_name = mc::NamedField(variant_arg_ident.name);
add_fragment_sibling_local(field_name, Some(variant_info.id));
}
}
mc::PositionalField(tuple_idx) => {
let variant_arg_types = &variant_info.args;
for (i, _variant_arg_ty) in variant_arg_types.iter().enumerate() {
if tuple_idx == i {
continue;
}
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
}
}
ref sty_and_variant_info => {
let msg = format!("type {} ({:?}) is not fragmentable",
parent_ty.repr(tcx), sty_and_variant_info);
let opt_span = origin_id.and_then(|id|tcx.map.opt_span(id));
tcx.sess.opt_span_bug(opt_span, &msg[..])
}
}
}
/// Adds the single sibling `LpExtend(parent, new_field_name)` of `origin_lp` (the original
/// loan-path).
fn add_fragment_sibling_core<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
parent: Rc<LoanPath<'tcx>>,
mc: mc::MutabilityCategory,
new_field_name: mc::FieldName,
origin_lp: &Rc<LoanPath<'tcx>>,
enum_variant_did: Option<ast::DefId>) -> MovePathIndex {
let opt_variant_did = match parent.kind {
LpDowncast(_, variant_did) => Some(variant_did),
LpVar(..) | LpUpvar(..) | LpExtend(..) => enum_variant_did,
};
let loan_path_elem = LpInterior(InteriorField(new_field_name));
let new_lp_type = match new_field_name { | mc::NamedField(ast_name) =>
ty::named_element_ty(tcx, parent.to_type(), ast_name, opt_variant_did),
mc::PositionalField(idx) =>
ty::positional_element_ty(tcx, parent.to_type(), idx, opt_variant_did), | random_line_split |
|
fragments.rs | .md`.
use self::Fragment::*;
use borrowck::InteriorKind::{InteriorField, InteriorElement};
use borrowck::LoanPath;
use borrowck::LoanPathKind::{LpVar, LpUpvar, LpDowncast, LpExtend};
use borrowck::LoanPathElem::{LpDeref, LpInterior};
use borrowck::move_data::InvalidMovePathIndex;
use borrowck::move_data::{MoveData, MovePathIndex};
use rustc::middle::ty;
use rustc::middle::mem_categorization as mc;
use rustc::util::ppaux::{Repr, UserString};
use std::mem;
use std::rc::Rc;
use syntax::ast;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Fragment {
// This represents the path described by the move path index
Just(MovePathIndex),
// This represents the collection of all but one of the elements
// from an array at the path described by the move path index.
// Note that attached MovePathIndex should have mem_categorization
// of InteriorElement (i.e. array dereference `&foo[..]`).
AllButOneFrom(MovePathIndex),
}
impl Fragment {
fn loan_path_repr<'tcx>(&self, move_data: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) -> String {
let repr = |mpi| move_data.path_loan_path(mpi).repr(tcx);
match *self {
Just(mpi) => repr(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", repr(mpi)),
}
}
fn loan_path_user_string<'tcx>(&self,
move_data: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>) -> String {
let user_string = |mpi| move_data.path_loan_path(mpi).user_string(tcx);
match *self {
Just(mpi) => user_string(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", user_string(mpi)),
}
}
}
pub struct FragmentSets {
/// During move_data construction, `moved_leaf_paths` tracks paths
/// that have been used directly by being moved out of. When
/// move_data construction has been completed, `moved_leaf_paths`
/// tracks such paths that are *leaf fragments* (e.g. `a.j` if we
/// never move out any child like `a.j.x`); any parent paths
/// (e.g. `a` for the `a.j` example) are moved over to
/// `parents_of_fragments`.
moved_leaf_paths: Vec<MovePathIndex>,
/// `assigned_leaf_paths` tracks paths that have been used
/// directly by being overwritten, but is otherwise much like
/// `moved_leaf_paths`.
assigned_leaf_paths: Vec<MovePathIndex>,
/// `parents_of_fragments` tracks paths that are definitely
/// parents of paths that have been moved.
///
/// FIXME(pnkfelix) probably do not want/need
/// `parents_of_fragments` at all, if we can avoid it.
///
/// Update: I do not see a way to to avoid it. Maybe just remove
/// above fixme, or at least document why doing this may be hard.
parents_of_fragments: Vec<MovePathIndex>,
/// During move_data construction (specifically the
/// fixup_fragment_sets call), `unmoved_fragments` tracks paths
/// that have been "left behind" after a sibling has been moved or
/// assigned. When move_data construction has been completed,
/// `unmoved_fragments` tracks paths that were *only* results of
/// being left-behind, and never directly moved themselves.
unmoved_fragments: Vec<Fragment>,
}
impl FragmentSets {
pub fn new() -> FragmentSets {
FragmentSets {
unmoved_fragments: Vec::new(),
moved_leaf_paths: Vec::new(),
assigned_leaf_paths: Vec::new(),
parents_of_fragments: Vec::new(),
}
}
pub fn add_move(&mut self, path_index: MovePathIndex) {
self.moved_leaf_paths.push(path_index);
}
pub fn add_assignment(&mut self, path_index: MovePathIndex) {
self.assigned_leaf_paths.push(path_index);
}
}
pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
sp: Span,
id: ast::NodeId) {
let span_err = tcx.map.attrs(id).iter()
.any(|a| a.check_name("rustc_move_fragments"));
let print = tcx.sess.opts.debugging_opts.print_move_fragments;
if!span_err &&!print { return; }
let instrument_all_paths = |kind, vec_rc: &Vec<MovePathIndex>| {
for (i, mpi) in vec_rc.iter().enumerate() {
let render = || this.path_loan_path(*mpi).user_string(tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render()));
}
if print {
println!("id:{} {}[{}] `{}`", id, kind, i, render());
}
}
};
let instrument_all_fragments = |kind, vec_rc: &Vec<Fragment>| {
for (i, f) in vec_rc.iter().enumerate() {
let render = || f.loan_path_user_string(this, tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render()));
}
if print {
println!("id:{} {}[{}] `{}`", id, kind, i, render());
}
}
};
let fragments = this.fragments.borrow();
instrument_all_paths("moved_leaf_path", &fragments.moved_leaf_paths);
instrument_all_fragments("unmoved_fragment", &fragments.unmoved_fragments);
instrument_all_paths("parent_of_fragments", &fragments.parents_of_fragments);
instrument_all_paths("assigned_leaf_path", &fragments.assigned_leaf_paths);
}
/// Normalizes the fragment sets in `this`; i.e., removes duplicate entries, constructs the set of
/// parents, and constructs the left-over fragments.
///
/// Note: "left-over fragments" means paths that were not directly referenced in moves nor
/// assignments, but must nonetheless be tracked as potential drop obligations.
pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) {
let mut fragments = this.fragments.borrow_mut();
// Swap out contents of fragments so that we can modify the fields
// without borrowing the common fragments.
let mut unmoved = mem::replace(&mut fragments.unmoved_fragments, vec![]);
let mut parents = mem::replace(&mut fragments.parents_of_fragments, vec![]);
let mut moved = mem::replace(&mut fragments.moved_leaf_paths, vec![]);
let mut assigned = mem::replace(&mut fragments.assigned_leaf_paths, vec![]);
let path_lps = |mpis: &[MovePathIndex]| -> Vec<String> {
mpis.iter().map(|mpi| this.path_loan_path(*mpi).repr(tcx)).collect()
};
let frag_lps = |fs: &[Fragment]| -> Vec<String> {
fs.iter().map(|f| f.loan_path_repr(this, tcx)).collect()
};
// First, filter out duplicates
moved.sort();
moved.dedup();
debug!("fragments 1 moved: {:?}", path_lps(&moved[..]));
assigned.sort();
assigned.dedup();
debug!("fragments 1 assigned: {:?}", path_lps(&assigned[..]));
// Second, build parents from the moved and assigned.
for m in &moved {
let mut p = this.path_parent(*m);
while p!= InvalidMovePathIndex {
parents.push(p);
p = this.path_parent(p);
}
}
for a in &assigned {
let mut p = this.path_parent(*a);
while p!= InvalidMovePathIndex {
parents.push(p);
p = this.path_parent(p);
}
}
parents.sort();
parents.dedup();
debug!("fragments 2 parents: {:?}", path_lps(&parents[..]));
// Third, filter the moved and assigned fragments down to just the non-parents
moved.retain(|f| non_member(*f, &parents[..]));
debug!("fragments 3 moved: {:?}", path_lps(&moved[..]));
assigned.retain(|f| non_member(*f, &parents[..]));
debug!("fragments 3 assigned: {:?}", path_lps(&assigned[..]));
// Fourth, build the leftover from the moved, assigned, and parents.
for m in &moved {
let lp = this.path_loan_path(*m);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
for a in &assigned {
let lp = this.path_loan_path(*a);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
for p in &parents {
let lp = this.path_loan_path(*p);
add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
}
unmoved.sort();
unmoved.dedup();
debug!("fragments 4 unmoved: {:?}", frag_lps(&unmoved[..]));
// Fifth, filter the leftover fragments down to its core.
unmoved.retain(|f| match *f {
AllButOneFrom(_) => true,
Just(mpi) => non_member(mpi, &parents[..]) &&
non_member(mpi, &moved[..]) &&
non_member(mpi, &assigned[..])
});
debug!("fragments 5 unmoved: {:?}", frag_lps(&unmoved[..]));
// Swap contents back in.
fragments.unmoved_fragments = unmoved;
fragments.parents_of_fragments = parents;
fragments.moved_leaf_paths = moved;
fragments.assigned_leaf_paths = assigned;
return;
fn non_member(elem: MovePathIndex, set: &[MovePathIndex]) -> bool {
match set.binary_search(&elem) {
Ok(_) => false,
Err(_) => true,
}
}
}
/// Adds all of the precisely-tracked siblings of `lp` as potential move paths of interest. For
/// example, if `lp` represents `s.x.j`, then adds moves paths for `s.x.i` and `s.x.k`, the
/// siblings of `s.x.j`.
fn | <'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
lp: Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>) {
match lp.kind {
LpVar(_) | LpUpvar(..) => {} // Local variables have no siblings.
// Consuming a downcast is like consuming the original value, so propage inward.
LpDowncast(ref loan_parent, _) => {
add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
}
// *LV for Unique consumes the contents of the box (at
// least when it is non-copy...), so propagate inward.
LpExtend(ref loan_parent, _, LpDeref(mc::Unique)) => {
add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
}
// *LV for unsafe and borrowed pointers do not consume their loan path, so stop here.
LpExtend(_, _, LpDeref(mc::UnsafePtr(..))) |
LpExtend(_, _, LpDeref(mc::Implicit(..))) |
LpExtend(_, _, LpDeref(mc::BorrowedPtr(..))) => {}
// FIXME (pnkfelix): LV[j] should be tracked, at least in the
// sense of we will track the remaining drop obligation of the
// rest of the array.
//
// Well, either that or LV[j] should be made illegal.
// But even then, we will need to deal with destructuring
// bind.
//
// Anyway, for now: LV[j] is not tracked precisely
LpExtend(_, _, LpInterior(InteriorElement(..))) => {
let mp = this.move_path(tcx, lp.clone());
gathered_fragments.push(AllButOneFrom(mp));
}
// field access LV.x and tuple access LV#k are the cases
// we are interested in
LpExtend(ref loan_parent, mc,
LpInterior(InteriorField(ref field_name))) => {
let enum_variant_info = match loan_parent.kind {
LpDowncast(ref loan_parent_2, variant_def_id) =>
Some((variant_def_id, loan_parent_2.clone())),
LpExtend(..) | LpVar(..) | LpUpvar(..) =>
None,
};
add_fragment_siblings_for_extension(
this,
tcx,
gathered_fragments,
loan_parent, mc, field_name, &lp, origin_id, enum_variant_info);
}
}
}
/// We have determined that `origin_lp` destructures to LpExtend(parent, original_field_name).
/// Based on this, add move paths for all of the siblings of `origin_lp`.
fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
parent_lp: &Rc<LoanPath<'tcx>>,
mc: mc::MutabilityCategory,
origin_field_name: &mc::FieldName,
origin_lp: &Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>,
enum_variant_info: Option<(ast::DefId,
Rc<LoanPath<'tcx>>)>) {
let parent_ty = parent_lp.to_type();
let mut add_fragment_sibling_local = |field_name, variant_did| {
add_fragment_sibling_core(
this, tcx, gathered_fragments, parent_lp.clone(), mc, field_name, origin_lp,
variant_did);
};
match (&parent_ty.sty, enum_variant_info) {
(&ty::ty_tup(ref v), None) => {
let tuple_idx = match *origin_field_name {
mc::PositionalField(tuple_idx) => tuple_idx,
mc::NamedField(_) =>
panic!("tuple type {} should not have named fields.",
parent_ty.repr(tcx)),
};
let tuple_len = v.len();
for i in 0..tuple_len {
if i == tuple_idx { continue }
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
(&ty::ty_struct(def_id, ref _substs), None) => {
let fields = ty::lookup_struct_fields(tcx, def_id);
match *origin_field_name {
mc::NamedField(ast_name) => {
for f in &fields {
if f.name == ast_name {
continue;
}
let field_name = mc::NamedField(f.name);
add_fragment_sibling_local(field_name, None);
}
}
mc::PositionalField(tuple_idx) => {
for (i, _f) in fields.iter().enumerate() {
if i == tuple_idx {
continue
}
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
}
}
(&ty::ty_enum(enum_def_id, substs), ref enum_variant_info) => {
let variant_info = {
let mut variants = ty::substd_enum_variants(tcx, enum_def_id, substs);
match *enum_variant_info {
Some((variant_def_id, ref _lp2)) =>
variants.iter()
.find(|variant| variant.id == variant_def_id)
.expect("enum_variant_with_id(): no variant exists with that ID")
.clone(),
None => {
assert_eq!(variants.len(), 1);
variants.pop().unwrap()
}
}
};
match *origin_field_name {
mc::NamedField(ast_name) => {
let variant_arg_names = variant_info.arg_names.as_ref().unwrap();
for variant_arg_ident in variant_arg_names {
if variant_arg_ident.name == ast_name {
continue;
}
let field_name = mc::NamedField(variant_arg_ident.name);
add_fragment_sibling_local(field_name, Some(variant_info.id));
}
}
mc::PositionalField(tuple_idx) => {
let variant_arg_types = &variant_info.args;
for (i, _variant_arg_ty) in variant_arg_types.iter().enumerate() {
if tuple_idx == i {
continue;
}
let field_name = mc::PositionalField(i);
add_fragment_sibling_local(field_name, None);
}
}
}
}
ref sty_and_variant_info => {
let msg = format!("type {} ({:?}) is not fragmentable",
parent_ty.repr(tcx), sty_and_variant_info);
let opt_span = origin_id.and_then(|id|tcx.map.opt_span(id));
tcx.sess.opt_span_bug(opt_span, &msg[..])
}
}
}
/// Adds the single sibling `LpExtend(parent, new_field_name)` of `origin_lp` (the original
/// loan-path).
fn add_fragment_sibling_core<'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
parent: Rc<LoanPath<'tcx>>,
mc: mc::MutabilityCategory,
new_field_name: mc::FieldName,
origin_lp: &Rc<LoanPath<'tcx>>,
enum_variant_did: Option<ast::DefId>) -> MovePathIndex {
let opt_variant_did = match parent.kind {
LpDowncast(_, variant_did) => Some(variant | add_fragment_siblings | identifier_name |
rtnl.rs | impl_var!(
/// Internet address families
Af, libc::c_uchar,
Inet => libc::AF_INET as libc::c_uchar,
Inet6 => libc::AF_INET6 as libc::c_uchar
);
impl_var!(
/// General address families for sockets
RtAddrFamily, u8,
Unspecified => libc::AF_UNSPEC as u8,
UnixOrLocal => libc::AF_UNIX as u8,
Inet => libc::AF_INET as u8,
Inet6 => libc::AF_INET6 as u8,
Ipx => libc::AF_IPX as u8,
Netlink => libc::AF_NETLINK as u8,
X25 => libc::AF_X25 as u8,
Ax25 => libc::AF_AX25 as u8,
Atmpvc => libc::AF_ATMPVC as u8,
Appletalk => libc::AF_APPLETALK as u8,
Packet => libc::AF_PACKET as u8,
Alg => libc::AF_ALG as u8
);
impl_var!(
/// Interface address flags
IfaF, u32,
Secondary => libc::IFA_F_SECONDARY,
Temporary => libc::IFA_F_TEMPORARY,
Nodad => libc::IFA_F_NODAD,
Optimistic => libc::IFA_F_OPTIMISTIC,
Dadfailed => libc::IFA_F_DADFAILED,
Homeaddress => libc::IFA_F_HOMEADDRESS,
Deprecated => libc::IFA_F_DEPRECATED,
Tentative => libc::IFA_F_TENTATIVE,
Permanent => libc::IFA_F_PERMANENT,
#[cfg(target_env="gnu")]
Managetempaddr => libc::IFA_F_MANAGETEMPADDR,
#[cfg(target_env="gnu")]
Noprefixroute => libc::IFA_F_NOPREFIXROUTE,
#[cfg(target_env="gnu")]
Mcautojoin => libc::IFA_F_MCAUTOJOIN,
#[cfg(target_env="gnu")]
StablePrivacy => libc::IFA_F_STABLE_PRIVACY
);
impl_var!(
/// `rtm_type`
/// The results of a lookup from a route table
Rtn, libc::c_uchar,
Unspec => libc::RTN_UNSPEC,
Unicast => libc::RTN_UNICAST,
Local => libc::RTN_LOCAL,
Broadcast => libc::RTN_BROADCAST,
Anycast => libc::RTN_ANYCAST,
Multicast => libc::RTN_MULTICAST,
Blackhole => libc::RTN_BLACKHOLE,
Unreachable => libc::RTN_UNREACHABLE,
Prohibit => libc::RTN_PROHIBIT,
Throw => libc::RTN_THROW,
Nat => libc::RTN_NAT,
Xresolve => libc::RTN_XRESOLVE
);
impl_var!(
/// `rtm_protocol`
/// The origins of routes that are defined in the kernel
Rtprot, libc::c_uchar,
Unspec => libc::RTPROT_UNSPEC,
Redirect => libc::RTPROT_REDIRECT,
Kernel => libc::RTPROT_KERNEL,
Boot => libc::RTPROT_BOOT,
Static => libc::RTPROT_STATIC
);
impl_var!(
/// `rtm_scope`
/// The distance between destinations
RtScope, libc::c_uchar,
Universe => libc::RT_SCOPE_UNIVERSE,
Site => libc::RT_SCOPE_SITE,
Link => libc::RT_SCOPE_LINK,
Host => libc::RT_SCOPE_HOST,
Nowhere => libc::RT_SCOPE_NOWHERE
);
impl_var!(
/// `rt_class_t`
/// Reserved route table identifiers
RtTable, libc::c_uchar,
Unspec => libc::RT_TABLE_UNSPEC,
Compat => libc::RT_TABLE_COMPAT,
Default => libc::RT_TABLE_DEFAULT,
Main => libc::RT_TABLE_MAIN,
Local => libc::RT_TABLE_LOCAL
);
impl_var!(
/// `rtm_flags`
/// Flags for rtnetlink messages
RtmF, libc::c_uint,
Notify => libc::RTM_F_NOTIFY,
Cloned => libc::RTM_F_CLONED,
Equalize => libc::RTM_F_EQUALIZE,
Prefix => libc::RTM_F_PREFIX,
#[cfg(target_env="gnu")]
LookupTable => libc::RTM_F_LOOKUP_TABLE,
#[cfg(target_env="gnu")]
FibMatch => libc::RTM_F_FIB_MATCH
);
impl_var!(
/// Arp neighbor cache entry states
Nud, u16,
None => libc::NUD_NONE,
Incomplete => libc::NUD_INCOMPLETE,
Reachable => libc::NUD_REACHABLE,
Stale => libc::NUD_STALE,
Delay => libc::NUD_DELAY,
Probe => libc::NUD_PROBE,
Failed => libc::NUD_FAILED,
Noarp => libc::NUD_NOARP,
Permanent => libc::NUD_PERMANENT
);
impl_var!(
/// Arp neighbor cache entry flags
Ntf, u8,
Use => libc::NTF_USE,
Self_ => libc::NTF_SELF,
Master => libc::NTF_MASTER,
Proxy => libc::NTF_PROXY,
#[cfg(target_env="gnu")]
ExtLearned => libc::NTF_EXT_LEARNED,
#[cfg(target_env="gnu")]
Offloaded => libc::NTF_OFFLOADED,
Router => libc::NTF_ROUTER
);
impl_trait!(
/// Marker trait for `Rtattr.rta_type` field
RtaType,
libc::c_ushort
);
impl_var_trait!(
/// Enum for use with `Rtattr.rta_type`.
/// Values are interface information message attributes. Used with `Ifinfomsg`.
Ifla, libc::c_ushort, RtaType,
Unspec => libc::IFLA_UNSPEC,
Address => libc::IFLA_ADDRESS,
Broadcast => libc::IFLA_BROADCAST,
Ifname => libc::IFLA_IFNAME,
Mtu => libc::IFLA_MTU, | Priority => libc::IFLA_PRIORITY,
Master => libc::IFLA_MASTER,
Wireless => libc::IFLA_WIRELESS,
Protinfo => libc::IFLA_PROTINFO,
Txqlen => libc::IFLA_TXQLEN,
Map => libc::IFLA_MAP,
Weight => libc::IFLA_WEIGHT,
Operstate => libc::IFLA_OPERSTATE,
Linkmode => libc::IFLA_LINKMODE,
Linkinfo => libc::IFLA_LINKINFO,
NetNsPid => libc::IFLA_NET_NS_PID,
Ifalias => libc::IFLA_IFALIAS,
NumVf => libc::IFLA_NUM_VF,
VfinfoList => libc::IFLA_VFINFO_LIST,
Stats64 => libc::IFLA_STATS64,
VfPorts => libc::IFLA_VF_PORTS,
PortSelf => libc::IFLA_PORT_SELF,
AfSpec => libc::IFLA_AF_SPEC,
Group => libc::IFLA_GROUP,
NetNsFd => libc::IFLA_NET_NS_FD,
ExtMask => libc::IFLA_EXT_MASK,
Promiscuity => libc::IFLA_PROMISCUITY,
NumTxQueues => libc::IFLA_NUM_TX_QUEUES,
NumRxQueues => libc::IFLA_NUM_RX_QUEUES,
Carrier => libc::IFLA_CARRIER,
PhysPortId => libc::IFLA_PHYS_PORT_ID,
CarrierChanges => libc::IFLA_CARRIER_CHANGES,
PhysSwitchId => libc::IFLA_PHYS_SWITCH_ID,
LinkNetnsid => libc::IFLA_LINK_NETNSID,
PhysPortName => libc::IFLA_PHYS_PORT_NAME,
ProtoDown => libc::IFLA_PROTO_DOWN
);
impl_trait!(
/// Marker trait for `Rtattr.rta_type` field
IflaInfoType,
libc::c_ushort
);
impl_var_trait!(
/// Enum for use with `Rtattr.rta_type`.
/// Values are nested attributes to IFLA_LINKMODE.
IflaInfo, libc::c_ushort, IflaInfoType,
Unspec => libc::IFLA_INFO_UNSPEC,
Kind => libc::IFLA_INFO_KIND,
Data => libc::IFLA_INFO_DATA,
Xstats => libc::IFLA_INFO_XSTATS,
SlaveKind => libc::IFLA_INFO_SLAVE_KIND,
SlaveData => libc::IFLA_INFO_SLAVE_DATA
);
impl_var_trait!(
/// Enum for use with `Rtattr.rta_type`.
/// Values are interface address message attributes. Used with `Ifaddrmsg`.
Ifa, libc::c_ushort, RtaType,
Unspec => libc::IFA_UNSPEC,
Address => libc::IFA_ADDRESS,
Local => libc::IFA_LOCAL,
Label => libc::IFA_LABEL,
Broadcast => libc::IFA_BROADCAST,
Anycast => libc::IFA_ANYCAST,
Cacheinfo => libc::IFA_CACHEINFO,
Multicast => libc::IFA_MULTICAST,
#[cfg(target_env="gnu")]
Flags => libc::IFA_FLAGS
);
impl_var_trait!(
/// Enum for use with `Rtattr.rta_type`.
/// Values are routing message attributes. Used with `Rtmsg`.
Rta, libc::c_ushort, RtaType,
Unspec => libc::RTA_UNSPEC,
Dst => libc::RTA_DST,
Src => libc::RTA_SRC,
Iif => libc::RTA_IIF,
Oif => libc::RTA_OIF,
Gateway => libc::RTA_GATEWAY,
Priority => libc::RTA_PRIORITY,
Prefsrc => libc::RTA_PREFSRC,
Metrics => libc::RTA_METRICS,
Multipath => libc::RTA_MULTIPATH,
Protoinfo => libc::RTA_PROTOINFO, // no longer used in Linux
Flow => libc::RTA_FLOW,
Cacheinfo => libc::RTA_CACHEINFO,
Session => libc::RTA_SESSION, // no longer used in Linux
MpAlgo => libc::RTA_MP_ALGO, // no longer used in Linux
Table => libc::RTA_TABLE,
Mark => libc::RTA_MARK,
MfcStats => libc::RTA_MFC_STATS,
#[cfg(target_env="gnu")]
Via => libc::RTA_VIA,
#[cfg(target_env="gnu")]
Newdst => libc::RTA_NEWDST,
#[cfg(target_env="gnu")]
Pref => libc::RTA_PREF,
#[cfg(target_env="gnu")]
EncapType => libc::RTA_ENCAP_TYPE,
#[cfg(target_env="gnu")]
Encap => libc::RTA_ENCAP,
#[cfg(target_env="gnu")]
Expires => libc::RTA_EXPIRES,
#[cfg(target_env="gnu")]
Pad => libc::RTA_PAD,
#[cfg(target_env="gnu")]
Uid => libc::RTA_UID,
#[cfg(target_env="gnu")]
TtlPropagate => libc::RTA_TTL_PROPAGATE
);
impl_var_trait!(
/// Enum for use with `Rtattr.rta_type` -
/// Values specify queuing discipline attributes. Used with `Tcmsg`.
Tca, libc::c_ushort, RtaType,
Unspec => libc::TCA_UNSPEC,
Kind => libc::TCA_KIND,
Options => libc::TCA_OPTIONS,
Stats => libc::TCA_STATS,
Xstats => libc::TCA_XSTATS,
Rate => libc::TCA_RATE,
Fcnt => libc::TCA_FCNT,
Stats2 => libc::TCA_STATS2,
Stab => libc::TCA_STAB
);
impl_var_trait!(
/// Enum for use with `Rtattr.rta_type` -
/// Values specify neighbor table attributes
Nda, libc::c_ushort, RtaType,
Unspec => libc::NDA_UNSPEC,
Dst => libc::NDA_DST,
Lladdr => libc::NDA_LLADDR,
Cacheinfo => libc::NDA_CACHEINFO,
Probes => libc::NDA_PROBES,
Vlan => libc::NDA_VLAN,
Port => libc::NDA_PORT,
Vni => libc::NDA_VNI,
Ifindex => libc::NDA_IFINDEX,
#[cfg(target_env="gnu")]
Master => libc::NDA_MASTER,
#[cfg(target_env="gnu")]
LinkNetnsid => libc::NDA_LINK_NETNSID,
#[cfg(target_env="gnu")]
SrcVni => libc::NDA_SRC_VNI
);
impl_var!(
/// Interface types
Arphrd, libc::c_ushort,
Netrom => libc::ARPHRD_NETROM,
Ether => libc::ARPHRD_ETHER,
Eether => libc::ARPHRD_EETHER,
AX25 => libc::ARPHRD_AX25,
Pronet => libc::ARPHRD_PRONET,
Chaos => libc::ARPHRD_CHAOS,
Ieee802 => libc::ARPHRD_IEEE802,
Arcnet => libc::ARPHRD_ARCNET,
Appletlk => libc::ARPHRD_APPLETLK,
Dlci => libc::ARPHRD_DLCI,
Atm => libc::ARPHRD_APPLETLK,
Metricom => libc::ARPHRD_METRICOM,
Ieee1394 => libc::ARPHRD_IEEE1394,
Eui64 => libc::ARPHRD_EUI64,
Infiniband => libc::ARPHRD_INFINIBAND,
// Possibly more types here - need to look into ARP more
Void => libc::ARPHRD_VOID,
None => libc::ARPHRD_NONE
);
impl_var!(
/// Values for `ifi_flags` in `Ifinfomsg`
Iff, libc::c_uint,
Up => libc::IFF_UP as libc::c_uint,
Broadcast => libc::IFF_BROADCAST as libc::c_uint,
Debug => libc::IFF_DEBUG as libc::c_uint,
Loopback => libc::IFF_LOOPBACK as libc::c_uint,
Pointopoint => libc::IFF_POINTOPOINT as libc::c_uint,
Running => libc::IFF_RUNNING as libc::c_uint,
Noarp => libc::IFF_NOARP as libc::c_uint,
Promisc => libc::IFF_PROMISC as libc::c_uint,
Notrailers => libc::IFF_NOTRAILERS as libc::c_uint,
Allmulti => libc::IFF_ALLMULTI as libc::c_uint,
Master => libc::IFF_MASTER as libc::c_uint,
Slave => libc::IFF_SLAVE as libc::c_uint,
Multicast => libc::IFF_MULTICAST as libc::c_uint,
Portsel => libc::IFF_PORTSEL as libc::c_uint,
Automedia => libc::IFF_AUTOMEDIA as libc::c_uint,
Dynamic => libc::IFF_DYNAMIC as libc::c_uint,
LowerUp => libc::IFF_LOWER_UP as libc::c_uint,
Dormant => libc::IFF_DORMANT as libc::c_uint,
Echo => libc::IFF_ECHO as libc::c_uint
// Possibly more types here - need to look into private flags for interfaces
); | Link => libc::IFLA_LINK,
Qdisc => libc::IFLA_QDISC,
Stats => libc::IFLA_STATS,
Cost => libc::IFLA_COST, | random_line_split |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env: HashMap<String, Option<CString>>,
cwd: Path,
}
impl Show for ProcessBuilder {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!(write!(f, "`{}", String::from_utf8_lossy(self.program.as_bytes_no_nul())));
for arg in self.args.iter() {
try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes_no_nul())));
}
write!(f, "`")
}
}
impl ProcessBuilder {
pub fn arg<T: ToCStr>(mut self, arg: T) -> ProcessBuilder {
self.args.push(arg.to_c_str());
self
}
pub fn args<T: ToCStr>(mut self, arguments: &[T]) -> ProcessBuilder {
self.args.extend(arguments.iter().map(|t| t.to_c_str()));
self
}
pub fn get_args(&self) -> &[CString] {
self.args.as_slice()
}
pub fn cwd(mut self, path: Path) -> ProcessBuilder {
self.cwd = path;
self
}
pub fn env<T: ToCStr>(mut self, key: &str, val: Option<T>) -> ProcessBuilder |
// TODO: should InheritFd be hardcoded?
pub fn exec(&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if exit.success() {
Ok(())
} else {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&exit), None))
}
}
pub fn exec_with_output(&self) -> Result<ProcessOutput, ProcessError> {
let command = self.build_command();
let output = try!(command.output().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if output.status.success() {
Ok(output)
} else {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&output.status), Some(&output)))
}
}
pub fn build_command(&self) -> Command {
let mut command = Command::new(self.program.as_bytes_no_nul());
command.cwd(&self.cwd);
for arg in self.args.iter() {
command.arg(arg.as_bytes_no_nul());
}
for (k, v) in self.env.iter() {
let k = k.as_slice();
match *v {
Some(ref v) => { command.env(k, v.as_bytes_no_nul()); }
None => { command.env_remove(k); }
}
}
command
}
fn debug_string(&self) -> String {
let program = String::from_utf8_lossy(self.program.as_bytes_no_nul());
let mut program = program.into_string();
for arg in self.args.iter() {
program.push_char(' ');
let s = String::from_utf8_lossy(arg.as_bytes_no_nul());
program.push_str(s.as_slice());
}
program
}
}
pub fn process<T: ToCStr>(cmd: T) -> ProcessBuilder {
ProcessBuilder {
program: cmd.to_c_str(),
args: Vec::new(),
cwd: os::getcwd(),
env: HashMap::new(),
}
}
| {
self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
self
} | identifier_body |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env: HashMap<String, Option<CString>>,
cwd: Path,
}
impl Show for ProcessBuilder {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!(write!(f, "`{}", String::from_utf8_lossy(self.program.as_bytes_no_nul())));
for arg in self.args.iter() {
try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes_no_nul())));
}
write!(f, "`")
}
}
impl ProcessBuilder {
pub fn arg<T: ToCStr>(mut self, arg: T) -> ProcessBuilder {
self.args.push(arg.to_c_str());
self
}
pub fn args<T: ToCStr>(mut self, arguments: &[T]) -> ProcessBuilder {
self.args.extend(arguments.iter().map(|t| t.to_c_str()));
self
}
pub fn get_args(&self) -> &[CString] {
self.args.as_slice()
}
pub fn cwd(mut self, path: Path) -> ProcessBuilder {
self.cwd = path;
self
}
pub fn env<T: ToCStr>(mut self, key: &str, val: Option<T>) -> ProcessBuilder {
self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
self
}
// TODO: should InheritFd be hardcoded?
pub fn exec(&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if exit.success() {
Ok(())
} else {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&exit), None))
}
}
pub fn exec_with_output(&self) -> Result<ProcessOutput, ProcessError> {
let command = self.build_command();
let output = try!(command.output().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if output.status.success() {
Ok(output)
} else {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&output.status), Some(&output)))
}
}
pub fn build_command(&self) -> Command {
let mut command = Command::new(self.program.as_bytes_no_nul());
command.cwd(&self.cwd);
for arg in self.args.iter() {
command.arg(arg.as_bytes_no_nul());
}
for (k, v) in self.env.iter() {
let k = k.as_slice();
match *v {
Some(ref v) => { command.env(k, v.as_bytes_no_nul()); }
None => { command.env_remove(k); }
}
}
command
} | fn debug_string(&self) -> String {
let program = String::from_utf8_lossy(self.program.as_bytes_no_nul());
let mut program = program.into_string();
for arg in self.args.iter() {
program.push_char(' ');
let s = String::from_utf8_lossy(arg.as_bytes_no_nul());
program.push_str(s.as_slice());
}
program
}
}
pub fn process<T: ToCStr>(cmd: T) -> ProcessBuilder {
ProcessBuilder {
program: cmd.to_c_str(),
args: Vec::new(),
cwd: os::getcwd(),
env: HashMap::new(),
}
} | random_line_split |
|
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env: HashMap<String, Option<CString>>,
cwd: Path,
}
impl Show for ProcessBuilder {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!(write!(f, "`{}", String::from_utf8_lossy(self.program.as_bytes_no_nul())));
for arg in self.args.iter() {
try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes_no_nul())));
}
write!(f, "`")
}
}
impl ProcessBuilder {
pub fn arg<T: ToCStr>(mut self, arg: T) -> ProcessBuilder {
self.args.push(arg.to_c_str());
self
}
pub fn args<T: ToCStr>(mut self, arguments: &[T]) -> ProcessBuilder {
self.args.extend(arguments.iter().map(|t| t.to_c_str()));
self
}
pub fn get_args(&self) -> &[CString] {
self.args.as_slice()
}
pub fn cwd(mut self, path: Path) -> ProcessBuilder {
self.cwd = path;
self
}
pub fn env<T: ToCStr>(mut self, key: &str, val: Option<T>) -> ProcessBuilder {
self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
self
}
// TODO: should InheritFd be hardcoded?
pub fn | (&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if exit.success() {
Ok(())
} else {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&exit), None))
}
}
pub fn exec_with_output(&self) -> Result<ProcessOutput, ProcessError> {
let command = self.build_command();
let output = try!(command.output().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if output.status.success() {
Ok(output)
} else {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&output.status), Some(&output)))
}
}
pub fn build_command(&self) -> Command {
let mut command = Command::new(self.program.as_bytes_no_nul());
command.cwd(&self.cwd);
for arg in self.args.iter() {
command.arg(arg.as_bytes_no_nul());
}
for (k, v) in self.env.iter() {
let k = k.as_slice();
match *v {
Some(ref v) => { command.env(k, v.as_bytes_no_nul()); }
None => { command.env_remove(k); }
}
}
command
}
fn debug_string(&self) -> String {
let program = String::from_utf8_lossy(self.program.as_bytes_no_nul());
let mut program = program.into_string();
for arg in self.args.iter() {
program.push_char(' ');
let s = String::from_utf8_lossy(arg.as_bytes_no_nul());
program.push_str(s.as_slice());
}
program
}
}
pub fn process<T: ToCStr>(cmd: T) -> ProcessBuilder {
ProcessBuilder {
program: cmd.to_c_str(),
args: Vec::new(),
cwd: os::getcwd(),
env: HashMap::new(),
}
}
| exec | identifier_name |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env: HashMap<String, Option<CString>>,
cwd: Path,
}
impl Show for ProcessBuilder {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!(write!(f, "`{}", String::from_utf8_lossy(self.program.as_bytes_no_nul())));
for arg in self.args.iter() {
try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes_no_nul())));
}
write!(f, "`")
}
}
impl ProcessBuilder {
pub fn arg<T: ToCStr>(mut self, arg: T) -> ProcessBuilder {
self.args.push(arg.to_c_str());
self
}
pub fn args<T: ToCStr>(mut self, arguments: &[T]) -> ProcessBuilder {
self.args.extend(arguments.iter().map(|t| t.to_c_str()));
self
}
pub fn get_args(&self) -> &[CString] {
self.args.as_slice()
}
pub fn cwd(mut self, path: Path) -> ProcessBuilder {
self.cwd = path;
self
}
pub fn env<T: ToCStr>(mut self, key: &str, val: Option<T>) -> ProcessBuilder {
self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
self
}
// TODO: should InheritFd be hardcoded?
pub fn exec(&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if exit.success() {
Ok(())
} else {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&exit), None))
}
}
pub fn exec_with_output(&self) -> Result<ProcessOutput, ProcessError> {
let command = self.build_command();
let output = try!(command.output().map_err(|e| {
process_error(format!("Could not execute process `{}`",
self.debug_string()),
Some(e), None, None)
}));
if output.status.success() {
Ok(output)
} else |
}
pub fn build_command(&self) -> Command {
let mut command = Command::new(self.program.as_bytes_no_nul());
command.cwd(&self.cwd);
for arg in self.args.iter() {
command.arg(arg.as_bytes_no_nul());
}
for (k, v) in self.env.iter() {
let k = k.as_slice();
match *v {
Some(ref v) => { command.env(k, v.as_bytes_no_nul()); }
None => { command.env_remove(k); }
}
}
command
}
fn debug_string(&self) -> String {
let program = String::from_utf8_lossy(self.program.as_bytes_no_nul());
let mut program = program.into_string();
for arg in self.args.iter() {
program.push_char(' ');
let s = String::from_utf8_lossy(arg.as_bytes_no_nul());
program.push_str(s.as_slice());
}
program
}
}
pub fn process<T: ToCStr>(cmd: T) -> ProcessBuilder {
ProcessBuilder {
program: cmd.to_c_str(),
args: Vec::new(),
cwd: os::getcwd(),
env: HashMap::new(),
}
}
| {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&output.status), Some(&output)))
} | conditional_block |
variance-trait-matching.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.
// Issue #5781. Tests that subtyping is handled properly in trait matching.
trait Make<'a> {
fn make(x: &'a mut isize) -> Self;
}
impl<'a> Make<'a> for &'a mut isize {
fn make(x: &'a mut isize) -> &'a mut isize {
x
}
}
fn f() -> &'static mut isize {
let mut x = 1;
let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough
y | }
fn main() {} | random_line_split |
|
variance-trait-matching.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.
// Issue #5781. Tests that subtyping is handled properly in trait matching.
trait Make<'a> {
fn make(x: &'a mut isize) -> Self;
}
impl<'a> Make<'a> for &'a mut isize {
fn make(x: &'a mut isize) -> &'a mut isize {
x
}
}
fn f() -> &'static mut isize |
fn main() {}
| {
let mut x = 1;
let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough
y
} | identifier_body |
variance-trait-matching.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.
// Issue #5781. Tests that subtyping is handled properly in trait matching.
trait Make<'a> {
fn make(x: &'a mut isize) -> Self;
}
impl<'a> Make<'a> for &'a mut isize {
fn make(x: &'a mut isize) -> &'a mut isize {
x
}
}
fn | () -> &'static mut isize {
let mut x = 1;
let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough
y
}
fn main() {}
| f | identifier_name |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graphql_text_printer::print_ir;
use relay_test_schema::TEST_SCHEMA;
pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> | {
let source_location = SourceLocationKey::standalone(fixture.file_name);
let ast = parse_executable(fixture.content, source_location).unwrap();
build(&TEST_SCHEMA, &ast.definitions)
.map(|definitions| print_ir(&TEST_SCHEMA, &definitions).join("\n\n"))
.map_err(|errors| {
errors
.into_iter()
.map(|error| format!("{:?}", error))
.collect::<Vec<_>>()
.join("\n\n")
})
} | identifier_body |
|
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graphql_text_printer::print_ir;
use relay_test_schema::TEST_SCHEMA;
pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> {
let source_location = SourceLocationKey::standalone(fixture.file_name);
let ast = parse_executable(fixture.content, source_location).unwrap();
build(&TEST_SCHEMA, &ast.definitions)
.map(|definitions| print_ir(&TEST_SCHEMA, &definitions).join("\n\n"))
.map_err(|errors| {
errors
.into_iter()
.map(|error| format!("{:?}", error))
.collect::<Vec<_>>()
.join("\n\n") | } | }) | random_line_split |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graphql_text_printer::print_ir;
use relay_test_schema::TEST_SCHEMA;
pub fn | (fixture: &Fixture<'_>) -> Result<String, String> {
let source_location = SourceLocationKey::standalone(fixture.file_name);
let ast = parse_executable(fixture.content, source_location).unwrap();
build(&TEST_SCHEMA, &ast.definitions)
.map(|definitions| print_ir(&TEST_SCHEMA, &definitions).join("\n\n"))
.map_err(|errors| {
errors
.into_iter()
.map(|error| format!("{:?}", error))
.collect::<Vec<_>>()
.join("\n\n")
})
}
| transform_fixture | identifier_name |
bunch.rs |
#![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
let mut ba = [0;16];
try!(misc::io::read_fully(&mut f, &mut ba));
Ok(ba)
}
fn to_hex_string(ba: &[u8]) -> String {
let strs: Vec<String> = ba.iter()
.map(|b| format!("{:02X}", b))
.collect();
strs.connect("")
}
let ba = bytes().unwrap();
to_hex_string(&ba)
}
fn tempfile(base: &str) -> String {
std::fs::create_dir("tmp");
let file = "tmp/".to_string() + base + "_" + &tid();
file
}
#[bench]
fn | (b: &mut test::Bencher) {
fn f() -> lsm::Result<bool> {
//println!("running");
let db = try!(lsm::db::new(tempfile("bunch"), lsm::DEFAULT_SETTINGS));
const NUM : usize = 10000;
let mut a = Vec::new();
for i in 0.. 10 {
let g = try!(db.WriteSegmentFromSortedSequence(lsm::GenerateNumbers {cur: i * NUM, end: (i+1) * NUM, step: i+1}));
a.push(g);
}
{
let lck = try!(db.GetWriteLock());
try!(lck.commitSegments(a.clone()));
}
let g3 = try!(db.merge(0, 2, None));
assert!(g3.is_some());
let g3 = g3.unwrap();
{
let lck = try!(db.GetWriteLock());
try!(lck.commitMerge(g3));
}
let res : lsm::Result<bool> = Ok(true);
res
}
b.iter(|| assert!(f().is_ok()) );
}
| bunch | identifier_name |
bunch.rs | #![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
let mut ba = [0;16];
try!(misc::io::read_fully(&mut f, &mut ba));
Ok(ba)
}
fn to_hex_string(ba: &[u8]) -> String {
let strs: Vec<String> = ba.iter()
.map(|b| format!("{:02X}", b))
.collect();
strs.connect("")
}
let ba = bytes().unwrap();
to_hex_string(&ba)
}
fn tempfile(base: &str) -> String {
std::fs::create_dir("tmp");
let file = "tmp/".to_string() + base + "_" + &tid();
file
}
#[bench]
fn bunch(b: &mut test::Bencher) {
fn f() -> lsm::Result<bool> {
//println!("running");
let db = try!(lsm::db::new(tempfile("bunch"), lsm::DEFAULT_SETTINGS));
const NUM : usize = 10000;
let mut a = Vec::new();
for i in 0.. 10 {
let g = try!(db.WriteSegmentFromSortedSequence(lsm::GenerateNumbers {cur: i * NUM, end: (i+1) * NUM, step: i+1}));
a.push(g); | {
let lck = try!(db.GetWriteLock());
try!(lck.commitSegments(a.clone()));
}
let g3 = try!(db.merge(0, 2, None));
assert!(g3.is_some());
let g3 = g3.unwrap();
{
let lck = try!(db.GetWriteLock());
try!(lck.commitMerge(g3));
}
let res : lsm::Result<bool> = Ok(true);
res
}
b.iter(|| assert!(f().is_ok()) );
} | } | random_line_split |
bunch.rs |
#![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
let mut ba = [0;16];
try!(misc::io::read_fully(&mut f, &mut ba));
Ok(ba)
}
fn to_hex_string(ba: &[u8]) -> String |
let ba = bytes().unwrap();
to_hex_string(&ba)
}
fn tempfile(base: &str) -> String {
std::fs::create_dir("tmp");
let file = "tmp/".to_string() + base + "_" + &tid();
file
}
#[bench]
fn bunch(b: &mut test::Bencher) {
fn f() -> lsm::Result<bool> {
//println!("running");
let db = try!(lsm::db::new(tempfile("bunch"), lsm::DEFAULT_SETTINGS));
const NUM : usize = 10000;
let mut a = Vec::new();
for i in 0.. 10 {
let g = try!(db.WriteSegmentFromSortedSequence(lsm::GenerateNumbers {cur: i * NUM, end: (i+1) * NUM, step: i+1}));
a.push(g);
}
{
let lck = try!(db.GetWriteLock());
try!(lck.commitSegments(a.clone()));
}
let g3 = try!(db.merge(0, 2, None));
assert!(g3.is_some());
let g3 = g3.unwrap();
{
let lck = try!(db.GetWriteLock());
try!(lck.commitMerge(g3));
}
let res : lsm::Result<bool> = Ok(true);
res
}
b.iter(|| assert!(f().is_ok()) );
}
| {
let strs: Vec<String> = ba.iter()
.map(|b| format!("{:02X}", b))
.collect();
strs.connect("")
} | identifier_body |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct RMPR {
bits: u8,
}
impl RMPR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _RMPW<'a> {
w: &'a mut W,
}
impl<'a> _RMPW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
self.w.bits &=!((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(always)]
pub fn rmp(&self) -> RMPR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
RMPR { bits }
}
} | #[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(always)]
pub fn rmp(&mut self) -> _RMPW {
_RMPW { w: self }
}
} | impl W {
#[doc = r" Reset value of the register"] | random_line_split |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct | {
bits: u8,
}
impl RMPR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _RMPW<'a> {
w: &'a mut W,
}
impl<'a> _RMPW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
self.w.bits &=!((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(always)]
pub fn rmp(&self) -> RMPR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
RMPR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(always)]
pub fn rmp(&mut self) -> _RMPW {
_RMPW { w: self }
}
}
| RMPR | identifier_name |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
|
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct RMPR {
bits: u8,
}
impl RMPR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _RMPW<'a> {
w: &'a mut W,
}
impl<'a> _RMPW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
self.w.bits &=!((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(always)]
pub fn rmp(&self) -> RMPR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
RMPR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(always)]
pub fn rmp(&mut self) -> _RMPW {
_RMPW { w: self }
}
}
| {
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
} | 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/. */
#![deny(unsafe_code)]
extern crate gfx;
extern crate ipc_channel;
extern crate metrics;
extern crate msg;
extern crate net_traits;
extern crate profile_traits;
extern crate script_traits;
extern crate servo_url;
extern crate webrender_api;
| // This module contains traits in layout used generically
// in the rest of Servo.
// The traits are here instead of in layout so
// that these modules won't have to depend on layout.
use gfx::font_cache_thread::FontCacheThread;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg::constellation_msg::PipelineId;
use msg::constellation_msg::TopLevelBrowsingContextId;
use net_traits::image_cache::ImageCache;
use profile_traits::{mem, time};
use script_traits::{ConstellationControlMsg, LayoutControlMsg};
use script_traits::LayoutMsg as ConstellationMsg;
use servo_url::ServoUrl;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
// A static method creating a layout thread
// Here to remove the compositor -> layout dependency
pub trait LayoutThreadFactory {
type Message;
fn create(id: PipelineId,
top_level_browsing_context_id: TopLevelBrowsingContextId,
url: ServoUrl,
is_iframe: bool,
chan: (Sender<Self::Message>, Receiver<Self::Message>),
pipeline_port: IpcReceiver<LayoutControlMsg>,
constellation_chan: IpcSender<ConstellationMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
image_cache: Arc<ImageCache>,
font_cache_thread: FontCacheThread,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
content_process_shutdown_chan: Option<IpcSender<()>>,
webrender_api_sender: webrender_api::RenderApiSender,
layout_threads: usize,
paint_time_metrics: PaintTimeMetrics);
} | random_line_split |
|
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_section_unref(ptr),
}
}
impl CssSection {
pub fn get_end_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
}
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
//pub fn get_file(&self) -> /*Ignored*/Option<gio::File> {
// unsafe { TODO: call ffi::gtk_css_section_get_file() }
//}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
pub fn | (&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
}
pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
}
}
}
| get_section_type | identifier_name |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_section_unref(ptr),
}
}
impl CssSection {
pub fn get_end_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
}
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
//pub fn get_file(&self) -> /*Ignored*/Option<gio::File> {
// unsafe { TODO: call ffi::gtk_css_section_get_file() }
//}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
pub fn get_section_type(&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
} | }
} |
pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
} | random_line_split |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_section_unref(ptr),
}
}
impl CssSection {
pub fn get_end_line(&self) -> u32 |
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
//pub fn get_file(&self) -> /*Ignored*/Option<gio::File> {
// unsafe { TODO: call ffi::gtk_css_section_get_file() }
//}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
pub fn get_section_type(&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
}
pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
}
}
}
| {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
} | identifier_body |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> bool{
match val{
&Some(_) => false,
&None => true
}
}
/// Check that a field is not empty
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty<T>(val: Option<T>) -> bool{
match val{
Some(_) => true,
None => false
}
}
/// Check that a String field is not empty
///
/// # Arguments
/// `val` - Option<String> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty_string(val: Option<String>) -> bool |
/// Check that two values are identical
///
/// # Arguments
/// `val1` - Generic type T
/// `val2` - Generic type T
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn equals<T: PartialEq>(val1: T, val2: T) -> bool{
val1 == val2
}
/// Check if a string matches a regular expression
///
/// # Arguments
/// `value`
/// `regex`
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn matches(value: &str, regex: &str) -> bool{
let re = Regex::new(regex).unwrap();
re.is_match(value)
}
| {
match val{
Some(v) => !v.is_empty(),
None => false
}
} | identifier_body |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> bool{
match val{
&Some(_) => false,
&None => true
}
}
/// Check that a field is not empty
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty<T>(val: Option<T>) -> bool{
match val{
Some(_) => true,
None => false
}
}
/// Check that a String field is not empty
///
/// # Arguments
/// `val` - Option<String> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty_string(val: Option<String>) -> bool{
match val{
Some(v) =>!v.is_empty(),
None => false
}
}
/// Check that two values are identical
///
/// # Arguments
/// `val1` - Generic type T
/// `val2` - Generic type T
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn equals<T: PartialEq>(val1: T, val2: T) -> bool{
val1 == val2
}
/// Check if a string matches a regular expression
///
/// # Arguments
/// `value`
/// `regex`
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn | (value: &str, regex: &str) -> bool{
let re = Regex::new(regex).unwrap();
re.is_match(value)
}
| matches | identifier_name |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> bool{
match val{
&Some(_) => false,
&None => true | /// Check that a field is not empty
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty<T>(val: Option<T>) -> bool{
match val{
Some(_) => true,
None => false
}
}
/// Check that a String field is not empty
///
/// # Arguments
/// `val` - Option<String> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty_string(val: Option<String>) -> bool{
match val{
Some(v) =>!v.is_empty(),
None => false
}
}
/// Check that two values are identical
///
/// # Arguments
/// `val1` - Generic type T
/// `val2` - Generic type T
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn equals<T: PartialEq>(val1: T, val2: T) -> bool{
val1 == val2
}
/// Check if a string matches a regular expression
///
/// # Arguments
/// `value`
/// `regex`
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn matches(value: &str, regex: &str) -> bool{
let re = Regex::new(regex).unwrap();
re.is_match(value)
} | }
}
| random_line_split |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow logic.
contents: Branches,
}
#[derive(Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Branches {
// xyz ordering
// This isn't an array because we can't move out of an array.
lll: TreeBody,
llh: TreeBody,
lhl: TreeBody,
lhh: TreeBody,
hll: TreeBody,
hlh: TreeBody,
hhl: TreeBody,
hhh: TreeBody,
}
/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum TreeBody {
Empty,
Leaf(Voxel),
Branch(Box<Branches>),
}
impl Branches {
pub fn empty() -> Branches {
Branches {
lll: TreeBody::Empty,
llh: TreeBody::Empty,
lhl: TreeBody::Empty,
lhh: TreeBody::Empty,
hll: TreeBody::Empty,
hlh: TreeBody::Empty,
hhl: TreeBody::Empty,
hhh: TreeBody::Empty,
}
}
pub fn get<'a>(&'a self, x: usize, y: usize, z: usize) -> &'a TreeBody {
let this: &'a [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&this[x][y][z]
}
pub fn get_mut<'a>(&'a mut self, x: usize, y: usize, z: usize) -> &'a mut TreeBody {
let this: &'a mut [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&mut this[x][y][z]
}
}
impl VoxelTree {
pub fn new() -> VoxelTree {
VoxelTree {
lg_size: 0,
contents: Branches::empty(),
}
}
/// Is this voxel (non-strictly) within an origin-centered voxel with
/// size `2^lg_size`?
pub fn contains_bounds(&self, voxel: &voxel::Bounds) -> bool {
let high;
if voxel.lg_size >= 0 {
high = (1 << self.lg_size) >> voxel.lg_size;
} else {
high = (1 << self.lg_size) << (-voxel.lg_size);
}
voxel.x < high &&
voxel.y < high &&
voxel.z < high &&
{
let low = -high;
voxel.x >= low &&
voxel.y >= low &&
voxel.z >= low &&
true
}
}
/// Ensure that this tree can hold the provided voxel.
pub fn grow_to_hold(&mut self, voxel: &voxel::Bounds) {
while!self.contains_bounds(voxel) {
// Double the bounds in every direction.
self.lg_size += 1;
// Pull out `self.contents` so we can move out of it.
let contents = mem::replace(&mut self.contents, Branches::empty());
// We re-construct the tree with bounds twice the size (but still centered
// around the origin) by deconstructing the top level of branches,
// creating a new doubly-sized top level, and moving the old branches back
// in as the new top level's children. e.g. in 2D:
//
// ---------------------------
// | | |0| | |
// | | |0| | |
// --------------- ------------|0|------------
// | 1 |0| 2 | | | 1 |0| 2 | |
// | |0| | | | |0| | |
// |------0------| |------------0------------|
// 000000000000000 ==> |0000000000000000000000000|
// |------0------| |------------0------------|
// | |0| | | | |0| | |
// | 3 |0| 4 | | | 3 |0| 4 | |
// --------------- |------------0------------|
// | | |0| | |
// | | |0| | |
// ---------------------------
macro_rules! at(
($c_idx:ident, $b_idx:ident) => {{
let mut branches = Branches::empty();
branches.$b_idx = contents.$c_idx;
TreeBody::Branch(Box::new(branches))
}}
);
self.contents =
Branches {
lll: at!(lll, hhh),
llh: at!(llh, hhl),
lhl: at!(lhl, hlh),
lhh: at!(lhh, hll),
hll: at!(hll, lhh),
hlh: at!(hlh, lhl),
hhl: at!(hhl, llh),
hhh: at!(hhh, lll),
};
}
}
fn find_mask(&self, voxel: &voxel::Bounds) -> i32 {
// When we compare the voxel position to octree bounds to choose subtrees
// for insertion, we'll be comparing voxel position to values of 2^n and
// -2^n, so we can just use the position bits to branch directly.
// This actually works for negative values too, without much wrestling:
// we need to branch on the sign bit up front, but after that, two's
// complement magic means the branching on bits works regardless of sign.
let mut mask = (1 << self.lg_size) >> 1;
// Shift everything by the voxel's lg_size, so we can compare the mask to 0
// to know whether we're done.
if voxel.lg_size >= 0 {
mask = mask >> voxel.lg_size;
} else {
// TODO: Check for overflow.
mask = mask << -voxel.lg_size;
}
mask
}
fn find_mut<'a, Step, E>(
&'a mut self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a mut TreeBody, E> where
Step: FnMut(&'a mut TreeBody) -> Result<&'a mut Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &mut self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get_mut(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| ((x & mask)!= 0) as usize,
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
fn find<'a, Step, E>(
&'a self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a TreeBody, E> where
Step: FnMut(&'a TreeBody) -> Result<&'a Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| { ((x & mask)!= 0) as usize },
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
/// Find a voxel inside this tree.
/// If it doesn't exist, it will be created as empty.
pub fn get_mut_or_create<'a>(&'a mut self, voxel: &voxel::Bounds) -> &'a mut TreeBody {
self.grow_to_hold(voxel);
let branch: Result<_, ()> =
self.find_mut(voxel, |branch| { Ok(VoxelTree::get_mut_or_create_step(branch)) });
branch.unwrap()
}
fn get_mut_or_create_step<'a>(
branch: &'a mut TreeBody,
) -> &'a mut Branches {
// "Step down" the tree.
match *branch {
// Branches; we can go straight to the branching logic.
TreeBody::Branch(ref mut b) => b,
// Otherwise, keep going, but we need to insert a voxel inside the
// space occupied by the current branch.
TreeBody::Empty => {
// Replace this branch with 8 empty sub-branches - who's gonna notice?
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
TreeBody::Leaf(_) => {
// Erase this leaf and replace it with 8 empty sub-branches.
// This behavior is pretty debatable, but we need to do something,
// and it's easier to debug accidentally replacing a big chunk
// with a smaller one than to debug a nop.
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
}
}
/// Find a voxel inside this tree.
pub fn get<'a>(&'a self, voxel: &voxel::Bounds) -> Option<&'a Voxel> {
if!self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&TreeBody::Branch(ref branches) => Ok(branches.deref()),
_ => Err(()),
}
};
match self.find(voxel, get_step) {
Ok(&TreeBody::Leaf(ref t)) => Some(t),
_ => None,
}
}
/// Find a voxel inside this tree.
pub fn get_mut<'a>(&'a mut self, voxel: &voxel::Bounds) -> Option<&'a mut Voxel> {
if!self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&mut TreeBody::Branch(ref mut branches) => Ok(branches.deref_mut()),
_ => Err(()),
}
};
match self.find_mut(voxel, get_step) {
Ok(&mut TreeBody::Leaf(ref mut t)) => Some(t),
_ => None,
}
}
pub fn cast_ray<'a, Act, R>(
&'a self,
ray: &Ray3<f32>,
act: &mut Act,
) -> Option<R>
where
// TODO: Does this *have* to be callback-based?
Act: FnMut(voxel::Bounds, &'a Voxel) -> Option<R>
{
let coords = [
if ray.origin.x >= 0.0 {1} else {0},
if ray.origin.y >= 0.0 {1} else {0},
if ray.origin.z >= 0.0 {1} else {0},
];
// NB: The children are half the size of the tree itself,
// but tree.lg_size=0 means it extends tree.lg_size=0 in *each direction*,
// so the "actual" size of the tree as a voxel would be tree.lg_size+1.
let child_lg_size = self.lg_size as i16;
let mut make_bounds = |coords: [usize; 3]| {
voxel::Bounds {
x: coords[0] as i32 - 1,
y: coords[1] as i32 - 1,
z: coords[2] as i32 - 1,
lg_size: child_lg_size,
}
};
match raycast::cast_ray_branches(
&self.contents,
ray,
None,
coords,
&mut make_bounds,
act,
) {
Ok(r) => Some(r),
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use voxel;
use super::{VoxelTree, TreeBody};
#[test]
fn insert_and_lookup() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(8, -8, 4, 0)) = TreeBody::Leaf(2);
*tree.get_mut_or_create(voxel::Bounds::new(2, 0, 4, 4)) = TreeBody::Leaf(3);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(4);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(5);
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
assert_eq!(tree.get(voxel::Bounds::new(8, -8, 4, 0)), Some(&2));
assert_eq!(tree.get(voxel::Bounds::new(9, 0, 16, 2)), Some(&5));
assert_eq!(tree.get(voxel::Bounds::new(2, 0, 4, 4)), None);
}
#[test]
fn wrong_voxel_size_is_not_found() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, -4, 1)) = TreeBody::Leaf(1);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 0)), None);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 2)), None);
}
#[test]
fn | () {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 1));
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 2));
tree.grow_to_hold(voxel::Bounds::new(-32, 32, -128, 3));
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
}
#[test]
fn simple_cast_ray() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
let actual = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
assert_eq!(actual, Some((voxel::Bounds::new(4, 4, 4, 0), &2)));
}
#[bench]
fn simple_inserts(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
bencher.iter(|| {
*tree.get_mut_or_create(voxel::Bounds::new(0, 0, 0, 0)) = TreeBody::Leaf(0);
});
test::black_box(tree);
}
#[bench]
fn bench_cast_ray(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
bencher.iter(|| {
let r = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
test::black_box(r);
});
}
}
| grow_is_transparent | identifier_name |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow logic.
contents: Branches,
}
#[derive(Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Branches {
// xyz ordering
// This isn't an array because we can't move out of an array.
lll: TreeBody,
llh: TreeBody,
lhl: TreeBody,
lhh: TreeBody,
hll: TreeBody,
hlh: TreeBody,
hhl: TreeBody,
hhh: TreeBody,
}
/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum TreeBody {
Empty,
Leaf(Voxel),
Branch(Box<Branches>),
}
impl Branches {
pub fn empty() -> Branches {
Branches {
lll: TreeBody::Empty,
llh: TreeBody::Empty,
lhl: TreeBody::Empty,
lhh: TreeBody::Empty,
hll: TreeBody::Empty,
hlh: TreeBody::Empty,
hhl: TreeBody::Empty,
hhh: TreeBody::Empty,
}
}
pub fn get<'a>(&'a self, x: usize, y: usize, z: usize) -> &'a TreeBody {
let this: &'a [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&this[x][y][z]
}
pub fn get_mut<'a>(&'a mut self, x: usize, y: usize, z: usize) -> &'a mut TreeBody {
let this: &'a mut [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&mut this[x][y][z]
}
}
impl VoxelTree {
pub fn new() -> VoxelTree {
VoxelTree {
lg_size: 0,
contents: Branches::empty(),
}
}
/// Is this voxel (non-strictly) within an origin-centered voxel with
/// size `2^lg_size`?
pub fn contains_bounds(&self, voxel: &voxel::Bounds) -> bool {
let high;
if voxel.lg_size >= 0 {
high = (1 << self.lg_size) >> voxel.lg_size;
} else {
high = (1 << self.lg_size) << (-voxel.lg_size);
}
voxel.x < high &&
voxel.y < high &&
voxel.z < high &&
{
let low = -high;
voxel.x >= low &&
voxel.y >= low &&
voxel.z >= low &&
true
}
}
/// Ensure that this tree can hold the provided voxel.
pub fn grow_to_hold(&mut self, voxel: &voxel::Bounds) {
while!self.contains_bounds(voxel) {
// Double the bounds in every direction.
self.lg_size += 1;
// Pull out `self.contents` so we can move out of it.
let contents = mem::replace(&mut self.contents, Branches::empty());
// We re-construct the tree with bounds twice the size (but still centered
// around the origin) by deconstructing the top level of branches,
// creating a new doubly-sized top level, and moving the old branches back
// in as the new top level's children. e.g. in 2D:
//
// ---------------------------
// | | |0| | |
// | | |0| | |
// --------------- ------------|0|------------
// | 1 |0| 2 | | | 1 |0| 2 | |
// | |0| | | | |0| | |
// |------0------| |------------0------------|
// 000000000000000 ==> |0000000000000000000000000|
// |------0------| |------------0------------|
// | |0| | | | |0| | |
// | 3 |0| 4 | | | 3 |0| 4 | |
// --------------- |------------0------------|
// | | |0| | |
// | | |0| | |
// ---------------------------
macro_rules! at(
($c_idx:ident, $b_idx:ident) => {{
let mut branches = Branches::empty();
branches.$b_idx = contents.$c_idx;
TreeBody::Branch(Box::new(branches))
}}
);
self.contents =
Branches {
lll: at!(lll, hhh),
llh: at!(llh, hhl),
lhl: at!(lhl, hlh),
lhh: at!(lhh, hll),
hll: at!(hll, lhh),
hlh: at!(hlh, lhl),
hhl: at!(hhl, llh),
hhh: at!(hhh, lll),
};
}
}
fn find_mask(&self, voxel: &voxel::Bounds) -> i32 {
// When we compare the voxel position to octree bounds to choose subtrees
// for insertion, we'll be comparing voxel position to values of 2^n and
// -2^n, so we can just use the position bits to branch directly.
// This actually works for negative values too, without much wrestling:
// we need to branch on the sign bit up front, but after that, two's
// complement magic means the branching on bits works regardless of sign.
let mut mask = (1 << self.lg_size) >> 1;
// Shift everything by the voxel's lg_size, so we can compare the mask to 0
// to know whether we're done.
if voxel.lg_size >= 0 {
mask = mask >> voxel.lg_size;
} else {
// TODO: Check for overflow.
mask = mask << -voxel.lg_size;
}
mask
}
fn find_mut<'a, Step, E>(
&'a mut self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a mut TreeBody, E> where
Step: FnMut(&'a mut TreeBody) -> Result<&'a mut Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &mut self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get_mut(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| ((x & mask)!= 0) as usize,
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
fn find<'a, Step, E>(
&'a self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a TreeBody, E> where
Step: FnMut(&'a TreeBody) -> Result<&'a Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| { ((x & mask)!= 0) as usize },
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
/// Find a voxel inside this tree.
/// If it doesn't exist, it will be created as empty.
pub fn get_mut_or_create<'a>(&'a mut self, voxel: &voxel::Bounds) -> &'a mut TreeBody {
self.grow_to_hold(voxel);
let branch: Result<_, ()> =
self.find_mut(voxel, |branch| { Ok(VoxelTree::get_mut_or_create_step(branch)) });
branch.unwrap()
}
fn get_mut_or_create_step<'a>(
branch: &'a mut TreeBody,
) -> &'a mut Branches {
// "Step down" the tree.
match *branch {
// Branches; we can go straight to the branching logic.
TreeBody::Branch(ref mut b) => b,
// Otherwise, keep going, but we need to insert a voxel inside the
// space occupied by the current branch.
TreeBody::Empty => {
// Replace this branch with 8 empty sub-branches - who's gonna notice?
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
TreeBody::Leaf(_) => {
// Erase this leaf and replace it with 8 empty sub-branches.
// This behavior is pretty debatable, but we need to do something,
// and it's easier to debug accidentally replacing a big chunk
// with a smaller one than to debug a nop.
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
}
}
/// Find a voxel inside this tree.
pub fn get<'a>(&'a self, voxel: &voxel::Bounds) -> Option<&'a Voxel> {
if!self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&TreeBody::Branch(ref branches) => Ok(branches.deref()),
_ => Err(()),
}
};
match self.find(voxel, get_step) {
Ok(&TreeBody::Leaf(ref t)) => Some(t),
_ => None,
}
}
/// Find a voxel inside this tree.
pub fn get_mut<'a>(&'a mut self, voxel: &voxel::Bounds) -> Option<&'a mut Voxel> {
if!self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&mut TreeBody::Branch(ref mut branches) => Ok(branches.deref_mut()),
_ => Err(()),
}
};
match self.find_mut(voxel, get_step) {
Ok(&mut TreeBody::Leaf(ref mut t)) => Some(t),
_ => None,
}
}
pub fn cast_ray<'a, Act, R>(
&'a self,
ray: &Ray3<f32>,
act: &mut Act,
) -> Option<R>
where
// TODO: Does this *have* to be callback-based?
Act: FnMut(voxel::Bounds, &'a Voxel) -> Option<R>
{
let coords = [
if ray.origin.x >= 0.0 {1} else {0},
if ray.origin.y >= 0.0 {1} else {0},
if ray.origin.z >= 0.0 {1} else | ,
];
// NB: The children are half the size of the tree itself,
// but tree.lg_size=0 means it extends tree.lg_size=0 in *each direction*,
// so the "actual" size of the tree as a voxel would be tree.lg_size+1.
let child_lg_size = self.lg_size as i16;
let mut make_bounds = |coords: [usize; 3]| {
voxel::Bounds {
x: coords[0] as i32 - 1,
y: coords[1] as i32 - 1,
z: coords[2] as i32 - 1,
lg_size: child_lg_size,
}
};
match raycast::cast_ray_branches(
&self.contents,
ray,
None,
coords,
&mut make_bounds,
act,
) {
Ok(r) => Some(r),
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use voxel;
use super::{VoxelTree, TreeBody};
#[test]
fn insert_and_lookup() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(8, -8, 4, 0)) = TreeBody::Leaf(2);
*tree.get_mut_or_create(voxel::Bounds::new(2, 0, 4, 4)) = TreeBody::Leaf(3);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(4);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(5);
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
assert_eq!(tree.get(voxel::Bounds::new(8, -8, 4, 0)), Some(&2));
assert_eq!(tree.get(voxel::Bounds::new(9, 0, 16, 2)), Some(&5));
assert_eq!(tree.get(voxel::Bounds::new(2, 0, 4, 4)), None);
}
#[test]
fn wrong_voxel_size_is_not_found() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, -4, 1)) = TreeBody::Leaf(1);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 0)), None);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 2)), None);
}
#[test]
fn grow_is_transparent() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 1));
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 2));
tree.grow_to_hold(voxel::Bounds::new(-32, 32, -128, 3));
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
}
#[test]
fn simple_cast_ray() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
let actual = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
assert_eq!(actual, Some((voxel::Bounds::new(4, 4, 4, 0), &2)));
}
#[bench]
fn simple_inserts(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
bencher.iter(|| {
*tree.get_mut_or_create(voxel::Bounds::new(0, 0, 0, 0)) = TreeBody::Leaf(0);
});
test::black_box(tree);
}
#[bench]
fn bench_cast_ray(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
bencher.iter(|| {
let r = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
test::black_box(r);
});
}
}
| {0} | conditional_block |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow logic.
contents: Branches,
}
#[derive(Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Branches {
// xyz ordering
// This isn't an array because we can't move out of an array.
lll: TreeBody,
llh: TreeBody,
lhl: TreeBody,
lhh: TreeBody,
hll: TreeBody,
hlh: TreeBody,
hhl: TreeBody,
hhh: TreeBody,
}
/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum TreeBody {
Empty,
Leaf(Voxel),
Branch(Box<Branches>),
}
impl Branches {
pub fn empty() -> Branches {
Branches {
lll: TreeBody::Empty,
llh: TreeBody::Empty,
lhl: TreeBody::Empty,
lhh: TreeBody::Empty,
hll: TreeBody::Empty,
hlh: TreeBody::Empty,
hhl: TreeBody::Empty,
hhh: TreeBody::Empty,
}
}
pub fn get<'a>(&'a self, x: usize, y: usize, z: usize) -> &'a TreeBody {
let this: &'a [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&this[x][y][z]
}
pub fn get_mut<'a>(&'a mut self, x: usize, y: usize, z: usize) -> &'a mut TreeBody {
let this: &'a mut [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&mut this[x][y][z]
}
}
impl VoxelTree {
pub fn new() -> VoxelTree {
VoxelTree {
lg_size: 0,
contents: Branches::empty(),
}
}
/// Is this voxel (non-strictly) within an origin-centered voxel with
/// size `2^lg_size`?
pub fn contains_bounds(&self, voxel: &voxel::Bounds) -> bool {
let high;
if voxel.lg_size >= 0 {
high = (1 << self.lg_size) >> voxel.lg_size;
} else {
high = (1 << self.lg_size) << (-voxel.lg_size);
}
voxel.x < high &&
voxel.y < high &&
voxel.z < high &&
{
let low = -high;
voxel.x >= low &&
voxel.y >= low &&
voxel.z >= low &&
true
}
}
/// Ensure that this tree can hold the provided voxel.
pub fn grow_to_hold(&mut self, voxel: &voxel::Bounds) {
while!self.contains_bounds(voxel) {
// Double the bounds in every direction.
self.lg_size += 1;
// Pull out `self.contents` so we can move out of it.
let contents = mem::replace(&mut self.contents, Branches::empty());
// We re-construct the tree with bounds twice the size (but still centered
// around the origin) by deconstructing the top level of branches,
// creating a new doubly-sized top level, and moving the old branches back
// in as the new top level's children. e.g. in 2D:
//
// ---------------------------
// | | |0| | |
// | | |0| | |
// --------------- ------------|0|------------
// | 1 |0| 2 | | | 1 |0| 2 | |
// | |0| | | | |0| | |
// |------0------| |------------0------------|
// 000000000000000 ==> |0000000000000000000000000|
// |------0------| |------------0------------|
// | |0| | | | |0| | |
// | 3 |0| 4 | | | 3 |0| 4 | |
// --------------- |------------0------------|
// | | |0| | |
// | | |0| | |
// ---------------------------
macro_rules! at(
($c_idx:ident, $b_idx:ident) => {{
let mut branches = Branches::empty();
branches.$b_idx = contents.$c_idx;
TreeBody::Branch(Box::new(branches))
}}
);
self.contents =
Branches {
lll: at!(lll, hhh),
llh: at!(llh, hhl),
lhl: at!(lhl, hlh),
lhh: at!(lhh, hll),
hll: at!(hll, lhh),
hlh: at!(hlh, lhl),
hhl: at!(hhl, llh),
hhh: at!(hhh, lll),
};
}
}
fn find_mask(&self, voxel: &voxel::Bounds) -> i32 {
// When we compare the voxel position to octree bounds to choose subtrees
// for insertion, we'll be comparing voxel position to values of 2^n and
// -2^n, so we can just use the position bits to branch directly.
// This actually works for negative values too, without much wrestling:
// we need to branch on the sign bit up front, but after that, two's
// complement magic means the branching on bits works regardless of sign.
let mut mask = (1 << self.lg_size) >> 1;
// Shift everything by the voxel's lg_size, so we can compare the mask to 0
// to know whether we're done.
if voxel.lg_size >= 0 {
mask = mask >> voxel.lg_size;
} else {
// TODO: Check for overflow.
mask = mask << -voxel.lg_size;
}
mask
}
fn find_mut<'a, Step, E>(
&'a mut self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a mut TreeBody, E> where
Step: FnMut(&'a mut TreeBody) -> Result<&'a mut Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &mut self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get_mut(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| ((x & mask)!= 0) as usize,
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
fn find<'a, Step, E>(
&'a self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a TreeBody, E> where
Step: FnMut(&'a TreeBody) -> Result<&'a Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| { ((x & mask)!= 0) as usize },
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
/// Find a voxel inside this tree.
/// If it doesn't exist, it will be created as empty.
pub fn get_mut_or_create<'a>(&'a mut self, voxel: &voxel::Bounds) -> &'a mut TreeBody {
self.grow_to_hold(voxel);
let branch: Result<_, ()> =
self.find_mut(voxel, |branch| { Ok(VoxelTree::get_mut_or_create_step(branch)) });
branch.unwrap()
}
fn get_mut_or_create_step<'a>(
branch: &'a mut TreeBody,
) -> &'a mut Branches {
// "Step down" the tree.
match *branch {
// Branches; we can go straight to the branching logic.
TreeBody::Branch(ref mut b) => b,
// Otherwise, keep going, but we need to insert a voxel inside the
// space occupied by the current branch.
TreeBody::Empty => {
// Replace this branch with 8 empty sub-branches - who's gonna notice?
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
TreeBody::Leaf(_) => {
// Erase this leaf and replace it with 8 empty sub-branches.
// This behavior is pretty debatable, but we need to do something,
// and it's easier to debug accidentally replacing a big chunk
// with a smaller one than to debug a nop.
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
}
}
/// Find a voxel inside this tree.
pub fn get<'a>(&'a self, voxel: &voxel::Bounds) -> Option<&'a Voxel> {
if!self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&TreeBody::Branch(ref branches) => Ok(branches.deref()),
_ => Err(()),
}
};
match self.find(voxel, get_step) {
Ok(&TreeBody::Leaf(ref t)) => Some(t),
_ => None,
}
}
/// Find a voxel inside this tree.
pub fn get_mut<'a>(&'a mut self, voxel: &voxel::Bounds) -> Option<&'a mut Voxel> |
pub fn cast_ray<'a, Act, R>(
&'a self,
ray: &Ray3<f32>,
act: &mut Act,
) -> Option<R>
where
// TODO: Does this *have* to be callback-based?
Act: FnMut(voxel::Bounds, &'a Voxel) -> Option<R>
{
let coords = [
if ray.origin.x >= 0.0 {1} else {0},
if ray.origin.y >= 0.0 {1} else {0},
if ray.origin.z >= 0.0 {1} else {0},
];
// NB: The children are half the size of the tree itself,
// but tree.lg_size=0 means it extends tree.lg_size=0 in *each direction*,
// so the "actual" size of the tree as a voxel would be tree.lg_size+1.
let child_lg_size = self.lg_size as i16;
let mut make_bounds = |coords: [usize; 3]| {
voxel::Bounds {
x: coords[0] as i32 - 1,
y: coords[1] as i32 - 1,
z: coords[2] as i32 - 1,
lg_size: child_lg_size,
}
};
match raycast::cast_ray_branches(
&self.contents,
ray,
None,
coords,
&mut make_bounds,
act,
) {
Ok(r) => Some(r),
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use voxel;
use super::{VoxelTree, TreeBody};
#[test]
fn insert_and_lookup() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(8, -8, 4, 0)) = TreeBody::Leaf(2);
*tree.get_mut_or_create(voxel::Bounds::new(2, 0, 4, 4)) = TreeBody::Leaf(3);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(4);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(5);
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
assert_eq!(tree.get(voxel::Bounds::new(8, -8, 4, 0)), Some(&2));
assert_eq!(tree.get(voxel::Bounds::new(9, 0, 16, 2)), Some(&5));
assert_eq!(tree.get(voxel::Bounds::new(2, 0, 4, 4)), None);
}
#[test]
fn wrong_voxel_size_is_not_found() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, -4, 1)) = TreeBody::Leaf(1);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 0)), None);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 2)), None);
}
#[test]
fn grow_is_transparent() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 1));
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 2));
tree.grow_to_hold(voxel::Bounds::new(-32, 32, -128, 3));
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
}
#[test]
fn simple_cast_ray() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
let actual = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
assert_eq!(actual, Some((voxel::Bounds::new(4, 4, 4, 0), &2)));
}
#[bench]
fn simple_inserts(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
bencher.iter(|| {
*tree.get_mut_or_create(voxel::Bounds::new(0, 0, 0, 0)) = TreeBody::Leaf(0);
});
test::black_box(tree);
}
#[bench]
fn bench_cast_ray(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
bencher.iter(|| {
let r = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
test::black_box(r);
});
}
}
| {
if !self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&mut TreeBody::Branch(ref mut branches) => Ok(branches.deref_mut()),
_ => Err(()),
}
};
match self.find_mut(voxel, get_step) {
Ok(&mut TreeBody::Leaf(ref mut t)) => Some(t),
_ => None,
}
} | identifier_body |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow logic.
contents: Branches,
}
#[derive(Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Branches {
// xyz ordering
// This isn't an array because we can't move out of an array.
lll: TreeBody,
llh: TreeBody, | lhh: TreeBody,
hll: TreeBody,
hlh: TreeBody,
hhl: TreeBody,
hhh: TreeBody,
}
/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum TreeBody {
Empty,
Leaf(Voxel),
Branch(Box<Branches>),
}
impl Branches {
pub fn empty() -> Branches {
Branches {
lll: TreeBody::Empty,
llh: TreeBody::Empty,
lhl: TreeBody::Empty,
lhh: TreeBody::Empty,
hll: TreeBody::Empty,
hlh: TreeBody::Empty,
hhl: TreeBody::Empty,
hhh: TreeBody::Empty,
}
}
pub fn get<'a>(&'a self, x: usize, y: usize, z: usize) -> &'a TreeBody {
let this: &'a [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&this[x][y][z]
}
pub fn get_mut<'a>(&'a mut self, x: usize, y: usize, z: usize) -> &'a mut TreeBody {
let this: &'a mut [[[TreeBody; 2]; 2]; 2] = unsafe {
mem::transmute(self)
};
&mut this[x][y][z]
}
}
impl VoxelTree {
pub fn new() -> VoxelTree {
VoxelTree {
lg_size: 0,
contents: Branches::empty(),
}
}
/// Is this voxel (non-strictly) within an origin-centered voxel with
/// size `2^lg_size`?
pub fn contains_bounds(&self, voxel: &voxel::Bounds) -> bool {
let high;
if voxel.lg_size >= 0 {
high = (1 << self.lg_size) >> voxel.lg_size;
} else {
high = (1 << self.lg_size) << (-voxel.lg_size);
}
voxel.x < high &&
voxel.y < high &&
voxel.z < high &&
{
let low = -high;
voxel.x >= low &&
voxel.y >= low &&
voxel.z >= low &&
true
}
}
/// Ensure that this tree can hold the provided voxel.
pub fn grow_to_hold(&mut self, voxel: &voxel::Bounds) {
while!self.contains_bounds(voxel) {
// Double the bounds in every direction.
self.lg_size += 1;
// Pull out `self.contents` so we can move out of it.
let contents = mem::replace(&mut self.contents, Branches::empty());
// We re-construct the tree with bounds twice the size (but still centered
// around the origin) by deconstructing the top level of branches,
// creating a new doubly-sized top level, and moving the old branches back
// in as the new top level's children. e.g. in 2D:
//
// ---------------------------
// | | |0| | |
// | | |0| | |
// --------------- ------------|0|------------
// | 1 |0| 2 | | | 1 |0| 2 | |
// | |0| | | | |0| | |
// |------0------| |------------0------------|
// 000000000000000 ==> |0000000000000000000000000|
// |------0------| |------------0------------|
// | |0| | | | |0| | |
// | 3 |0| 4 | | | 3 |0| 4 | |
// --------------- |------------0------------|
// | | |0| | |
// | | |0| | |
// ---------------------------
macro_rules! at(
($c_idx:ident, $b_idx:ident) => {{
let mut branches = Branches::empty();
branches.$b_idx = contents.$c_idx;
TreeBody::Branch(Box::new(branches))
}}
);
self.contents =
Branches {
lll: at!(lll, hhh),
llh: at!(llh, hhl),
lhl: at!(lhl, hlh),
lhh: at!(lhh, hll),
hll: at!(hll, lhh),
hlh: at!(hlh, lhl),
hhl: at!(hhl, llh),
hhh: at!(hhh, lll),
};
}
}
fn find_mask(&self, voxel: &voxel::Bounds) -> i32 {
// When we compare the voxel position to octree bounds to choose subtrees
// for insertion, we'll be comparing voxel position to values of 2^n and
// -2^n, so we can just use the position bits to branch directly.
// This actually works for negative values too, without much wrestling:
// we need to branch on the sign bit up front, but after that, two's
// complement magic means the branching on bits works regardless of sign.
let mut mask = (1 << self.lg_size) >> 1;
// Shift everything by the voxel's lg_size, so we can compare the mask to 0
// to know whether we're done.
if voxel.lg_size >= 0 {
mask = mask >> voxel.lg_size;
} else {
// TODO: Check for overflow.
mask = mask << -voxel.lg_size;
}
mask
}
fn find_mut<'a, Step, E>(
&'a mut self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a mut TreeBody, E> where
Step: FnMut(&'a mut TreeBody) -> Result<&'a mut Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &mut self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get_mut(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| ((x & mask)!= 0) as usize,
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
fn find<'a, Step, E>(
&'a self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a TreeBody, E> where
Step: FnMut(&'a TreeBody) -> Result<&'a Branches, E>,
{
let mut mask = self.find_mask(voxel);
let mut branches = &self.contents;
macro_rules! iter(
($select:expr, $step:block) => {{
let branches_temp = branches;
let x = $select(voxel.x);
let y = $select(voxel.y);
let z = $select(voxel.z);
let branch = branches_temp.get(x, y, z);
$step;
// We've reached the voxel.
if mask == 0 {
return Ok(branch)
}
branches = try!(step(branch));
}}
);
iter!(|x| (x >= 0) as usize, {});
loop {
iter!(
|x| { ((x & mask)!= 0) as usize },
// Branch through half this size next time.
{ mask = mask >> 1; }
);
}
}
/// Find a voxel inside this tree.
/// If it doesn't exist, it will be created as empty.
pub fn get_mut_or_create<'a>(&'a mut self, voxel: &voxel::Bounds) -> &'a mut TreeBody {
self.grow_to_hold(voxel);
let branch: Result<_, ()> =
self.find_mut(voxel, |branch| { Ok(VoxelTree::get_mut_or_create_step(branch)) });
branch.unwrap()
}
fn get_mut_or_create_step<'a>(
branch: &'a mut TreeBody,
) -> &'a mut Branches {
// "Step down" the tree.
match *branch {
// Branches; we can go straight to the branching logic.
TreeBody::Branch(ref mut b) => b,
// Otherwise, keep going, but we need to insert a voxel inside the
// space occupied by the current branch.
TreeBody::Empty => {
// Replace this branch with 8 empty sub-branches - who's gonna notice?
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
TreeBody::Leaf(_) => {
// Erase this leaf and replace it with 8 empty sub-branches.
// This behavior is pretty debatable, but we need to do something,
// and it's easier to debug accidentally replacing a big chunk
// with a smaller one than to debug a nop.
*branch = TreeBody::Branch(Box::new(Branches::empty()));
match *branch {
TreeBody::Branch(ref mut b) => b,
_ => unreachable!(),
}
},
}
}
/// Find a voxel inside this tree.
pub fn get<'a>(&'a self, voxel: &voxel::Bounds) -> Option<&'a Voxel> {
if!self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&TreeBody::Branch(ref branches) => Ok(branches.deref()),
_ => Err(()),
}
};
match self.find(voxel, get_step) {
Ok(&TreeBody::Leaf(ref t)) => Some(t),
_ => None,
}
}
/// Find a voxel inside this tree.
pub fn get_mut<'a>(&'a mut self, voxel: &voxel::Bounds) -> Option<&'a mut Voxel> {
if!self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&mut TreeBody::Branch(ref mut branches) => Ok(branches.deref_mut()),
_ => Err(()),
}
};
match self.find_mut(voxel, get_step) {
Ok(&mut TreeBody::Leaf(ref mut t)) => Some(t),
_ => None,
}
}
pub fn cast_ray<'a, Act, R>(
&'a self,
ray: &Ray3<f32>,
act: &mut Act,
) -> Option<R>
where
// TODO: Does this *have* to be callback-based?
Act: FnMut(voxel::Bounds, &'a Voxel) -> Option<R>
{
let coords = [
if ray.origin.x >= 0.0 {1} else {0},
if ray.origin.y >= 0.0 {1} else {0},
if ray.origin.z >= 0.0 {1} else {0},
];
// NB: The children are half the size of the tree itself,
// but tree.lg_size=0 means it extends tree.lg_size=0 in *each direction*,
// so the "actual" size of the tree as a voxel would be tree.lg_size+1.
let child_lg_size = self.lg_size as i16;
let mut make_bounds = |coords: [usize; 3]| {
voxel::Bounds {
x: coords[0] as i32 - 1,
y: coords[1] as i32 - 1,
z: coords[2] as i32 - 1,
lg_size: child_lg_size,
}
};
match raycast::cast_ray_branches(
&self.contents,
ray,
None,
coords,
&mut make_bounds,
act,
) {
Ok(r) => Some(r),
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use voxel;
use super::{VoxelTree, TreeBody};
#[test]
fn insert_and_lookup() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(8, -8, 4, 0)) = TreeBody::Leaf(2);
*tree.get_mut_or_create(voxel::Bounds::new(2, 0, 4, 4)) = TreeBody::Leaf(3);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(4);
*tree.get_mut_or_create(voxel::Bounds::new(9, 0, 16, 2)) = TreeBody::Leaf(5);
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
assert_eq!(tree.get(voxel::Bounds::new(8, -8, 4, 0)), Some(&2));
assert_eq!(tree.get(voxel::Bounds::new(9, 0, 16, 2)), Some(&5));
assert_eq!(tree.get(voxel::Bounds::new(2, 0, 4, 4)), None);
}
#[test]
fn wrong_voxel_size_is_not_found() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, -4, 1)) = TreeBody::Leaf(1);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 0)), None);
assert_eq!(tree.get(voxel::Bounds::new(4, 4, -4, 2)), None);
}
#[test]
fn grow_is_transparent() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 1));
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 2));
tree.grow_to_hold(voxel::Bounds::new(-32, 32, -128, 3));
assert_eq!(tree.get(voxel::Bounds::new(1, 1, 1, 0)), Some(&1));
}
#[test]
fn simple_cast_ray() {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
let actual = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
assert_eq!(actual, Some((voxel::Bounds::new(4, 4, 4, 0), &2)));
}
#[bench]
fn simple_inserts(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
bencher.iter(|| {
*tree.get_mut_or_create(voxel::Bounds::new(0, 0, 0, 0)) = TreeBody::Leaf(0);
});
test::black_box(tree);
}
#[bench]
fn bench_cast_ray(bencher: &mut test::Bencher) {
let mut tree: VoxelTree<i32> = VoxelTree::new();
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 30));
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
*tree.get_mut_or_create(voxel::Bounds::new(4, 4, 4, 0)) = TreeBody::Leaf(2);
bencher.iter(|| {
let r = tree.cast_ray(
[4.5, 3.0, 4.5],
[0.1, 0.8, 0.1],
// Return the first voxel we hit.
&mut |bounds, v| Some((bounds, v)),
);
test::black_box(r);
});
}
} | lhl: TreeBody, | random_line_split |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debug_bytes")]
use std::fmt;
#[cfg(feature = "debug_bytes")]
macro_rules! debug_bytes {
($($arg:tt)*) => {
eprint!($($arg)*);
}
}
#[cfg(not(feature = "debug_bytes"))]
macro_rules! debug_bytes {
($($arg:tt)*) => {};
}
#[cfg(feature = "debug_bytes")]
struct ByteBuf<'a>(&'a [u8]);
#[cfg(feature = "debug_bytes")]
impl<'a> fmt::LowerHex for ByteBuf<'a> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <= b'Z')
|| (val >= b'a' && val <= b'z')
|| val == b'_'
{
fmtr.write_fmt(format_args!("{}", val as char))?;
} else {
fmtr.write_fmt(format_args!(r"\x{:02x}", byte))?;
}
}
Ok(())
}
}
pub trait DeRead<'de> {
/// read next byte (if peeked byte not discarded return it)
fn next(&mut self) -> anyhow::Result<u8>;
/// peek next byte (peeked byte should come in next and next_bytes unless discarded)
fn peek(&mut self) -> anyhow::Result<u8>;
/// how many bytes have been read so far.
/// this doesn't include the peeked byte
fn read_count(&self) -> usize;
/// discard peeked byte
fn discard(&mut self);
/// read next byte (if peeked byte not discarded include it)
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>>;
/// read u32 as native endian
fn next_u32(&mut self, scratch: &mut Vec<u8>) -> anyhow::Result<u32> {
let bytes = self
.next_bytes(4, scratch)
.context("error while parsing u32")?
.get_ref();
Ok(NativeEndian::read_u32(bytes))
}
}
pub struct SliceRead<'a> {
slice: &'a [u8],
index: usize,
}
impl<'a> SliceRead<'a> {
pub fn new(slice: &'a [u8]) -> Self {
SliceRead { slice, index: 0 }
}
}
pub struct IoRead<R>
where
R: io::Read,
{
reader: R,
read_count: usize,
/// Temporary storage of peeked byte.
peeked: Option<u8>,
}
impl<R> IoRead<R>
where
R: io::Read,
{
pub fn new(reader: R) -> Self {
debug_bytes!("Read bytes:\n");
IoRead {
reader,
read_count: 0,
peeked: None,
}
}
}
impl<R> Drop for IoRead<R>
where
R: io::Read,
{
fn drop(&mut self) {
debug_bytes!("\n");
}
}
impl<'a> DeRead<'a> for SliceRead<'a> {
fn next(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while reading next byte");
} | self.index += 1;
Ok(ch)
}
fn peek(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while peeking next byte");
}
Ok(self.slice[self.index])
}
#[inline]
fn read_count(&self) -> usize {
self.index
}
#[inline]
fn discard(&mut self) {
self.index += 1;
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
_scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'a,'s, [u8]>> {
// BSER has no escaping or anything similar, so just go ahead and return
// a reference to the bytes.
if self.index + len > self.slice.len() {
bail!("eof while parsing bytes/string");
}
let borrowed = &self.slice[self.index..(self.index + len)];
self.index += len;
Ok(Reference::Borrowed(borrowed))
}
}
impl<'de, R> DeRead<'de> for IoRead<R>
where
R: io::Read,
{
fn next(&mut self) -> anyhow::Result<u8> {
match self.peeked.take() {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.read_count += 1;
Ok(buffer[0])
}
}
}
fn peek(&mut self) -> anyhow::Result<u8> {
match self.peeked {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.peeked = Some(buffer[0]);
self.read_count += 1;
Ok(buffer[0])
}
}
}
#[inline]
fn read_count(&self) -> usize {
match self.peeked {
Some(_) => self.read_count - 1,
None => self.read_count,
}
}
#[inline]
fn discard(&mut self) {
self.peeked = None
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>> {
scratch.resize(len, 0);
let mut idx = 0;
if self.peeked.is_some() {
idx += 1;
}
if idx < len {
self.reader.read_exact(&mut scratch[idx..len])?;
debug_bytes!("{:x}", ByteBuf(&scratch[idx..len]));
self.read_count += len - idx;
}
if let Some(peeked) = self.peeked.take() {
scratch[0] = peeked;
}
Ok(Reference::Copied(&scratch[0..len]))
}
}
#[derive(Debug)]
pub enum Reference<'b, 'c, T:?Sized> {
Borrowed(&'b T),
Copied(&'c T),
}
impl<'b, 'c, T> Reference<'b, 'c, T>
where
T:?Sized,
{
pub fn map_result<F, U, E>(self, f: F) -> anyhow::Result<Reference<'b, 'c, U>>
where
F: FnOnce(&T) -> result::Result<&U, E>,
E: std::error::Error + Send + Sync +'static,
U:?Sized + 'b + 'c,
{
match self {
Reference::Borrowed(borrowed) => Ok(Reference::Borrowed(f(borrowed)?)),
Reference::Copied(copied) => Ok(Reference::Copied(f(copied)?)),
}
}
pub fn get_ref<'a>(&self) -> &'a T
where
'b: 'a,
'c: 'a,
{
match *self {
Reference::Borrowed(borrowed) => borrowed,
Reference::Copied(copied) => copied,
}
}
} | let ch = self.slice[self.index]; | random_line_split |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debug_bytes")]
use std::fmt;
#[cfg(feature = "debug_bytes")]
macro_rules! debug_bytes {
($($arg:tt)*) => {
eprint!($($arg)*);
}
}
#[cfg(not(feature = "debug_bytes"))]
macro_rules! debug_bytes {
($($arg:tt)*) => {};
}
#[cfg(feature = "debug_bytes")]
struct ByteBuf<'a>(&'a [u8]);
#[cfg(feature = "debug_bytes")]
impl<'a> fmt::LowerHex for ByteBuf<'a> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <= b'Z')
|| (val >= b'a' && val <= b'z')
|| val == b'_'
{
fmtr.write_fmt(format_args!("{}", val as char))?;
} else {
fmtr.write_fmt(format_args!(r"\x{:02x}", byte))?;
}
}
Ok(())
}
}
pub trait DeRead<'de> {
/// read next byte (if peeked byte not discarded return it)
fn next(&mut self) -> anyhow::Result<u8>;
/// peek next byte (peeked byte should come in next and next_bytes unless discarded)
fn peek(&mut self) -> anyhow::Result<u8>;
/// how many bytes have been read so far.
/// this doesn't include the peeked byte
fn read_count(&self) -> usize;
/// discard peeked byte
fn discard(&mut self);
/// read next byte (if peeked byte not discarded include it)
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>>;
/// read u32 as native endian
fn next_u32(&mut self, scratch: &mut Vec<u8>) -> anyhow::Result<u32> {
let bytes = self
.next_bytes(4, scratch)
.context("error while parsing u32")?
.get_ref();
Ok(NativeEndian::read_u32(bytes))
}
}
pub struct SliceRead<'a> {
slice: &'a [u8],
index: usize,
}
impl<'a> SliceRead<'a> {
pub fn new(slice: &'a [u8]) -> Self {
SliceRead { slice, index: 0 }
}
}
pub struct IoRead<R>
where
R: io::Read,
{
reader: R,
read_count: usize,
/// Temporary storage of peeked byte.
peeked: Option<u8>,
}
impl<R> IoRead<R>
where
R: io::Read,
{
pub fn new(reader: R) -> Self {
debug_bytes!("Read bytes:\n");
IoRead {
reader,
read_count: 0,
peeked: None,
}
}
}
impl<R> Drop for IoRead<R>
where
R: io::Read,
{
fn drop(&mut self) {
debug_bytes!("\n");
}
}
impl<'a> DeRead<'a> for SliceRead<'a> {
fn next(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while reading next byte");
}
let ch = self.slice[self.index];
self.index += 1;
Ok(ch)
}
fn peek(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while peeking next byte");
}
Ok(self.slice[self.index])
}
#[inline]
fn read_count(&self) -> usize {
self.index
}
#[inline]
fn discard(&mut self) {
self.index += 1;
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
_scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'a,'s, [u8]>> {
// BSER has no escaping or anything similar, so just go ahead and return
// a reference to the bytes.
if self.index + len > self.slice.len() |
let borrowed = &self.slice[self.index..(self.index + len)];
self.index += len;
Ok(Reference::Borrowed(borrowed))
}
}
impl<'de, R> DeRead<'de> for IoRead<R>
where
R: io::Read,
{
fn next(&mut self) -> anyhow::Result<u8> {
match self.peeked.take() {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.read_count += 1;
Ok(buffer[0])
}
}
}
fn peek(&mut self) -> anyhow::Result<u8> {
match self.peeked {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.peeked = Some(buffer[0]);
self.read_count += 1;
Ok(buffer[0])
}
}
}
#[inline]
fn read_count(&self) -> usize {
match self.peeked {
Some(_) => self.read_count - 1,
None => self.read_count,
}
}
#[inline]
fn discard(&mut self) {
self.peeked = None
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>> {
scratch.resize(len, 0);
let mut idx = 0;
if self.peeked.is_some() {
idx += 1;
}
if idx < len {
self.reader.read_exact(&mut scratch[idx..len])?;
debug_bytes!("{:x}", ByteBuf(&scratch[idx..len]));
self.read_count += len - idx;
}
if let Some(peeked) = self.peeked.take() {
scratch[0] = peeked;
}
Ok(Reference::Copied(&scratch[0..len]))
}
}
#[derive(Debug)]
pub enum Reference<'b, 'c, T:?Sized> {
Borrowed(&'b T),
Copied(&'c T),
}
impl<'b, 'c, T> Reference<'b, 'c, T>
where
T:?Sized,
{
pub fn map_result<F, U, E>(self, f: F) -> anyhow::Result<Reference<'b, 'c, U>>
where
F: FnOnce(&T) -> result::Result<&U, E>,
E: std::error::Error + Send + Sync +'static,
U:?Sized + 'b + 'c,
{
match self {
Reference::Borrowed(borrowed) => Ok(Reference::Borrowed(f(borrowed)?)),
Reference::Copied(copied) => Ok(Reference::Copied(f(copied)?)),
}
}
pub fn get_ref<'a>(&self) -> &'a T
where
'b: 'a,
'c: 'a,
{
match *self {
Reference::Borrowed(borrowed) => borrowed,
Reference::Copied(copied) => copied,
}
}
}
| {
bail!("eof while parsing bytes/string");
} | conditional_block |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debug_bytes")]
use std::fmt;
#[cfg(feature = "debug_bytes")]
macro_rules! debug_bytes {
($($arg:tt)*) => {
eprint!($($arg)*);
}
}
#[cfg(not(feature = "debug_bytes"))]
macro_rules! debug_bytes {
($($arg:tt)*) => {};
}
#[cfg(feature = "debug_bytes")]
struct | <'a>(&'a [u8]);
#[cfg(feature = "debug_bytes")]
impl<'a> fmt::LowerHex for ByteBuf<'a> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <= b'Z')
|| (val >= b'a' && val <= b'z')
|| val == b'_'
{
fmtr.write_fmt(format_args!("{}", val as char))?;
} else {
fmtr.write_fmt(format_args!(r"\x{:02x}", byte))?;
}
}
Ok(())
}
}
pub trait DeRead<'de> {
/// read next byte (if peeked byte not discarded return it)
fn next(&mut self) -> anyhow::Result<u8>;
/// peek next byte (peeked byte should come in next and next_bytes unless discarded)
fn peek(&mut self) -> anyhow::Result<u8>;
/// how many bytes have been read so far.
/// this doesn't include the peeked byte
fn read_count(&self) -> usize;
/// discard peeked byte
fn discard(&mut self);
/// read next byte (if peeked byte not discarded include it)
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>>;
/// read u32 as native endian
fn next_u32(&mut self, scratch: &mut Vec<u8>) -> anyhow::Result<u32> {
let bytes = self
.next_bytes(4, scratch)
.context("error while parsing u32")?
.get_ref();
Ok(NativeEndian::read_u32(bytes))
}
}
pub struct SliceRead<'a> {
slice: &'a [u8],
index: usize,
}
impl<'a> SliceRead<'a> {
pub fn new(slice: &'a [u8]) -> Self {
SliceRead { slice, index: 0 }
}
}
pub struct IoRead<R>
where
R: io::Read,
{
reader: R,
read_count: usize,
/// Temporary storage of peeked byte.
peeked: Option<u8>,
}
impl<R> IoRead<R>
where
R: io::Read,
{
pub fn new(reader: R) -> Self {
debug_bytes!("Read bytes:\n");
IoRead {
reader,
read_count: 0,
peeked: None,
}
}
}
impl<R> Drop for IoRead<R>
where
R: io::Read,
{
fn drop(&mut self) {
debug_bytes!("\n");
}
}
impl<'a> DeRead<'a> for SliceRead<'a> {
fn next(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while reading next byte");
}
let ch = self.slice[self.index];
self.index += 1;
Ok(ch)
}
fn peek(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while peeking next byte");
}
Ok(self.slice[self.index])
}
#[inline]
fn read_count(&self) -> usize {
self.index
}
#[inline]
fn discard(&mut self) {
self.index += 1;
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
_scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'a,'s, [u8]>> {
// BSER has no escaping or anything similar, so just go ahead and return
// a reference to the bytes.
if self.index + len > self.slice.len() {
bail!("eof while parsing bytes/string");
}
let borrowed = &self.slice[self.index..(self.index + len)];
self.index += len;
Ok(Reference::Borrowed(borrowed))
}
}
impl<'de, R> DeRead<'de> for IoRead<R>
where
R: io::Read,
{
fn next(&mut self) -> anyhow::Result<u8> {
match self.peeked.take() {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.read_count += 1;
Ok(buffer[0])
}
}
}
fn peek(&mut self) -> anyhow::Result<u8> {
match self.peeked {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.peeked = Some(buffer[0]);
self.read_count += 1;
Ok(buffer[0])
}
}
}
#[inline]
fn read_count(&self) -> usize {
match self.peeked {
Some(_) => self.read_count - 1,
None => self.read_count,
}
}
#[inline]
fn discard(&mut self) {
self.peeked = None
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>> {
scratch.resize(len, 0);
let mut idx = 0;
if self.peeked.is_some() {
idx += 1;
}
if idx < len {
self.reader.read_exact(&mut scratch[idx..len])?;
debug_bytes!("{:x}", ByteBuf(&scratch[idx..len]));
self.read_count += len - idx;
}
if let Some(peeked) = self.peeked.take() {
scratch[0] = peeked;
}
Ok(Reference::Copied(&scratch[0..len]))
}
}
#[derive(Debug)]
pub enum Reference<'b, 'c, T:?Sized> {
Borrowed(&'b T),
Copied(&'c T),
}
impl<'b, 'c, T> Reference<'b, 'c, T>
where
T:?Sized,
{
pub fn map_result<F, U, E>(self, f: F) -> anyhow::Result<Reference<'b, 'c, U>>
where
F: FnOnce(&T) -> result::Result<&U, E>,
E: std::error::Error + Send + Sync +'static,
U:?Sized + 'b + 'c,
{
match self {
Reference::Borrowed(borrowed) => Ok(Reference::Borrowed(f(borrowed)?)),
Reference::Copied(copied) => Ok(Reference::Copied(f(copied)?)),
}
}
pub fn get_ref<'a>(&self) -> &'a T
where
'b: 'a,
'c: 'a,
{
match *self {
Reference::Borrowed(borrowed) => borrowed,
Reference::Copied(copied) => copied,
}
}
}
| ByteBuf | identifier_name |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debug_bytes")]
use std::fmt;
#[cfg(feature = "debug_bytes")]
macro_rules! debug_bytes {
($($arg:tt)*) => {
eprint!($($arg)*);
}
}
#[cfg(not(feature = "debug_bytes"))]
macro_rules! debug_bytes {
($($arg:tt)*) => {};
}
#[cfg(feature = "debug_bytes")]
struct ByteBuf<'a>(&'a [u8]);
#[cfg(feature = "debug_bytes")]
impl<'a> fmt::LowerHex for ByteBuf<'a> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> result::Result<(), fmt::Error> |
}
pub trait DeRead<'de> {
/// read next byte (if peeked byte not discarded return it)
fn next(&mut self) -> anyhow::Result<u8>;
/// peek next byte (peeked byte should come in next and next_bytes unless discarded)
fn peek(&mut self) -> anyhow::Result<u8>;
/// how many bytes have been read so far.
/// this doesn't include the peeked byte
fn read_count(&self) -> usize;
/// discard peeked byte
fn discard(&mut self);
/// read next byte (if peeked byte not discarded include it)
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>>;
/// read u32 as native endian
fn next_u32(&mut self, scratch: &mut Vec<u8>) -> anyhow::Result<u32> {
let bytes = self
.next_bytes(4, scratch)
.context("error while parsing u32")?
.get_ref();
Ok(NativeEndian::read_u32(bytes))
}
}
pub struct SliceRead<'a> {
slice: &'a [u8],
index: usize,
}
impl<'a> SliceRead<'a> {
pub fn new(slice: &'a [u8]) -> Self {
SliceRead { slice, index: 0 }
}
}
pub struct IoRead<R>
where
R: io::Read,
{
reader: R,
read_count: usize,
/// Temporary storage of peeked byte.
peeked: Option<u8>,
}
impl<R> IoRead<R>
where
R: io::Read,
{
pub fn new(reader: R) -> Self {
debug_bytes!("Read bytes:\n");
IoRead {
reader,
read_count: 0,
peeked: None,
}
}
}
impl<R> Drop for IoRead<R>
where
R: io::Read,
{
fn drop(&mut self) {
debug_bytes!("\n");
}
}
impl<'a> DeRead<'a> for SliceRead<'a> {
fn next(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while reading next byte");
}
let ch = self.slice[self.index];
self.index += 1;
Ok(ch)
}
fn peek(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while peeking next byte");
}
Ok(self.slice[self.index])
}
#[inline]
fn read_count(&self) -> usize {
self.index
}
#[inline]
fn discard(&mut self) {
self.index += 1;
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
_scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'a,'s, [u8]>> {
// BSER has no escaping or anything similar, so just go ahead and return
// a reference to the bytes.
if self.index + len > self.slice.len() {
bail!("eof while parsing bytes/string");
}
let borrowed = &self.slice[self.index..(self.index + len)];
self.index += len;
Ok(Reference::Borrowed(borrowed))
}
}
impl<'de, R> DeRead<'de> for IoRead<R>
where
R: io::Read,
{
fn next(&mut self) -> anyhow::Result<u8> {
match self.peeked.take() {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.read_count += 1;
Ok(buffer[0])
}
}
}
fn peek(&mut self) -> anyhow::Result<u8> {
match self.peeked {
Some(peeked) => Ok(peeked),
None => {
let mut buffer = [0; 1];
self.reader.read_exact(&mut buffer)?;
debug_bytes!("{:x}", ByteBuf(&buffer));
self.peeked = Some(buffer[0]);
self.read_count += 1;
Ok(buffer[0])
}
}
}
#[inline]
fn read_count(&self) -> usize {
match self.peeked {
Some(_) => self.read_count - 1,
None => self.read_count,
}
}
#[inline]
fn discard(&mut self) {
self.peeked = None
}
fn next_bytes<'s>(
&'s mut self,
len: usize,
scratch: &'s mut Vec<u8>,
) -> anyhow::Result<Reference<'de,'s, [u8]>> {
scratch.resize(len, 0);
let mut idx = 0;
if self.peeked.is_some() {
idx += 1;
}
if idx < len {
self.reader.read_exact(&mut scratch[idx..len])?;
debug_bytes!("{:x}", ByteBuf(&scratch[idx..len]));
self.read_count += len - idx;
}
if let Some(peeked) = self.peeked.take() {
scratch[0] = peeked;
}
Ok(Reference::Copied(&scratch[0..len]))
}
}
#[derive(Debug)]
pub enum Reference<'b, 'c, T:?Sized> {
Borrowed(&'b T),
Copied(&'c T),
}
impl<'b, 'c, T> Reference<'b, 'c, T>
where
T:?Sized,
{
pub fn map_result<F, U, E>(self, f: F) -> anyhow::Result<Reference<'b, 'c, U>>
where
F: FnOnce(&T) -> result::Result<&U, E>,
E: std::error::Error + Send + Sync +'static,
U:?Sized + 'b + 'c,
{
match self {
Reference::Borrowed(borrowed) => Ok(Reference::Borrowed(f(borrowed)?)),
Reference::Copied(copied) => Ok(Reference::Copied(f(copied)?)),
}
}
pub fn get_ref<'a>(&self) -> &'a T
where
'b: 'a,
'c: 'a,
{
match *self {
Reference::Borrowed(borrowed) => borrowed,
Reference::Copied(copied) => copied,
}
}
}
| {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <= b'Z')
|| (val >= b'a' && val <= b'z')
|| val == b'_'
{
fmtr.write_fmt(format_args!("{}", val as char))?;
} else {
fmtr.write_fmt(format_args!(r"\x{:02x}", byte))?;
}
}
Ok(())
} | identifier_body |
htmlbuttonelement.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::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLButtonElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{HTMLButtonElementDerived, HTMLFieldSetElementDerived};
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{Element, ElementTypeId};
use dom::event::Event;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmlformelement::{FormSubmitter, FormControl};
use dom::htmlformelement::{SubmittedFrom};
use dom::node::{Node, NodeTypeId, document_from_node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use util::str::DOMString;
#[derive(JSTraceable, PartialEq, Copy, Clone)]
#[allow(dead_code)]
#[derive(HeapSizeOf)]
enum ButtonType {
ButtonSubmit,
ButtonReset,
ButtonButton,
ButtonMenu
}
#[dom_struct]
pub struct HTMLButtonElement {
htmlelement: HTMLElement,
button_type: Cell<ButtonType>
}
impl HTMLButtonElementDerived for EventTarget {
fn is_htmlbuttonelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)))
}
}
impl HTMLButtonElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLButtonElement {
HTMLButtonElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLButtonElement, localName, prefix, document),
//TODO: implement button_type in after_set_attr
button_type: Cell::new(ButtonType::ButtonSubmit)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLButtonElement> {
let element = HTMLButtonElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLButtonElementBinding::Wrap)
}
}
impl HTMLButtonElementMethods for HTMLButtonElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_getter!(Disabled);
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-button-type
fn Type(&self) -> DOMString {
let elem = ElementCast::from_ref(self);
let mut ty = elem.get_string_attribute(&atom!("type"));
ty.make_ascii_lowercase();
// https://html.spec.whatwg.org/multipage/#attr-button-type
match &*ty {
"reset" | "button" | "menu" => ty,
_ => "submit".to_owned()
}
}
// https://html.spec.whatwg.org/multipage/#dom-button-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#htmlbuttonelement
make_url_or_base_getter!(FormAction);
make_setter!(SetFormAction, "formaction");
make_enumerated_getter!(
FormEnctype, "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data"));
make_setter!(SetFormEnctype, "formenctype");
make_enumerated_getter!(FormMethod, "get", ("post") | ("dialog"));
make_setter!(SetFormMethod, "formmethod");
make_getter!(FormTarget);
make_setter!(SetFormTarget, "formtarget");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-button-value
make_getter!(Value);
// https://html.spec.whatwg.org/multipage/#dom-button-value
make_setter!(SetValue, "value");
}
impl VirtualMethods for HTMLButtonElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(true);
node.set_enabled_state(false);
},
_ => ()
}
}
fn before_remove_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(false);
node.set_enabled_state(true);
node.check_ancestors_disabled_state_for_form_control();
},
_ => ()
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
node.check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) {
node.check_ancestors_disabled_state_for_form_control();
} else {
node.check_disabled_attribute();
}
}
}
impl<'a> FormControl<'a> for &'a HTMLButtonElement {
fn to_element(self) -> &'a Element {
ElementCast::from_ref(self)
}
}
impl<'a> Activatable for &'a HTMLButtonElement {
fn as_element<'b>(&'b self) -> &'b Element {
ElementCast::from_ref(*self)
}
fn is_instance_activatable(&self) -> bool {
//https://html.spec.whatwg.org/multipage/#the-button-element
let node = NodeCast::from_ref(*self);
!(node.get_disabled_state())
}
// https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps
// https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior
fn pre_click_activation(&self) |
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.button_type.get();
match ty {
//https://html.spec.whatwg.org/multipage/#attr-button-type-submit-state
ButtonType::ButtonSubmit => {
self.form_owner().map(|o| {
o.r().submit(SubmittedFrom::NotFromFormSubmitMethod,
FormSubmitter::ButtonElement(self.clone()))
});
},
_ => ()
}
}
// https://html.spec.whatwg.org/multipage/#implicit-submission
#[allow(unsafe_code)]
fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let doc = document_from_node(*self);
let node = NodeCast::from_ref(doc.r());
let owner = self.form_owner();
let elem = ElementCast::from_ref(*self);
if owner.is_none() || elem.click_in_progress() {
return;
}
// This is safe because we are stopping after finding the first element
// and only then performing actions which may modify the DOM tree
unsafe {
node.query_selector_iter("button[type=submit]".to_owned()).unwrap()
.filter_map(HTMLButtonElementCast::to_root)
.find(|r| r.r().form_owner() == owner)
.map(|s| s.r().synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey));
}
}
}
| {
} | identifier_body |
htmlbuttonelement.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::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLButtonElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{HTMLButtonElementDerived, HTMLFieldSetElementDerived};
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{Element, ElementTypeId};
use dom::event::Event;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmlformelement::{FormSubmitter, FormControl};
use dom::htmlformelement::{SubmittedFrom};
use dom::node::{Node, NodeTypeId, document_from_node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use util::str::DOMString;
#[derive(JSTraceable, PartialEq, Copy, Clone)]
#[allow(dead_code)]
#[derive(HeapSizeOf)]
enum ButtonType {
ButtonSubmit,
ButtonReset,
ButtonButton,
ButtonMenu
}
#[dom_struct]
pub struct HTMLButtonElement {
htmlelement: HTMLElement,
button_type: Cell<ButtonType>
}
impl HTMLButtonElementDerived for EventTarget {
fn is_htmlbuttonelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)))
}
}
impl HTMLButtonElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLButtonElement {
HTMLButtonElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLButtonElement, localName, prefix, document),
//TODO: implement button_type in after_set_attr
button_type: Cell::new(ButtonType::ButtonSubmit)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLButtonElement> {
let element = HTMLButtonElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLButtonElementBinding::Wrap)
}
}
impl HTMLButtonElementMethods for HTMLButtonElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_getter!(Disabled);
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-button-type
fn Type(&self) -> DOMString {
let elem = ElementCast::from_ref(self);
let mut ty = elem.get_string_attribute(&atom!("type"));
ty.make_ascii_lowercase();
// https://html.spec.whatwg.org/multipage/#attr-button-type
match &*ty {
"reset" | "button" | "menu" => ty,
_ => "submit".to_owned()
}
}
// https://html.spec.whatwg.org/multipage/#dom-button-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#htmlbuttonelement
make_url_or_base_getter!(FormAction);
make_setter!(SetFormAction, "formaction");
make_enumerated_getter!(
FormEnctype, "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data"));
make_setter!(SetFormEnctype, "formenctype");
make_enumerated_getter!(FormMethod, "get", ("post") | ("dialog"));
make_setter!(SetFormMethod, "formmethod");
make_getter!(FormTarget);
make_setter!(SetFormTarget, "formtarget");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-button-value
make_getter!(Value);
// https://html.spec.whatwg.org/multipage/#dom-button-value
make_setter!(SetValue, "value");
}
impl VirtualMethods for HTMLButtonElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(true);
node.set_enabled_state(false);
},
_ => ()
}
}
fn before_remove_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(false);
node.set_enabled_state(true);
node.check_ancestors_disabled_state_for_form_control();
},
_ => ()
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
node.check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) {
node.check_ancestors_disabled_state_for_form_control();
} else {
node.check_disabled_attribute();
}
}
}
impl<'a> FormControl<'a> for &'a HTMLButtonElement {
fn to_element(self) -> &'a Element {
ElementCast::from_ref(self)
}
}
impl<'a> Activatable for &'a HTMLButtonElement {
fn as_element<'b>(&'b self) -> &'b Element {
ElementCast::from_ref(*self)
}
fn is_instance_activatable(&self) -> bool {
//https://html.spec.whatwg.org/multipage/#the-button-element
let node = NodeCast::from_ref(*self);
!(node.get_disabled_state())
}
// https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps
// https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior
fn | (&self) {
}
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.button_type.get();
match ty {
//https://html.spec.whatwg.org/multipage/#attr-button-type-submit-state
ButtonType::ButtonSubmit => {
self.form_owner().map(|o| {
o.r().submit(SubmittedFrom::NotFromFormSubmitMethod,
FormSubmitter::ButtonElement(self.clone()))
});
},
_ => ()
}
}
// https://html.spec.whatwg.org/multipage/#implicit-submission
#[allow(unsafe_code)]
fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let doc = document_from_node(*self);
let node = NodeCast::from_ref(doc.r());
let owner = self.form_owner();
let elem = ElementCast::from_ref(*self);
if owner.is_none() || elem.click_in_progress() {
return;
}
// This is safe because we are stopping after finding the first element
// and only then performing actions which may modify the DOM tree
unsafe {
node.query_selector_iter("button[type=submit]".to_owned()).unwrap()
.filter_map(HTMLButtonElementCast::to_root)
.find(|r| r.r().form_owner() == owner)
.map(|s| s.r().synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey));
}
}
}
| pre_click_activation | identifier_name |
htmlbuttonelement.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::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLButtonElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{HTMLButtonElementDerived, HTMLFieldSetElementDerived};
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{Element, ElementTypeId};
use dom::event::Event;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmlformelement::{FormSubmitter, FormControl};
use dom::htmlformelement::{SubmittedFrom};
use dom::node::{Node, NodeTypeId, document_from_node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use util::str::DOMString;
#[derive(JSTraceable, PartialEq, Copy, Clone)]
#[allow(dead_code)]
#[derive(HeapSizeOf)]
enum ButtonType {
ButtonSubmit,
ButtonReset,
ButtonButton,
ButtonMenu
}
#[dom_struct]
pub struct HTMLButtonElement {
htmlelement: HTMLElement,
button_type: Cell<ButtonType>
}
impl HTMLButtonElementDerived for EventTarget {
fn is_htmlbuttonelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)))
}
}
impl HTMLButtonElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLButtonElement {
HTMLButtonElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLButtonElement, localName, prefix, document),
//TODO: implement button_type in after_set_attr
button_type: Cell::new(ButtonType::ButtonSubmit)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLButtonElement> {
let element = HTMLButtonElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLButtonElementBinding::Wrap)
}
}
impl HTMLButtonElementMethods for HTMLButtonElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_getter!(Disabled);
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-button-type
fn Type(&self) -> DOMString {
let elem = ElementCast::from_ref(self);
let mut ty = elem.get_string_attribute(&atom!("type"));
ty.make_ascii_lowercase();
// https://html.spec.whatwg.org/multipage/#attr-button-type
match &*ty {
"reset" | "button" | "menu" => ty,
_ => "submit".to_owned()
}
}
// https://html.spec.whatwg.org/multipage/#dom-button-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#htmlbuttonelement
make_url_or_base_getter!(FormAction);
make_setter!(SetFormAction, "formaction");
make_enumerated_getter!(
FormEnctype, "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data"));
make_setter!(SetFormEnctype, "formenctype");
make_enumerated_getter!(FormMethod, "get", ("post") | ("dialog"));
make_setter!(SetFormMethod, "formmethod");
make_getter!(FormTarget);
make_setter!(SetFormTarget, "formtarget");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-button-value
make_getter!(Value);
// https://html.spec.whatwg.org/multipage/#dom-button-value
make_setter!(SetValue, "value");
}
impl VirtualMethods for HTMLButtonElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(true);
node.set_enabled_state(false);
},
_ => ()
}
}
fn before_remove_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(false);
node.set_enabled_state(true);
node.check_ancestors_disabled_state_for_form_control();
},
_ => ()
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
node.check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) {
node.check_ancestors_disabled_state_for_form_control();
} else {
node.check_disabled_attribute();
}
}
}
impl<'a> FormControl<'a> for &'a HTMLButtonElement {
fn to_element(self) -> &'a Element {
ElementCast::from_ref(self)
}
}
impl<'a> Activatable for &'a HTMLButtonElement {
fn as_element<'b>(&'b self) -> &'b Element {
ElementCast::from_ref(*self)
}
fn is_instance_activatable(&self) -> bool {
//https://html.spec.whatwg.org/multipage/#the-button-element
let node = NodeCast::from_ref(*self);
!(node.get_disabled_state())
}
// https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps
// https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior
fn pre_click_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.button_type.get();
match ty {
//https://html.spec.whatwg.org/multipage/#attr-button-type-submit-state
ButtonType::ButtonSubmit => {
self.form_owner().map(|o| {
o.r().submit(SubmittedFrom::NotFromFormSubmitMethod,
FormSubmitter::ButtonElement(self.clone()))
});
},
_ => ()
} | }
// https://html.spec.whatwg.org/multipage/#implicit-submission
#[allow(unsafe_code)]
fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let doc = document_from_node(*self);
let node = NodeCast::from_ref(doc.r());
let owner = self.form_owner();
let elem = ElementCast::from_ref(*self);
if owner.is_none() || elem.click_in_progress() {
return;
}
// This is safe because we are stopping after finding the first element
// and only then performing actions which may modify the DOM tree
unsafe {
node.query_selector_iter("button[type=submit]".to_owned()).unwrap()
.filter_map(HTMLButtonElementCast::to_root)
.find(|r| r.r().form_owner() == owner)
.map(|s| s.r().synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey));
}
}
} | random_line_split |
|
cli.rs | //! Command argument types
//! The deserialized structures of the command args.
#![allow(non_camel_case_types,non_snake_case)]
use core::fmt;
use core::str::FromStr;
use docopt;
use opengl_graphics::OpenGL;
use rustc_serialize::{Decodable,Decoder};
use std::net;
docopt!(pub Args derive Debug,concat!("
Usage: ",PROGRAM_NAME!()," [options]
",PROGRAM_NAME!()," --help
A game with tetrominos falling.
Options:
-h, --help Show this message
-v, --version Show version
--credits Show credits/staff
--manual Show instruction manual/guide for the game
--online=CONNECTION Available modes: none, server, client [default: none]
--host=ADDR Network address used for the online connection [default: 0.0.0.0]
--port=N Network port used for the online connection [default: 7374]
--window-size=SIZE Window size [default: 800x600]
--window-mode=MODE Available modes: window, fullscreen [default: window]
--gl-backend=BACKEND Not implemented yet. Available backends: sdl2, glfw, glutin [default: glutin]
--gl-version=NN Available versions: 20, 21, 30, 31, 32, 33, 40, 41, 42, 43, 44, 45 [default: 32]
"),
flag_online : OnlineConnection,
flag_host : Host,
flag_port : Port,
flag_window_size: WindowSize,
flag_window_mode: WindowMode,
flag_gl_backend : GlBackend,
flag_gl_version : GlVersion,
);
///Workaround for the creation of Args because the docopt macro is not making everything public
#[inline(always)]
pub fn Args_docopt() -> docopt::Docopt{Args::docopt()}
#[derive(Debug)]
pub struct | (pub net::IpAddr);
impl Decodable for Host{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
Ok(Host(match net::IpAddr::from_str(str){
Ok(addr) => addr,
Err(_) => try!(try!(try!(
net::lookup_host(str).map_err(|_| d.error("Error when lookup_host")))
.next().ok_or_else(|| d.error("No hosts when lookup_host")))
.map_err(|_| d.error("Error when converting to IpAddr with lookup_host")))
.ip()
}))
}
}
pub type Port = u16;
#[derive(Debug,RustcDecodable)]
pub enum OnlineConnection{none,server,client}
#[derive(Debug)]
pub struct WindowSize(pub u32,pub u32);
impl Decodable for WindowSize{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
let (w,h) = str.split_at(try!(str.find('x').ok_or_else(|| d.error("Invalid format: Missing 'x' in \"<WIDTH>x<HEIGHT>\""))));
Ok(WindowSize(
try!(FromStr::from_str(w).map_err(|_| d.error("Invalid format: <WIDTH> in (<SIZE> = <WIDTH>x<HEIGHT>) is not a valid positive integer"))),
try!(FromStr::from_str(&h[1..]).map_err(|_| d.error("Invalid format: <HEIGHT> in (<SIZE> = <WIDTH>x<HEIGHT>) is not a valid positive integer")))
))
}
}
#[derive(Debug,RustcDecodable)]
pub enum WindowMode{window,fullscreen}
#[derive(Debug,RustcDecodable)]
pub enum GlBackend{sdl2,glfw,glutin}
pub struct GlVersion(pub OpenGL);
impl fmt::Debug for GlVersion{
fn fmt(&self,f: &mut fmt::Formatter) -> fmt::Result{
write!(f,"{}",match self.0{
OpenGL::V2_0 => "v2.0",
OpenGL::V2_1 => "v2.1",
OpenGL::V3_0 => "v3.0",
OpenGL::V3_1 => "v3.1",
OpenGL::V3_2 => "v3.2",
OpenGL::V3_3 => "v3.3",
OpenGL::V4_0 => "v4.0",
OpenGL::V4_1 => "v4.1",
OpenGL::V4_2 => "v4.2",
OpenGL::V4_3 => "v4.3",
OpenGL::V4_4 => "v4.4",
OpenGL::V4_5 => "v4.5",
})
}
}
impl Decodable for GlVersion{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
Ok(GlVersion(
match try!(u8::from_str(str).map_err(|_| d.error("Invalid format: <NN> in (--gl-version=NN) is not a valid positive integer"))){
20 => OpenGL::V2_0,
21 => OpenGL::V2_1,
30 => OpenGL::V3_0,
31 => OpenGL::V3_1,
32 => OpenGL::V3_2,
33 => OpenGL::V3_3,
40 => OpenGL::V4_0,
41 => OpenGL::V4_1,
42 => OpenGL::V4_2,
43 => OpenGL::V4_3,
44 => OpenGL::V4_4,
45 => OpenGL::V4_5,
_ => return Err(d.error("Invalid version number was given"))
}
))
}
}
| Host | identifier_name |
cli.rs | //! Command argument types
//! The deserialized structures of the command args.
#![allow(non_camel_case_types,non_snake_case)]
use core::fmt;
use core::str::FromStr;
use docopt;
use opengl_graphics::OpenGL;
use rustc_serialize::{Decodable,Decoder};
use std::net;
docopt!(pub Args derive Debug,concat!("
Usage: ",PROGRAM_NAME!()," [options]
",PROGRAM_NAME!()," --help
A game with tetrominos falling.
Options:
-h, --help Show this message
-v, --version Show version
--credits Show credits/staff
--manual Show instruction manual/guide for the game
--online=CONNECTION Available modes: none, server, client [default: none]
--host=ADDR Network address used for the online connection [default: 0.0.0.0]
--port=N Network port used for the online connection [default: 7374]
--window-size=SIZE Window size [default: 800x600]
--window-mode=MODE Available modes: window, fullscreen [default: window]
--gl-backend=BACKEND Not implemented yet. Available backends: sdl2, glfw, glutin [default: glutin]
--gl-version=NN Available versions: 20, 21, 30, 31, 32, 33, 40, 41, 42, 43, 44, 45 [default: 32]
"),
flag_online : OnlineConnection,
flag_host : Host,
flag_port : Port,
flag_window_size: WindowSize,
flag_window_mode: WindowMode,
flag_gl_backend : GlBackend,
flag_gl_version : GlVersion,
);
///Workaround for the creation of Args because the docopt macro is not making everything public
#[inline(always)]
pub fn Args_docopt() -> docopt::Docopt{Args::docopt()}
#[derive(Debug)]
pub struct Host(pub net::IpAddr);
impl Decodable for Host{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
Ok(Host(match net::IpAddr::from_str(str){
Ok(addr) => addr,
Err(_) => try!(try!(try!(
net::lookup_host(str).map_err(|_| d.error("Error when lookup_host")))
.next().ok_or_else(|| d.error("No hosts when lookup_host")))
.map_err(|_| d.error("Error when converting to IpAddr with lookup_host")))
.ip()
}))
}
}
pub type Port = u16;
#[derive(Debug,RustcDecodable)]
pub enum OnlineConnection{none,server,client}
#[derive(Debug)]
pub struct WindowSize(pub u32,pub u32);
impl Decodable for WindowSize{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
let (w,h) = str.split_at(try!(str.find('x').ok_or_else(|| d.error("Invalid format: Missing 'x' in \"<WIDTH>x<HEIGHT>\""))));
Ok(WindowSize(
try!(FromStr::from_str(w).map_err(|_| d.error("Invalid format: <WIDTH> in (<SIZE> = <WIDTH>x<HEIGHT>) is not a valid positive integer"))),
try!(FromStr::from_str(&h[1..]).map_err(|_| d.error("Invalid format: <HEIGHT> in (<SIZE> = <WIDTH>x<HEIGHT>) is not a valid positive integer")))
))
}
}
#[derive(Debug,RustcDecodable)]
pub enum WindowMode{window,fullscreen}
#[derive(Debug,RustcDecodable)]
pub enum GlBackend{sdl2,glfw,glutin}
pub struct GlVersion(pub OpenGL); | impl fmt::Debug for GlVersion{
fn fmt(&self,f: &mut fmt::Formatter) -> fmt::Result{
write!(f,"{}",match self.0{
OpenGL::V2_0 => "v2.0",
OpenGL::V2_1 => "v2.1",
OpenGL::V3_0 => "v3.0",
OpenGL::V3_1 => "v3.1",
OpenGL::V3_2 => "v3.2",
OpenGL::V3_3 => "v3.3",
OpenGL::V4_0 => "v4.0",
OpenGL::V4_1 => "v4.1",
OpenGL::V4_2 => "v4.2",
OpenGL::V4_3 => "v4.3",
OpenGL::V4_4 => "v4.4",
OpenGL::V4_5 => "v4.5",
})
}
}
impl Decodable for GlVersion{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
Ok(GlVersion(
match try!(u8::from_str(str).map_err(|_| d.error("Invalid format: <NN> in (--gl-version=NN) is not a valid positive integer"))){
20 => OpenGL::V2_0,
21 => OpenGL::V2_1,
30 => OpenGL::V3_0,
31 => OpenGL::V3_1,
32 => OpenGL::V3_2,
33 => OpenGL::V3_3,
40 => OpenGL::V4_0,
41 => OpenGL::V4_1,
42 => OpenGL::V4_2,
43 => OpenGL::V4_3,
44 => OpenGL::V4_4,
45 => OpenGL::V4_5,
_ => return Err(d.error("Invalid version number was given"))
}
))
}
} | random_line_split |
|
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url;
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths;
use support::git::repo;
use hamcrest::assert_that;
fn registry_path() -> PathBuf { paths::root().join("registry") }
fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() }
fn upload_path() -> PathBuf |
fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
fn setup() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config).unwrap().write_all(&format!(r#"
[registry]
index = "{reg}"
token = "api-token"
"#, reg = registry()).as_bytes()).unwrap();
fs::create_dir_all(&upload_path().join("api/v1/crates")).unwrap();
repo(®istry_path())
.file("config.json", &format!(r#"{{
"dl": "{0}",
"api": "{0}"
}}"#, upload()))
.build();
}
test!(simple {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
"#)
.file("src/main.rs", "fn main() {}");
assert_that(p.cargo_process("publish").arg("--no-verify"),
execs().with_status(0).with_stdout(&format!("\
{updating} registry `{reg}`
{packaging} foo v0.0.1 ({dir})
{uploading} foo v0.0.1 ({dir})
",
updating = UPDATING,
uploading = UPLOADING,
packaging = PACKAGING,
dir = p.url(),
reg = registry())));
let mut f = File::open(&upload_path().join("api/v1/crates/new")).unwrap();
// Skip the metadata payload and the size of the tarball
let mut sz = [0; 4];
assert_eq!(f.read(&mut sz).unwrap(), 4);
let sz = ((sz[0] as u32) << 0) |
((sz[1] as u32) << 8) |
((sz[2] as u32) << 16) |
((sz[3] as u32) << 24);
f.seek(SeekFrom::Current(sz as i64 + 4)).unwrap();
// Verify the tarball
let mut rdr = GzDecoder::new(f).unwrap();
assert_eq!(rdr.header().filename().unwrap(), "foo-0.0.1.crate".as_bytes());
let mut contents = Vec::new();
rdr.read_to_end(&mut contents).unwrap();
let inner = Cursor::new(contents);
let ar = Archive::new(inner);
for file in ar.files().unwrap() {
let file = file.unwrap();
let fname = file.header().path_bytes();
let fname = &*fname;
assert!(fname == b"foo-0.0.1/Cargo.toml" ||
fname == b"foo-0.0.1/src/main.rs",
"unexpected filename: {:?}", file.header().path());
}
});
test!(git_deps {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
[dependencies.foo]
git = "git://path/to/nowhere"
"#)
.file("src/main.rs", "fn main() {}");
assert_that(p.cargo_process("publish").arg("-v").arg("--no-verify"),
execs().with_status(101).with_stderr("\
all dependencies must come from the same source.
dependency `foo` comes from git://path/to/nowhere instead
"));
});
test!(path_dependency_no_version {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
[dependencies.bar]
path = "bar"
"#)
.file("src/main.rs", "fn main() {}")
.file("bar/Cargo.toml", r#"
[package]
name = "bar"
version = "0.0.1"
authors = []
"#)
.file("bar/src/lib.rs", "");
assert_that(p.cargo_process("publish"),
execs().with_status(101).with_stderr("\
all path dependencies must have a version specified when publishing.
dependency `bar` does not specify a version
"));
});
| { paths::root().join("upload") } | identifier_body |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url; | use support::git::repo;
use hamcrest::assert_that;
fn registry_path() -> PathBuf { paths::root().join("registry") }
fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() }
fn upload_path() -> PathBuf { paths::root().join("upload") }
fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
fn setup() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config).unwrap().write_all(&format!(r#"
[registry]
index = "{reg}"
token = "api-token"
"#, reg = registry()).as_bytes()).unwrap();
fs::create_dir_all(&upload_path().join("api/v1/crates")).unwrap();
repo(®istry_path())
.file("config.json", &format!(r#"{{
"dl": "{0}",
"api": "{0}"
}}"#, upload()))
.build();
}
test!(simple {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
"#)
.file("src/main.rs", "fn main() {}");
assert_that(p.cargo_process("publish").arg("--no-verify"),
execs().with_status(0).with_stdout(&format!("\
{updating} registry `{reg}`
{packaging} foo v0.0.1 ({dir})
{uploading} foo v0.0.1 ({dir})
",
updating = UPDATING,
uploading = UPLOADING,
packaging = PACKAGING,
dir = p.url(),
reg = registry())));
let mut f = File::open(&upload_path().join("api/v1/crates/new")).unwrap();
// Skip the metadata payload and the size of the tarball
let mut sz = [0; 4];
assert_eq!(f.read(&mut sz).unwrap(), 4);
let sz = ((sz[0] as u32) << 0) |
((sz[1] as u32) << 8) |
((sz[2] as u32) << 16) |
((sz[3] as u32) << 24);
f.seek(SeekFrom::Current(sz as i64 + 4)).unwrap();
// Verify the tarball
let mut rdr = GzDecoder::new(f).unwrap();
assert_eq!(rdr.header().filename().unwrap(), "foo-0.0.1.crate".as_bytes());
let mut contents = Vec::new();
rdr.read_to_end(&mut contents).unwrap();
let inner = Cursor::new(contents);
let ar = Archive::new(inner);
for file in ar.files().unwrap() {
let file = file.unwrap();
let fname = file.header().path_bytes();
let fname = &*fname;
assert!(fname == b"foo-0.0.1/Cargo.toml" ||
fname == b"foo-0.0.1/src/main.rs",
"unexpected filename: {:?}", file.header().path());
}
});
test!(git_deps {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
[dependencies.foo]
git = "git://path/to/nowhere"
"#)
.file("src/main.rs", "fn main() {}");
assert_that(p.cargo_process("publish").arg("-v").arg("--no-verify"),
execs().with_status(101).with_stderr("\
all dependencies must come from the same source.
dependency `foo` comes from git://path/to/nowhere instead
"));
});
test!(path_dependency_no_version {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
[dependencies.bar]
path = "bar"
"#)
.file("src/main.rs", "fn main() {}")
.file("bar/Cargo.toml", r#"
[package]
name = "bar"
version = "0.0.1"
authors = []
"#)
.file("bar/src/lib.rs", "");
assert_that(p.cargo_process("publish"),
execs().with_status(101).with_stderr("\
all path dependencies must have a version specified when publishing.
dependency `bar` does not specify a version
"));
}); |
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths; | random_line_split |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url;
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths;
use support::git::repo;
use hamcrest::assert_that;
fn registry_path() -> PathBuf { paths::root().join("registry") }
fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() }
fn upload_path() -> PathBuf { paths::root().join("upload") }
fn | () -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
fn setup() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config).unwrap().write_all(&format!(r#"
[registry]
index = "{reg}"
token = "api-token"
"#, reg = registry()).as_bytes()).unwrap();
fs::create_dir_all(&upload_path().join("api/v1/crates")).unwrap();
repo(®istry_path())
.file("config.json", &format!(r#"{{
"dl": "{0}",
"api": "{0}"
}}"#, upload()))
.build();
}
test!(simple {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
"#)
.file("src/main.rs", "fn main() {}");
assert_that(p.cargo_process("publish").arg("--no-verify"),
execs().with_status(0).with_stdout(&format!("\
{updating} registry `{reg}`
{packaging} foo v0.0.1 ({dir})
{uploading} foo v0.0.1 ({dir})
",
updating = UPDATING,
uploading = UPLOADING,
packaging = PACKAGING,
dir = p.url(),
reg = registry())));
let mut f = File::open(&upload_path().join("api/v1/crates/new")).unwrap();
// Skip the metadata payload and the size of the tarball
let mut sz = [0; 4];
assert_eq!(f.read(&mut sz).unwrap(), 4);
let sz = ((sz[0] as u32) << 0) |
((sz[1] as u32) << 8) |
((sz[2] as u32) << 16) |
((sz[3] as u32) << 24);
f.seek(SeekFrom::Current(sz as i64 + 4)).unwrap();
// Verify the tarball
let mut rdr = GzDecoder::new(f).unwrap();
assert_eq!(rdr.header().filename().unwrap(), "foo-0.0.1.crate".as_bytes());
let mut contents = Vec::new();
rdr.read_to_end(&mut contents).unwrap();
let inner = Cursor::new(contents);
let ar = Archive::new(inner);
for file in ar.files().unwrap() {
let file = file.unwrap();
let fname = file.header().path_bytes();
let fname = &*fname;
assert!(fname == b"foo-0.0.1/Cargo.toml" ||
fname == b"foo-0.0.1/src/main.rs",
"unexpected filename: {:?}", file.header().path());
}
});
test!(git_deps {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
[dependencies.foo]
git = "git://path/to/nowhere"
"#)
.file("src/main.rs", "fn main() {}");
assert_that(p.cargo_process("publish").arg("-v").arg("--no-verify"),
execs().with_status(101).with_stderr("\
all dependencies must come from the same source.
dependency `foo` comes from git://path/to/nowhere instead
"));
});
test!(path_dependency_no_version {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
[dependencies.bar]
path = "bar"
"#)
.file("src/main.rs", "fn main() {}")
.file("bar/Cargo.toml", r#"
[package]
name = "bar"
version = "0.0.1"
authors = []
"#)
.file("bar/src/lib.rs", "");
assert_that(p.cargo_process("publish"),
execs().with_status(101).with_stderr("\
all path dependencies must have a version specified when publishing.
dependency `bar` does not specify a version
"));
});
| upload | identifier_name |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr(u8)]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum SubscribeReturnCode {
MaximumQoSLevel0 = 0x00,
MaximumQoSLevel1 = 0x01,
MaximumQoSLevel2 = 0x02,
Failure = 0x80,
}
#[derive(Debug, Eq, PartialEq)]
pub struct SubackPacket {
fixed_header: FixedHeader,
packet_identifier: PacketIdentifier,
payload: SubackPacketPayload,
}
impl SubackPacket {
pub fn new(pkid: u16, subscribes: Vec<SubscribeReturnCode>) -> SubackPacket {
let mut pk = SubackPacket {
fixed_header: FixedHeader::new(PacketType::with_default(ControlType::SubscribeAcknowledgement), 0),
packet_identifier: PacketIdentifier(pkid),
payload: SubackPacketPayload::new(subscribes),
};
pk.fixed_header.remaining_length =
pk.encoded_variable_headers_length() + pk.payload.encoded_length();
pk
}
pub fn packet_identifier(&self) -> u16 {
self.packet_identifier.0
}
pub fn set_packet_identifier(&mut self, pkid: u16) {
self.packet_identifier.0 = pkid;
}
}
impl<'a> Packet<'a> for SubackPacket {
type Payload = SubackPacketPayload;
fn fixed_header(&self) -> &FixedHeader {
&self.fixed_header
}
fn payload(&self) -> &Self::Payload {
&self.payload
}
fn encode_variable_headers<W: Write>(&self, writer: &mut W) -> Result<(), PacketError<'a, Self>> {
try!(self.packet_identifier.encode(writer));
Ok(())
}
fn encoded_variable_headers_length(&self) -> u32 {
self.packet_identifier.encoded_length()
}
fn decode_packet<R: Read>(reader: &mut R, fixed_header: FixedHeader) -> Result<Self, PacketError<'a, Self>> {
let packet_identifier: PacketIdentifier = try!(PacketIdentifier::decode(reader));
let payload: SubackPacketPayload =
try!(SubackPacketPayload::decode_with(reader, Some(fixed_header.remaining_length
- packet_identifier.encoded_length()))
.map_err(PacketError::PayloadError));
Ok(SubackPacket {
fixed_header: fixed_header,
packet_identifier: packet_identifier,
payload: payload,
})
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct SubackPacketPayload {
subscribes: Vec<SubscribeReturnCode>,
}
impl SubackPacketPayload {
pub fn new(subs: Vec<SubscribeReturnCode>) -> SubackPacketPayload {
SubackPacketPayload {
subscribes: subs,
}
}
pub fn | (&self) -> &[SubscribeReturnCode] {
&self.subscribes[..]
}
}
impl<'a> Encodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), Self::Err> {
for code in self.subscribes.iter() {
try!(writer.write_u8(*code as u8));
}
Ok(())
}
fn encoded_length(&self) -> u32 {
self.subscribes.len() as u32
}
}
impl<'a> Decodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
type Cond = u32;
fn decode_with<R: Read>(reader: &mut R, payload_len: Option<u32>)
-> Result<SubackPacketPayload, SubackPacketPayloadError> {
let payload_len = payload_len.expect("Must provide payload length");
let mut subs = Vec::new();
for _ in 0..payload_len {
let retcode = match try!(reader.read_u8()) {
0x00 => SubscribeReturnCode::MaximumQoSLevel0,
0x01 => SubscribeReturnCode::MaximumQoSLevel1,
0x02 => SubscribeReturnCode::MaximumQoSLevel2,
0x80 => SubscribeReturnCode::Failure,
code => return Err(SubackPacketPayloadError::InvalidSubscribeReturnCode(code)),
};
subs.push(retcode);
}
Ok(SubackPacketPayload::new(subs))
}
}
#[derive(Debug)]
pub enum SubackPacketPayloadError {
IoError(io::Error),
InvalidSubscribeReturnCode(u8),
}
impl fmt::Display for SubackPacketPayloadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&SubackPacketPayloadError::IoError(ref err) => err.fmt(f),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(code) =>
write!(f, "Invalid subscribe return code {}", code),
}
}
}
impl Error for SubackPacketPayloadError {
fn description(&self) -> &str {
match self {
&SubackPacketPayloadError::IoError(ref err) => err.description(),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => "Invalid subscribe return code",
}
}
fn cause(&self) -> Option<&Error> {
match self {
&SubackPacketPayloadError::IoError(ref err) => Some(err),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => None,
}
}
}
impl From<byteorder::Error> for SubackPacketPayloadError {
fn from(err: byteorder::Error) -> SubackPacketPayloadError {
SubackPacketPayloadError::IoError(From::from(err))
}
}
| subscribes | identifier_name |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr(u8)]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum SubscribeReturnCode {
MaximumQoSLevel0 = 0x00,
MaximumQoSLevel1 = 0x01,
MaximumQoSLevel2 = 0x02,
Failure = 0x80,
}
#[derive(Debug, Eq, PartialEq)]
pub struct SubackPacket {
fixed_header: FixedHeader,
packet_identifier: PacketIdentifier,
payload: SubackPacketPayload,
}
impl SubackPacket {
pub fn new(pkid: u16, subscribes: Vec<SubscribeReturnCode>) -> SubackPacket {
let mut pk = SubackPacket {
fixed_header: FixedHeader::new(PacketType::with_default(ControlType::SubscribeAcknowledgement), 0),
packet_identifier: PacketIdentifier(pkid),
payload: SubackPacketPayload::new(subscribes),
};
pk.fixed_header.remaining_length =
pk.encoded_variable_headers_length() + pk.payload.encoded_length();
pk
}
pub fn packet_identifier(&self) -> u16 {
self.packet_identifier.0
}
pub fn set_packet_identifier(&mut self, pkid: u16) {
self.packet_identifier.0 = pkid;
}
}
impl<'a> Packet<'a> for SubackPacket {
type Payload = SubackPacketPayload;
fn fixed_header(&self) -> &FixedHeader {
&self.fixed_header
}
fn payload(&self) -> &Self::Payload {
&self.payload
}
fn encode_variable_headers<W: Write>(&self, writer: &mut W) -> Result<(), PacketError<'a, Self>> |
fn encoded_variable_headers_length(&self) -> u32 {
self.packet_identifier.encoded_length()
}
fn decode_packet<R: Read>(reader: &mut R, fixed_header: FixedHeader) -> Result<Self, PacketError<'a, Self>> {
let packet_identifier: PacketIdentifier = try!(PacketIdentifier::decode(reader));
let payload: SubackPacketPayload =
try!(SubackPacketPayload::decode_with(reader, Some(fixed_header.remaining_length
- packet_identifier.encoded_length()))
.map_err(PacketError::PayloadError));
Ok(SubackPacket {
fixed_header: fixed_header,
packet_identifier: packet_identifier,
payload: payload,
})
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct SubackPacketPayload {
subscribes: Vec<SubscribeReturnCode>,
}
impl SubackPacketPayload {
pub fn new(subs: Vec<SubscribeReturnCode>) -> SubackPacketPayload {
SubackPacketPayload {
subscribes: subs,
}
}
pub fn subscribes(&self) -> &[SubscribeReturnCode] {
&self.subscribes[..]
}
}
impl<'a> Encodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), Self::Err> {
for code in self.subscribes.iter() {
try!(writer.write_u8(*code as u8));
}
Ok(())
}
fn encoded_length(&self) -> u32 {
self.subscribes.len() as u32
}
}
impl<'a> Decodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
type Cond = u32;
fn decode_with<R: Read>(reader: &mut R, payload_len: Option<u32>)
-> Result<SubackPacketPayload, SubackPacketPayloadError> {
let payload_len = payload_len.expect("Must provide payload length");
let mut subs = Vec::new();
for _ in 0..payload_len {
let retcode = match try!(reader.read_u8()) {
0x00 => SubscribeReturnCode::MaximumQoSLevel0,
0x01 => SubscribeReturnCode::MaximumQoSLevel1,
0x02 => SubscribeReturnCode::MaximumQoSLevel2,
0x80 => SubscribeReturnCode::Failure,
code => return Err(SubackPacketPayloadError::InvalidSubscribeReturnCode(code)),
};
subs.push(retcode);
}
Ok(SubackPacketPayload::new(subs))
}
}
#[derive(Debug)]
pub enum SubackPacketPayloadError {
IoError(io::Error),
InvalidSubscribeReturnCode(u8),
}
impl fmt::Display for SubackPacketPayloadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&SubackPacketPayloadError::IoError(ref err) => err.fmt(f),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(code) =>
write!(f, "Invalid subscribe return code {}", code),
}
}
}
impl Error for SubackPacketPayloadError {
fn description(&self) -> &str {
match self {
&SubackPacketPayloadError::IoError(ref err) => err.description(),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => "Invalid subscribe return code",
}
}
fn cause(&self) -> Option<&Error> {
match self {
&SubackPacketPayloadError::IoError(ref err) => Some(err),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => None,
}
}
}
impl From<byteorder::Error> for SubackPacketPayloadError {
fn from(err: byteorder::Error) -> SubackPacketPayloadError {
SubackPacketPayloadError::IoError(From::from(err))
}
}
| {
try!(self.packet_identifier.encode(writer));
Ok(())
} | identifier_body |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr(u8)]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum SubscribeReturnCode {
MaximumQoSLevel0 = 0x00,
MaximumQoSLevel1 = 0x01,
MaximumQoSLevel2 = 0x02,
Failure = 0x80,
}
#[derive(Debug, Eq, PartialEq)]
pub struct SubackPacket {
fixed_header: FixedHeader,
packet_identifier: PacketIdentifier,
payload: SubackPacketPayload,
}
impl SubackPacket {
pub fn new(pkid: u16, subscribes: Vec<SubscribeReturnCode>) -> SubackPacket {
let mut pk = SubackPacket {
fixed_header: FixedHeader::new(PacketType::with_default(ControlType::SubscribeAcknowledgement), 0),
packet_identifier: PacketIdentifier(pkid),
payload: SubackPacketPayload::new(subscribes),
};
pk.fixed_header.remaining_length =
pk.encoded_variable_headers_length() + pk.payload.encoded_length();
pk
}
pub fn packet_identifier(&self) -> u16 {
self.packet_identifier.0
}
pub fn set_packet_identifier(&mut self, pkid: u16) {
self.packet_identifier.0 = pkid;
}
}
impl<'a> Packet<'a> for SubackPacket {
type Payload = SubackPacketPayload;
fn fixed_header(&self) -> &FixedHeader {
&self.fixed_header
}
fn payload(&self) -> &Self::Payload {
&self.payload
}
fn encode_variable_headers<W: Write>(&self, writer: &mut W) -> Result<(), PacketError<'a, Self>> {
try!(self.packet_identifier.encode(writer));
Ok(())
}
fn encoded_variable_headers_length(&self) -> u32 {
self.packet_identifier.encoded_length()
}
fn decode_packet<R: Read>(reader: &mut R, fixed_header: FixedHeader) -> Result<Self, PacketError<'a, Self>> {
let packet_identifier: PacketIdentifier = try!(PacketIdentifier::decode(reader));
let payload: SubackPacketPayload =
try!(SubackPacketPayload::decode_with(reader, Some(fixed_header.remaining_length
- packet_identifier.encoded_length()))
.map_err(PacketError::PayloadError));
Ok(SubackPacket {
fixed_header: fixed_header,
packet_identifier: packet_identifier,
payload: payload,
})
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct SubackPacketPayload {
subscribes: Vec<SubscribeReturnCode>,
}
impl SubackPacketPayload {
pub fn new(subs: Vec<SubscribeReturnCode>) -> SubackPacketPayload {
SubackPacketPayload {
subscribes: subs,
}
}
pub fn subscribes(&self) -> &[SubscribeReturnCode] {
&self.subscribes[..]
}
}
impl<'a> Encodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), Self::Err> {
for code in self.subscribes.iter() {
try!(writer.write_u8(*code as u8));
}
Ok(())
}
fn encoded_length(&self) -> u32 {
self.subscribes.len() as u32
}
}
impl<'a> Decodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
type Cond = u32;
fn decode_with<R: Read>(reader: &mut R, payload_len: Option<u32>)
-> Result<SubackPacketPayload, SubackPacketPayloadError> {
let payload_len = payload_len.expect("Must provide payload length");
let mut subs = Vec::new();
for _ in 0..payload_len {
let retcode = match try!(reader.read_u8()) {
0x00 => SubscribeReturnCode::MaximumQoSLevel0,
0x01 => SubscribeReturnCode::MaximumQoSLevel1,
0x02 => SubscribeReturnCode::MaximumQoSLevel2,
0x80 => SubscribeReturnCode::Failure,
code => return Err(SubackPacketPayloadError::InvalidSubscribeReturnCode(code)),
};
subs.push(retcode);
}
Ok(SubackPacketPayload::new(subs))
}
}
#[derive(Debug)]
pub enum SubackPacketPayloadError {
IoError(io::Error),
InvalidSubscribeReturnCode(u8),
}
impl fmt::Display for SubackPacketPayloadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&SubackPacketPayloadError::IoError(ref err) => err.fmt(f),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(code) =>
write!(f, "Invalid subscribe return code {}", code),
}
}
}
impl Error for SubackPacketPayloadError { | match self {
&SubackPacketPayloadError::IoError(ref err) => err.description(),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => "Invalid subscribe return code",
}
}
fn cause(&self) -> Option<&Error> {
match self {
&SubackPacketPayloadError::IoError(ref err) => Some(err),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => None,
}
}
}
impl From<byteorder::Error> for SubackPacketPayloadError {
fn from(err: byteorder::Error) -> SubackPacketPayloadError {
SubackPacketPayloadError::IoError(From::from(err))
}
} | fn description(&self) -> &str { | random_line_split |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* markov-music is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with markov-music. If not, see <http://www.gnu.org/licenses/>.
*/
use {diesel, Error, Result, StdResult};
use diesel::sqlite::SqliteConnection;
use super::Database;
use super::models::*;
use super::schema::*;
pub struct | {
conn: SqliteConnection,
}
impl SqliteDatabase {
pub fn new<S: AsRef<str>>(url: S) -> Result<Self> {
let conn = SqliteConnection::establish(url.as_ref())?;
Ok(SqliteDatabase { conn: conn })
}
}
impl Database for SqliteDatabase {
type Error = Error;
fn modify_weight(
&mut self,
song: &str,
next: &str,
diff: i32,
) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
let row = associations::table
.find((song, next))
.first::<Association>(&self.conn)
.optional()?;
let weight = row.map(|assoc| assoc.weight).unwrap_or(0) + diff;
let new_assoc = NewAssociation {
song: song,
next: next,
weight: weight,
};
diesel::replace_into(starters::table)
.values(&[new_assoc])
.execute(&self.conn)?;
Ok(())
})
}
fn clear(&mut self, song: &str) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
diesel::delete(associations::table.filter(dsl::song.eq(song)))
.execute(&self.conn)?;
Ok(())
})
}
}
| SqliteDatabase | identifier_name |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* markov-music is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with markov-music. If not, see <http://www.gnu.org/licenses/>.
*/
use {diesel, Error, Result, StdResult};
use diesel::sqlite::SqliteConnection;
use super::Database;
use super::models::*;
use super::schema::*;
pub struct SqliteDatabase {
conn: SqliteConnection,
}
impl SqliteDatabase {
pub fn new<S: AsRef<str>>(url: S) -> Result<Self> {
let conn = SqliteConnection::establish(url.as_ref())?;
Ok(SqliteDatabase { conn: conn })
}
}
impl Database for SqliteDatabase {
type Error = Error;
fn modify_weight(
&mut self,
song: &str,
next: &str,
diff: i32,
) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
let row = associations::table
.find((song, next))
.first::<Association>(&self.conn)
.optional()?;
let weight = row.map(|assoc| assoc.weight).unwrap_or(0) + diff;
let new_assoc = NewAssociation {
song: song,
next: next,
weight: weight,
};
| Ok(())
})
}
fn clear(&mut self, song: &str) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
diesel::delete(associations::table.filter(dsl::song.eq(song)))
.execute(&self.conn)?;
Ok(())
})
}
} | diesel::replace_into(starters::table)
.values(&[new_assoc])
.execute(&self.conn)?;
| random_line_split |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* markov-music is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with markov-music. If not, see <http://www.gnu.org/licenses/>.
*/
use {diesel, Error, Result, StdResult};
use diesel::sqlite::SqliteConnection;
use super::Database;
use super::models::*;
use super::schema::*;
pub struct SqliteDatabase {
conn: SqliteConnection,
}
impl SqliteDatabase {
pub fn new<S: AsRef<str>>(url: S) -> Result<Self> {
let conn = SqliteConnection::establish(url.as_ref())?;
Ok(SqliteDatabase { conn: conn })
}
}
impl Database for SqliteDatabase {
type Error = Error;
fn modify_weight(
&mut self,
song: &str,
next: &str,
diff: i32,
) -> Result<()> | Ok(())
})
}
fn clear(&mut self, song: &str) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
diesel::delete(associations::table.filter(dsl::song.eq(song)))
.execute(&self.conn)?;
Ok(())
})
}
}
| {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
let row = associations::table
.find((song, next))
.first::<Association>(&self.conn)
.optional()?;
let weight = row.map(|assoc| assoc.weight).unwrap_or(0) + diff;
let new_assoc = NewAssociation {
song: song,
next: next,
weight: weight,
};
diesel::replace_into(starters::table)
.values(&[new_assoc])
.execute(&self.conn)?;
| identifier_body |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
#![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inlining_but_not_all-inline[External]
#[inline]
pub fn inlined_function()
|
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[External]
pub fn foo() {
inline::inlined_function();
}
}
pub mod user2 {
use super::inline;
//~ MONO_ITEM fn user2::bar @@ local_inlining_but_not_all-user2[External]
pub fn bar() {
inline::inlined_function();
}
}
pub mod non_user {
//~ MONO_ITEM fn non_user::baz @@ local_inlining_but_not_all-non_user[External]
pub fn baz() {
}
}
| {
} | identifier_body |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation | #![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inlining_but_not_all-inline[External]
#[inline]
pub fn inlined_function()
{
}
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[External]
pub fn foo() {
inline::inlined_function();
}
}
pub mod user2 {
use super::inline;
//~ MONO_ITEM fn user2::bar @@ local_inlining_but_not_all-user2[External]
pub fn bar() {
inline::inlined_function();
}
}
pub mod non_user {
//~ MONO_ITEM fn non_user::baz @@ local_inlining_but_not_all-non_user[External]
pub fn baz() {
}
} | // incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
| random_line_split |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
#![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inlining_but_not_all-inline[External]
#[inline]
pub fn | ()
{
}
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[External]
pub fn foo() {
inline::inlined_function();
}
}
pub mod user2 {
use super::inline;
//~ MONO_ITEM fn user2::bar @@ local_inlining_but_not_all-user2[External]
pub fn bar() {
inline::inlined_function();
}
}
pub mod non_user {
//~ MONO_ITEM fn non_user::baz @@ local_inlining_but_not_all-non_user[External]
pub fn baz() {
}
}
| inlined_function | identifier_name |
mod.rs | mut [u64] = unsafe { cast::transmute(slice) };
for dest in as_u64.mut_iter() {
*dest = self.next_u64();
}
// the above will have filled up the vector as much as
// possible in multiples of 8 bytes.
let mut remaining = dest.len() % 8;
// space for a u32
if remaining >= 4 {
let mut slice: Slice<u32> = unsafe { cast::transmute_copy(&dest) };
slice.len /= size_of::<u32>();
let as_u32: &mut [u32] = unsafe { cast::transmute(slice) };
as_u32[as_u32.len() - 1] = self.next_u32();
remaining -= 4;
}
// exactly filled
if remaining == 0 { return }
// now we know we've either got 1, 2 or 3 spots to go,
// i.e. exactly one u32 is enough.
let rand = self.next_u32();
let remaining_index = dest.len() - remaining;
match dest.mut_slice_from(remaining_index) {
[ref mut a] => {
*a = rand as u8;
}
[ref mut a, ref mut b] => {
*a = rand as u8;
*b = (rand >> 8) as u8;
}
[ref mut a, ref mut b, ref mut c] => {
*a = rand as u8;
*b = (rand >> 8) as u8;
*c = (rand >> 16) as u8;
}
_ => fail2!("Rng.fill_bytes: the impossible occurred: remaining!= 1, 2 or 3")
}
}
/// Return a random value of a Rand type.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{:?}", rng.gen::<(f64, bool)>());
/// }
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
Rand::rand(self)
}
/// Return a random vector of the specified length.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let x: ~[uint] = rng.gen_vec(10);
/// println!("{:?}", x);
/// println!("{:?}", rng.gen_vec::<(f64, bool)>(5));
/// }
/// ```
fn gen_vec<T: Rand>(&mut self, len: uint) -> ~[T] {
vec::from_fn(len, |_| self.gen())
}
/// Generate a random primitive integer in the range [`low`,
/// `high`). Fails if `low >= high`.
///
/// This gives a uniform distribution (assuming this RNG is itself
/// uniform), even for edge cases like `gen_integer_range(0u8,
/// 170)`, which a naive modulo operation would return numbers
/// less than 85 with double the probability to those greater than
/// 85.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let n: uint = rng.gen_integer_range(0u, 10);
/// println!("{}", n);
/// let m: int = rng.gen_integer_range(-40, 400);
/// println!("{}", m);
/// }
/// ```
fn gen_integer_range<T: Rand + Int>(&mut self, low: T, high: T) -> T {
assert!(low < high, "RNG.gen_integer_range called with low >= high");
let range = (high - low).to_u64().unwrap();
let accept_zone = u64::max_value - u64::max_value % range;
loop {
let rand = self.gen::<u64>();
if rand < accept_zone {
return low + NumCast::from(rand % range).unwrap();
}
}
}
/// Return a bool with a 1 in n chance of true
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// }
/// ```
fn | (&mut self, n: uint) -> bool {
n == 0 || self.gen_integer_range(0, n) == 0
}
/// Return a random string of the specified length composed of
/// A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println(rand::task_rng().gen_ascii_str(10));
/// }
/// ```
fn gen_ascii_str(&mut self, len: uint) -> ~str {
static GEN_ASCII_STR_CHARSET: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789");
let mut s = str::with_capacity(len);
for _ in range(0, len) {
s.push_char(self.choose(GEN_ASCII_STR_CHARSET) as char)
}
s
}
/// Choose an item randomly, failing if `values` is empty.
fn choose<T: Clone>(&mut self, values: &[T]) -> T {
self.choose_option(values).expect("Rng.choose: `values` is empty").clone()
}
/// Choose `Some(&item)` randomly, returning `None` if values is
/// empty.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println!("{:?}", rand::task_rng().choose_option([1,2,4,8,16,32]));
/// println!("{:?}", rand::task_rng().choose_option([]));
/// }
/// ```
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
None
} else {
Some(&values[self.gen_integer_range(0u, values.len())])
}
}
/// Choose an item respecting the relative weights, failing if the sum of
/// the weights is 0
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{}", rng.choose_weighted(x));
/// }
/// ```
fn choose_weighted<T:Clone>(&mut self, v: &[Weighted<T>]) -> T {
self.choose_weighted_option(v).expect("Rng.choose_weighted: total weight is 0")
}
/// Choose Some(item) respecting the relative weights, returning none if
/// the sum of the weights is 0
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{:?}", rng.choose_weighted_option(x));
/// }
/// ```
fn choose_weighted_option<T:Clone>(&mut self, v: &[Weighted<T>])
-> Option<T> {
let mut total = 0u;
for item in v.iter() {
total += item.weight;
}
if total == 0u {
return None;
}
let chosen = self.gen_integer_range(0u, total);
let mut so_far = 0u;
for item in v.iter() {
so_far += item.weight;
if so_far > chosen {
return Some(item.item.clone());
}
}
unreachable!();
}
/// Return a vec containing copies of the items, in order, where
/// the weight of the item determines how many copies there are
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{}", rng.weighted_vec(x));
/// }
/// ```
fn weighted_vec<T:Clone>(&mut self, v: &[Weighted<T>]) -> ~[T] {
let mut r = ~[];
for item in v.iter() {
for _ in range(0u, item.weight) {
r.push(item.item.clone());
}
}
r
}
/// Shuffle a vec
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println!("{:?}", rand::task_rng().shuffle(~[1,2,3]));
/// }
/// ```
fn shuffle<T>(&mut self, values: ~[T]) -> ~[T] {
let mut v = values;
self.shuffle_mut(v);
v
}
/// Shuffle a mutable vector in place.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let mut y = [1,2,3];
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// }
/// ```
fn shuffle_mut<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
i -= 1u;
// lock element i in place.
values.swap(i, self.gen_integer_range(0u, i + 1u));
}
}
/// Randomly sample up to `n` elements from an iterator.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let sample = rng.sample(range(1, 100), 5);
/// println!("{:?}", sample);
/// }
/// ```
fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
let mut reservoir : ~[A] = vec::with_capacity(n);
for (i, elem) in iter.enumerate() {
if i < n {
reservoir.push(elem);
continue
}
let k = self.gen_integer_range(0, i + 1);
if k < reservoir.len() {
reservoir[k] = elem
}
}
reservoir
}
}
/// A random number generator that can be explicitly seeded to produce
/// the same stream of randomness multiple times.
pub trait SeedableRng<Seed>: Rng {
/// Reseed an RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// }
/// ```
fn reseed(&mut self, Seed);
/// Create a new RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// }
/// ```
fn from_seed(seed: Seed) -> Self;
}
/// Create a random number generator with a default algorithm and seed.
///
/// It returns the cryptographically-safest `Rng` algorithm currently
/// available in Rust. If you require a specifically seeded `Rng` for
/// consistency over time you should pick one algorithm and create the
/// `Rng` yourself.
///
/// This is a very expensive operation as it has to read randomness
/// from the operating system and use this in an expensive seeding
/// operation. If one does not require high performance generation of
/// random numbers, `task_rng` and/or `random` may be more
/// appropriate.
pub fn rng() -> StdRng {
StdRng::new()
}
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[cfg(not(target_word_size="64"))]
pub struct StdRng { priv rng: IsaacRng }
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[cfg(target_word_size="64")]
pub struct StdRng { priv rng: Isaac64Rng }
impl StdRng {
/// Create a randomly seeded instance of `StdRng`. This reads
/// randomness from the OS to seed the PRNG.
#[cfg(not(target_word_size="64"))]
pub fn new() -> StdRng {
StdRng { rng: IsaacRng::new() }
}
/// Create a randomly seeded instance of `StdRng`. This reads
/// randomness from the OS to seed the PRNG.
#[cfg(target_word_size="64")]
pub fn new() -> StdRng {
StdRng { rng: Isaac64Rng::new() }
}
}
impl Rng for StdRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.rng.next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.rng.next_u64()
}
}
impl<'self> SeedableRng<&'self [uint]> for StdRng {
fn reseed(&mut self, seed: &'self [uint]) {
// the internal RNG can just be seeded from the above
// randomness.
self.rng.reseed(unsafe {cast::transmute(seed)})
}
fn from_seed(seed: &'self [uint]) -> StdRng {
StdRng { rng: SeedableRng::from_seed(unsafe {cast::transmute(seed)}) }
}
}
/// Create a weak random number generator with a default algorithm and seed.
///
/// It returns the fastest `Rng` algorithm currently available in Rust without
/// consideration for cryptography or security. If you require a specifically
/// seeded `Rng` for consistency over time you should pick one algorithm and
/// create the `Rng` yourself.
///
/// This will read randomness from the operating system to seed the
/// generator.
pub fn weak_rng() -> XorShiftRng {
XorShiftRng::new()
}
/// An [Xorshift random number
/// generator](http://en.wikipedia.org/wiki/Xorshift).
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng`.
pub struct XorShiftRng {
priv x: u32,
priv y: u32,
priv z: u32,
priv w: u32,
}
impl Rng for XorShiftRng {
#[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x;
let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w = self.w;
self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
self.w
}
}
impl SeedableRng<[u32,.. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32,.. 4]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
self.x = seed[0];
self.y = seed[1];
self.z = seed[2];
self.w = seed[3];
}
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
fn from_seed(seed: [u32,.. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
}
}
impl XorShiftRng {
/// Create an xor shift random number generator with a random seed.
pub fn new() -> XorShiftRng {
let mut s = [0u8,..16];
loop {
let mut r = OSRng::new();
r.fill_bytes(s);
if!s.iter().all(|x| *x == 0) {
break;
}
}
let s: [u32,..4] = unsafe { cast::transmute(s) };
SeedableRng::from_seed(s)
}
}
/// Controls how the task-local RNG is reseeded.
struct TaskRngReseeder;
impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
*rng = StdRng::new();
}
}
static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
/// The task-local RNG.
pub type TaskRng = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
// used to make space in TLS for a random number generator
local_data_key!(TASK_RNG_KEY: @mut TaskRng)
/// Retrieve the lazily-initialized task-local random number
/// generator, seeded by the system. Intended to be used in method
/// chaining style, e.g. `task_rng().gen::<int>()`.
///
/// The RNG provided will reseed itself from the operating system
/// after generating a certain amount of randomness.
///
/// The internal RNG used is platform and architecture dependent, even
/// if the operating system random number generator is rigged to give
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
pub fn task_rng() -> @mut TaskRng {
let r = local_data::get(TASK_RNG_KEY, |k| k.map(|k| *k));
match r {
None => {
let rng = @mut reseeding::ReseedingRng::new(StdRng::new(),
TASK_RNG_RESEED_THRESHOLD,
TaskRngReseeder);
local_data::set(TASK_RNG_KEY, rng);
rng
}
Some(rng) => rng
}
}
// Allow direct chaining with `task_rng`
impl<R: Rng> Rng for @mut R {
#[inline]
fn next_u32(&mut self) -> u32 {
(**self).next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
(**self).next_u64()
}
#[inline]
fn fill_bytes(&mut self, bytes: &mut [u8]) {
(**self).fill_bytes(bytes);
}
}
/// Generate a random value using the task-local random number
/// generator.
///
/// # Example
///
/// ```rust
/// use std::rand::random;
///
/// fn main() {
/// if random() {
/// let x = random();
/// println!("{}", 2u * x);
/// } else {
/// println!("{}", random::<f64>());
/// }
/// }
/// ```
#[inline]
pub fn random<T: Rand>() -> T {
task_rng().gen()
}
#[cfg(test)]
mod test {
use iter::{Iterator, range};
use option::{Option, Some};
use super::*;
#[test]
fn test_fill_bytes_default() {
let mut r = weak_rng();
let mut v = [0u8,.. 100];
r.fill_bytes(v);
}
#[test]
fn test_gen_integer_range() {
let mut r = rng();
for _ in range(0, 1000) {
let a = r.gen_integer_range(-3i, 42);
assert!(a >= -3 && a < 42);
assert_eq!(r.gen_integer_range(0, 1), 0);
assert_eq!(r.gen_integer_range(-12, -11), -12);
}
for _ in range(0, 1000) {
let a = r.gen_integer_range(10, 42); | gen_weighted_bool | identifier_name |
mod.rs |
/// `high`). Fails if `low >= high`.
///
/// This gives a uniform distribution (assuming this RNG is itself
/// uniform), even for edge cases like `gen_integer_range(0u8,
/// 170)`, which a naive modulo operation would return numbers
/// less than 85 with double the probability to those greater than
/// 85.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let n: uint = rng.gen_integer_range(0u, 10);
/// println!("{}", n);
/// let m: int = rng.gen_integer_range(-40, 400);
/// println!("{}", m);
/// }
/// ```
fn gen_integer_range<T: Rand + Int>(&mut self, low: T, high: T) -> T {
assert!(low < high, "RNG.gen_integer_range called with low >= high");
let range = (high - low).to_u64().unwrap();
let accept_zone = u64::max_value - u64::max_value % range;
loop {
let rand = self.gen::<u64>();
if rand < accept_zone {
return low + NumCast::from(rand % range).unwrap();
}
}
}
/// Return a bool with a 1 in n chance of true
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// }
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
n == 0 || self.gen_integer_range(0, n) == 0
}
/// Return a random string of the specified length composed of
/// A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println(rand::task_rng().gen_ascii_str(10));
/// }
/// ```
fn gen_ascii_str(&mut self, len: uint) -> ~str {
static GEN_ASCII_STR_CHARSET: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789");
let mut s = str::with_capacity(len);
for _ in range(0, len) {
s.push_char(self.choose(GEN_ASCII_STR_CHARSET) as char)
}
s
}
/// Choose an item randomly, failing if `values` is empty.
fn choose<T: Clone>(&mut self, values: &[T]) -> T {
self.choose_option(values).expect("Rng.choose: `values` is empty").clone()
}
/// Choose `Some(&item)` randomly, returning `None` if values is
/// empty.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println!("{:?}", rand::task_rng().choose_option([1,2,4,8,16,32]));
/// println!("{:?}", rand::task_rng().choose_option([]));
/// }
/// ```
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
None
} else {
Some(&values[self.gen_integer_range(0u, values.len())])
}
}
/// Choose an item respecting the relative weights, failing if the sum of
/// the weights is 0
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{}", rng.choose_weighted(x));
/// }
/// ```
fn choose_weighted<T:Clone>(&mut self, v: &[Weighted<T>]) -> T {
self.choose_weighted_option(v).expect("Rng.choose_weighted: total weight is 0")
}
/// Choose Some(item) respecting the relative weights, returning none if
/// the sum of the weights is 0
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{:?}", rng.choose_weighted_option(x));
/// }
/// ```
fn choose_weighted_option<T:Clone>(&mut self, v: &[Weighted<T>])
-> Option<T> {
let mut total = 0u;
for item in v.iter() {
total += item.weight;
}
if total == 0u {
return None;
}
let chosen = self.gen_integer_range(0u, total);
let mut so_far = 0u;
for item in v.iter() {
so_far += item.weight;
if so_far > chosen {
return Some(item.item.clone());
}
}
unreachable!();
}
/// Return a vec containing copies of the items, in order, where
/// the weight of the item determines how many copies there are
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{}", rng.weighted_vec(x));
/// }
/// ```
fn weighted_vec<T:Clone>(&mut self, v: &[Weighted<T>]) -> ~[T] {
let mut r = ~[];
for item in v.iter() {
for _ in range(0u, item.weight) {
r.push(item.item.clone());
}
}
r
}
/// Shuffle a vec
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println!("{:?}", rand::task_rng().shuffle(~[1,2,3]));
/// }
/// ```
fn shuffle<T>(&mut self, values: ~[T]) -> ~[T] {
let mut v = values;
self.shuffle_mut(v);
v
}
/// Shuffle a mutable vector in place.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let mut y = [1,2,3];
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// }
/// ```
fn shuffle_mut<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
i -= 1u;
// lock element i in place.
values.swap(i, self.gen_integer_range(0u, i + 1u));
}
}
/// Randomly sample up to `n` elements from an iterator.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let sample = rng.sample(range(1, 100), 5);
/// println!("{:?}", sample);
/// }
/// ```
fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
let mut reservoir : ~[A] = vec::with_capacity(n);
for (i, elem) in iter.enumerate() {
if i < n {
reservoir.push(elem);
continue
}
let k = self.gen_integer_range(0, i + 1);
if k < reservoir.len() {
reservoir[k] = elem
}
}
reservoir
}
}
/// A random number generator that can be explicitly seeded to produce
/// the same stream of randomness multiple times.
pub trait SeedableRng<Seed>: Rng {
/// Reseed an RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// }
/// ```
fn reseed(&mut self, Seed);
/// Create a new RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// }
/// ```
fn from_seed(seed: Seed) -> Self;
}
/// Create a random number generator with a default algorithm and seed.
///
/// It returns the cryptographically-safest `Rng` algorithm currently
/// available in Rust. If you require a specifically seeded `Rng` for
/// consistency over time you should pick one algorithm and create the
/// `Rng` yourself.
///
/// This is a very expensive operation as it has to read randomness
/// from the operating system and use this in an expensive seeding
/// operation. If one does not require high performance generation of
/// random numbers, `task_rng` and/or `random` may be more
/// appropriate.
pub fn rng() -> StdRng {
StdRng::new()
}
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[cfg(not(target_word_size="64"))]
pub struct StdRng { priv rng: IsaacRng }
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[cfg(target_word_size="64")]
pub struct StdRng { priv rng: Isaac64Rng }
impl StdRng {
/// Create a randomly seeded instance of `StdRng`. This reads
/// randomness from the OS to seed the PRNG.
#[cfg(not(target_word_size="64"))]
pub fn new() -> StdRng {
StdRng { rng: IsaacRng::new() }
}
/// Create a randomly seeded instance of `StdRng`. This reads
/// randomness from the OS to seed the PRNG.
#[cfg(target_word_size="64")]
pub fn new() -> StdRng {
StdRng { rng: Isaac64Rng::new() }
}
}
impl Rng for StdRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.rng.next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.rng.next_u64()
}
}
impl<'self> SeedableRng<&'self [uint]> for StdRng {
fn reseed(&mut self, seed: &'self [uint]) {
// the internal RNG can just be seeded from the above
// randomness.
self.rng.reseed(unsafe {cast::transmute(seed)})
}
fn from_seed(seed: &'self [uint]) -> StdRng {
StdRng { rng: SeedableRng::from_seed(unsafe {cast::transmute(seed)}) }
}
}
/// Create a weak random number generator with a default algorithm and seed.
///
/// It returns the fastest `Rng` algorithm currently available in Rust without
/// consideration for cryptography or security. If you require a specifically
/// seeded `Rng` for consistency over time you should pick one algorithm and
/// create the `Rng` yourself.
///
/// This will read randomness from the operating system to seed the
/// generator.
pub fn weak_rng() -> XorShiftRng {
XorShiftRng::new()
}
/// An [Xorshift random number
/// generator](http://en.wikipedia.org/wiki/Xorshift).
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng`.
pub struct XorShiftRng {
priv x: u32,
priv y: u32,
priv z: u32,
priv w: u32,
}
impl Rng for XorShiftRng {
#[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x;
let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w = self.w;
self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
self.w
}
}
impl SeedableRng<[u32,.. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32,.. 4]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
self.x = seed[0];
self.y = seed[1];
self.z = seed[2];
self.w = seed[3];
}
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
fn from_seed(seed: [u32,.. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
}
}
impl XorShiftRng {
/// Create an xor shift random number generator with a random seed.
pub fn new() -> XorShiftRng {
let mut s = [0u8,..16];
loop {
let mut r = OSRng::new();
r.fill_bytes(s);
if!s.iter().all(|x| *x == 0) {
break;
}
}
let s: [u32,..4] = unsafe { cast::transmute(s) };
SeedableRng::from_seed(s)
}
}
/// Controls how the task-local RNG is reseeded.
struct TaskRngReseeder;
impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
*rng = StdRng::new();
}
}
static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
/// The task-local RNG.
pub type TaskRng = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
// used to make space in TLS for a random number generator
local_data_key!(TASK_RNG_KEY: @mut TaskRng)
/// Retrieve the lazily-initialized task-local random number
/// generator, seeded by the system. Intended to be used in method
/// chaining style, e.g. `task_rng().gen::<int>()`.
///
/// The RNG provided will reseed itself from the operating system
/// after generating a certain amount of randomness.
///
/// The internal RNG used is platform and architecture dependent, even
/// if the operating system random number generator is rigged to give
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
pub fn task_rng() -> @mut TaskRng {
let r = local_data::get(TASK_RNG_KEY, |k| k.map(|k| *k));
match r {
None => {
let rng = @mut reseeding::ReseedingRng::new(StdRng::new(),
TASK_RNG_RESEED_THRESHOLD,
TaskRngReseeder);
local_data::set(TASK_RNG_KEY, rng);
rng
}
Some(rng) => rng
}
}
// Allow direct chaining with `task_rng`
impl<R: Rng> Rng for @mut R {
#[inline]
fn next_u32(&mut self) -> u32 {
(**self).next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
(**self).next_u64()
}
#[inline]
fn fill_bytes(&mut self, bytes: &mut [u8]) {
(**self).fill_bytes(bytes);
}
}
/// Generate a random value using the task-local random number
/// generator.
///
/// # Example
///
/// ```rust
/// use std::rand::random;
///
/// fn main() {
/// if random() {
/// let x = random();
/// println!("{}", 2u * x);
/// } else {
/// println!("{}", random::<f64>());
/// }
/// }
/// ```
#[inline]
pub fn random<T: Rand>() -> T {
task_rng().gen()
}
#[cfg(test)]
mod test {
use iter::{Iterator, range};
use option::{Option, Some};
use super::*;
#[test]
fn test_fill_bytes_default() {
let mut r = weak_rng();
let mut v = [0u8,.. 100];
r.fill_bytes(v);
}
#[test]
fn test_gen_integer_range() {
let mut r = rng();
for _ in range(0, 1000) {
let a = r.gen_integer_range(-3i, 42);
assert!(a >= -3 && a < 42);
assert_eq!(r.gen_integer_range(0, 1), 0);
assert_eq!(r.gen_integer_range(-12, -11), -12);
}
for _ in range(0, 1000) {
let a = r.gen_integer_range(10, 42);
assert!(a >= 10 && a < 42);
assert_eq!(r.gen_integer_range(0, 1), 0);
assert_eq!(r.gen_integer_range(3_000_000u, 3_000_001), 3_000_000);
}
}
#[test]
#[should_fail]
fn test_gen_integer_range_fail_int() {
let mut r = rng();
r.gen_integer_range(5i, -2);
}
#[test]
#[should_fail]
fn test_gen_integer_range_fail_uint() {
let mut r = rng();
r.gen_integer_range(5u, 2u);
}
#[test]
fn test_gen_f64() {
let mut r = rng();
let a = r.gen::<f64>();
let b = r.gen::<f64>();
debug2!("{:?}", (a, b));
}
#[test]
fn test_gen_weighted_bool() {
let mut r = rng();
assert_eq!(r.gen_weighted_bool(0u), true);
assert_eq!(r.gen_weighted_bool(1u), true);
}
#[test]
fn test_gen_ascii_str() {
let mut r = rng();
debug2!("{}", r.gen_ascii_str(10u));
debug2!("{}", r.gen_ascii_str(10u));
debug2!("{}", r.gen_ascii_str(10u));
assert_eq!(r.gen_ascii_str(0u).len(), 0u);
assert_eq!(r.gen_ascii_str(10u).len(), 10u);
assert_eq!(r.gen_ascii_str(16u).len(), 16u);
}
#[test]
fn test_gen_vec() {
let mut r = rng();
assert_eq!(r.gen_vec::<u8>(0u).len(), 0u);
assert_eq!(r.gen_vec::<u8>(10u).len(), 10u);
assert_eq!(r.gen_vec::<f64>(16u).len(), 16u);
}
#[test]
fn test_choose() {
let mut r = rng();
assert_eq!(r.choose([1, 1, 1]), 1);
}
#[test]
fn test_choose_option() {
let mut r = rng();
let v: &[int] = &[];
assert!(r.choose_option(v).is_none());
let i = 1;
let v = [1,1,1];
assert_eq!(r.choose_option(v), Some(&i));
}
#[test]
fn test_choose_weighted() {
let mut r = rng();
assert!(r.choose_weighted([
Weighted { weight: 1u, item: 42 },
]) == 42);
assert!(r.choose_weighted([
Weighted { weight: 0u, item: 42 },
Weighted { weight: 1u, item: 43 },
]) == 43); | random_line_split |
||
mod.rs | mut [u64] = unsafe { cast::transmute(slice) };
for dest in as_u64.mut_iter() {
*dest = self.next_u64();
}
// the above will have filled up the vector as much as
// possible in multiples of 8 bytes.
let mut remaining = dest.len() % 8;
// space for a u32
if remaining >= 4 {
let mut slice: Slice<u32> = unsafe { cast::transmute_copy(&dest) };
slice.len /= size_of::<u32>();
let as_u32: &mut [u32] = unsafe { cast::transmute(slice) };
as_u32[as_u32.len() - 1] = self.next_u32();
remaining -= 4;
}
// exactly filled
if remaining == 0 { return }
// now we know we've either got 1, 2 or 3 spots to go,
// i.e. exactly one u32 is enough.
let rand = self.next_u32();
let remaining_index = dest.len() - remaining;
match dest.mut_slice_from(remaining_index) {
[ref mut a] => {
*a = rand as u8;
}
[ref mut a, ref mut b] => {
*a = rand as u8;
*b = (rand >> 8) as u8;
}
[ref mut a, ref mut b, ref mut c] => {
*a = rand as u8;
*b = (rand >> 8) as u8;
*c = (rand >> 16) as u8;
}
_ => fail2!("Rng.fill_bytes: the impossible occurred: remaining!= 1, 2 or 3")
}
}
/// Return a random value of a Rand type.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{:?}", rng.gen::<(f64, bool)>());
/// }
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
Rand::rand(self)
}
/// Return a random vector of the specified length.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let x: ~[uint] = rng.gen_vec(10);
/// println!("{:?}", x);
/// println!("{:?}", rng.gen_vec::<(f64, bool)>(5));
/// }
/// ```
fn gen_vec<T: Rand>(&mut self, len: uint) -> ~[T] {
vec::from_fn(len, |_| self.gen())
}
/// Generate a random primitive integer in the range [`low`,
/// `high`). Fails if `low >= high`.
///
/// This gives a uniform distribution (assuming this RNG is itself
/// uniform), even for edge cases like `gen_integer_range(0u8,
/// 170)`, which a naive modulo operation would return numbers
/// less than 85 with double the probability to those greater than
/// 85.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let n: uint = rng.gen_integer_range(0u, 10);
/// println!("{}", n);
/// let m: int = rng.gen_integer_range(-40, 400);
/// println!("{}", m);
/// }
/// ```
fn gen_integer_range<T: Rand + Int>(&mut self, low: T, high: T) -> T {
assert!(low < high, "RNG.gen_integer_range called with low >= high");
let range = (high - low).to_u64().unwrap();
let accept_zone = u64::max_value - u64::max_value % range;
loop {
let rand = self.gen::<u64>();
if rand < accept_zone {
return low + NumCast::from(rand % range).unwrap();
}
}
}
/// Return a bool with a 1 in n chance of true
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// }
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
n == 0 || self.gen_integer_range(0, n) == 0
}
/// Return a random string of the specified length composed of
/// A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println(rand::task_rng().gen_ascii_str(10));
/// }
/// ```
fn gen_ascii_str(&mut self, len: uint) -> ~str {
static GEN_ASCII_STR_CHARSET: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789");
let mut s = str::with_capacity(len);
for _ in range(0, len) {
s.push_char(self.choose(GEN_ASCII_STR_CHARSET) as char)
}
s
}
/// Choose an item randomly, failing if `values` is empty.
fn choose<T: Clone>(&mut self, values: &[T]) -> T {
self.choose_option(values).expect("Rng.choose: `values` is empty").clone()
}
/// Choose `Some(&item)` randomly, returning `None` if values is
/// empty.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println!("{:?}", rand::task_rng().choose_option([1,2,4,8,16,32]));
/// println!("{:?}", rand::task_rng().choose_option([]));
/// }
/// ```
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
None
} else {
Some(&values[self.gen_integer_range(0u, values.len())])
}
}
/// Choose an item respecting the relative weights, failing if the sum of
/// the weights is 0
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{}", rng.choose_weighted(x));
/// }
/// ```
fn choose_weighted<T:Clone>(&mut self, v: &[Weighted<T>]) -> T {
self.choose_weighted_option(v).expect("Rng.choose_weighted: total weight is 0")
}
/// Choose Some(item) respecting the relative weights, returning none if
/// the sum of the weights is 0
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{:?}", rng.choose_weighted_option(x));
/// }
/// ```
fn choose_weighted_option<T:Clone>(&mut self, v: &[Weighted<T>])
-> Option<T> {
let mut total = 0u;
for item in v.iter() {
total += item.weight;
}
if total == 0u {
return None;
}
let chosen = self.gen_integer_range(0u, total);
let mut so_far = 0u;
for item in v.iter() {
so_far += item.weight;
if so_far > chosen {
return Some(item.item.clone());
}
}
unreachable!();
}
/// Return a vec containing copies of the items, in order, where
/// the weight of the item determines how many copies there are
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::rng();
/// let x = [rand::Weighted {weight: 4, item: 'a'},
/// rand::Weighted {weight: 2, item: 'b'},
/// rand::Weighted {weight: 2, item: 'c'}];
/// println!("{}", rng.weighted_vec(x));
/// }
/// ```
fn weighted_vec<T:Clone>(&mut self, v: &[Weighted<T>]) -> ~[T] {
let mut r = ~[];
for item in v.iter() {
for _ in range(0u, item.weight) {
r.push(item.item.clone());
}
}
r
}
/// Shuffle a vec
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// println!("{:?}", rand::task_rng().shuffle(~[1,2,3]));
/// }
/// ```
fn shuffle<T>(&mut self, values: ~[T]) -> ~[T] {
let mut v = values;
self.shuffle_mut(v);
v
}
/// Shuffle a mutable vector in place.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let mut y = [1,2,3];
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// }
/// ```
fn shuffle_mut<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
i -= 1u;
// lock element i in place.
values.swap(i, self.gen_integer_range(0u, i + 1u));
}
}
/// Randomly sample up to `n` elements from an iterator.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng = rand::task_rng();
/// let sample = rng.sample(range(1, 100), 5);
/// println!("{:?}", sample);
/// }
/// ```
fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
let mut reservoir : ~[A] = vec::with_capacity(n);
for (i, elem) in iter.enumerate() {
if i < n {
reservoir.push(elem);
continue
}
let k = self.gen_integer_range(0, i + 1);
if k < reservoir.len() {
reservoir[k] = elem
}
}
reservoir
}
}
/// A random number generator that can be explicitly seeded to produce
/// the same stream of randomness multiple times.
pub trait SeedableRng<Seed>: Rng {
/// Reseed an RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// }
/// ```
fn reseed(&mut self, Seed);
/// Create a new RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>());
/// }
/// ```
fn from_seed(seed: Seed) -> Self;
}
/// Create a random number generator with a default algorithm and seed.
///
/// It returns the cryptographically-safest `Rng` algorithm currently
/// available in Rust. If you require a specifically seeded `Rng` for
/// consistency over time you should pick one algorithm and create the
/// `Rng` yourself.
///
/// This is a very expensive operation as it has to read randomness
/// from the operating system and use this in an expensive seeding
/// operation. If one does not require high performance generation of
/// random numbers, `task_rng` and/or `random` may be more
/// appropriate.
pub fn rng() -> StdRng {
StdRng::new()
}
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[cfg(not(target_word_size="64"))]
pub struct StdRng { priv rng: IsaacRng }
/// The standard RNG. This is designed to be efficient on the current
/// platform.
#[cfg(target_word_size="64")]
pub struct StdRng { priv rng: Isaac64Rng }
impl StdRng {
/// Create a randomly seeded instance of `StdRng`. This reads
/// randomness from the OS to seed the PRNG.
#[cfg(not(target_word_size="64"))]
pub fn new() -> StdRng {
StdRng { rng: IsaacRng::new() }
}
/// Create a randomly seeded instance of `StdRng`. This reads
/// randomness from the OS to seed the PRNG.
#[cfg(target_word_size="64")]
pub fn new() -> StdRng {
StdRng { rng: Isaac64Rng::new() }
}
}
impl Rng for StdRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.rng.next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.rng.next_u64()
}
}
impl<'self> SeedableRng<&'self [uint]> for StdRng {
fn reseed(&mut self, seed: &'self [uint]) {
// the internal RNG can just be seeded from the above
// randomness.
self.rng.reseed(unsafe {cast::transmute(seed)})
}
fn from_seed(seed: &'self [uint]) -> StdRng {
StdRng { rng: SeedableRng::from_seed(unsafe {cast::transmute(seed)}) }
}
}
/// Create a weak random number generator with a default algorithm and seed.
///
/// It returns the fastest `Rng` algorithm currently available in Rust without
/// consideration for cryptography or security. If you require a specifically
/// seeded `Rng` for consistency over time you should pick one algorithm and
/// create the `Rng` yourself.
///
/// This will read randomness from the operating system to seed the
/// generator.
pub fn weak_rng() -> XorShiftRng |
/// An [Xorshift random number
/// generator](http://en.wikipedia.org/wiki/Xorshift).
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng`.
pub struct XorShiftRng {
priv x: u32,
priv y: u32,
priv z: u32,
priv w: u32,
}
impl Rng for XorShiftRng {
#[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x;
let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w = self.w;
self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
self.w
}
}
impl SeedableRng<[u32,.. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32,.. 4]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
self.x = seed[0];
self.y = seed[1];
self.z = seed[2];
self.w = seed[3];
}
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
fn from_seed(seed: [u32,.. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
}
}
impl XorShiftRng {
/// Create an xor shift random number generator with a random seed.
pub fn new() -> XorShiftRng {
let mut s = [0u8,..16];
loop {
let mut r = OSRng::new();
r.fill_bytes(s);
if!s.iter().all(|x| *x == 0) {
break;
}
}
let s: [u32,..4] = unsafe { cast::transmute(s) };
SeedableRng::from_seed(s)
}
}
/// Controls how the task-local RNG is reseeded.
struct TaskRngReseeder;
impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
*rng = StdRng::new();
}
}
static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
/// The task-local RNG.
pub type TaskRng = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
// used to make space in TLS for a random number generator
local_data_key!(TASK_RNG_KEY: @mut TaskRng)
/// Retrieve the lazily-initialized task-local random number
/// generator, seeded by the system. Intended to be used in method
/// chaining style, e.g. `task_rng().gen::<int>()`.
///
/// The RNG provided will reseed itself from the operating system
/// after generating a certain amount of randomness.
///
/// The internal RNG used is platform and architecture dependent, even
/// if the operating system random number generator is rigged to give
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
pub fn task_rng() -> @mut TaskRng {
let r = local_data::get(TASK_RNG_KEY, |k| k.map(|k| *k));
match r {
None => {
let rng = @mut reseeding::ReseedingRng::new(StdRng::new(),
TASK_RNG_RESEED_THRESHOLD,
TaskRngReseeder);
local_data::set(TASK_RNG_KEY, rng);
rng
}
Some(rng) => rng
}
}
// Allow direct chaining with `task_rng`
impl<R: Rng> Rng for @mut R {
#[inline]
fn next_u32(&mut self) -> u32 {
(**self).next_u32()
}
#[inline]
fn next_u64(&mut self) -> u64 {
(**self).next_u64()
}
#[inline]
fn fill_bytes(&mut self, bytes: &mut [u8]) {
(**self).fill_bytes(bytes);
}
}
/// Generate a random value using the task-local random number
/// generator.
///
/// # Example
///
/// ```rust
/// use std::rand::random;
///
/// fn main() {
/// if random() {
/// let x = random();
/// println!("{}", 2u * x);
/// } else {
/// println!("{}", random::<f64>());
/// }
/// }
/// ```
#[inline]
pub fn random<T: Rand>() -> T {
task_rng().gen()
}
#[cfg(test)]
mod test {
use iter::{Iterator, range};
use option::{Option, Some};
use super::*;
#[test]
fn test_fill_bytes_default() {
let mut r = weak_rng();
let mut v = [0u8,.. 100];
r.fill_bytes(v);
}
#[test]
fn test_gen_integer_range() {
let mut r = rng();
for _ in range(0, 1000) {
let a = r.gen_integer_range(-3i, 42);
assert!(a >= -3 && a < 42);
assert_eq!(r.gen_integer_range(0, 1), 0);
assert_eq!(r.gen_integer_range(-12, -11), -12);
}
for _ in range(0, 1000) {
let a = r.gen_integer_range(10, 42); | {
XorShiftRng::new()
} | identifier_body |
example.rs | pub fn verse(n: i32) -> String {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and pass it around, no more bottles of beer on the wall.\n".to_string(),
2 => "2 bottles of beer on the wall, 2 bottles of beer.\n\
Take one down and pass it around, 1 bottle of beer on the wall.\n".to_string(),
n if n > 2 && n <= 99 =>
format!(
"{n} bottles of beer on the wall, {n} bottles of beer.\n\
Take one down and pass it around, {n_minus_1} bottles of beer on the wall.\n",
n=n,
n_minus_1=n - 1),
_ =>
panic!(), | pub fn sing(start: i32, end: i32) -> String {
let mut song = Vec::new();
for n in (end.. start + 1).rev() {
song.push(verse(n))
}
song.connect("\n")
} | }
}
| random_line_split |
example.rs | pub fn verse(n: i32) -> String |
pub fn sing(start: i32, end: i32) -> String {
let mut song = Vec::new();
for n in (end.. start + 1).rev() {
song.push(verse(n))
}
song.connect("\n")
}
| {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and pass it around, no more bottles of beer on the wall.\n".to_string(),
2 => "2 bottles of beer on the wall, 2 bottles of beer.\n\
Take one down and pass it around, 1 bottle of beer on the wall.\n".to_string(),
n if n > 2 && n <= 99 =>
format!(
"{n} bottles of beer on the wall, {n} bottles of beer.\n\
Take one down and pass it around, {n_minus_1} bottles of beer on the wall.\n",
n=n,
n_minus_1=n - 1),
_ =>
panic!(),
}
} | identifier_body |
example.rs | pub fn | (n: i32) -> String {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and pass it around, no more bottles of beer on the wall.\n".to_string(),
2 => "2 bottles of beer on the wall, 2 bottles of beer.\n\
Take one down and pass it around, 1 bottle of beer on the wall.\n".to_string(),
n if n > 2 && n <= 99 =>
format!(
"{n} bottles of beer on the wall, {n} bottles of beer.\n\
Take one down and pass it around, {n_minus_1} bottles of beer on the wall.\n",
n=n,
n_minus_1=n - 1),
_ =>
panic!(),
}
}
pub fn sing(start: i32, end: i32) -> String {
let mut song = Vec::new();
for n in (end.. start + 1).rev() {
song.push(verse(n))
}
song.connect("\n")
}
| verse | identifier_name |
unboxed-closures-blanket-fn-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // 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(unused_variables)]
// Test that you can supply `&F` where `F: FnMut()`.
#![feature(lang_items)]
fn a<F:FnMut() -> i32>(mut f: F) -> i32 {
f()
}
fn b(f: &mut FnMut() -> i32) -> i32 {
a(f)
}
fn c<F:FnMut() -> i32>(f: &mut F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&mut || 22);
assert_eq!(x, 22);
let x = c(&mut || 22);
assert_eq!(x, 22);
} | // file at the top-level directory of this distribution and at | random_line_split |
unboxed-closures-blanket-fn-mut.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.
// run-pass
#![allow(unused_variables)]
// Test that you can supply `&F` where `F: FnMut()`.
#![feature(lang_items)]
fn a<F:FnMut() -> i32>(mut f: F) -> i32 |
fn b(f: &mut FnMut() -> i32) -> i32 {
a(f)
}
fn c<F:FnMut() -> i32>(f: &mut F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&mut || 22);
assert_eq!(x, 22);
let x = c(&mut || 22);
assert_eq!(x, 22);
}
| {
f()
} | identifier_body |
unboxed-closures-blanket-fn-mut.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.
// run-pass
#![allow(unused_variables)]
// Test that you can supply `&F` where `F: FnMut()`.
#![feature(lang_items)]
fn a<F:FnMut() -> i32>(mut f: F) -> i32 {
f()
}
fn | (f: &mut FnMut() -> i32) -> i32 {
a(f)
}
fn c<F:FnMut() -> i32>(f: &mut F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&mut || 22);
assert_eq!(x, 22);
let x = c(&mut || 22);
assert_eq!(x, 22);
}
| b | identifier_name |
simd.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print/d i8x16
// check:$1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
// debugger:print/d i16x8
// check:$2 = {16, 17, 18, 19, 20, 21, 22, 23}
// debugger:print/d i32x4
// check:$3 = {24, 25, 26, 27}
// debugger:print/d i64x2
// check:$4 = {28, 29}
// debugger:print/d u8x16
// check:$5 = {30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}
// debugger:print/d u16x8
// check:$6 = {46, 47, 48, 49, 50, 51, 52, 53}
// debugger:print/d u32x4
// check:$7 = {54, 55, 56, 57}
// debugger:print/d u64x2
// check:$8 = {58, 59}
// debugger:print f32x4
// check:$9 = {60.5, 61.5, 62.5, 63.5}
// debugger:print f64x2
// check:$10 = {64.5, 65.5}
// debugger:continue
#![allow(experimental)]
#![allow(unused_variable)]
use std::unstable::simd::{i8x16, i16x8,i32x4,i64x2,u8x16,u16x8,u32x4,u64x2,f32x4,f64x2};
fn main() {
let i8x16 = i8x16(0i8, 1i8, 2i8, 3i8, 4i8, 5i8, 6i8, 7i8,
8i8, 9i8, 10i8, 11i8, 12i8, 13i8, 14i8, 15i8);
let i16x8 = i16x8(16i16, 17i16, 18i16, 19i16, 20i16, 21i16, 22i16, 23i16);
let i32x4 = i32x4(24i32, 25i32, 26i32, 27i32);
let i64x2 = i64x2(28i64, 29i64);
let u8x16 = u8x16(30u8, 31u8, 32u8, 33u8, 34u8, 35u8, 36u8, 37u8,
38u8, 39u8, 40u8, 41u8, 42u8, 43u8, 44u8, 45u8);
let u16x8 = u16x8(46u16, 47u16, 48u16, 49u16, 50u16, 51u16, 52u16, 53u16);
let u32x4 = u32x4(54u32, 55u32, 56u32, 57u32);
let u64x2 = u64x2(58u64, 59u64);
let f32x4 = f32x4(60.5f32, 61.5f32, 62.5f32, 63.5f32);
let f64x2 = f64x2(64.5f64, 65.5f64); |
#[inline(never)]
fn zzz() { () } |
zzz();
} | random_line_split |
simd.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print/d i8x16
// check:$1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
// debugger:print/d i16x8
// check:$2 = {16, 17, 18, 19, 20, 21, 22, 23}
// debugger:print/d i32x4
// check:$3 = {24, 25, 26, 27}
// debugger:print/d i64x2
// check:$4 = {28, 29}
// debugger:print/d u8x16
// check:$5 = {30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}
// debugger:print/d u16x8
// check:$6 = {46, 47, 48, 49, 50, 51, 52, 53}
// debugger:print/d u32x4
// check:$7 = {54, 55, 56, 57}
// debugger:print/d u64x2
// check:$8 = {58, 59}
// debugger:print f32x4
// check:$9 = {60.5, 61.5, 62.5, 63.5}
// debugger:print f64x2
// check:$10 = {64.5, 65.5}
// debugger:continue
#![allow(experimental)]
#![allow(unused_variable)]
use std::unstable::simd::{i8x16, i16x8,i32x4,i64x2,u8x16,u16x8,u32x4,u64x2,f32x4,f64x2};
fn main() {
let i8x16 = i8x16(0i8, 1i8, 2i8, 3i8, 4i8, 5i8, 6i8, 7i8,
8i8, 9i8, 10i8, 11i8, 12i8, 13i8, 14i8, 15i8);
let i16x8 = i16x8(16i16, 17i16, 18i16, 19i16, 20i16, 21i16, 22i16, 23i16);
let i32x4 = i32x4(24i32, 25i32, 26i32, 27i32);
let i64x2 = i64x2(28i64, 29i64);
let u8x16 = u8x16(30u8, 31u8, 32u8, 33u8, 34u8, 35u8, 36u8, 37u8,
38u8, 39u8, 40u8, 41u8, 42u8, 43u8, 44u8, 45u8);
let u16x8 = u16x8(46u16, 47u16, 48u16, 49u16, 50u16, 51u16, 52u16, 53u16);
let u32x4 = u32x4(54u32, 55u32, 56u32, 57u32);
let u64x2 = u64x2(58u64, 59u64);
let f32x4 = f32x4(60.5f32, 61.5f32, 62.5f32, 63.5f32);
let f64x2 = f64x2(64.5f64, 65.5f64);
zzz();
}
#[inline(never)]
fn | () { () }
| zzz | identifier_name |
simd.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print/d i8x16
// check:$1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
// debugger:print/d i16x8
// check:$2 = {16, 17, 18, 19, 20, 21, 22, 23}
// debugger:print/d i32x4
// check:$3 = {24, 25, 26, 27}
// debugger:print/d i64x2
// check:$4 = {28, 29}
// debugger:print/d u8x16
// check:$5 = {30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}
// debugger:print/d u16x8
// check:$6 = {46, 47, 48, 49, 50, 51, 52, 53}
// debugger:print/d u32x4
// check:$7 = {54, 55, 56, 57}
// debugger:print/d u64x2
// check:$8 = {58, 59}
// debugger:print f32x4
// check:$9 = {60.5, 61.5, 62.5, 63.5}
// debugger:print f64x2
// check:$10 = {64.5, 65.5}
// debugger:continue
#![allow(experimental)]
#![allow(unused_variable)]
use std::unstable::simd::{i8x16, i16x8,i32x4,i64x2,u8x16,u16x8,u32x4,u64x2,f32x4,f64x2};
fn main() |
#[inline(never)]
fn zzz() { () }
| {
let i8x16 = i8x16(0i8, 1i8, 2i8, 3i8, 4i8, 5i8, 6i8, 7i8,
8i8, 9i8, 10i8, 11i8, 12i8, 13i8, 14i8, 15i8);
let i16x8 = i16x8(16i16, 17i16, 18i16, 19i16, 20i16, 21i16, 22i16, 23i16);
let i32x4 = i32x4(24i32, 25i32, 26i32, 27i32);
let i64x2 = i64x2(28i64, 29i64);
let u8x16 = u8x16(30u8, 31u8, 32u8, 33u8, 34u8, 35u8, 36u8, 37u8,
38u8, 39u8, 40u8, 41u8, 42u8, 43u8, 44u8, 45u8);
let u16x8 = u16x8(46u16, 47u16, 48u16, 49u16, 50u16, 51u16, 52u16, 53u16);
let u32x4 = u32x4(54u32, 55u32, 56u32, 57u32);
let u64x2 = u64x2(58u64, 59u64);
let f32x4 = f32x4(60.5f32, 61.5f32, 62.5f32, 63.5f32);
let f64x2 = f64x2(64.5f64, 65.5f64);
zzz();
} | identifier_body |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::ffi::OsString;
use std::fs::{File, read_dir, OpenOptions, DirBuilder};
use std::io;
use std::io::{Write, Read, Seek};
use std::mem::transmute; | use std::str;
pub struct Wal {
fs: File,
dir: String,
}
impl Wal {
pub fn new(dir: &str) -> Result<Wal, io::Error> {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(true).create(dir).unwrap();
fss = read_dir(&dir);
}
let mut fnum = 0;
for dir_entry in fss? {
let entry = dir_entry?;
let epath = entry.path();
if let Some(fname) = epath.clone().file_stem() {
if tmp.len() < fname.len() || (tmp.len() == fname.len() && tmp.as_os_str() < fname) {
tmp = fname.to_os_string();
big_path = epath;
fnum += 1;
}
}
}
if fnum == 0 {
tmp = OsString::from("1");
let fpath = dir.to_string() + "/1.log";
big_path = Path::new(&*fpath).to_path_buf();
}
let fs = OpenOptions::new().read(true).create(true).write(true).open(big_path)?;
let hstr = tmp.into_string().unwrap();
let hi = hstr.parse::<u32>();
match hi {
Err(_) => {
return Err(io::Error::new(io::ErrorKind::Other, "not number file name"));
}
Ok(_) => {}
}
Ok(Wal { fs: fs, dir: dir.to_string() })
}
pub fn set_height(&mut self, height: usize) -> Result<(), io::Error> {
let mut name = height.to_string();
name = name + ".log";
let pathname = self.dir.clone() + "/";
let filename = pathname.clone() + &*name;
self.fs = OpenOptions::new().create(true).read(true).write(true).open(filename)?;
if height > 2 {
let mut delname = (height - 2).to_string();
delname = delname + ".log";
let delfilename = pathname + &*delname;
let _ = ::std::fs::remove_file(delfilename);
}
Ok(())
}
pub fn save(&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mtype.to_le()) };
self.fs.seek(io::SeekFrom::End(0))?;
self.fs.write(&len_bytes[..])?;
self.fs.write(&type_bytes[..])?;
let hlen = self.fs.write(msg.as_slice())?;
self.fs.flush()?;
Ok(hlen)
}
pub fn load(&mut self) -> Vec<(u8, Vec<u8>)> {
let mut vec_buf: Vec<u8> = Vec::new();
let mut vec_out: Vec<(u8, Vec<u8>)> = Vec::new();
self.fs.seek(io::SeekFrom::Start(0)).unwrap();
let res_fsize = self.fs.read_to_end(&mut vec_buf);
if res_fsize.is_err() {
return vec_out;
}
let fsize = res_fsize.unwrap();
if fsize <= 5 {
return vec_out;
}
let mut index = 0;
loop {
if index + 5 > fsize {
break;
}
let hd: [u8; 4] = [vec_buf[index], vec_buf[index + 1], vec_buf[index + 2], vec_buf[index + 3]];
let tmp: u32 = unsafe { transmute::<[u8; 4], u32>(hd) };
let bodylen = tmp as usize;
let mtype = vec_buf[index + 4];
index += 5;
if index + bodylen > fsize {
break;
}
vec_out.push((mtype, vec_buf[index..index + bodylen].to_vec()));
index += bodylen;
}
vec_out
}
} | use std::path::{PathBuf, Path}; | random_line_split |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::ffi::OsString;
use std::fs::{File, read_dir, OpenOptions, DirBuilder};
use std::io;
use std::io::{Write, Read, Seek};
use std::mem::transmute;
use std::path::{PathBuf, Path};
use std::str;
pub struct Wal {
fs: File,
dir: String,
}
impl Wal {
pub fn new(dir: &str) -> Result<Wal, io::Error> {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(true).create(dir).unwrap();
fss = read_dir(&dir);
}
let mut fnum = 0;
for dir_entry in fss? {
let entry = dir_entry?;
let epath = entry.path();
if let Some(fname) = epath.clone().file_stem() {
if tmp.len() < fname.len() || (tmp.len() == fname.len() && tmp.as_os_str() < fname) {
tmp = fname.to_os_string();
big_path = epath;
fnum += 1;
}
}
}
if fnum == 0 {
tmp = OsString::from("1");
let fpath = dir.to_string() + "/1.log";
big_path = Path::new(&*fpath).to_path_buf();
}
let fs = OpenOptions::new().read(true).create(true).write(true).open(big_path)?;
let hstr = tmp.into_string().unwrap();
let hi = hstr.parse::<u32>();
match hi {
Err(_) => {
return Err(io::Error::new(io::ErrorKind::Other, "not number file name"));
}
Ok(_) => {}
}
Ok(Wal { fs: fs, dir: dir.to_string() })
}
pub fn set_height(&mut self, height: usize) -> Result<(), io::Error> {
let mut name = height.to_string();
name = name + ".log";
let pathname = self.dir.clone() + "/";
let filename = pathname.clone() + &*name;
self.fs = OpenOptions::new().create(true).read(true).write(true).open(filename)?;
if height > 2 |
Ok(())
}
pub fn save(&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mtype.to_le()) };
self.fs.seek(io::SeekFrom::End(0))?;
self.fs.write(&len_bytes[..])?;
self.fs.write(&type_bytes[..])?;
let hlen = self.fs.write(msg.as_slice())?;
self.fs.flush()?;
Ok(hlen)
}
pub fn load(&mut self) -> Vec<(u8, Vec<u8>)> {
let mut vec_buf: Vec<u8> = Vec::new();
let mut vec_out: Vec<(u8, Vec<u8>)> = Vec::new();
self.fs.seek(io::SeekFrom::Start(0)).unwrap();
let res_fsize = self.fs.read_to_end(&mut vec_buf);
if res_fsize.is_err() {
return vec_out;
}
let fsize = res_fsize.unwrap();
if fsize <= 5 {
return vec_out;
}
let mut index = 0;
loop {
if index + 5 > fsize {
break;
}
let hd: [u8; 4] = [vec_buf[index], vec_buf[index + 1], vec_buf[index + 2], vec_buf[index + 3]];
let tmp: u32 = unsafe { transmute::<[u8; 4], u32>(hd) };
let bodylen = tmp as usize;
let mtype = vec_buf[index + 4];
index += 5;
if index + bodylen > fsize {
break;
}
vec_out.push((mtype, vec_buf[index..index + bodylen].to_vec()));
index += bodylen;
}
vec_out
}
}
| {
let mut delname = (height - 2).to_string();
delname = delname + ".log";
let delfilename = pathname + &*delname;
let _ = ::std::fs::remove_file(delfilename);
} | conditional_block |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::ffi::OsString;
use std::fs::{File, read_dir, OpenOptions, DirBuilder};
use std::io;
use std::io::{Write, Read, Seek};
use std::mem::transmute;
use std::path::{PathBuf, Path};
use std::str;
pub struct Wal {
fs: File,
dir: String,
}
impl Wal {
pub fn new(dir: &str) -> Result<Wal, io::Error> | }
}
if fnum == 0 {
tmp = OsString::from("1");
let fpath = dir.to_string() + "/1.log";
big_path = Path::new(&*fpath).to_path_buf();
}
let fs = OpenOptions::new().read(true).create(true).write(true).open(big_path)?;
let hstr = tmp.into_string().unwrap();
let hi = hstr.parse::<u32>();
match hi {
Err(_) => {
return Err(io::Error::new(io::ErrorKind::Other, "not number file name"));
}
Ok(_) => {}
}
Ok(Wal { fs: fs, dir: dir.to_string() })
}
pub fn set_height(&mut self, height: usize) -> Result<(), io::Error> {
let mut name = height.to_string();
name = name + ".log";
let pathname = self.dir.clone() + "/";
let filename = pathname.clone() + &*name;
self.fs = OpenOptions::new().create(true).read(true).write(true).open(filename)?;
if height > 2 {
let mut delname = (height - 2).to_string();
delname = delname + ".log";
let delfilename = pathname + &*delname;
let _ = ::std::fs::remove_file(delfilename);
}
Ok(())
}
pub fn save(&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mtype.to_le()) };
self.fs.seek(io::SeekFrom::End(0))?;
self.fs.write(&len_bytes[..])?;
self.fs.write(&type_bytes[..])?;
let hlen = self.fs.write(msg.as_slice())?;
self.fs.flush()?;
Ok(hlen)
}
pub fn load(&mut self) -> Vec<(u8, Vec<u8>)> {
let mut vec_buf: Vec<u8> = Vec::new();
let mut vec_out: Vec<(u8, Vec<u8>)> = Vec::new();
self.fs.seek(io::SeekFrom::Start(0)).unwrap();
let res_fsize = self.fs.read_to_end(&mut vec_buf);
if res_fsize.is_err() {
return vec_out;
}
let fsize = res_fsize.unwrap();
if fsize <= 5 {
return vec_out;
}
let mut index = 0;
loop {
if index + 5 > fsize {
break;
}
let hd: [u8; 4] = [vec_buf[index], vec_buf[index + 1], vec_buf[index + 2], vec_buf[index + 3]];
let tmp: u32 = unsafe { transmute::<[u8; 4], u32>(hd) };
let bodylen = tmp as usize;
let mtype = vec_buf[index + 4];
index += 5;
if index + bodylen > fsize {
break;
}
vec_out.push((mtype, vec_buf[index..index + bodylen].to_vec()));
index += bodylen;
}
vec_out
}
}
| {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(true).create(dir).unwrap();
fss = read_dir(&dir);
}
let mut fnum = 0;
for dir_entry in fss? {
let entry = dir_entry?;
let epath = entry.path();
if let Some(fname) = epath.clone().file_stem() {
if tmp.len() < fname.len() || (tmp.len() == fname.len() && tmp.as_os_str() < fname) {
tmp = fname.to_os_string();
big_path = epath;
fnum += 1;
} | identifier_body |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::ffi::OsString;
use std::fs::{File, read_dir, OpenOptions, DirBuilder};
use std::io;
use std::io::{Write, Read, Seek};
use std::mem::transmute;
use std::path::{PathBuf, Path};
use std::str;
pub struct Wal {
fs: File,
dir: String,
}
impl Wal {
pub fn new(dir: &str) -> Result<Wal, io::Error> {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(true).create(dir).unwrap();
fss = read_dir(&dir);
}
let mut fnum = 0;
for dir_entry in fss? {
let entry = dir_entry?;
let epath = entry.path();
if let Some(fname) = epath.clone().file_stem() {
if tmp.len() < fname.len() || (tmp.len() == fname.len() && tmp.as_os_str() < fname) {
tmp = fname.to_os_string();
big_path = epath;
fnum += 1;
}
}
}
if fnum == 0 {
tmp = OsString::from("1");
let fpath = dir.to_string() + "/1.log";
big_path = Path::new(&*fpath).to_path_buf();
}
let fs = OpenOptions::new().read(true).create(true).write(true).open(big_path)?;
let hstr = tmp.into_string().unwrap();
let hi = hstr.parse::<u32>();
match hi {
Err(_) => {
return Err(io::Error::new(io::ErrorKind::Other, "not number file name"));
}
Ok(_) => {}
}
Ok(Wal { fs: fs, dir: dir.to_string() })
}
pub fn set_height(&mut self, height: usize) -> Result<(), io::Error> {
let mut name = height.to_string();
name = name + ".log";
let pathname = self.dir.clone() + "/";
let filename = pathname.clone() + &*name;
self.fs = OpenOptions::new().create(true).read(true).write(true).open(filename)?;
if height > 2 {
let mut delname = (height - 2).to_string();
delname = delname + ".log";
let delfilename = pathname + &*delname;
let _ = ::std::fs::remove_file(delfilename);
}
Ok(())
}
pub fn | (&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mtype.to_le()) };
self.fs.seek(io::SeekFrom::End(0))?;
self.fs.write(&len_bytes[..])?;
self.fs.write(&type_bytes[..])?;
let hlen = self.fs.write(msg.as_slice())?;
self.fs.flush()?;
Ok(hlen)
}
pub fn load(&mut self) -> Vec<(u8, Vec<u8>)> {
let mut vec_buf: Vec<u8> = Vec::new();
let mut vec_out: Vec<(u8, Vec<u8>)> = Vec::new();
self.fs.seek(io::SeekFrom::Start(0)).unwrap();
let res_fsize = self.fs.read_to_end(&mut vec_buf);
if res_fsize.is_err() {
return vec_out;
}
let fsize = res_fsize.unwrap();
if fsize <= 5 {
return vec_out;
}
let mut index = 0;
loop {
if index + 5 > fsize {
break;
}
let hd: [u8; 4] = [vec_buf[index], vec_buf[index + 1], vec_buf[index + 2], vec_buf[index + 3]];
let tmp: u32 = unsafe { transmute::<[u8; 4], u32>(hd) };
let bodylen = tmp as usize;
let mtype = vec_buf[index + 4];
index += 5;
if index + bodylen > fsize {
break;
}
vec_out.push((mtype, vec_buf[index..index + bodylen].to_vec()));
index += bodylen;
}
vec_out
}
}
| save | identifier_name |
forcetouchevent.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::ForceTouchEventBinding;
use dom::bindings::codegen::Bindings::ForceTouchEventBinding::ForceTouchEventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root};
use dom::bindings::num::Finite;
use dom::bindings::reflector::reflect_dom_object;
use dom::uievent::UIEvent;
use dom::window::Window;
use util::str::DOMString;
#[dom_struct]
pub struct ForceTouchEvent {
uievent: UIEvent,
force: f32,
}
impl ForceTouchEvent {
fn new_inherited(force: f32) -> ForceTouchEvent {
ForceTouchEvent {
uievent: UIEvent::new_inherited(),
force: force,
}
}
| type_: DOMString,
force: f32) -> Root<ForceTouchEvent> {
let event = box ForceTouchEvent::new_inherited(force);
let ev = reflect_dom_object(event, GlobalRef::Window(window), ForceTouchEventBinding::Wrap);
ev.upcast::<UIEvent>().InitUIEvent(type_, true, true, Some(window), 0);
ev
}
}
impl<'a> ForceTouchEventMethods for &'a ForceTouchEvent {
fn ServoForce(&self) -> Finite<f32> {
Finite::wrap(self.force)
}
fn SERVO_FORCE_AT_MOUSE_DOWN(&self) -> Finite<f32> {
Finite::wrap(1.0)
}
fn SERVO_FORCE_AT_FORCE_MOUSE_DOWN(&self) -> Finite<f32> {
Finite::wrap(2.0)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.uievent.IsTrusted()
}
} | pub fn new(window: &Window, | random_line_split |
forcetouchevent.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::ForceTouchEventBinding;
use dom::bindings::codegen::Bindings::ForceTouchEventBinding::ForceTouchEventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root};
use dom::bindings::num::Finite;
use dom::bindings::reflector::reflect_dom_object;
use dom::uievent::UIEvent;
use dom::window::Window;
use util::str::DOMString;
#[dom_struct]
pub struct ForceTouchEvent {
uievent: UIEvent,
force: f32,
}
impl ForceTouchEvent {
fn | (force: f32) -> ForceTouchEvent {
ForceTouchEvent {
uievent: UIEvent::new_inherited(),
force: force,
}
}
pub fn new(window: &Window,
type_: DOMString,
force: f32) -> Root<ForceTouchEvent> {
let event = box ForceTouchEvent::new_inherited(force);
let ev = reflect_dom_object(event, GlobalRef::Window(window), ForceTouchEventBinding::Wrap);
ev.upcast::<UIEvent>().InitUIEvent(type_, true, true, Some(window), 0);
ev
}
}
impl<'a> ForceTouchEventMethods for &'a ForceTouchEvent {
fn ServoForce(&self) -> Finite<f32> {
Finite::wrap(self.force)
}
fn SERVO_FORCE_AT_MOUSE_DOWN(&self) -> Finite<f32> {
Finite::wrap(1.0)
}
fn SERVO_FORCE_AT_FORCE_MOUSE_DOWN(&self) -> Finite<f32> {
Finite::wrap(2.0)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.uievent.IsTrusted()
}
}
| new_inherited | identifier_name |
forcetouchevent.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::ForceTouchEventBinding;
use dom::bindings::codegen::Bindings::ForceTouchEventBinding::ForceTouchEventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root};
use dom::bindings::num::Finite;
use dom::bindings::reflector::reflect_dom_object;
use dom::uievent::UIEvent;
use dom::window::Window;
use util::str::DOMString;
#[dom_struct]
pub struct ForceTouchEvent {
uievent: UIEvent,
force: f32,
}
impl ForceTouchEvent {
fn new_inherited(force: f32) -> ForceTouchEvent {
ForceTouchEvent {
uievent: UIEvent::new_inherited(),
force: force,
}
}
pub fn new(window: &Window,
type_: DOMString,
force: f32) -> Root<ForceTouchEvent> {
let event = box ForceTouchEvent::new_inherited(force);
let ev = reflect_dom_object(event, GlobalRef::Window(window), ForceTouchEventBinding::Wrap);
ev.upcast::<UIEvent>().InitUIEvent(type_, true, true, Some(window), 0);
ev
}
}
impl<'a> ForceTouchEventMethods for &'a ForceTouchEvent {
fn ServoForce(&self) -> Finite<f32> {
Finite::wrap(self.force)
}
fn SERVO_FORCE_AT_MOUSE_DOWN(&self) -> Finite<f32> {
Finite::wrap(1.0)
}
fn SERVO_FORCE_AT_FORCE_MOUSE_DOWN(&self) -> Finite<f32> |
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.uievent.IsTrusted()
}
}
| {
Finite::wrap(2.0)
} | identifier_body |
webvr_traits.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use webvr::*;
pub type WebVRResult<T> = Result<T, String>;
// Messages from Script thread to WebVR thread.
#[derive(Deserialize, Serialize)]
pub enum WebVRMsg {
RegisterContext(PipelineId),
UnregisterContext(PipelineId),
PollEvents(IpcSender<bool>),
GetDisplays(IpcSender<WebVRResult<Vec<VRDisplayData>>>),
GetFrameData(PipelineId, u64, f64, f64, IpcSender<WebVRResult<VRFrameData>>),
ResetPose(PipelineId, u64, IpcSender<WebVRResult<VRDisplayData>>),
RequestPresent(PipelineId, u64, IpcSender<WebVRResult<()>>),
ExitPresent(PipelineId, u64, Option<IpcSender<WebVRResult<()>>>),
CreateCompositor(u64),
Exit,
} | * 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 ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId; | random_line_split |
webvr_traits.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 ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use webvr::*;
pub type WebVRResult<T> = Result<T, String>;
// Messages from Script thread to WebVR thread.
#[derive(Deserialize, Serialize)]
pub enum | {
RegisterContext(PipelineId),
UnregisterContext(PipelineId),
PollEvents(IpcSender<bool>),
GetDisplays(IpcSender<WebVRResult<Vec<VRDisplayData>>>),
GetFrameData(PipelineId, u64, f64, f64, IpcSender<WebVRResult<VRFrameData>>),
ResetPose(PipelineId, u64, IpcSender<WebVRResult<VRDisplayData>>),
RequestPresent(PipelineId, u64, IpcSender<WebVRResult<()>>),
ExitPresent(PipelineId, u64, Option<IpcSender<WebVRResult<()>>>),
CreateCompositor(u64),
Exit,
}
| WebVRMsg | identifier_name |
run.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::{Arc, Mutex, Condvar};
use ctrlc::CtrlC;
use fdlimit::raise_fd_limit;
use ethcore_logger::{Config as LogConfig, setup_log};
use ethcore_rpc::{NetworkSettings, is_major_importing};
use ethsync::NetworkConfiguration;
use util::{Colour, version, U256};
use io::{MayPanic, ForwardPanic, PanicHandler};
use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, ChainNotify, BlockChainClient};
use ethcore::service::ClientService;
use ethcore::account_provider::AccountProvider;
use ethcore::miner::{Miner, MinerService, ExternalMiner, MinerOptions};
use ethcore::snapshot;
use ethsync::SyncConfig;
use informant::Informant;
use rpc::{HttpServer, IpcServer, HttpConfiguration, IpcConfiguration};
use signer::SignerServer;
use dapps::WebappServer;
use io_handler::ClientIoHandler;
use params::{
SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch,
tracing_switch_to_bool, fatdb_switch_to_bool,
};
use helpers::{to_client_config, execute_upgrades, passwords_from_files};
use dir::Directories;
use cache::CacheConfig;
use user_defaults::UserDefaults;
use dapps;
use signer;
use modules;
use rpc_apis;
use rpc;
use url;
// how often to take periodic snapshots.
const SNAPSHOT_PERIOD: u64 = 10000;
// how many blocks to wait before starting a periodic snapshot.
const SNAPSHOT_HISTORY: u64 = 500;
#[derive(Debug, PartialEq)]
pub struct RunCmd {
pub cache_config: CacheConfig,
pub dirs: Directories,
pub spec: SpecType,
pub pruning: Pruning,
pub pruning_history: u64,
/// Some if execution should be daemonized. Contains pid_file path.
pub daemon: Option<String>,
pub logger_config: LogConfig,
pub miner_options: MinerOptions,
pub http_conf: HttpConfiguration,
pub ipc_conf: IpcConfiguration,
pub net_conf: NetworkConfiguration,
pub network_id: Option<U256>,
pub warp_sync: bool,
pub acc_conf: AccountsConfig,
pub gas_pricer: GasPricerConfig,
pub miner_extras: MinerExtras,
pub mode: Mode,
pub tracing: Switch,
pub fat_db: Switch,
pub compaction: DatabaseCompactionProfile,
pub wal: bool,
pub vm_type: VMType,
pub enable_network: bool,
pub geth_compatibility: bool,
pub signer_port: Option<u16>,
pub net_settings: NetworkSettings,
pub dapps_conf: dapps::Configuration,
pub signer_conf: signer::Configuration,
pub ui: bool,
pub name: String,
pub custom_bootnodes: bool,
pub no_periodic_snapshot: bool,
pub check_seal: bool,
}
pub fn execute(cmd: RunCmd) -> Result<(), String> {
// set up panic handler
let panic_handler = PanicHandler::new_in_arc();
// set up logger
let logger = try!(setup_log(&cmd.logger_config));
// increase max number of open files
raise_fd_limit();
// create dirs used by parity
try!(cmd.dirs.create_dirs());
// load spec
let spec = try!(cmd.spec.spec());
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
// database paths
let db_dirs = cmd.dirs.database(genesis_hash, spec.fork_name.clone());
// user defaults path
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let mut user_defaults = try!(UserDefaults::load(&user_defaults_path));
// select pruning algorithm
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(cmd.tracing, &user_defaults));
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm));
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.fork_path().as_path())));
// run in daemon mode
if let Some(pid_file) = cmd.daemon {
try!(daemonize(pid_file));
}
// display info about used pruning algorithm
info!("Starting {}", Colour::White.bold().paint(version()));
info!("State DB configuation: {}{}{}",
Colour::White.bold().paint(algorithm.as_str()),
match fat_db {
true => Colour::White.bold().paint(" +Fat").to_string(),
false => "".to_owned(),
},
match tracing {
true => Colour::White.bold().paint(" +Trace").to_string(),
false => "".to_owned(),
}
);
// display warning about using experimental journaldb alorithm
if!algorithm.is_stable() {
warn!("Your chosen strategy is {}! You can re-run with --pruning to change.", Colour::Red.bold().paint("unstable"));
}
// create sync config
let mut sync_config = SyncConfig::default();
sync_config.network_id = match cmd.network_id {
Some(id) => id,
None => spec.network_id(),
};
if spec.subprotocol_name().len()!= 3 {
warn!("Your chain specification's subprotocol length is not 3. Ignoring.");
} else {
sync_config.subprotocol_name.clone_from_slice(spec.subprotocol_name().as_bytes());
}
sync_config.fork_block = spec.fork_block();
sync_config.warp_sync = cmd.warp_sync;
// prepare account provider
let account_provider = Arc::new(try!(prepare_account_provider(&cmd.dirs, cmd.acc_conf)));
// create miner
let miner = Miner::new(cmd.miner_options, cmd.gas_pricer.into(), &spec, Some(account_provider.clone()));
miner.set_author(cmd.miner_extras.author);
miner.set_gas_floor_target(cmd.miner_extras.gas_floor_target);
miner.set_gas_ceil_target(cmd.miner_extras.gas_ceil_target);
miner.set_extra_data(cmd.miner_extras.extra_data);
miner.set_transactions_limit(cmd.miner_extras.transactions_limit);
// create client config
let client_config = to_client_config(
&cmd.cache_config,
cmd.mode,
tracing,
fat_db,
cmd.compaction,
cmd.wal,
cmd.vm_type,
cmd.name,
algorithm,
cmd.pruning_history,
cmd.check_seal,
);
// set up bootnodes
let mut net_conf = cmd.net_conf;
if!cmd.custom_bootnodes {
net_conf.boot_nodes = spec.nodes.clone();
}
// set network path.
net_conf.net_config_path = Some(db_dirs.network_path().to_string_lossy().into_owned());
// create supervisor
let mut hypervisor = modules::hypervisor(&cmd.dirs.ipc_path());
// create client service.
let service = try!(ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&cmd.dirs.ipc_path(),
miner.clone(),
).map_err(|e| format!("Client service error: {:?}", e)));
// forward panics from service
panic_handler.forward_from(&service);
// take handle to client
let client = service.client();
let snapshot_service = service.snapshot_service();
// create external miner
let external_miner = Arc::new(ExternalMiner::default());
// create sync object
let (sync_provider, manage_network, chain_notify) = try!(modules::sync(
&mut hypervisor, sync_config, net_conf.into(), client.clone(), snapshot_service.clone(), &cmd.logger_config,
).map_err(|e| format!("Sync error: {}", e)));
service.add_notify(chain_notify.clone());
// start network
if cmd.enable_network {
chain_notify.start();
}
// set up dependencies for rpc servers
let signer_path = cmd.signer_conf.signer_path.clone();
let deps_for_rpc_apis = Arc::new(rpc_apis::Dependencies {
signer_service: Arc::new(rpc_apis::SignerService::new(move || {
signer::generate_new_token(signer_path.clone()).map_err(|e| format!("{:?}", e))
}, cmd.signer_port)),
client: client.clone(),
sync: sync_provider.clone(),
net: manage_network.clone(),
secret_store: account_provider.clone(),
miner: miner.clone(),
external_miner: external_miner.clone(),
logger: logger.clone(),
settings: Arc::new(cmd.net_settings.clone()),
net_service: manage_network.clone(),
geth_compatibility: cmd.geth_compatibility,
dapps_port: match cmd.dapps_conf.enabled {
true => Some(cmd.dapps_conf.port),
false => None,
},
});
let dependencies = rpc::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start rpc servers
let http_server = try!(rpc::new_http(cmd.http_conf, &dependencies));
let ipc_server = try!(rpc::new_ipc(cmd.ipc_conf, &dependencies));
let dapps_deps = dapps::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
client: client.clone(),
sync: sync_provider.clone(),
};
// start dapps server
let dapps_server = try!(dapps::new(cmd.dapps_conf.clone(), dapps_deps));
let signer_deps = signer::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start signer server
let signer_server = try!(signer::start(cmd.signer_conf, signer_deps));
let informant = Arc::new(Informant::new(
service.client(),
Some(sync_provider.clone()),
Some(manage_network.clone()),
Some(snapshot_service.clone()),
cmd.logger_config.color
));
let info_notify: Arc<ChainNotify> = informant.clone();
service.add_notify(info_notify);
let io_handler = Arc::new(ClientIoHandler {
client: service.client(),
info: informant,
sync: sync_provider.clone(),
net: manage_network.clone(),
accounts: account_provider.clone(),
shutdown: Default::default(),
});
service.register_io_handler(io_handler.clone()).expect("Error registering IO handler");
// the watcher must be kept alive.
let _watcher = match cmd.no_periodic_snapshot {
true => None,
false => {
let sync = sync_provider.clone();
let watcher = Arc::new(snapshot::Watcher::new(
service.client(),
move || is_major_importing(Some(sync.status().state), client.queue_info()),
service.io().channel(),
SNAPSHOT_PERIOD,
SNAPSHOT_HISTORY,
));
service.add_notify(watcher.clone());
Some(watcher)
},
};
// start ui
if cmd.ui {
if!cmd.dapps_conf.enabled {
return Err("Cannot use UI command with Dapps turned off.".into())
}
url::open(&format!("http://{}:{}/", cmd.dapps_conf.interface, cmd.dapps_conf.port));
}
// save user defaults
user_defaults.pruning = algorithm;
user_defaults.tracing = tracing;
try!(user_defaults.save(&user_defaults_path));
// Handle exit
wait_for_exit(panic_handler, http_server, ipc_server, dapps_server, signer_server);
// to make sure timer does not spawn requests while shutdown is in progress
io_handler.shutdown.store(true, ::std::sync::atomic::Ordering::SeqCst);
// just Arc is dropping here, to allow other reference release in its default time
drop(io_handler);
// hypervisor should be shutdown first while everything still works and can be
// terminated gracefully
drop(hypervisor);
Ok(())
}
#[cfg(not(windows))]
fn daemonize(pid_file: String) -> Result<(), String> {
extern crate daemonize;
daemonize::Daemonize::new()
.pid_file(pid_file)
.chown_pid_file(true)
.start()
.map(|_| ())
.map_err(|e| format!("Couldn't daemonize; {}", e))
}
#[cfg(windows)]
fn daemonize(_pid_file: String) -> Result<(), String> {
Err("daemon is no supported on windows".into())
}
fn prepare_account_provider(dirs: &Directories, cfg: AccountsConfig) -> Result<AccountProvider, String> {
use ethcore::ethstore::EthStore;
use ethcore::ethstore::dir::DiskDirectory;
let passwords = try!(passwords_from_files(cfg.password_files));
let dir = Box::new(try!(DiskDirectory::create(dirs.keys.clone()).map_err(|e| format!("Could not open keys directory: {}", e))));
let account_service = AccountProvider::new(Box::new(
try!(EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e)))
));
for a in cfg.unlocked_accounts {
if passwords.iter().find(|p| account_service.unlock_account_permanently(a, (*p).clone()).is_ok()).is_none() {
return Err(format!("No password found to unlock account {}. Make sure valid password is present in files passed using `--password`.", a));
}
}
Ok(account_service)
}
fn | (
panic_handler: Arc<PanicHandler>,
_http_server: Option<HttpServer>,
_ipc_server: Option<IpcServer>,
_dapps_server: Option<WebappServer>,
_signer_server: Option<SignerServer>
) {
let exit = Arc::new(Condvar::new());
// Handle possible exits
let e = exit.clone();
CtrlC::set_handler(move || { e.notify_all(); });
// Handle panics
let e = exit.clone();
panic_handler.on_panic(move |_reason| { e.notify_all(); });
// Wait for signal
let mutex = Mutex::new(());
let _ = exit.wait(mutex.lock().unwrap());
info!("Finishing work, please wait...");
}
| wait_for_exit | identifier_name |
run.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::{Arc, Mutex, Condvar};
use ctrlc::CtrlC;
use fdlimit::raise_fd_limit;
use ethcore_logger::{Config as LogConfig, setup_log};
use ethcore_rpc::{NetworkSettings, is_major_importing};
use ethsync::NetworkConfiguration;
use util::{Colour, version, U256};
use io::{MayPanic, ForwardPanic, PanicHandler};
use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, ChainNotify, BlockChainClient};
use ethcore::service::ClientService;
use ethcore::account_provider::AccountProvider;
use ethcore::miner::{Miner, MinerService, ExternalMiner, MinerOptions};
use ethcore::snapshot;
use ethsync::SyncConfig;
use informant::Informant;
use rpc::{HttpServer, IpcServer, HttpConfiguration, IpcConfiguration};
use signer::SignerServer;
use dapps::WebappServer;
use io_handler::ClientIoHandler;
use params::{
SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch,
tracing_switch_to_bool, fatdb_switch_to_bool,
};
use helpers::{to_client_config, execute_upgrades, passwords_from_files};
use dir::Directories;
use cache::CacheConfig;
use user_defaults::UserDefaults;
use dapps;
use signer;
use modules;
use rpc_apis;
use rpc;
use url;
// how often to take periodic snapshots.
const SNAPSHOT_PERIOD: u64 = 10000;
// how many blocks to wait before starting a periodic snapshot.
const SNAPSHOT_HISTORY: u64 = 500;
#[derive(Debug, PartialEq)]
pub struct RunCmd {
pub cache_config: CacheConfig,
pub dirs: Directories,
pub spec: SpecType,
pub pruning: Pruning,
pub pruning_history: u64,
/// Some if execution should be daemonized. Contains pid_file path.
pub daemon: Option<String>,
pub logger_config: LogConfig,
pub miner_options: MinerOptions,
pub http_conf: HttpConfiguration,
pub ipc_conf: IpcConfiguration,
pub net_conf: NetworkConfiguration,
pub network_id: Option<U256>,
pub warp_sync: bool,
pub acc_conf: AccountsConfig,
pub gas_pricer: GasPricerConfig,
pub miner_extras: MinerExtras,
pub mode: Mode,
pub tracing: Switch,
pub fat_db: Switch,
pub compaction: DatabaseCompactionProfile,
pub wal: bool,
pub vm_type: VMType,
pub enable_network: bool,
pub geth_compatibility: bool,
pub signer_port: Option<u16>,
pub net_settings: NetworkSettings,
pub dapps_conf: dapps::Configuration,
pub signer_conf: signer::Configuration,
pub ui: bool,
pub name: String,
pub custom_bootnodes: bool,
pub no_periodic_snapshot: bool,
pub check_seal: bool,
}
pub fn execute(cmd: RunCmd) -> Result<(), String> {
// set up panic handler
let panic_handler = PanicHandler::new_in_arc();
// set up logger
let logger = try!(setup_log(&cmd.logger_config));
// increase max number of open files
raise_fd_limit();
// create dirs used by parity
try!(cmd.dirs.create_dirs());
// load spec
let spec = try!(cmd.spec.spec());
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
// database paths
let db_dirs = cmd.dirs.database(genesis_hash, spec.fork_name.clone());
// user defaults path
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let mut user_defaults = try!(UserDefaults::load(&user_defaults_path));
// select pruning algorithm
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(cmd.tracing, &user_defaults));
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm));
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.fork_path().as_path())));
// run in daemon mode
if let Some(pid_file) = cmd.daemon {
try!(daemonize(pid_file));
}
// display info about used pruning algorithm
info!("Starting {}", Colour::White.bold().paint(version()));
info!("State DB configuation: {}{}{}",
Colour::White.bold().paint(algorithm.as_str()),
match fat_db {
true => Colour::White.bold().paint(" +Fat").to_string(),
false => "".to_owned(),
},
match tracing {
true => Colour::White.bold().paint(" +Trace").to_string(),
false => "".to_owned(),
}
);
// display warning about using experimental journaldb alorithm
if!algorithm.is_stable() {
warn!("Your chosen strategy is {}! You can re-run with --pruning to change.", Colour::Red.bold().paint("unstable"));
}
// create sync config
let mut sync_config = SyncConfig::default();
sync_config.network_id = match cmd.network_id {
Some(id) => id,
None => spec.network_id(),
};
if spec.subprotocol_name().len()!= 3 {
warn!("Your chain specification's subprotocol length is not 3. Ignoring.");
} else {
sync_config.subprotocol_name.clone_from_slice(spec.subprotocol_name().as_bytes());
}
sync_config.fork_block = spec.fork_block();
sync_config.warp_sync = cmd.warp_sync;
// prepare account provider
let account_provider = Arc::new(try!(prepare_account_provider(&cmd.dirs, cmd.acc_conf))); | let miner = Miner::new(cmd.miner_options, cmd.gas_pricer.into(), &spec, Some(account_provider.clone()));
miner.set_author(cmd.miner_extras.author);
miner.set_gas_floor_target(cmd.miner_extras.gas_floor_target);
miner.set_gas_ceil_target(cmd.miner_extras.gas_ceil_target);
miner.set_extra_data(cmd.miner_extras.extra_data);
miner.set_transactions_limit(cmd.miner_extras.transactions_limit);
// create client config
let client_config = to_client_config(
&cmd.cache_config,
cmd.mode,
tracing,
fat_db,
cmd.compaction,
cmd.wal,
cmd.vm_type,
cmd.name,
algorithm,
cmd.pruning_history,
cmd.check_seal,
);
// set up bootnodes
let mut net_conf = cmd.net_conf;
if!cmd.custom_bootnodes {
net_conf.boot_nodes = spec.nodes.clone();
}
// set network path.
net_conf.net_config_path = Some(db_dirs.network_path().to_string_lossy().into_owned());
// create supervisor
let mut hypervisor = modules::hypervisor(&cmd.dirs.ipc_path());
// create client service.
let service = try!(ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&cmd.dirs.ipc_path(),
miner.clone(),
).map_err(|e| format!("Client service error: {:?}", e)));
// forward panics from service
panic_handler.forward_from(&service);
// take handle to client
let client = service.client();
let snapshot_service = service.snapshot_service();
// create external miner
let external_miner = Arc::new(ExternalMiner::default());
// create sync object
let (sync_provider, manage_network, chain_notify) = try!(modules::sync(
&mut hypervisor, sync_config, net_conf.into(), client.clone(), snapshot_service.clone(), &cmd.logger_config,
).map_err(|e| format!("Sync error: {}", e)));
service.add_notify(chain_notify.clone());
// start network
if cmd.enable_network {
chain_notify.start();
}
// set up dependencies for rpc servers
let signer_path = cmd.signer_conf.signer_path.clone();
let deps_for_rpc_apis = Arc::new(rpc_apis::Dependencies {
signer_service: Arc::new(rpc_apis::SignerService::new(move || {
signer::generate_new_token(signer_path.clone()).map_err(|e| format!("{:?}", e))
}, cmd.signer_port)),
client: client.clone(),
sync: sync_provider.clone(),
net: manage_network.clone(),
secret_store: account_provider.clone(),
miner: miner.clone(),
external_miner: external_miner.clone(),
logger: logger.clone(),
settings: Arc::new(cmd.net_settings.clone()),
net_service: manage_network.clone(),
geth_compatibility: cmd.geth_compatibility,
dapps_port: match cmd.dapps_conf.enabled {
true => Some(cmd.dapps_conf.port),
false => None,
},
});
let dependencies = rpc::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start rpc servers
let http_server = try!(rpc::new_http(cmd.http_conf, &dependencies));
let ipc_server = try!(rpc::new_ipc(cmd.ipc_conf, &dependencies));
let dapps_deps = dapps::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
client: client.clone(),
sync: sync_provider.clone(),
};
// start dapps server
let dapps_server = try!(dapps::new(cmd.dapps_conf.clone(), dapps_deps));
let signer_deps = signer::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start signer server
let signer_server = try!(signer::start(cmd.signer_conf, signer_deps));
let informant = Arc::new(Informant::new(
service.client(),
Some(sync_provider.clone()),
Some(manage_network.clone()),
Some(snapshot_service.clone()),
cmd.logger_config.color
));
let info_notify: Arc<ChainNotify> = informant.clone();
service.add_notify(info_notify);
let io_handler = Arc::new(ClientIoHandler {
client: service.client(),
info: informant,
sync: sync_provider.clone(),
net: manage_network.clone(),
accounts: account_provider.clone(),
shutdown: Default::default(),
});
service.register_io_handler(io_handler.clone()).expect("Error registering IO handler");
// the watcher must be kept alive.
let _watcher = match cmd.no_periodic_snapshot {
true => None,
false => {
let sync = sync_provider.clone();
let watcher = Arc::new(snapshot::Watcher::new(
service.client(),
move || is_major_importing(Some(sync.status().state), client.queue_info()),
service.io().channel(),
SNAPSHOT_PERIOD,
SNAPSHOT_HISTORY,
));
service.add_notify(watcher.clone());
Some(watcher)
},
};
// start ui
if cmd.ui {
if!cmd.dapps_conf.enabled {
return Err("Cannot use UI command with Dapps turned off.".into())
}
url::open(&format!("http://{}:{}/", cmd.dapps_conf.interface, cmd.dapps_conf.port));
}
// save user defaults
user_defaults.pruning = algorithm;
user_defaults.tracing = tracing;
try!(user_defaults.save(&user_defaults_path));
// Handle exit
wait_for_exit(panic_handler, http_server, ipc_server, dapps_server, signer_server);
// to make sure timer does not spawn requests while shutdown is in progress
io_handler.shutdown.store(true, ::std::sync::atomic::Ordering::SeqCst);
// just Arc is dropping here, to allow other reference release in its default time
drop(io_handler);
// hypervisor should be shutdown first while everything still works and can be
// terminated gracefully
drop(hypervisor);
Ok(())
}
#[cfg(not(windows))]
fn daemonize(pid_file: String) -> Result<(), String> {
extern crate daemonize;
daemonize::Daemonize::new()
.pid_file(pid_file)
.chown_pid_file(true)
.start()
.map(|_| ())
.map_err(|e| format!("Couldn't daemonize; {}", e))
}
#[cfg(windows)]
fn daemonize(_pid_file: String) -> Result<(), String> {
Err("daemon is no supported on windows".into())
}
fn prepare_account_provider(dirs: &Directories, cfg: AccountsConfig) -> Result<AccountProvider, String> {
use ethcore::ethstore::EthStore;
use ethcore::ethstore::dir::DiskDirectory;
let passwords = try!(passwords_from_files(cfg.password_files));
let dir = Box::new(try!(DiskDirectory::create(dirs.keys.clone()).map_err(|e| format!("Could not open keys directory: {}", e))));
let account_service = AccountProvider::new(Box::new(
try!(EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e)))
));
for a in cfg.unlocked_accounts {
if passwords.iter().find(|p| account_service.unlock_account_permanently(a, (*p).clone()).is_ok()).is_none() {
return Err(format!("No password found to unlock account {}. Make sure valid password is present in files passed using `--password`.", a));
}
}
Ok(account_service)
}
fn wait_for_exit(
panic_handler: Arc<PanicHandler>,
_http_server: Option<HttpServer>,
_ipc_server: Option<IpcServer>,
_dapps_server: Option<WebappServer>,
_signer_server: Option<SignerServer>
) {
let exit = Arc::new(Condvar::new());
// Handle possible exits
let e = exit.clone();
CtrlC::set_handler(move || { e.notify_all(); });
// Handle panics
let e = exit.clone();
panic_handler.on_panic(move |_reason| { e.notify_all(); });
// Wait for signal
let mutex = Mutex::new(());
let _ = exit.wait(mutex.lock().unwrap());
info!("Finishing work, please wait...");
} |
// create miner | random_line_split |
run.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::{Arc, Mutex, Condvar};
use ctrlc::CtrlC;
use fdlimit::raise_fd_limit;
use ethcore_logger::{Config as LogConfig, setup_log};
use ethcore_rpc::{NetworkSettings, is_major_importing};
use ethsync::NetworkConfiguration;
use util::{Colour, version, U256};
use io::{MayPanic, ForwardPanic, PanicHandler};
use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, ChainNotify, BlockChainClient};
use ethcore::service::ClientService;
use ethcore::account_provider::AccountProvider;
use ethcore::miner::{Miner, MinerService, ExternalMiner, MinerOptions};
use ethcore::snapshot;
use ethsync::SyncConfig;
use informant::Informant;
use rpc::{HttpServer, IpcServer, HttpConfiguration, IpcConfiguration};
use signer::SignerServer;
use dapps::WebappServer;
use io_handler::ClientIoHandler;
use params::{
SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch,
tracing_switch_to_bool, fatdb_switch_to_bool,
};
use helpers::{to_client_config, execute_upgrades, passwords_from_files};
use dir::Directories;
use cache::CacheConfig;
use user_defaults::UserDefaults;
use dapps;
use signer;
use modules;
use rpc_apis;
use rpc;
use url;
// how often to take periodic snapshots.
const SNAPSHOT_PERIOD: u64 = 10000;
// how many blocks to wait before starting a periodic snapshot.
const SNAPSHOT_HISTORY: u64 = 500;
#[derive(Debug, PartialEq)]
pub struct RunCmd {
pub cache_config: CacheConfig,
pub dirs: Directories,
pub spec: SpecType,
pub pruning: Pruning,
pub pruning_history: u64,
/// Some if execution should be daemonized. Contains pid_file path.
pub daemon: Option<String>,
pub logger_config: LogConfig,
pub miner_options: MinerOptions,
pub http_conf: HttpConfiguration,
pub ipc_conf: IpcConfiguration,
pub net_conf: NetworkConfiguration,
pub network_id: Option<U256>,
pub warp_sync: bool,
pub acc_conf: AccountsConfig,
pub gas_pricer: GasPricerConfig,
pub miner_extras: MinerExtras,
pub mode: Mode,
pub tracing: Switch,
pub fat_db: Switch,
pub compaction: DatabaseCompactionProfile,
pub wal: bool,
pub vm_type: VMType,
pub enable_network: bool,
pub geth_compatibility: bool,
pub signer_port: Option<u16>,
pub net_settings: NetworkSettings,
pub dapps_conf: dapps::Configuration,
pub signer_conf: signer::Configuration,
pub ui: bool,
pub name: String,
pub custom_bootnodes: bool,
pub no_periodic_snapshot: bool,
pub check_seal: bool,
}
pub fn execute(cmd: RunCmd) -> Result<(), String> {
// set up panic handler
let panic_handler = PanicHandler::new_in_arc();
// set up logger
let logger = try!(setup_log(&cmd.logger_config));
// increase max number of open files
raise_fd_limit();
// create dirs used by parity
try!(cmd.dirs.create_dirs());
// load spec
let spec = try!(cmd.spec.spec());
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
// database paths
let db_dirs = cmd.dirs.database(genesis_hash, spec.fork_name.clone());
// user defaults path
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let mut user_defaults = try!(UserDefaults::load(&user_defaults_path));
// select pruning algorithm
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(cmd.tracing, &user_defaults));
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm));
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.fork_path().as_path())));
// run in daemon mode
if let Some(pid_file) = cmd.daemon {
try!(daemonize(pid_file));
}
// display info about used pruning algorithm
info!("Starting {}", Colour::White.bold().paint(version()));
info!("State DB configuation: {}{}{}",
Colour::White.bold().paint(algorithm.as_str()),
match fat_db {
true => Colour::White.bold().paint(" +Fat").to_string(),
false => "".to_owned(),
},
match tracing {
true => Colour::White.bold().paint(" +Trace").to_string(),
false => "".to_owned(),
}
);
// display warning about using experimental journaldb alorithm
if!algorithm.is_stable() {
warn!("Your chosen strategy is {}! You can re-run with --pruning to change.", Colour::Red.bold().paint("unstable"));
}
// create sync config
let mut sync_config = SyncConfig::default();
sync_config.network_id = match cmd.network_id {
Some(id) => id,
None => spec.network_id(),
};
if spec.subprotocol_name().len()!= 3 | else {
sync_config.subprotocol_name.clone_from_slice(spec.subprotocol_name().as_bytes());
}
sync_config.fork_block = spec.fork_block();
sync_config.warp_sync = cmd.warp_sync;
// prepare account provider
let account_provider = Arc::new(try!(prepare_account_provider(&cmd.dirs, cmd.acc_conf)));
// create miner
let miner = Miner::new(cmd.miner_options, cmd.gas_pricer.into(), &spec, Some(account_provider.clone()));
miner.set_author(cmd.miner_extras.author);
miner.set_gas_floor_target(cmd.miner_extras.gas_floor_target);
miner.set_gas_ceil_target(cmd.miner_extras.gas_ceil_target);
miner.set_extra_data(cmd.miner_extras.extra_data);
miner.set_transactions_limit(cmd.miner_extras.transactions_limit);
// create client config
let client_config = to_client_config(
&cmd.cache_config,
cmd.mode,
tracing,
fat_db,
cmd.compaction,
cmd.wal,
cmd.vm_type,
cmd.name,
algorithm,
cmd.pruning_history,
cmd.check_seal,
);
// set up bootnodes
let mut net_conf = cmd.net_conf;
if!cmd.custom_bootnodes {
net_conf.boot_nodes = spec.nodes.clone();
}
// set network path.
net_conf.net_config_path = Some(db_dirs.network_path().to_string_lossy().into_owned());
// create supervisor
let mut hypervisor = modules::hypervisor(&cmd.dirs.ipc_path());
// create client service.
let service = try!(ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&cmd.dirs.ipc_path(),
miner.clone(),
).map_err(|e| format!("Client service error: {:?}", e)));
// forward panics from service
panic_handler.forward_from(&service);
// take handle to client
let client = service.client();
let snapshot_service = service.snapshot_service();
// create external miner
let external_miner = Arc::new(ExternalMiner::default());
// create sync object
let (sync_provider, manage_network, chain_notify) = try!(modules::sync(
&mut hypervisor, sync_config, net_conf.into(), client.clone(), snapshot_service.clone(), &cmd.logger_config,
).map_err(|e| format!("Sync error: {}", e)));
service.add_notify(chain_notify.clone());
// start network
if cmd.enable_network {
chain_notify.start();
}
// set up dependencies for rpc servers
let signer_path = cmd.signer_conf.signer_path.clone();
let deps_for_rpc_apis = Arc::new(rpc_apis::Dependencies {
signer_service: Arc::new(rpc_apis::SignerService::new(move || {
signer::generate_new_token(signer_path.clone()).map_err(|e| format!("{:?}", e))
}, cmd.signer_port)),
client: client.clone(),
sync: sync_provider.clone(),
net: manage_network.clone(),
secret_store: account_provider.clone(),
miner: miner.clone(),
external_miner: external_miner.clone(),
logger: logger.clone(),
settings: Arc::new(cmd.net_settings.clone()),
net_service: manage_network.clone(),
geth_compatibility: cmd.geth_compatibility,
dapps_port: match cmd.dapps_conf.enabled {
true => Some(cmd.dapps_conf.port),
false => None,
},
});
let dependencies = rpc::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start rpc servers
let http_server = try!(rpc::new_http(cmd.http_conf, &dependencies));
let ipc_server = try!(rpc::new_ipc(cmd.ipc_conf, &dependencies));
let dapps_deps = dapps::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
client: client.clone(),
sync: sync_provider.clone(),
};
// start dapps server
let dapps_server = try!(dapps::new(cmd.dapps_conf.clone(), dapps_deps));
let signer_deps = signer::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start signer server
let signer_server = try!(signer::start(cmd.signer_conf, signer_deps));
let informant = Arc::new(Informant::new(
service.client(),
Some(sync_provider.clone()),
Some(manage_network.clone()),
Some(snapshot_service.clone()),
cmd.logger_config.color
));
let info_notify: Arc<ChainNotify> = informant.clone();
service.add_notify(info_notify);
let io_handler = Arc::new(ClientIoHandler {
client: service.client(),
info: informant,
sync: sync_provider.clone(),
net: manage_network.clone(),
accounts: account_provider.clone(),
shutdown: Default::default(),
});
service.register_io_handler(io_handler.clone()).expect("Error registering IO handler");
// the watcher must be kept alive.
let _watcher = match cmd.no_periodic_snapshot {
true => None,
false => {
let sync = sync_provider.clone();
let watcher = Arc::new(snapshot::Watcher::new(
service.client(),
move || is_major_importing(Some(sync.status().state), client.queue_info()),
service.io().channel(),
SNAPSHOT_PERIOD,
SNAPSHOT_HISTORY,
));
service.add_notify(watcher.clone());
Some(watcher)
},
};
// start ui
if cmd.ui {
if!cmd.dapps_conf.enabled {
return Err("Cannot use UI command with Dapps turned off.".into())
}
url::open(&format!("http://{}:{}/", cmd.dapps_conf.interface, cmd.dapps_conf.port));
}
// save user defaults
user_defaults.pruning = algorithm;
user_defaults.tracing = tracing;
try!(user_defaults.save(&user_defaults_path));
// Handle exit
wait_for_exit(panic_handler, http_server, ipc_server, dapps_server, signer_server);
// to make sure timer does not spawn requests while shutdown is in progress
io_handler.shutdown.store(true, ::std::sync::atomic::Ordering::SeqCst);
// just Arc is dropping here, to allow other reference release in its default time
drop(io_handler);
// hypervisor should be shutdown first while everything still works and can be
// terminated gracefully
drop(hypervisor);
Ok(())
}
#[cfg(not(windows))]
fn daemonize(pid_file: String) -> Result<(), String> {
extern crate daemonize;
daemonize::Daemonize::new()
.pid_file(pid_file)
.chown_pid_file(true)
.start()
.map(|_| ())
.map_err(|e| format!("Couldn't daemonize; {}", e))
}
#[cfg(windows)]
fn daemonize(_pid_file: String) -> Result<(), String> {
Err("daemon is no supported on windows".into())
}
fn prepare_account_provider(dirs: &Directories, cfg: AccountsConfig) -> Result<AccountProvider, String> {
use ethcore::ethstore::EthStore;
use ethcore::ethstore::dir::DiskDirectory;
let passwords = try!(passwords_from_files(cfg.password_files));
let dir = Box::new(try!(DiskDirectory::create(dirs.keys.clone()).map_err(|e| format!("Could not open keys directory: {}", e))));
let account_service = AccountProvider::new(Box::new(
try!(EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e)))
));
for a in cfg.unlocked_accounts {
if passwords.iter().find(|p| account_service.unlock_account_permanently(a, (*p).clone()).is_ok()).is_none() {
return Err(format!("No password found to unlock account {}. Make sure valid password is present in files passed using `--password`.", a));
}
}
Ok(account_service)
}
fn wait_for_exit(
panic_handler: Arc<PanicHandler>,
_http_server: Option<HttpServer>,
_ipc_server: Option<IpcServer>,
_dapps_server: Option<WebappServer>,
_signer_server: Option<SignerServer>
) {
let exit = Arc::new(Condvar::new());
// Handle possible exits
let e = exit.clone();
CtrlC::set_handler(move || { e.notify_all(); });
// Handle panics
let e = exit.clone();
panic_handler.on_panic(move |_reason| { e.notify_all(); });
// Wait for signal
let mutex = Mutex::new(());
let _ = exit.wait(mutex.lock().unwrap());
info!("Finishing work, please wait...");
}
| {
warn!("Your chain specification's subprotocol length is not 3. Ignoring.");
} | conditional_block |
run.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::{Arc, Mutex, Condvar};
use ctrlc::CtrlC;
use fdlimit::raise_fd_limit;
use ethcore_logger::{Config as LogConfig, setup_log};
use ethcore_rpc::{NetworkSettings, is_major_importing};
use ethsync::NetworkConfiguration;
use util::{Colour, version, U256};
use io::{MayPanic, ForwardPanic, PanicHandler};
use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, ChainNotify, BlockChainClient};
use ethcore::service::ClientService;
use ethcore::account_provider::AccountProvider;
use ethcore::miner::{Miner, MinerService, ExternalMiner, MinerOptions};
use ethcore::snapshot;
use ethsync::SyncConfig;
use informant::Informant;
use rpc::{HttpServer, IpcServer, HttpConfiguration, IpcConfiguration};
use signer::SignerServer;
use dapps::WebappServer;
use io_handler::ClientIoHandler;
use params::{
SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch,
tracing_switch_to_bool, fatdb_switch_to_bool,
};
use helpers::{to_client_config, execute_upgrades, passwords_from_files};
use dir::Directories;
use cache::CacheConfig;
use user_defaults::UserDefaults;
use dapps;
use signer;
use modules;
use rpc_apis;
use rpc;
use url;
// how often to take periodic snapshots.
const SNAPSHOT_PERIOD: u64 = 10000;
// how many blocks to wait before starting a periodic snapshot.
const SNAPSHOT_HISTORY: u64 = 500;
#[derive(Debug, PartialEq)]
pub struct RunCmd {
pub cache_config: CacheConfig,
pub dirs: Directories,
pub spec: SpecType,
pub pruning: Pruning,
pub pruning_history: u64,
/// Some if execution should be daemonized. Contains pid_file path.
pub daemon: Option<String>,
pub logger_config: LogConfig,
pub miner_options: MinerOptions,
pub http_conf: HttpConfiguration,
pub ipc_conf: IpcConfiguration,
pub net_conf: NetworkConfiguration,
pub network_id: Option<U256>,
pub warp_sync: bool,
pub acc_conf: AccountsConfig,
pub gas_pricer: GasPricerConfig,
pub miner_extras: MinerExtras,
pub mode: Mode,
pub tracing: Switch,
pub fat_db: Switch,
pub compaction: DatabaseCompactionProfile,
pub wal: bool,
pub vm_type: VMType,
pub enable_network: bool,
pub geth_compatibility: bool,
pub signer_port: Option<u16>,
pub net_settings: NetworkSettings,
pub dapps_conf: dapps::Configuration,
pub signer_conf: signer::Configuration,
pub ui: bool,
pub name: String,
pub custom_bootnodes: bool,
pub no_periodic_snapshot: bool,
pub check_seal: bool,
}
pub fn execute(cmd: RunCmd) -> Result<(), String> {
// set up panic handler
let panic_handler = PanicHandler::new_in_arc();
// set up logger
let logger = try!(setup_log(&cmd.logger_config));
// increase max number of open files
raise_fd_limit();
// create dirs used by parity
try!(cmd.dirs.create_dirs());
// load spec
let spec = try!(cmd.spec.spec());
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
// database paths
let db_dirs = cmd.dirs.database(genesis_hash, spec.fork_name.clone());
// user defaults path
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let mut user_defaults = try!(UserDefaults::load(&user_defaults_path));
// select pruning algorithm
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(cmd.tracing, &user_defaults));
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm));
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.fork_path().as_path())));
// run in daemon mode
if let Some(pid_file) = cmd.daemon {
try!(daemonize(pid_file));
}
// display info about used pruning algorithm
info!("Starting {}", Colour::White.bold().paint(version()));
info!("State DB configuation: {}{}{}",
Colour::White.bold().paint(algorithm.as_str()),
match fat_db {
true => Colour::White.bold().paint(" +Fat").to_string(),
false => "".to_owned(),
},
match tracing {
true => Colour::White.bold().paint(" +Trace").to_string(),
false => "".to_owned(),
}
);
// display warning about using experimental journaldb alorithm
if!algorithm.is_stable() {
warn!("Your chosen strategy is {}! You can re-run with --pruning to change.", Colour::Red.bold().paint("unstable"));
}
// create sync config
let mut sync_config = SyncConfig::default();
sync_config.network_id = match cmd.network_id {
Some(id) => id,
None => spec.network_id(),
};
if spec.subprotocol_name().len()!= 3 {
warn!("Your chain specification's subprotocol length is not 3. Ignoring.");
} else {
sync_config.subprotocol_name.clone_from_slice(spec.subprotocol_name().as_bytes());
}
sync_config.fork_block = spec.fork_block();
sync_config.warp_sync = cmd.warp_sync;
// prepare account provider
let account_provider = Arc::new(try!(prepare_account_provider(&cmd.dirs, cmd.acc_conf)));
// create miner
let miner = Miner::new(cmd.miner_options, cmd.gas_pricer.into(), &spec, Some(account_provider.clone()));
miner.set_author(cmd.miner_extras.author);
miner.set_gas_floor_target(cmd.miner_extras.gas_floor_target);
miner.set_gas_ceil_target(cmd.miner_extras.gas_ceil_target);
miner.set_extra_data(cmd.miner_extras.extra_data);
miner.set_transactions_limit(cmd.miner_extras.transactions_limit);
// create client config
let client_config = to_client_config(
&cmd.cache_config,
cmd.mode,
tracing,
fat_db,
cmd.compaction,
cmd.wal,
cmd.vm_type,
cmd.name,
algorithm,
cmd.pruning_history,
cmd.check_seal,
);
// set up bootnodes
let mut net_conf = cmd.net_conf;
if!cmd.custom_bootnodes {
net_conf.boot_nodes = spec.nodes.clone();
}
// set network path.
net_conf.net_config_path = Some(db_dirs.network_path().to_string_lossy().into_owned());
// create supervisor
let mut hypervisor = modules::hypervisor(&cmd.dirs.ipc_path());
// create client service.
let service = try!(ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&cmd.dirs.ipc_path(),
miner.clone(),
).map_err(|e| format!("Client service error: {:?}", e)));
// forward panics from service
panic_handler.forward_from(&service);
// take handle to client
let client = service.client();
let snapshot_service = service.snapshot_service();
// create external miner
let external_miner = Arc::new(ExternalMiner::default());
// create sync object
let (sync_provider, manage_network, chain_notify) = try!(modules::sync(
&mut hypervisor, sync_config, net_conf.into(), client.clone(), snapshot_service.clone(), &cmd.logger_config,
).map_err(|e| format!("Sync error: {}", e)));
service.add_notify(chain_notify.clone());
// start network
if cmd.enable_network {
chain_notify.start();
}
// set up dependencies for rpc servers
let signer_path = cmd.signer_conf.signer_path.clone();
let deps_for_rpc_apis = Arc::new(rpc_apis::Dependencies {
signer_service: Arc::new(rpc_apis::SignerService::new(move || {
signer::generate_new_token(signer_path.clone()).map_err(|e| format!("{:?}", e))
}, cmd.signer_port)),
client: client.clone(),
sync: sync_provider.clone(),
net: manage_network.clone(),
secret_store: account_provider.clone(),
miner: miner.clone(),
external_miner: external_miner.clone(),
logger: logger.clone(),
settings: Arc::new(cmd.net_settings.clone()),
net_service: manage_network.clone(),
geth_compatibility: cmd.geth_compatibility,
dapps_port: match cmd.dapps_conf.enabled {
true => Some(cmd.dapps_conf.port),
false => None,
},
});
let dependencies = rpc::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start rpc servers
let http_server = try!(rpc::new_http(cmd.http_conf, &dependencies));
let ipc_server = try!(rpc::new_ipc(cmd.ipc_conf, &dependencies));
let dapps_deps = dapps::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
client: client.clone(),
sync: sync_provider.clone(),
};
// start dapps server
let dapps_server = try!(dapps::new(cmd.dapps_conf.clone(), dapps_deps));
let signer_deps = signer::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
// start signer server
let signer_server = try!(signer::start(cmd.signer_conf, signer_deps));
let informant = Arc::new(Informant::new(
service.client(),
Some(sync_provider.clone()),
Some(manage_network.clone()),
Some(snapshot_service.clone()),
cmd.logger_config.color
));
let info_notify: Arc<ChainNotify> = informant.clone();
service.add_notify(info_notify);
let io_handler = Arc::new(ClientIoHandler {
client: service.client(),
info: informant,
sync: sync_provider.clone(),
net: manage_network.clone(),
accounts: account_provider.clone(),
shutdown: Default::default(),
});
service.register_io_handler(io_handler.clone()).expect("Error registering IO handler");
// the watcher must be kept alive.
let _watcher = match cmd.no_periodic_snapshot {
true => None,
false => {
let sync = sync_provider.clone();
let watcher = Arc::new(snapshot::Watcher::new(
service.client(),
move || is_major_importing(Some(sync.status().state), client.queue_info()),
service.io().channel(),
SNAPSHOT_PERIOD,
SNAPSHOT_HISTORY,
));
service.add_notify(watcher.clone());
Some(watcher)
},
};
// start ui
if cmd.ui {
if!cmd.dapps_conf.enabled {
return Err("Cannot use UI command with Dapps turned off.".into())
}
url::open(&format!("http://{}:{}/", cmd.dapps_conf.interface, cmd.dapps_conf.port));
}
// save user defaults
user_defaults.pruning = algorithm;
user_defaults.tracing = tracing;
try!(user_defaults.save(&user_defaults_path));
// Handle exit
wait_for_exit(panic_handler, http_server, ipc_server, dapps_server, signer_server);
// to make sure timer does not spawn requests while shutdown is in progress
io_handler.shutdown.store(true, ::std::sync::atomic::Ordering::SeqCst);
// just Arc is dropping here, to allow other reference release in its default time
drop(io_handler);
// hypervisor should be shutdown first while everything still works and can be
// terminated gracefully
drop(hypervisor);
Ok(())
}
#[cfg(not(windows))]
fn daemonize(pid_file: String) -> Result<(), String> {
extern crate daemonize;
daemonize::Daemonize::new()
.pid_file(pid_file)
.chown_pid_file(true)
.start()
.map(|_| ())
.map_err(|e| format!("Couldn't daemonize; {}", e))
}
#[cfg(windows)]
fn daemonize(_pid_file: String) -> Result<(), String> |
fn prepare_account_provider(dirs: &Directories, cfg: AccountsConfig) -> Result<AccountProvider, String> {
use ethcore::ethstore::EthStore;
use ethcore::ethstore::dir::DiskDirectory;
let passwords = try!(passwords_from_files(cfg.password_files));
let dir = Box::new(try!(DiskDirectory::create(dirs.keys.clone()).map_err(|e| format!("Could not open keys directory: {}", e))));
let account_service = AccountProvider::new(Box::new(
try!(EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e)))
));
for a in cfg.unlocked_accounts {
if passwords.iter().find(|p| account_service.unlock_account_permanently(a, (*p).clone()).is_ok()).is_none() {
return Err(format!("No password found to unlock account {}. Make sure valid password is present in files passed using `--password`.", a));
}
}
Ok(account_service)
}
fn wait_for_exit(
panic_handler: Arc<PanicHandler>,
_http_server: Option<HttpServer>,
_ipc_server: Option<IpcServer>,
_dapps_server: Option<WebappServer>,
_signer_server: Option<SignerServer>
) {
let exit = Arc::new(Condvar::new());
// Handle possible exits
let e = exit.clone();
CtrlC::set_handler(move || { e.notify_all(); });
// Handle panics
let e = exit.clone();
panic_handler.on_panic(move |_reason| { e.notify_all(); });
// Wait for signal
let mutex = Mutex::new(());
let _ = exit.wait(mutex.lock().unwrap());
info!("Finishing work, please wait...");
}
| {
Err("daemon is no supported on windows".into())
} | identifier_body |
util.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(unknown_lints)]
// client and server share different parts of utils.
#![allow(dead_code)]
#![allow(cast_lossless)]
use std::f64::consts::PI;
use serde_json;
use grpcio_proto::example::route_guide::*;
#[derive(Serialize, Deserialize, Debug)]
struct PointRef {
latitude: i32,
longitude: i32,
}
#[derive(Serialize, Deserialize, Debug)]
struct | {
location: PointRef,
name: String,
}
impl From<FeatureRef> for Feature {
fn from(r: FeatureRef) -> Feature {
let mut f = Feature::default();
f.set_name(r.name);
f.mut_location().set_latitude(r.location.latitude);
f.mut_location().set_longitude(r.location.longitude);
f
}
}
pub fn load_db() -> Vec<Feature> {
let data = include_str!("db.json");
let features: Vec<FeatureRef> = serde_json::from_str(data).unwrap();
features.into_iter().map(From::from).collect()
}
pub fn same_point(lhs: &Point, rhs: &Point) -> bool {
lhs.get_longitude() == rhs.get_longitude() && lhs.get_latitude() == rhs.get_latitude()
}
pub fn fit_in(lhs: &Point, rhs: &Rectangle) -> bool {
let hi = rhs.get_hi();
let lo = rhs.get_lo();
lhs.get_longitude() <= hi.get_longitude()
&& lhs.get_longitude() >= lo.get_longitude()
&& lhs.get_latitude() <= hi.get_latitude()
&& lhs.get_latitude() >= lo.get_latitude()
}
const COORD_FACTOR: f64 = 10000000.0;
pub fn convert_to_rad(num: f64) -> f64 {
num * PI / 180.0
}
pub fn format_point(p: &Point) -> String {
format!(
"{}, {}",
p.get_latitude() as f64 / COORD_FACTOR,
p.get_longitude() as f64 / COORD_FACTOR
)
}
pub fn cal_distance(lhs: &Point, rhs: &Point) -> f64 {
let lat1 = lhs.get_latitude() as f64 / COORD_FACTOR;
let lon1 = lhs.get_longitude() as f64 / COORD_FACTOR;
let lat2 = rhs.get_latitude() as f64 / COORD_FACTOR;
let lon2 = rhs.get_longitude() as f64 / COORD_FACTOR;
let lat_rad_1 = convert_to_rad(lat1);
let lat_rad_2 = convert_to_rad(lat2);
let delta_lat_rad = convert_to_rad(lat2 - lat1);
let delta_lon_rad = convert_to_rad(lon2 - lon1);
let a = (delta_lat_rad / 2.0).sin().powi(2)
+ lat_rad_1.cos() * lat_rad_2.cos() * (delta_lon_rad / 2.0).sin().powi(2);
let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
let r = 6371000.0; // metres
r * c
}
| FeatureRef | identifier_name |
util.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(unknown_lints)]
// client and server share different parts of utils.
#![allow(dead_code)]
#![allow(cast_lossless)]
use std::f64::consts::PI;
use serde_json;
use grpcio_proto::example::route_guide::*;
#[derive(Serialize, Deserialize, Debug)]
struct PointRef {
latitude: i32,
longitude: i32,
}
#[derive(Serialize, Deserialize, Debug)]
struct FeatureRef {
location: PointRef,
name: String,
}
impl From<FeatureRef> for Feature {
fn from(r: FeatureRef) -> Feature {
let mut f = Feature::default();
f.set_name(r.name);
f.mut_location().set_latitude(r.location.latitude); | f.mut_location().set_longitude(r.location.longitude);
f
}
}
pub fn load_db() -> Vec<Feature> {
let data = include_str!("db.json");
let features: Vec<FeatureRef> = serde_json::from_str(data).unwrap();
features.into_iter().map(From::from).collect()
}
pub fn same_point(lhs: &Point, rhs: &Point) -> bool {
lhs.get_longitude() == rhs.get_longitude() && lhs.get_latitude() == rhs.get_latitude()
}
pub fn fit_in(lhs: &Point, rhs: &Rectangle) -> bool {
let hi = rhs.get_hi();
let lo = rhs.get_lo();
lhs.get_longitude() <= hi.get_longitude()
&& lhs.get_longitude() >= lo.get_longitude()
&& lhs.get_latitude() <= hi.get_latitude()
&& lhs.get_latitude() >= lo.get_latitude()
}
const COORD_FACTOR: f64 = 10000000.0;
pub fn convert_to_rad(num: f64) -> f64 {
num * PI / 180.0
}
pub fn format_point(p: &Point) -> String {
format!(
"{}, {}",
p.get_latitude() as f64 / COORD_FACTOR,
p.get_longitude() as f64 / COORD_FACTOR
)
}
pub fn cal_distance(lhs: &Point, rhs: &Point) -> f64 {
let lat1 = lhs.get_latitude() as f64 / COORD_FACTOR;
let lon1 = lhs.get_longitude() as f64 / COORD_FACTOR;
let lat2 = rhs.get_latitude() as f64 / COORD_FACTOR;
let lon2 = rhs.get_longitude() as f64 / COORD_FACTOR;
let lat_rad_1 = convert_to_rad(lat1);
let lat_rad_2 = convert_to_rad(lat2);
let delta_lat_rad = convert_to_rad(lat2 - lat1);
let delta_lon_rad = convert_to_rad(lon2 - lon1);
let a = (delta_lat_rad / 2.0).sin().powi(2)
+ lat_rad_1.cos() * lat_rad_2.cos() * (delta_lon_rad / 2.0).sin().powi(2);
let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
let r = 6371000.0; // metres
r * c
} | random_line_split |
|
init.rs | use std::sync::{atomic, mpsc};
use std::{io, process, thread};
use ctrlc;
use crate::control::acio;
use crate::{args, control, disk, log, rpc, throttle, tracker};
use crate::{CONFIG, SHUTDOWN, THROT_TOKS};
pub fn init(args: args::Args) -> Result<(), ()> {
if let Some(level) = args.level {
log::log_init(level);
} else if cfg!(debug_assertions) {
log::log_init(log::LogLevel::Debug);
} else {
log::log_init(log::LogLevel::Info);
}
info!("Initializing");
// Since the config is lazy loaded, dereference now to check it.
CONFIG.port;
if let Err(e) = init_signals() {
error!("Failed to initialize signal handlers: {}", e);
return Err(());
}
Ok(())
}
pub fn run() -> Result<(), ()> {
match init_threads() {
Ok(threads) => {
for thread in threads {
if thread.join().is_err() {
error!("Unclean shutdown detected, terminating");
return Err(());
}
}
info!("Shutdown complete");
Ok(())
}
Err(e) => {
error!("Couldn't initialize synapse: {}", e);
Err(())
}
}
}
fn init_threads() -> io::Result<Vec<thread::JoinHandle<()>>> {
let cpoll = amy::Poller::new()?;
let mut creg = cpoll.get_registrar();
let (dh, disk_broadcast, dhj) = disk::start(&mut creg)?;
let (rh, rhj) = rpc::RPC::start(&mut creg, disk_broadcast.clone())?;
let (th, thj) = tracker::Tracker::start(&mut creg, disk_broadcast.clone())?;
let chans = acio::ACChans {
disk_tx: dh.tx,
disk_rx: dh.rx,
rpc_tx: rh.tx,
rpc_rx: rh.rx,
trk_tx: th.tx,
trk_rx: th.rx,
};
let (tx, rx) = mpsc::channel();
let cdb = disk_broadcast.clone();
let chj = thread::Builder::new()
.name("control".to_string())
.spawn(move || {
let throttler = throttle::Throttler::new(None, None, THROT_TOKS, &creg).unwrap();
let acio = acio::ACIO::new(cpoll, creg, chans).expect("Could not initialize IO");
match control::Control::new(acio, throttler, cdb) {
Ok(mut c) => {
tx.send(Ok(())).unwrap();
c.run();
}
Err(e) => {
tx.send(Err(e)).unwrap();
}
}
})
.unwrap();
rx.recv().unwrap()?;
Ok(vec![chj, dhj, rhj, thj])
}
fn init_signals() -> Result<(), ctrlc::Error> | {
ctrlc::set_handler(move || {
if SHUTDOWN.load(atomic::Ordering::SeqCst) {
info!("Terminating process!");
process::abort();
} else {
info!("Shutting down cleanly. Interrupt again to shut down immediately.");
SHUTDOWN.store(true, atomic::Ordering::SeqCst);
}
})
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.