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
build.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::fs; use std::io; use std::path::Path; fn check_signed_source() -> io::Result<()> { // Check if lib.rs is in sync with the Thrift compiler. let manifest_dir_path = std::env::var("CARGO_MANIFEST_DIR").unwrap(); let crate_path = Path::new(&manifest_dir_path); let fbcode_path = crate_path.ancestors().nth(4).unwrap(); let thrift_file_path = fbcode_path.join("configerator/structs/scm/hg/hgclientconf/hgclient.thrift"); if!thrift_file_path.exists()
println!( "cargo:rerun-if-changed={}", &thrift_file_path.to_string_lossy() ); let thrift_file_content = fs::read_to_string(&thrift_file_path)?; let hash = "4bc06e1c39884f65a4e9cd145972df39"; if!thrift_file_content.contains(hash) { let msg = format!( "thrift_types.rs and HASH need update: {} hash mismatch (expect: {})", &thrift_file_path.display(), hash, ); return Err(io::Error::new(io::ErrorKind::Other, msg)); } Ok(()) } fn main() -> io::Result<()> { check_signed_source() }
{ // Do not make it a fatal error on non-fbcode environment (ex. OSS). println!( "cargo:warning=Does not verify Thrift file at {}.", &thrift_file_path.display() ); return Ok(()); }
conditional_block
build.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::fs; use std::io; use std::path::Path; fn check_signed_source() -> io::Result<()> { // Check if lib.rs is in sync with the Thrift compiler. let manifest_dir_path = std::env::var("CARGO_MANIFEST_DIR").unwrap(); let crate_path = Path::new(&manifest_dir_path); let fbcode_path = crate_path.ancestors().nth(4).unwrap(); let thrift_file_path = fbcode_path.join("configerator/structs/scm/hg/hgclientconf/hgclient.thrift"); if!thrift_file_path.exists() { // Do not make it a fatal error on non-fbcode environment (ex. OSS). println!( "cargo:warning=Does not verify Thrift file at {}.", &thrift_file_path.display() ); return Ok(()); } println!( "cargo:rerun-if-changed={}", &thrift_file_path.to_string_lossy() ); let thrift_file_content = fs::read_to_string(&thrift_file_path)?; let hash = "4bc06e1c39884f65a4e9cd145972df39"; if!thrift_file_content.contains(hash) { let msg = format!( "thrift_types.rs and HASH need update: {} hash mismatch (expect: {})", &thrift_file_path.display(), hash, ); return Err(io::Error::new(io::ErrorKind::Other, msg)); } Ok(()) } fn main() -> io::Result<()>
{ check_signed_source() }
identifier_body
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate hyper; use ipc_channel::ipc; use net_traits::LoadConsumer::Channel; use net_traits::LoadData; use net_traits::ProgressMsg::{Payload, Done}; use self::hyper::header::ContentType; use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use std::sync::mpsc::channel; use url::Url; use net::data_loader::load; let (start_chan, start_port) = ipc::channel().unwrap(); load(LoadData::new(Url::parse(url).unwrap(), None), Channel(start_chan)); let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type, &content_type); assert_eq!(&response.metadata.charset, &charset); let progress = response.progress_port.recv().unwrap(); match data { None => { assert_eq!(progress, Done(Err("invalid data uri".to_string()))); } Some(dat) => { assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); } } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse("data:,hello%20world", None, None, Some(b"hello world".iter().map(|&x| x).collect())); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_charset() { assert_parse("data:text/plain;charset=latin1,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("latin1".to_string())))))), Some("latin1".to_string()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn base64() { assert_parse("data:;base64,C62+7w==", None, None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_ct() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_string()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset()
{ assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_string())))))), Some("koi8-r".to_string()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); }
identifier_body
data_loader.rs
use ipc_channel::ipc; use net_traits::LoadConsumer::Channel; use net_traits::LoadData; use net_traits::ProgressMsg::{Payload, Done}; use self::hyper::header::ContentType; use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use std::sync::mpsc::channel; use url::Url; use net::data_loader::load; let (start_chan, start_port) = ipc::channel().unwrap(); load(LoadData::new(Url::parse(url).unwrap(), None), Channel(start_chan)); let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type, &content_type); assert_eq!(&response.metadata.charset, &charset); let progress = response.progress_port.recv().unwrap(); match data { None => { assert_eq!(progress, Done(Err("invalid data uri".to_string()))); } Some(dat) => { assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); } } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse("data:,hello%20world", None, None, Some(b"hello world".iter().map(|&x| x).collect())); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_charset() { assert_parse("data:text/plain;charset=latin1,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("latin1".to_string())))))), Some("latin1".to_string()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn base64() { assert_parse("data:;base64,C62+7w==", None, None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_ct() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_string()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset() { assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_string())))))), Some("koi8-r".to_string()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); }
/* 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/. */ extern crate hyper;
random_line_split
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate hyper; use ipc_channel::ipc; use net_traits::LoadConsumer::Channel; use net_traits::LoadData; use net_traits::ProgressMsg::{Payload, Done}; use self::hyper::header::ContentType; use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use std::sync::mpsc::channel; use url::Url; use net::data_loader::load; let (start_chan, start_port) = ipc::channel().unwrap(); load(LoadData::new(Url::parse(url).unwrap(), None), Channel(start_chan)); let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type, &content_type); assert_eq!(&response.metadata.charset, &charset); let progress = response.progress_port.recv().unwrap(); match data { None => { assert_eq!(progress, Done(Err("invalid data uri".to_string()))); } Some(dat) => { assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); } } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse("data:,hello%20world", None, None, Some(b"hello world".iter().map(|&x| x).collect())); } #[test] fn
() { assert_parse( "data:text/plain,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn plain_charset() { assert_parse("data:text/plain;charset=latin1,hello", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("latin1".to_string())))))), Some("latin1".to_string()), Some(b"hello".iter().map(|&x| x).collect())); } #[test] fn base64() { assert_parse("data:;base64,C62+7w==", None, None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_ct() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_string()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset() { assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_string())))))), Some("koi8-r".to_string()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); }
plain_ct
identifier_name
type.rs
// rustfmt-normalize_comments: true fn types() { let x: [Vec<_>] = []; let y: *mut [SomeType; konst_funk()] = expr(); let z: (/* #digits */ usize, /* exp */ i16) = funk(); let z: (usize /* #digits */, i16 /* exp */) = funk(); } struct F { f: extern "C" fn(x: u8,... /* comment */), g: extern "C" fn(x: u8, /* comment */...), h: extern "C" fn(x: u8,...), i: extern "C" fn( x: u8, // comment 4 y: String, // comment 3 z: Foo, // comment ... // comment 2 ), } fn issue_1006(def_id_to_string: for<'a, 'b> unsafe fn(TyCtxt<'b, 'tcx, 'tcx>, DefId) -> String) {} fn impl_trait_fn_1() -> impl Fn(i32) -> Option<u8> {} fn impl_trait_fn_2<E>() -> impl Future<Item = &'a i64, Error = E> {} fn issue_1234() { do_parse!(name: take_while1!(is_token) >> (Header)) } // #2510 impl CombineTypes { pub fn pop_callback( &self, query_id: Uuid, ) -> Option<( ProjectId, Box<FnMut(&ProjectState, serde_json::Value, bool) -> () + Sync + Send>, )> { self.query_callbacks()(&query_id) } } // #2859 pub fn
<'a, T: Trait1 + Trait2 + 'a>( &fooo: u32, ) -> impl Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + 'a { } pub fn do_something<'a, T: Trait1 + Trait2 + 'a>( &fooo: u32, ) -> impl Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + 'a + 'b + 'c { } // #3051 token![impl]; token![impl]; // #3060 macro_rules! foo { ($foo_api: ty) => { type Target = ($foo_api) +'static; }; } type Target = (FooAPI) +'static; // #3137 fn foo<T>(t: T) where T: (FnOnce() -> ()) + Clone, U: (FnOnce() -> ()) +'static, { } // #3117 fn issue3117() { { { { { { { { { let opt: &mut Option<MyLongTypeHere> = unsafe { &mut *self.future.get() }; } } } } } } } } } // #3139 fn issue3139() { assert_eq!( to_json_value(&None::<i32>).unwrap(), json!({ "test": None::<i32> }) ); } // #3180 fn foo( a: SomeLongComplexType, b: SomeOtherLongComplexType, ) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>> { } type MyFn = fn( a: SomeLongComplexType, b: SomeOtherLongComplexType, ) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>>; // Const bound trait T: ~const Super {} const fn not_quite_const<S: ~const T>() -> i32 { <S as T>::CONST } struct S<T: ~const?Sized>(std::marker::PhantomData<T>); impl ~const T {} fn apit(_: impl ~const T) {} fn rpit() -> impl ~const T { S } pub struct Foo<T: Trait>(T); impl<T: ~const Trait> Foo<T> { fn new(t: T) -> Self { Self(t) } } // #4357 type T = typeof(1); impl T for.. {}
do_something
identifier_name
type.rs
// rustfmt-normalize_comments: true fn types() { let x: [Vec<_>] = []; let y: *mut [SomeType; konst_funk()] = expr(); let z: (/* #digits */ usize, /* exp */ i16) = funk(); let z: (usize /* #digits */, i16 /* exp */) = funk(); } struct F { f: extern "C" fn(x: u8,... /* comment */), g: extern "C" fn(x: u8, /* comment */...), h: extern "C" fn(x: u8,...), i: extern "C" fn( x: u8, // comment 4 y: String, // comment 3 z: Foo, // comment ... // comment 2 ), } fn issue_1006(def_id_to_string: for<'a, 'b> unsafe fn(TyCtxt<'b, 'tcx, 'tcx>, DefId) -> String) {} fn impl_trait_fn_1() -> impl Fn(i32) -> Option<u8> {} fn impl_trait_fn_2<E>() -> impl Future<Item = &'a i64, Error = E> {} fn issue_1234() { do_parse!(name: take_while1!(is_token) >> (Header)) } // #2510 impl CombineTypes { pub fn pop_callback( &self, query_id: Uuid, ) -> Option<( ProjectId, Box<FnMut(&ProjectState, serde_json::Value, bool) -> () + Sync + Send>, )> { self.query_callbacks()(&query_id) } } // #2859 pub fn do_something<'a, T: Trait1 + Trait2 + 'a>( &fooo: u32, ) -> impl Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + 'a { } pub fn do_something<'a, T: Trait1 + Trait2 + 'a>( &fooo: u32, ) -> impl Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + 'a + 'b + 'c { } // #3051 token![impl]; token![impl]; // #3060 macro_rules! foo { ($foo_api: ty) => { type Target = ($foo_api) +'static; }; } type Target = (FooAPI) +'static; // #3137 fn foo<T>(t: T) where T: (FnOnce() -> ()) + Clone, U: (FnOnce() -> ()) +'static, { } // #3117 fn issue3117() { { { { { { { { { let opt: &mut Option<MyLongTypeHere> = unsafe { &mut *self.future.get() }; } } } } } } } } } // #3139 fn issue3139() { assert_eq!( to_json_value(&None::<i32>).unwrap(), json!({ "test": None::<i32> }) ); } // #3180 fn foo( a: SomeLongComplexType, b: SomeOtherLongComplexType, ) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>> { } type MyFn = fn( a: SomeLongComplexType, b: SomeOtherLongComplexType, ) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>>; // Const bound trait T: ~const Super {} const fn not_quite_const<S: ~const T>() -> i32 { <S as T>::CONST } struct S<T: ~const?Sized>(std::marker::PhantomData<T>); impl ~const T {} fn apit(_: impl ~const T) {} fn rpit() -> impl ~const T { S } pub struct Foo<T: Trait>(T); impl<T: ~const Trait> Foo<T> { fn new(t: T) -> Self
} // #4357 type T = typeof(1); impl T for.. {}
{ Self(t) }
identifier_body
type.rs
// rustfmt-normalize_comments: true fn types() { let x: [Vec<_>] = []; let y: *mut [SomeType; konst_funk()] = expr(); let z: (/* #digits */ usize, /* exp */ i16) = funk(); let z: (usize /* #digits */, i16 /* exp */) = funk(); } struct F { f: extern "C" fn(x: u8,... /* comment */), g: extern "C" fn(x: u8, /* comment */...), h: extern "C" fn(x: u8,...), i: extern "C" fn( x: u8, // comment 4 y: String, // comment 3 z: Foo, // comment ... // comment 2 ), } fn issue_1006(def_id_to_string: for<'a, 'b> unsafe fn(TyCtxt<'b, 'tcx, 'tcx>, DefId) -> String) {} fn impl_trait_fn_1() -> impl Fn(i32) -> Option<u8> {} fn impl_trait_fn_2<E>() -> impl Future<Item = &'a i64, Error = E> {} fn issue_1234() { do_parse!(name: take_while1!(is_token) >> (Header)) } // #2510 impl CombineTypes { pub fn pop_callback( &self, query_id: Uuid, ) -> Option<( ProjectId, Box<FnMut(&ProjectState, serde_json::Value, bool) -> () + Sync + Send>, )> { self.query_callbacks()(&query_id) } } // #2859 pub fn do_something<'a, T: Trait1 + Trait2 + 'a>( &fooo: u32, ) -> impl Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + 'a { } pub fn do_something<'a, T: Trait1 + Trait2 + 'a>( &fooo: u32, ) -> impl Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + Future< Item = ( impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, impl Future<Item = (), Error = SomeError> + 'a, ), Error = SomeError, > + 'a + 'b + 'c { } // #3051 token![impl]; token![impl]; // #3060 macro_rules! foo { ($foo_api: ty) => { type Target = ($foo_api) +'static; }; } type Target = (FooAPI) +'static; // #3137 fn foo<T>(t: T)
{ } // #3117 fn issue3117() { { { { { { { { { let opt: &mut Option<MyLongTypeHere> = unsafe { &mut *self.future.get() }; } } } } } } } } } // #3139 fn issue3139() { assert_eq!( to_json_value(&None::<i32>).unwrap(), json!({ "test": None::<i32> }) ); } // #3180 fn foo( a: SomeLongComplexType, b: SomeOtherLongComplexType, ) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>> { } type MyFn = fn( a: SomeLongComplexType, b: SomeOtherLongComplexType, ) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>>; // Const bound trait T: ~const Super {} const fn not_quite_const<S: ~const T>() -> i32 { <S as T>::CONST } struct S<T: ~const?Sized>(std::marker::PhantomData<T>); impl ~const T {} fn apit(_: impl ~const T) {} fn rpit() -> impl ~const T { S } pub struct Foo<T: Trait>(T); impl<T: ~const Trait> Foo<T> { fn new(t: T) -> Self { Self(t) } } // #4357 type T = typeof(1); impl T for.. {}
where T: (FnOnce() -> ()) + Clone, U: (FnOnce() -> ()) + 'static,
random_line_split
ast.rs
//! JMESPath abstract syntax tree (AST). //! //! Inspecting the JMESPath AST can be useful for analyzing the way in //! which an expression was parsed and which features are utilized in //! an expression. //! //! Ast can be accessed directly from a parsed `jmespath::Expression` //! using the `as_ast()` method. An Ast can be created by using the //! `jmespath::parse()` function which returns an Ast rather than an //! `Expression`. //! //! ``` //! use jmespath; //! //! let ast = jmespath::parse("a || b && c").unwrap(); //! ``` use std::fmt; use Rcvar; use lexer::Token; /// A JMESPath expression abstract syntax tree. #[derive(Clone, PartialEq, Debug)] pub enum Ast { /// Compares two nodes using a comparator, returning true/false. Comparison { /// Approximate absolute position in the parsed expression. offset: usize, /// Comparator that compares the two results comparator: Comparator, /// Left hand side of the comparison lhs: Box<Ast>, /// Right hand side of the comparison rhs: Box<Ast>, }, /// If `predicate` evaluates to a truthy value, returns the /// result `then` Condition { /// Approximate absolute position in the parsed expression. offset: usize, /// The predicate to test. predicate: Box<Ast>, /// The node to traverse if the predicate is truthy. then: Box<Ast>, }, /// Returns the current node. Identity { /// Approximate absolute position in the parsed expression. offset: usize, }, /// Used by functions to dynamically evaluate argument values. Expref { /// Approximate absolute position in the parsed expression. offset: usize, /// Node to execute ast: Box<Ast>, }, /// Evaluates the node, then flattens it one level. Flatten { /// Approximate absolute position in the parsed expression. offset: usize, /// Node to execute and flatten node: Box<Ast>, }, /// Function name and a vec or function argument expressions. Function { /// Approximate absolute position in the parsed expression. offset: usize, /// Function name to invoke. name: String, /// Function arguments. args: Vec<Ast>, }, /// Extracts a key by name from a map. Field { /// Approximate absolute position in the parsed expression. offset: usize, /// Field name to extract. name: String, }, /// Extracts an index from a Vec. Index { /// Approximate absolute position in the parsed expression. offset: usize, /// Index to extract idx: i32, }, /// Resolves to a literal value. Literal { /// Approximate absolute position in the parsed expression. offset: usize, /// Literal value value: Rcvar, }, /// Evaluates to a list of evaluated expressions. MultiList { /// Approximate absolute position in the parsed expression. offset: usize, /// Elements of the list elements: Vec<Ast>, }, /// Evaluates to a map of key value pairs. MultiHash { /// Approximate absolute position in the parsed expression. offset: usize, /// Elements of the hash elements: Vec<KeyValuePair>, }, /// Evaluates to true/false based on if the expression is not truthy. Not { /// Approximate absolute position in the parsed expression. offset: usize, /// node to negate node: Box<Ast>, }, /// Evaluates LHS, and pushes each value through RHS. Projection { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the projection. lhs: Box<Ast>, /// Right hand side of the projection. rhs: Box<Ast>, }, /// Evaluates LHS. If it resolves to an object, returns a Vec of values. ObjectValues { /// Approximate absolute position in the parsed expression. offset: usize, /// Node to extract object values from. node: Box<Ast>, }, /// Evaluates LHS. If not truthy returns. Otherwise evaluates RHS. And { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the expression. lhs: Box<Ast>, /// Right hand side of the expression. rhs: Box<Ast>, }, /// Evaluates LHS. If truthy returns. Otherwise evaluates RHS. Or { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the expression. lhs: Box<Ast>, /// Right hand side of the expression. rhs: Box<Ast>, }, /// Returns a slice of a vec, using start, stop, and step. Slice { /// Approximate absolute position in the parsed expression. offset: usize, /// Starting index start: Option<i32>, /// Stopping index stop: Option<i32>, /// Step amount between extractions. step: i32, }, /// Evaluates RHS, then provides that value to the evaluation of RHS. Subexpr { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the expression. lhs: Box<Ast>, /// Right hand side of the expression. rhs: Box<Ast>, }, } impl fmt::Display for Ast { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "{:#?}", self) } } /// Represents a key value pair in a MultiHash. #[derive(Clone, PartialEq, Debug)] pub struct
{ /// Key name. pub key: String, /// Value expression used to determine the value. pub value: Ast, } /// Comparators used in Comparison nodes. #[derive(Clone, PartialEq, Debug)] pub enum Comparator { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, } /// Creates a Comparator from a Token. /// /// Note: panics if the Token is invalid. impl From<Token> for Comparator { fn from(token: Token) -> Self { match token { Token::Lt => Comparator::LessThan, Token::Lte => Comparator::LessThanEqual, Token::Gt => Comparator::GreaterThan, Token::Gte => Comparator::GreaterThanEqual, Token::Eq => Comparator::Equal, Token::Ne => Comparator::NotEqual, _ => panic!("Invalid token for comparator: {:?}", token), } } } #[cfg(test)] mod test { use super::*; #[test] fn displays_pretty_printed_ast_node() { let node = Ast::Field { name: "abc".to_string(), offset: 4, }; assert_eq!("Field {\n offset: 4,\n name: \"abc\",\n}", format!("{}", node)); } }
KeyValuePair
identifier_name
ast.rs
//! JMESPath abstract syntax tree (AST). //! //! Inspecting the JMESPath AST can be useful for analyzing the way in //! which an expression was parsed and which features are utilized in //! an expression. //! //! Ast can be accessed directly from a parsed `jmespath::Expression` //! using the `as_ast()` method. An Ast can be created by using the //! `jmespath::parse()` function which returns an Ast rather than an //! `Expression`. //! //! ``` //! use jmespath; //! //! let ast = jmespath::parse("a || b && c").unwrap(); //! ``` use std::fmt; use Rcvar; use lexer::Token; /// A JMESPath expression abstract syntax tree. #[derive(Clone, PartialEq, Debug)] pub enum Ast { /// Compares two nodes using a comparator, returning true/false. Comparison { /// Approximate absolute position in the parsed expression. offset: usize, /// Comparator that compares the two results comparator: Comparator, /// Left hand side of the comparison lhs: Box<Ast>, /// Right hand side of the comparison rhs: Box<Ast>, }, /// If `predicate` evaluates to a truthy value, returns the /// result `then` Condition { /// Approximate absolute position in the parsed expression. offset: usize, /// The predicate to test. predicate: Box<Ast>, /// The node to traverse if the predicate is truthy. then: Box<Ast>, }, /// Returns the current node. Identity { /// Approximate absolute position in the parsed expression. offset: usize, }, /// Used by functions to dynamically evaluate argument values. Expref { /// Approximate absolute position in the parsed expression. offset: usize, /// Node to execute ast: Box<Ast>, }, /// Evaluates the node, then flattens it one level. Flatten { /// Approximate absolute position in the parsed expression. offset: usize, /// Node to execute and flatten node: Box<Ast>, }, /// Function name and a vec or function argument expressions. Function { /// Approximate absolute position in the parsed expression. offset: usize, /// Function name to invoke. name: String, /// Function arguments. args: Vec<Ast>, }, /// Extracts a key by name from a map. Field { /// Approximate absolute position in the parsed expression. offset: usize, /// Field name to extract. name: String, }, /// Extracts an index from a Vec. Index { /// Approximate absolute position in the parsed expression. offset: usize, /// Index to extract idx: i32, }, /// Resolves to a literal value. Literal { /// Approximate absolute position in the parsed expression. offset: usize, /// Literal value value: Rcvar, }, /// Evaluates to a list of evaluated expressions. MultiList { /// Approximate absolute position in the parsed expression. offset: usize, /// Elements of the list elements: Vec<Ast>, }, /// Evaluates to a map of key value pairs. MultiHash { /// Approximate absolute position in the parsed expression. offset: usize, /// Elements of the hash elements: Vec<KeyValuePair>, }, /// Evaluates to true/false based on if the expression is not truthy. Not { /// Approximate absolute position in the parsed expression. offset: usize, /// node to negate node: Box<Ast>, }, /// Evaluates LHS, and pushes each value through RHS. Projection { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the projection. lhs: Box<Ast>, /// Right hand side of the projection. rhs: Box<Ast>, }, /// Evaluates LHS. If it resolves to an object, returns a Vec of values. ObjectValues { /// Approximate absolute position in the parsed expression. offset: usize, /// Node to extract object values from. node: Box<Ast>, }, /// Evaluates LHS. If not truthy returns. Otherwise evaluates RHS. And { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the expression. lhs: Box<Ast>, /// Right hand side of the expression. rhs: Box<Ast>, }, /// Evaluates LHS. If truthy returns. Otherwise evaluates RHS. Or { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the expression. lhs: Box<Ast>, /// Right hand side of the expression. rhs: Box<Ast>, }, /// Returns a slice of a vec, using start, stop, and step. Slice { /// Approximate absolute position in the parsed expression. offset: usize, /// Starting index start: Option<i32>, /// Stopping index stop: Option<i32>, /// Step amount between extractions. step: i32, }, /// Evaluates RHS, then provides that value to the evaluation of RHS. Subexpr { /// Approximate absolute position in the parsed expression. offset: usize, /// Left hand side of the expression. lhs: Box<Ast>, /// Right hand side of the expression. rhs: Box<Ast>, }, } impl fmt::Display for Ast { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "{:#?}", self) } }
/// Key name. pub key: String, /// Value expression used to determine the value. pub value: Ast, } /// Comparators used in Comparison nodes. #[derive(Clone, PartialEq, Debug)] pub enum Comparator { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, } /// Creates a Comparator from a Token. /// /// Note: panics if the Token is invalid. impl From<Token> for Comparator { fn from(token: Token) -> Self { match token { Token::Lt => Comparator::LessThan, Token::Lte => Comparator::LessThanEqual, Token::Gt => Comparator::GreaterThan, Token::Gte => Comparator::GreaterThanEqual, Token::Eq => Comparator::Equal, Token::Ne => Comparator::NotEqual, _ => panic!("Invalid token for comparator: {:?}", token), } } } #[cfg(test)] mod test { use super::*; #[test] fn displays_pretty_printed_ast_node() { let node = Ast::Field { name: "abc".to_string(), offset: 4, }; assert_eq!("Field {\n offset: 4,\n name: \"abc\",\n}", format!("{}", node)); } }
/// Represents a key value pair in a MultiHash. #[derive(Clone, PartialEq, Debug)] pub struct KeyValuePair {
random_line_split
triangle.rs
#[macro_use] extern crate glium; mod support; use glium::Surface; use glium::glutin; use glium::index::PrimitiveType; fn main() { use glium::DisplayBuild; // building the display, ie. the main object let display = glutin::WindowBuilder::new() .build_glium() .unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], color: [f32; 3], } implement_vertex!(Vertex, position, color); glium::VertexBuffer::new(&display, vec![ Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0] }, Vertex { position: [ 0.0, 0.5], color: [0.0, 0.0, 1.0] }, Vertex { position: [ 0.5, -0.5], color: [1.0, 0.0, 0.0] }, ] ) }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList, vec![0u16, 1, 2]); // compiling shaders and linking them together let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 matrix; in vec2 position; in vec3 color; out vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, 100 => { vertex: " #version 100
uniform lowp mat4 matrix; attribute lowp vec2 position; attribute lowp vec3 color; varying lowp vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 100 varying lowp vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, ).unwrap(); // the main loop support::start_loop(|| { // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ] }; // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap(); target.finish().unwrap(); // polling and handling the events received by the window for event in display.poll_events() { match event { glutin::Event::Closed => return support::Action::Stop, _ => () } } support::Action::Continue }); }
random_line_split
triangle.rs
#[macro_use] extern crate glium; mod support; use glium::Surface; use glium::glutin; use glium::index::PrimitiveType; fn
() { use glium::DisplayBuild; // building the display, ie. the main object let display = glutin::WindowBuilder::new() .build_glium() .unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], color: [f32; 3], } implement_vertex!(Vertex, position, color); glium::VertexBuffer::new(&display, vec![ Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0] }, Vertex { position: [ 0.0, 0.5], color: [0.0, 0.0, 1.0] }, Vertex { position: [ 0.5, -0.5], color: [1.0, 0.0, 0.0] }, ] ) }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList, vec![0u16, 1, 2]); // compiling shaders and linking them together let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 matrix; in vec2 position; in vec3 color; out vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, 100 => { vertex: " #version 100 uniform lowp mat4 matrix; attribute lowp vec2 position; attribute lowp vec3 color; varying lowp vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 100 varying lowp vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, ).unwrap(); // the main loop support::start_loop(|| { // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ] }; // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap(); target.finish().unwrap(); // polling and handling the events received by the window for event in display.poll_events() { match event { glutin::Event::Closed => return support::Action::Stop, _ => () } } support::Action::Continue }); }
main
identifier_name
triangle.rs
#[macro_use] extern crate glium; mod support; use glium::Surface; use glium::glutin; use glium::index::PrimitiveType; fn main()
Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0] }, Vertex { position: [ 0.0, 0.5], color: [0.0, 0.0, 1.0] }, Vertex { position: [ 0.5, -0.5], color: [1.0, 0.0, 0.0] }, ] ) }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList, vec![0u16, 1, 2]); // compiling shaders and linking them together let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 matrix; in vec2 position; in vec3 color; out vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, 100 => { vertex: " #version 100 uniform lowp mat4 matrix; attribute lowp vec2 position; attribute lowp vec3 color; varying lowp vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 100 varying lowp vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, ).unwrap(); // the main loop support::start_loop(|| { // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ] }; // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap(); target.finish().unwrap(); // polling and handling the events received by the window for event in display.poll_events() { match event { glutin::Event::Closed => return support::Action::Stop, _ => () } } support::Action::Continue }); }
{ use glium::DisplayBuild; // building the display, ie. the main object let display = glutin::WindowBuilder::new() .build_glium() .unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], color: [f32; 3], } implement_vertex!(Vertex, position, color); glium::VertexBuffer::new(&display, vec![
identifier_body
associated-types-multiple-types-one-trait.rs
trait Foo { type X; type Y; }
} fn have_x_want_y<T:Foo<X=u32>>(t: &T) { want_y(t); //~ ERROR type mismatch } fn have_y_want_x<T:Foo<Y=i32>>(t: &T) { want_x(t); //~ ERROR type mismatch } fn have_y_want_y<T:Foo<Y=i32>>(t: &T) { want_y(t); } fn have_xy_want_x<T:Foo<X=u32,Y=i32>>(t: &T) { want_x(t); } fn have_xy_want_y<T:Foo<X=u32,Y=i32>>(t: &T) { want_y(t); } fn have_xy_want_xy<T:Foo<X=u32,Y=i32>>(t: &T) { want_x(t); want_y(t); } fn want_x<T:Foo<X=u32>>(t: &T) { } fn want_y<T:Foo<Y=i32>>(t: &T) { } fn main() { }
fn have_x_want_x<T:Foo<X=u32>>(t: &T) { want_x(t);
random_line_split
associated-types-multiple-types-one-trait.rs
trait Foo { type X; type Y; } fn have_x_want_x<T:Foo<X=u32>>(t: &T) { want_x(t); } fn have_x_want_y<T:Foo<X=u32>>(t: &T) { want_y(t); //~ ERROR type mismatch } fn have_y_want_x<T:Foo<Y=i32>>(t: &T) { want_x(t); //~ ERROR type mismatch } fn have_y_want_y<T:Foo<Y=i32>>(t: &T) { want_y(t); } fn have_xy_want_x<T:Foo<X=u32,Y=i32>>(t: &T) { want_x(t); } fn have_xy_want_y<T:Foo<X=u32,Y=i32>>(t: &T) { want_y(t); } fn have_xy_want_xy<T:Foo<X=u32,Y=i32>>(t: &T) { want_x(t); want_y(t); } fn
<T:Foo<X=u32>>(t: &T) { } fn want_y<T:Foo<Y=i32>>(t: &T) { } fn main() { }
want_x
identifier_name
associated-types-multiple-types-one-trait.rs
trait Foo { type X; type Y; } fn have_x_want_x<T:Foo<X=u32>>(t: &T) { want_x(t); } fn have_x_want_y<T:Foo<X=u32>>(t: &T) { want_y(t); //~ ERROR type mismatch } fn have_y_want_x<T:Foo<Y=i32>>(t: &T) { want_x(t); //~ ERROR type mismatch } fn have_y_want_y<T:Foo<Y=i32>>(t: &T) { want_y(t); } fn have_xy_want_x<T:Foo<X=u32,Y=i32>>(t: &T) { want_x(t); } fn have_xy_want_y<T:Foo<X=u32,Y=i32>>(t: &T) { want_y(t); } fn have_xy_want_xy<T:Foo<X=u32,Y=i32>>(t: &T) { want_x(t); want_y(t); } fn want_x<T:Foo<X=u32>>(t: &T)
fn want_y<T:Foo<Y=i32>>(t: &T) { } fn main() { }
{ }
identifier_body
simplify.rs
#[link(name = "simplify", vers = "0.0.6")]; extern mod extra; use extra::json::Json; use extra::json::List; use extra::json::ToJson; use extra::treemap::TreeSet; use std::vec; #[deriving(Clone, Eq)] pub struct Point { x: float, y: float } impl ToJson for Point { fn to_json(&self) -> Json { List(~[self.x.to_json(),self.y.to_json()]) } } impl Sub<Point,Point> for Point { #[inline] fn sub(&self, other: &Point) -> Point { Point {x:self.x-other.x,y:self.y-other.y} } } impl Add<Point,Point> for Point { #[inline] fn add(&self, other: &Point) -> Point { Point { x:self.x+other.x,y:self.y+other.y }} } impl Mul<Point,Point> for Point { #[inline] fn mul(&self, other: &Point) -> Point { Point { x:self.x*other.x,y:self.y*other.y }} } impl Point { fn sum(self) -> float { self.x+self.y } fn sqsum(self) -> float { self.x * self.x + self.y * self.y} fn sub(self, other: float) -> Point { Point { x:self.x - other, y:self.y - other }} fn
(self, other: float) -> Point { Point { x:self.x * other, y:self.y * other }} fn add(self, other: float) -> Point { Point {x:self.x + other, y:self.y + other }} } type Pair = (uint, uint); fn calcStuff(p:Point,p1:Point,d1:Point)->float { let top = ((p - p1) * d1).sum(); let bottom = d1.sqsum(); if bottom == 0.0 { 0.0 }else{ top/bottom } } fn getSquareSegmentDistance(p: Point, p1: Point, p2: Point) -> float { let d1 = p2-p1; let d2 = match d1{ Point {x:0.0,_} | Point {y:0.0,_}=> {p1} _=>{ let t = calcStuff(p,p1,d1); if t>1.0 { p2 }else if t>0.0{ d1.mul(t)+p1 }else{ p1 } } }; (p-d2).sqsum() } fn simplifyRadialDistance(points:~[Point], sqTolerance:float) -> ~[Point]{ let mut it = points.iter(); it.next(); let mut prevPoint : Point = points[0u]; let mut newPoints : ~[Point] = ~[prevPoint]; let &last = points.last(); for &point in it{ if (point - prevPoint).sqsum() > sqTolerance { newPoints.push(point); prevPoint = point; } } if (prevPoint!= last) { newPoints.push(last); } newPoints } fn simplifyDouglasPeucker(points : ~[Point], tolerance : float) -> ~[Point]{ let len = points.len(); let mut markers = TreeSet::new(); let mut stack : ~[Pair] = ~[]; markers.insert(0u); markers.insert(len-1u); let mut pair:Pair = (0u,len-1u); loop { let first = pair.first(); let second = pair.second(); let (first_pt, second_pt) = (points[first], points[second]); let mut index = 0u; let mut max_sq_dist = 0.0f; let i = first + 1u; for (i, &point_i) in points.slice_from(i) .iter() .enumerate() .map(|(new_i, point)| (i + new_i, point)) .take_while(|&(i, _)| i < second) { let sq_dist = getSquareSegmentDistance(point_i, first_pt, second_pt); if (sq_dist > max_sq_dist) { index = i; max_sq_dist = sq_dist; } } if max_sq_dist > tolerance { markers.insert(index); stack.push((first,index)); stack.push((index,second)); } match stack.pop_opt() { Some(p)=>pair=p, None=>break }; } vec::from_fn(markers.len(),|k| points[k]) } pub fn simplify(points : ~[Point], sqTolerance : float, hq:bool) -> ~[Point]{ let tolerance = sqTolerance*sqTolerance; let pts:~[Point] = if hq { points } else { simplifyRadialDistance(points,tolerance) }; simplifyDouglasPeucker(pts,tolerance) }
mul
identifier_name
simplify.rs
#[link(name = "simplify", vers = "0.0.6")]; extern mod extra; use extra::json::Json; use extra::json::List; use extra::json::ToJson; use extra::treemap::TreeSet; use std::vec; #[deriving(Clone, Eq)] pub struct Point { x: float, y: float } impl ToJson for Point { fn to_json(&self) -> Json { List(~[self.x.to_json(),self.y.to_json()]) } } impl Sub<Point,Point> for Point { #[inline] fn sub(&self, other: &Point) -> Point { Point {x:self.x-other.x,y:self.y-other.y} } } impl Add<Point,Point> for Point { #[inline] fn add(&self, other: &Point) -> Point { Point { x:self.x+other.x,y:self.y+other.y }} } impl Mul<Point,Point> for Point { #[inline] fn mul(&self, other: &Point) -> Point { Point { x:self.x*other.x,y:self.y*other.y }} } impl Point { fn sum(self) -> float { self.x+self.y } fn sqsum(self) -> float { self.x * self.x + self.y * self.y} fn sub(self, other: float) -> Point { Point { x:self.x - other, y:self.y - other }} fn mul(self, other: float) -> Point { Point { x:self.x * other, y:self.y * other }} fn add(self, other: float) -> Point { Point {x:self.x + other, y:self.y + other }} } type Pair = (uint, uint); fn calcStuff(p:Point,p1:Point,d1:Point)->float { let top = ((p - p1) * d1).sum(); let bottom = d1.sqsum(); if bottom == 0.0 { 0.0 }else{ top/bottom } } fn getSquareSegmentDistance(p: Point, p1: Point, p2: Point) -> float { let d1 = p2-p1; let d2 = match d1{ Point {x:0.0,_} | Point {y:0.0,_}=> {p1} _=>{ let t = calcStuff(p,p1,d1); if t>1.0 { p2 }else if t>0.0{ d1.mul(t)+p1 }else{ p1 } }
}; (p-d2).sqsum() } fn simplifyRadialDistance(points:~[Point], sqTolerance:float) -> ~[Point]{ let mut it = points.iter(); it.next(); let mut prevPoint : Point = points[0u]; let mut newPoints : ~[Point] = ~[prevPoint]; let &last = points.last(); for &point in it{ if (point - prevPoint).sqsum() > sqTolerance { newPoints.push(point); prevPoint = point; } } if (prevPoint!= last) { newPoints.push(last); } newPoints } fn simplifyDouglasPeucker(points : ~[Point], tolerance : float) -> ~[Point]{ let len = points.len(); let mut markers = TreeSet::new(); let mut stack : ~[Pair] = ~[]; markers.insert(0u); markers.insert(len-1u); let mut pair:Pair = (0u,len-1u); loop { let first = pair.first(); let second = pair.second(); let (first_pt, second_pt) = (points[first], points[second]); let mut index = 0u; let mut max_sq_dist = 0.0f; let i = first + 1u; for (i, &point_i) in points.slice_from(i) .iter() .enumerate() .map(|(new_i, point)| (i + new_i, point)) .take_while(|&(i, _)| i < second) { let sq_dist = getSquareSegmentDistance(point_i, first_pt, second_pt); if (sq_dist > max_sq_dist) { index = i; max_sq_dist = sq_dist; } } if max_sq_dist > tolerance { markers.insert(index); stack.push((first,index)); stack.push((index,second)); } match stack.pop_opt() { Some(p)=>pair=p, None=>break }; } vec::from_fn(markers.len(),|k| points[k]) } pub fn simplify(points : ~[Point], sqTolerance : float, hq:bool) -> ~[Point]{ let tolerance = sqTolerance*sqTolerance; let pts:~[Point] = if hq { points } else { simplifyRadialDistance(points,tolerance) }; simplifyDouglasPeucker(pts,tolerance) }
random_line_split
simplify.rs
#[link(name = "simplify", vers = "0.0.6")]; extern mod extra; use extra::json::Json; use extra::json::List; use extra::json::ToJson; use extra::treemap::TreeSet; use std::vec; #[deriving(Clone, Eq)] pub struct Point { x: float, y: float } impl ToJson for Point { fn to_json(&self) -> Json
} impl Sub<Point,Point> for Point { #[inline] fn sub(&self, other: &Point) -> Point { Point {x:self.x-other.x,y:self.y-other.y} } } impl Add<Point,Point> for Point { #[inline] fn add(&self, other: &Point) -> Point { Point { x:self.x+other.x,y:self.y+other.y }} } impl Mul<Point,Point> for Point { #[inline] fn mul(&self, other: &Point) -> Point { Point { x:self.x*other.x,y:self.y*other.y }} } impl Point { fn sum(self) -> float { self.x+self.y } fn sqsum(self) -> float { self.x * self.x + self.y * self.y} fn sub(self, other: float) -> Point { Point { x:self.x - other, y:self.y - other }} fn mul(self, other: float) -> Point { Point { x:self.x * other, y:self.y * other }} fn add(self, other: float) -> Point { Point {x:self.x + other, y:self.y + other }} } type Pair = (uint, uint); fn calcStuff(p:Point,p1:Point,d1:Point)->float { let top = ((p - p1) * d1).sum(); let bottom = d1.sqsum(); if bottom == 0.0 { 0.0 }else{ top/bottom } } fn getSquareSegmentDistance(p: Point, p1: Point, p2: Point) -> float { let d1 = p2-p1; let d2 = match d1{ Point {x:0.0,_} | Point {y:0.0,_}=> {p1} _=>{ let t = calcStuff(p,p1,d1); if t>1.0 { p2 }else if t>0.0{ d1.mul(t)+p1 }else{ p1 } } }; (p-d2).sqsum() } fn simplifyRadialDistance(points:~[Point], sqTolerance:float) -> ~[Point]{ let mut it = points.iter(); it.next(); let mut prevPoint : Point = points[0u]; let mut newPoints : ~[Point] = ~[prevPoint]; let &last = points.last(); for &point in it{ if (point - prevPoint).sqsum() > sqTolerance { newPoints.push(point); prevPoint = point; } } if (prevPoint!= last) { newPoints.push(last); } newPoints } fn simplifyDouglasPeucker(points : ~[Point], tolerance : float) -> ~[Point]{ let len = points.len(); let mut markers = TreeSet::new(); let mut stack : ~[Pair] = ~[]; markers.insert(0u); markers.insert(len-1u); let mut pair:Pair = (0u,len-1u); loop { let first = pair.first(); let second = pair.second(); let (first_pt, second_pt) = (points[first], points[second]); let mut index = 0u; let mut max_sq_dist = 0.0f; let i = first + 1u; for (i, &point_i) in points.slice_from(i) .iter() .enumerate() .map(|(new_i, point)| (i + new_i, point)) .take_while(|&(i, _)| i < second) { let sq_dist = getSquareSegmentDistance(point_i, first_pt, second_pt); if (sq_dist > max_sq_dist) { index = i; max_sq_dist = sq_dist; } } if max_sq_dist > tolerance { markers.insert(index); stack.push((first,index)); stack.push((index,second)); } match stack.pop_opt() { Some(p)=>pair=p, None=>break }; } vec::from_fn(markers.len(),|k| points[k]) } pub fn simplify(points : ~[Point], sqTolerance : float, hq:bool) -> ~[Point]{ let tolerance = sqTolerance*sqTolerance; let pts:~[Point] = if hq { points } else { simplifyRadialDistance(points,tolerance) }; simplifyDouglasPeucker(pts,tolerance) }
{ List(~[self.x.to_json(),self.y.to_json()]) }
identifier_body
simplify.rs
#[link(name = "simplify", vers = "0.0.6")]; extern mod extra; use extra::json::Json; use extra::json::List; use extra::json::ToJson; use extra::treemap::TreeSet; use std::vec; #[deriving(Clone, Eq)] pub struct Point { x: float, y: float } impl ToJson for Point { fn to_json(&self) -> Json { List(~[self.x.to_json(),self.y.to_json()]) } } impl Sub<Point,Point> for Point { #[inline] fn sub(&self, other: &Point) -> Point { Point {x:self.x-other.x,y:self.y-other.y} } } impl Add<Point,Point> for Point { #[inline] fn add(&self, other: &Point) -> Point { Point { x:self.x+other.x,y:self.y+other.y }} } impl Mul<Point,Point> for Point { #[inline] fn mul(&self, other: &Point) -> Point { Point { x:self.x*other.x,y:self.y*other.y }} } impl Point { fn sum(self) -> float { self.x+self.y } fn sqsum(self) -> float { self.x * self.x + self.y * self.y} fn sub(self, other: float) -> Point { Point { x:self.x - other, y:self.y - other }} fn mul(self, other: float) -> Point { Point { x:self.x * other, y:self.y * other }} fn add(self, other: float) -> Point { Point {x:self.x + other, y:self.y + other }} } type Pair = (uint, uint); fn calcStuff(p:Point,p1:Point,d1:Point)->float { let top = ((p - p1) * d1).sum(); let bottom = d1.sqsum(); if bottom == 0.0 { 0.0 }else{ top/bottom } } fn getSquareSegmentDistance(p: Point, p1: Point, p2: Point) -> float { let d1 = p2-p1; let d2 = match d1{ Point {x:0.0,_} | Point {y:0.0,_}=> {p1} _=>{ let t = calcStuff(p,p1,d1); if t>1.0 { p2 }else if t>0.0
else{ p1 } } }; (p-d2).sqsum() } fn simplifyRadialDistance(points:~[Point], sqTolerance:float) -> ~[Point]{ let mut it = points.iter(); it.next(); let mut prevPoint : Point = points[0u]; let mut newPoints : ~[Point] = ~[prevPoint]; let &last = points.last(); for &point in it{ if (point - prevPoint).sqsum() > sqTolerance { newPoints.push(point); prevPoint = point; } } if (prevPoint!= last) { newPoints.push(last); } newPoints } fn simplifyDouglasPeucker(points : ~[Point], tolerance : float) -> ~[Point]{ let len = points.len(); let mut markers = TreeSet::new(); let mut stack : ~[Pair] = ~[]; markers.insert(0u); markers.insert(len-1u); let mut pair:Pair = (0u,len-1u); loop { let first = pair.first(); let second = pair.second(); let (first_pt, second_pt) = (points[first], points[second]); let mut index = 0u; let mut max_sq_dist = 0.0f; let i = first + 1u; for (i, &point_i) in points.slice_from(i) .iter() .enumerate() .map(|(new_i, point)| (i + new_i, point)) .take_while(|&(i, _)| i < second) { let sq_dist = getSquareSegmentDistance(point_i, first_pt, second_pt); if (sq_dist > max_sq_dist) { index = i; max_sq_dist = sq_dist; } } if max_sq_dist > tolerance { markers.insert(index); stack.push((first,index)); stack.push((index,second)); } match stack.pop_opt() { Some(p)=>pair=p, None=>break }; } vec::from_fn(markers.len(),|k| points[k]) } pub fn simplify(points : ~[Point], sqTolerance : float, hq:bool) -> ~[Point]{ let tolerance = sqTolerance*sqTolerance; let pts:~[Point] = if hq { points } else { simplifyRadialDistance(points,tolerance) }; simplifyDouglasPeucker(pts,tolerance) }
{ d1.mul(t)+p1 }
conditional_block
test_tr.rs
use common::util::*; #[test] fn test_toupper()
#[test] fn test_small_set2() { new_ucmd!() .args(&["0-9", "X"]).pipe_in("@0123456789").run().stdout_is("@XXXXXXXXXX"); } #[test] fn test_unicode() { new_ucmd!() .args(&[", ┬─┬", "╯︵┻━┻"]) .pipe_in("(,°□°), ┬─┬").run() .stdout_is("(╯°□°)╯︵┻━┻"); } #[test] fn test_delete() { new_ucmd!() .args(&["-d", "a-z"]).pipe_in("aBcD").run().stdout_is("BD"); } #[test] fn test_delete_complement() { new_ucmd!() .args(&["-d", "-c", "a-z"]).pipe_in("aBcD").run().stdout_is("ac"); }
{ new_ucmd!() .args(&["a-z", "A-Z"]).pipe_in("!abcd!").run().stdout_is("!ABCD!"); }
identifier_body
test_tr.rs
use common::util::*; #[test] fn test_toupper() { new_ucmd!() .args(&["a-z", "A-Z"]).pipe_in("!abcd!").run().stdout_is("!ABCD!"); } #[test] fn test_small_set2() { new_ucmd!() .args(&["0-9", "X"]).pipe_in("@0123456789").run().stdout_is("@XXXXXXXXXX"); } #[test] fn test_unicode() { new_ucmd!() .args(&[", ┬─┬", "╯︵┻━┻"]) .pipe_in("(,°□°), ┬─┬").run() .stdout_is("(╯°□°)╯︵┻━┻"); } #[test] fn test_delete() { new_ucmd!() .args(&["-d", "a-z"]).pipe_in("aBcD").run().stdout_is("BD"); } #[test] fn test_delete_complement() { new_ucmd!()
}
.args(&["-d", "-c", "a-z"]).pipe_in("aBcD").run().stdout_is("ac");
random_line_split
test_tr.rs
use common::util::*; #[test] fn test_toupper() { new_ucmd!() .args(&["a-z", "A-Z"]).pipe_in("!abcd!").run().stdout_is("!ABCD!"); } #[test] fn test_small_set2() { new_ucmd!() .args(&["0-9", "X"]).pipe_in("@0123456789").run().stdout_is("@XXXXXXXXXX"); } #[test] fn test_unicode() { new_ucmd!() .args(&[", ┬─┬", "╯︵┻━┻"]) .pipe_in("(,°□°), ┬─┬").run() .stdout_is("(╯°□°)╯︵┻━┻"); } #[test] fn test_delete() { new_ucmd!() .args(
z"]).pipe_in("aBcD").run().stdout_is("BD"); } #[test] fn test_delete_complement() { new_ucmd!() .args(&["-d", "-c", "a-z"]).pipe_in("aBcD").run().stdout_is("ac"); }
&["-d", "a-
identifier_name
relocation.rs
use std::io::{Read, Write}; use {Error, Header, SectionContent}; use types; use num_traits::{FromPrimitive, ToPrimitive}; /* A Represents the addend used to compute the value of the relocatable field. B Represents the base address at which a shared object has been loaded into memory during execution. Generally, a shared object is built with a 0 base virtual address, but the execution address will be different. G Represents the offset into the global offset table at which the relocation entry’s symbol will reside during execution. GOT Represents the address of the global offset table. L Represents the place (section offset or address) of the Procedure Linkage Table entry for a symbol. P Represents the place (section offset or address) of the storage unit being relocated -> that is the relocations offset in loaded memory, so for example a relocation at offset 0x3 in .text which is loaded at 0x100 will have P = 0x103 S Represents the value of the symbol whose index resides in the relocation entry. The AMD64 ABI architectures uses only Elf64_Rela relocation entries with explicit addends. The r_addend member serves as the relocation addend. */ #[allow(non_camel_case_types)] #[derive(Debug, Primitive, PartialEq, Clone)] pub enum Re
R_X86_64_NONE = 0, // none none R_X86_64_64 = 1, // word64 S + A R_X86_64_PC32 = 2, // word32 S + A - P R_X86_64_GOT32 = 3, // word32 G + A R_X86_64_PLT32 = 4, // word32 L + A - P R_X86_64_COPY = 5, // none none R_X86_64_GLOB_DAT = 6, // wordclass S R_X86_64_JUMP_SLOT = 7, // wordclass S R_X86_64_RELATIVE = 8, // wordclass B + A R_X86_64_GOTPCREL = 9, // word32 G + GOT + A - P R_X86_64_32 = 10, // word32 S + A R_X86_64_32S = 11, // word32 S + A R_X86_64_16 = 12, // word16 S + A R_X86_64_PC16 = 13, // word16 S + A - P R_X86_64_8 = 14, // word8 S + A R_X86_64_PC8 = 15, // word8 S + A - P /// First part of the tls_index structure: ID of module containing symbol /// writes the module id at this location /// in an executable this is always exactly 1, /// so this reloc is only emitted for DYN where the dynamic linker /// needs to give the module an id R_X86_64_DTPMOD64 = 16, // word64 /// Second part of tls_index: The Offset of the symbol in the TLS Block /// this is written into the GOT of _this_ unit by the dynamic linker, /// and the offset is into the TLS block of some other unit that actually /// defines that symbol R_X86_64_DTPOFF64 = 17, // word64 /// Offset in initial TLS Block in initial exec model /// no idea why this needs a different reloc type, this appears to be identical /// to R_X86_64_DTPOFF64 R_X86_64_TPOFF64 = 18, // word64 /// PC Relative address to the tls_index structure in the GOT /// in general dynamic model R_X86_64_TLSGD = 19, // word32 /// PC Relative address to the tls_index structure in the GOT /// in local dynamic model. that index only contains the module id, /// since the offset is known at link time and will be accessed via /// R_X86_64_DTPOFF32 R_X86_64_TLSLD = 20, // word32 /// Offset of the symbol in TLS Block (local dynamic model) R_X86_64_DTPOFF32 = 21, // word32 /// in initial exec model, this is a PC Relative offset to a GOT entry /// which contains the 32bit offset into the thread local block. /// this is emitted by the compiler when the thread local var will definately /// be inside the executable. R_X86_64_GOTTPOFF = 22, // word32 /// for initial exec model, this is the reloc on the GOT entry. R_X86_64_TPOFF32 = 23, // word32 R_X86_64_PC64 = 24, // word64 S + A - P R_X86_64_GOTOFF64 = 25, // word64 S + A - GOT R_X86_64_GOTPC32 = 26, // word32 GOT + A - P R_X86_64_SIZE32 = 32, // word32 Z + A R_X86_64_SIZE64 = 33, // word64 Z + A R_X86_64_GOTPC32_TLSDESC = 34, // word32 R_X86_64_TLSDESC_CALL = 35, // none R_X86_64_TLSDESC = 36, // word64×2 R_X86_64_IRELATIVE = 37, // wordclass indirect (B + A) R_X86_64_RELATIVE64 = 38, // word64 B + A //not documented. hopefully these are ok to be treated as R_X86_64_GOTPCREL R_X86_64_GOTPCRELX = 41, // word32 G + GOT + A - P R_X86_64_REX_GOTPCRELX = 42, //word32 G + GOT + A - P } impl Default for RelocationType { fn default() -> Self { RelocationType::R_X86_64_NONE } } #[derive(Default, Debug, Clone)] pub struct Relocation { pub addr: u64, pub sym: u32, pub rtype: RelocationType, pub addend: i64, } impl Relocation { pub fn entsize(eh: &Header) -> usize { match eh.machine { types::Machine::X86_64 => 3 * 8, _ => panic!("relocs for machine '{:?}' not implemented", eh.machine), } } pub fn from_reader<R>( mut io: R, _: Option<&SectionContent>, eh: &Header, ) -> Result<SectionContent, Error> where R: Read, { if eh.machine!= types::Machine::X86_64 { return Err(Error::UnsupportedMachineTypeForRelocation( eh.machine.clone(), )); } let mut r = Vec::new(); while let Ok(addr) = elf_read_u64!(eh, io) { let info = match elf_read_u64!(eh, io) { Ok(v) => v, _ => break, }; let sym = (info >> 32) as u32; let rtype = (info & 0xffffffff) as u32; let rtype = match RelocationType::from_u32(rtype) { Some(v) => v, None => { println!( "warning: unknown relocation type {} skipped while reading", rtype ); elf_read_u64!(eh, io)?; continue; } }; let addend = elf_read_u64!(eh, io)?; r.push(Relocation { addr: addr, sym: sym, rtype: rtype, addend: addend as i64, }); } Ok(SectionContent::Relocations(r)) } pub fn to_writer<W>( &self, mut io: W, eh: &Header, ) -> Result<(usize), Error> where W: Write, { elf_write_u64!(eh, io, self.addr)?; let info = (self.sym.to_u64().unwrap() << 32) + self.rtype.to_u64().unwrap(); elf_write_u64!(eh, io, info)?; elf_write_u64!(eh, io, self.addend as u64)?; Ok(8+8+8) } }
locationType {
identifier_name
relocation.rs
use std::io::{Read, Write}; use {Error, Header, SectionContent}; use types; use num_traits::{FromPrimitive, ToPrimitive}; /* A Represents the addend used to compute the value of the relocatable field. B Represents the base address at which a shared object has been loaded into memory during execution. Generally, a shared object is built with a 0 base virtual address, but the execution address will be different. G Represents the offset into the global offset table at which the relocation entry’s symbol will reside during execution. GOT Represents the address of the global offset table. L Represents the place (section offset or address) of the Procedure Linkage Table entry for a symbol. P Represents the place (section offset or address) of the storage unit being relocated -> that is the relocations offset in loaded memory, so for example a relocation at offset 0x3 in .text which is loaded at 0x100 will have P = 0x103 S Represents the value of the symbol whose index resides in the relocation entry. The AMD64 ABI architectures uses only Elf64_Rela relocation entries with explicit addends. The r_addend member serves as the relocation addend. */ #[allow(non_camel_case_types)] #[derive(Debug, Primitive, PartialEq, Clone)] pub enum RelocationType { R_X86_64_NONE = 0, // none none R_X86_64_64 = 1, // word64 S + A R_X86_64_PC32 = 2, // word32 S + A - P R_X86_64_GOT32 = 3, // word32 G + A R_X86_64_PLT32 = 4, // word32 L + A - P R_X86_64_COPY = 5, // none none R_X86_64_GLOB_DAT = 6, // wordclass S R_X86_64_JUMP_SLOT = 7, // wordclass S R_X86_64_RELATIVE = 8, // wordclass B + A R_X86_64_GOTPCREL = 9, // word32 G + GOT + A - P R_X86_64_32 = 10, // word32 S + A R_X86_64_32S = 11, // word32 S + A R_X86_64_16 = 12, // word16 S + A R_X86_64_PC16 = 13, // word16 S + A - P R_X86_64_8 = 14, // word8 S + A R_X86_64_PC8 = 15, // word8 S + A - P /// First part of the tls_index structure: ID of module containing symbol /// writes the module id at this location /// in an executable this is always exactly 1, /// so this reloc is only emitted for DYN where the dynamic linker /// needs to give the module an id R_X86_64_DTPMOD64 = 16, // word64 /// Second part of tls_index: The Offset of the symbol in the TLS Block /// this is written into the GOT of _this_ unit by the dynamic linker, /// and the offset is into the TLS block of some other unit that actually /// defines that symbol R_X86_64_DTPOFF64 = 17, // word64 /// Offset in initial TLS Block in initial exec model /// no idea why this needs a different reloc type, this appears to be identical /// to R_X86_64_DTPOFF64 R_X86_64_TPOFF64 = 18, // word64 /// PC Relative address to the tls_index structure in the GOT /// in general dynamic model R_X86_64_TLSGD = 19, // word32 /// PC Relative address to the tls_index structure in the GOT /// in local dynamic model. that index only contains the module id, /// since the offset is known at link time and will be accessed via /// R_X86_64_DTPOFF32 R_X86_64_TLSLD = 20, // word32 /// Offset of the symbol in TLS Block (local dynamic model) R_X86_64_DTPOFF32 = 21, // word32 /// in initial exec model, this is a PC Relative offset to a GOT entry /// which contains the 32bit offset into the thread local block. /// this is emitted by the compiler when the thread local var will definately /// be inside the executable. R_X86_64_GOTTPOFF = 22, // word32 /// for initial exec model, this is the reloc on the GOT entry. R_X86_64_TPOFF32 = 23, // word32 R_X86_64_PC64 = 24, // word64 S + A - P R_X86_64_GOTOFF64 = 25, // word64 S + A - GOT R_X86_64_GOTPC32 = 26, // word32 GOT + A - P R_X86_64_SIZE32 = 32, // word32 Z + A R_X86_64_SIZE64 = 33, // word64 Z + A R_X86_64_GOTPC32_TLSDESC = 34, // word32 R_X86_64_TLSDESC_CALL = 35, // none R_X86_64_TLSDESC = 36, // word64×2 R_X86_64_IRELATIVE = 37, // wordclass indirect (B + A) R_X86_64_RELATIVE64 = 38, // word64 B + A //not documented. hopefully these are ok to be treated as R_X86_64_GOTPCREL R_X86_64_GOTPCRELX = 41, // word32 G + GOT + A - P R_X86_64_REX_GOTPCRELX = 42, //word32 G + GOT + A - P } impl Default for RelocationType { fn default() -> Self { RelocationType::R_X86_64_NONE } } #[derive(Default, Debug, Clone)] pub struct Relocation { pub addr: u64, pub sym: u32, pub rtype: RelocationType, pub addend: i64, } impl Relocation { pub fn entsize(eh: &Header) -> usize { match eh.machine { types::Machine::X86_64 => 3 * 8, _ => panic!("relocs for machine '{:?}' not implemented", eh.machine), } } pub fn from_reader<R>( mut io: R, _: Option<&SectionContent>, eh: &Header, ) -> Result<SectionContent, Error> where R: Read, {
"warning: unknown relocation type {} skipped while reading", rtype ); elf_read_u64!(eh, io)?; continue; } }; let addend = elf_read_u64!(eh, io)?; r.push(Relocation { addr: addr, sym: sym, rtype: rtype, addend: addend as i64, }); } Ok(SectionContent::Relocations(r)) } pub fn to_writer<W>( &self, mut io: W, eh: &Header, ) -> Result<(usize), Error> where W: Write, { elf_write_u64!(eh, io, self.addr)?; let info = (self.sym.to_u64().unwrap() << 32) + self.rtype.to_u64().unwrap(); elf_write_u64!(eh, io, info)?; elf_write_u64!(eh, io, self.addend as u64)?; Ok(8+8+8) } }
if eh.machine != types::Machine::X86_64 { return Err(Error::UnsupportedMachineTypeForRelocation( eh.machine.clone(), )); } let mut r = Vec::new(); while let Ok(addr) = elf_read_u64!(eh, io) { let info = match elf_read_u64!(eh, io) { Ok(v) => v, _ => break, }; let sym = (info >> 32) as u32; let rtype = (info & 0xffffffff) as u32; let rtype = match RelocationType::from_u32(rtype) { Some(v) => v, None => { println!(
identifier_body
relocation.rs
use std::io::{Read, Write}; use {Error, Header, SectionContent}; use types; use num_traits::{FromPrimitive, ToPrimitive}; /* A Represents the addend used to compute the value of the relocatable field. B Represents the base address at which a shared object has been loaded into memory during execution. Generally, a shared object is built with a 0 base virtual address, but the execution address will be different. G Represents the offset into the global offset table at which the relocation entry’s symbol will reside during execution. GOT Represents the address of the global offset table. L Represents the place (section offset or address) of the Procedure Linkage Table entry for a symbol. P Represents the place (section offset or address) of the storage unit being relocated -> that is the relocations offset in loaded memory, so for example a relocation at offset 0x3 in .text which is loaded at 0x100 will have P = 0x103 S Represents the value of the symbol whose index resides in the relocation entry. The AMD64 ABI architectures uses only Elf64_Rela relocation entries with explicit addends. The r_addend member serves as the relocation addend. */ #[allow(non_camel_case_types)] #[derive(Debug, Primitive, PartialEq, Clone)] pub enum RelocationType { R_X86_64_NONE = 0, // none none R_X86_64_64 = 1, // word64 S + A R_X86_64_PC32 = 2, // word32 S + A - P R_X86_64_GOT32 = 3, // word32 G + A R_X86_64_PLT32 = 4, // word32 L + A - P R_X86_64_COPY = 5, // none none
R_X86_64_GOTPCREL = 9, // word32 G + GOT + A - P R_X86_64_32 = 10, // word32 S + A R_X86_64_32S = 11, // word32 S + A R_X86_64_16 = 12, // word16 S + A R_X86_64_PC16 = 13, // word16 S + A - P R_X86_64_8 = 14, // word8 S + A R_X86_64_PC8 = 15, // word8 S + A - P /// First part of the tls_index structure: ID of module containing symbol /// writes the module id at this location /// in an executable this is always exactly 1, /// so this reloc is only emitted for DYN where the dynamic linker /// needs to give the module an id R_X86_64_DTPMOD64 = 16, // word64 /// Second part of tls_index: The Offset of the symbol in the TLS Block /// this is written into the GOT of _this_ unit by the dynamic linker, /// and the offset is into the TLS block of some other unit that actually /// defines that symbol R_X86_64_DTPOFF64 = 17, // word64 /// Offset in initial TLS Block in initial exec model /// no idea why this needs a different reloc type, this appears to be identical /// to R_X86_64_DTPOFF64 R_X86_64_TPOFF64 = 18, // word64 /// PC Relative address to the tls_index structure in the GOT /// in general dynamic model R_X86_64_TLSGD = 19, // word32 /// PC Relative address to the tls_index structure in the GOT /// in local dynamic model. that index only contains the module id, /// since the offset is known at link time and will be accessed via /// R_X86_64_DTPOFF32 R_X86_64_TLSLD = 20, // word32 /// Offset of the symbol in TLS Block (local dynamic model) R_X86_64_DTPOFF32 = 21, // word32 /// in initial exec model, this is a PC Relative offset to a GOT entry /// which contains the 32bit offset into the thread local block. /// this is emitted by the compiler when the thread local var will definately /// be inside the executable. R_X86_64_GOTTPOFF = 22, // word32 /// for initial exec model, this is the reloc on the GOT entry. R_X86_64_TPOFF32 = 23, // word32 R_X86_64_PC64 = 24, // word64 S + A - P R_X86_64_GOTOFF64 = 25, // word64 S + A - GOT R_X86_64_GOTPC32 = 26, // word32 GOT + A - P R_X86_64_SIZE32 = 32, // word32 Z + A R_X86_64_SIZE64 = 33, // word64 Z + A R_X86_64_GOTPC32_TLSDESC = 34, // word32 R_X86_64_TLSDESC_CALL = 35, // none R_X86_64_TLSDESC = 36, // word64×2 R_X86_64_IRELATIVE = 37, // wordclass indirect (B + A) R_X86_64_RELATIVE64 = 38, // word64 B + A //not documented. hopefully these are ok to be treated as R_X86_64_GOTPCREL R_X86_64_GOTPCRELX = 41, // word32 G + GOT + A - P R_X86_64_REX_GOTPCRELX = 42, //word32 G + GOT + A - P } impl Default for RelocationType { fn default() -> Self { RelocationType::R_X86_64_NONE } } #[derive(Default, Debug, Clone)] pub struct Relocation { pub addr: u64, pub sym: u32, pub rtype: RelocationType, pub addend: i64, } impl Relocation { pub fn entsize(eh: &Header) -> usize { match eh.machine { types::Machine::X86_64 => 3 * 8, _ => panic!("relocs for machine '{:?}' not implemented", eh.machine), } } pub fn from_reader<R>( mut io: R, _: Option<&SectionContent>, eh: &Header, ) -> Result<SectionContent, Error> where R: Read, { if eh.machine!= types::Machine::X86_64 { return Err(Error::UnsupportedMachineTypeForRelocation( eh.machine.clone(), )); } let mut r = Vec::new(); while let Ok(addr) = elf_read_u64!(eh, io) { let info = match elf_read_u64!(eh, io) { Ok(v) => v, _ => break, }; let sym = (info >> 32) as u32; let rtype = (info & 0xffffffff) as u32; let rtype = match RelocationType::from_u32(rtype) { Some(v) => v, None => { println!( "warning: unknown relocation type {} skipped while reading", rtype ); elf_read_u64!(eh, io)?; continue; } }; let addend = elf_read_u64!(eh, io)?; r.push(Relocation { addr: addr, sym: sym, rtype: rtype, addend: addend as i64, }); } Ok(SectionContent::Relocations(r)) } pub fn to_writer<W>( &self, mut io: W, eh: &Header, ) -> Result<(usize), Error> where W: Write, { elf_write_u64!(eh, io, self.addr)?; let info = (self.sym.to_u64().unwrap() << 32) + self.rtype.to_u64().unwrap(); elf_write_u64!(eh, io, info)?; elf_write_u64!(eh, io, self.addend as u64)?; Ok(8+8+8) } }
R_X86_64_GLOB_DAT = 6, // wordclass S R_X86_64_JUMP_SLOT = 7, // wordclass S R_X86_64_RELATIVE = 8, // wordclass B + A
random_line_split
disk_space.rs
use std::path::Path; use std::time::Duration; use crossbeam_channel::Sender; use nix::sys::statvfs::statvfs; use serde_derive::Deserialize; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::errors::*; use crate::formatting::FormatTemplate; use crate::formatting::{prefix::Prefix, value::Value}; use crate::scheduler::Task; use crate::widgets::text::TextWidget; use crate::widgets::{I3BarWidget, State}; #[derive(Copy, Clone, Debug, Deserialize)] #[serde(rename_all = "lowercase")] pub enum InfoType { Available, Free, Used, } pub struct
{ id: usize, disk_space: TextWidget, update_interval: Duration, path: String, unit: Prefix, info_type: InfoType, warning: f64, alert: f64, alert_absolute: bool, format: FormatTemplate, icon: String, // DEPRECATED // TODO remove alias: String, } #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields, default)] pub struct DiskSpaceConfig { /// Path to collect information from pub path: String, /// Currently supported options are available, free, total and used /// Sets value used for {percentage} calculation /// total is the same as used, use format to set format string for output pub info_type: InfoType, /// Format string for output pub format: FormatTemplate, /// Unit that is used to display disk space. Options are B, KB, MB, GB and TB pub unit: String, /// Update interval in seconds #[serde(deserialize_with = "deserialize_duration")] pub interval: Duration, /// Diskspace warning (yellow) pub warning: f64, /// Diskspace alert (red) pub alert: f64, /// use absolute (unit) values for disk space alerts pub alert_absolute: bool, /// Alias that is displayed for path // DEPRECATED // TODO remove pub alias: String, } impl Default for DiskSpaceConfig { fn default() -> Self { Self { path: "/".to_string(), info_type: InfoType::Available, format: FormatTemplate::default(), unit: "GB".to_string(), interval: Duration::from_secs(20), warning: 20., alert: 10., alert_absolute: false, alias: "/".to_string(), } } } enum AlertType { Above, Below, } impl DiskSpace { fn compute_state(&self, value: f64, warning: f64, alert: f64, alert_type: AlertType) -> State { match alert_type { AlertType::Above => { if value > alert { State::Critical } else if value <= alert && value > warning { State::Warning } else { State::Idle } } AlertType::Below => { if 0. <= value && value < alert { State::Critical } else if alert <= value && value < warning { State::Warning } else { State::Idle } } } } } impl ConfigBlock for DiskSpace { type Config = DiskSpaceConfig; fn new( id: usize, block_config: Self::Config, shared_config: SharedConfig, _tx_update_request: Sender<Task>, ) -> Result<Self> { let icon = shared_config.get_icon("disk_drive")?; Ok(DiskSpace { id, update_interval: block_config.interval, disk_space: TextWidget::new(id, 0, shared_config), path: block_config.path, format: block_config.format.with_default("{available}")?, info_type: block_config.info_type, unit: match block_config.unit.as_str() { "TB" => Prefix::Tera, "GB" => Prefix::Giga, "MB" => Prefix::Mega, "KB" => Prefix::Kilo, "B" => Prefix::One, x => { return Err(BlockError( "disk_space".to_string(), format!("cannot set unit to '{}'", x), )) } }, warning: block_config.warning, alert: block_config.alert, alert_absolute: block_config.alert_absolute, icon: icon.trim().to_string(), alias: block_config.alias, }) } } impl Block for DiskSpace { fn update(&mut self) -> Result<Option<Update>> { let statvfs = statvfs(Path::new(self.path.as_str())) .block_error("disk_space", "failed to retrieve statvfs")?; let total = (statvfs.blocks() as u64) * (statvfs.fragment_size() as u64); let used = ((statvfs.blocks() as u64) - (statvfs.blocks_free() as u64)) * (statvfs.fragment_size() as u64); let available = (statvfs.blocks_available() as u64) * (statvfs.block_size() as u64); let free = (statvfs.blocks_free() as u64) * (statvfs.block_size() as u64); let result; let alert_type; match self.info_type { InfoType::Available => { result = available as f64; alert_type = AlertType::Below; } InfoType::Free => { result = free as f64; alert_type = AlertType::Below; } InfoType::Used => { result = used as f64; alert_type = AlertType::Above; } } let percentage = result / (total as f64) * 100.; let values = map!( "percentage" => Value::from_float(percentage).percents(), "path" => Value::from_string(self.path.clone()), "total" => Value::from_float(total as f64).bytes(), "used" => Value::from_float(used as f64).bytes(), "available" => Value::from_float(available as f64).bytes(), "free" => Value::from_float(free as f64).bytes(), "icon" => Value::from_string(self.icon.to_string()), //TODO remove "alias" => Value::from_string(self.alias.clone()), ); self.disk_space.set_texts(self.format.render(&values)?); // Send percentage to alert check if we don't want absolute alerts let alert_val = if self.alert_absolute { result / match self.unit { Prefix::Tera => 1u64 << 40, Prefix::Giga => 1u64 << 30, Prefix::Mega => 1u64 << 20, Prefix::Kilo => 1u64 << 10, Prefix::One => 1u64, _ => unreachable!(), } as f64 } else { percentage }; let state = self.compute_state(alert_val, self.warning, self.alert, alert_type); self.disk_space.set_state(state); Ok(Some(self.update_interval.into())) } fn view(&self) -> Vec<&dyn I3BarWidget> { vec![&self.disk_space] } fn id(&self) -> usize { self.id } }
DiskSpace
identifier_name
disk_space.rs
use std::path::Path; use std::time::Duration; use crossbeam_channel::Sender; use nix::sys::statvfs::statvfs; use serde_derive::Deserialize; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::errors::*; use crate::formatting::FormatTemplate; use crate::formatting::{prefix::Prefix, value::Value}; use crate::scheduler::Task; use crate::widgets::text::TextWidget; use crate::widgets::{I3BarWidget, State}; #[derive(Copy, Clone, Debug, Deserialize)] #[serde(rename_all = "lowercase")] pub enum InfoType { Available, Free, Used, } pub struct DiskSpace { id: usize, disk_space: TextWidget, update_interval: Duration, path: String, unit: Prefix, info_type: InfoType, warning: f64, alert: f64, alert_absolute: bool, format: FormatTemplate, icon: String, // DEPRECATED // TODO remove alias: String, } #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields, default)] pub struct DiskSpaceConfig { /// Path to collect information from pub path: String, /// Currently supported options are available, free, total and used /// Sets value used for {percentage} calculation /// total is the same as used, use format to set format string for output pub info_type: InfoType, /// Format string for output pub format: FormatTemplate, /// Unit that is used to display disk space. Options are B, KB, MB, GB and TB pub unit: String, /// Update interval in seconds #[serde(deserialize_with = "deserialize_duration")] pub interval: Duration, /// Diskspace warning (yellow) pub warning: f64, /// Diskspace alert (red) pub alert: f64, /// use absolute (unit) values for disk space alerts pub alert_absolute: bool, /// Alias that is displayed for path // DEPRECATED // TODO remove pub alias: String, } impl Default for DiskSpaceConfig { fn default() -> Self { Self { path: "/".to_string(), info_type: InfoType::Available, format: FormatTemplate::default(), unit: "GB".to_string(), interval: Duration::from_secs(20), warning: 20., alert: 10., alert_absolute: false, alias: "/".to_string(), } } } enum AlertType { Above, Below, } impl DiskSpace { fn compute_state(&self, value: f64, warning: f64, alert: f64, alert_type: AlertType) -> State { match alert_type { AlertType::Above => { if value > alert { State::Critical } else if value <= alert && value > warning { State::Warning } else { State::Idle } } AlertType::Below => { if 0. <= value && value < alert { State::Critical } else if alert <= value && value < warning { State::Warning } else { State::Idle } } } } } impl ConfigBlock for DiskSpace { type Config = DiskSpaceConfig; fn new( id: usize, block_config: Self::Config, shared_config: SharedConfig, _tx_update_request: Sender<Task>, ) -> Result<Self> { let icon = shared_config.get_icon("disk_drive")?; Ok(DiskSpace { id, update_interval: block_config.interval, disk_space: TextWidget::new(id, 0, shared_config), path: block_config.path, format: block_config.format.with_default("{available}")?, info_type: block_config.info_type, unit: match block_config.unit.as_str() { "TB" => Prefix::Tera, "GB" => Prefix::Giga, "MB" => Prefix::Mega, "KB" => Prefix::Kilo, "B" => Prefix::One, x => { return Err(BlockError( "disk_space".to_string(), format!("cannot set unit to '{}'", x), )) } }, warning: block_config.warning, alert: block_config.alert, alert_absolute: block_config.alert_absolute, icon: icon.trim().to_string(), alias: block_config.alias, }) } } impl Block for DiskSpace { fn update(&mut self) -> Result<Option<Update>> { let statvfs = statvfs(Path::new(self.path.as_str())) .block_error("disk_space", "failed to retrieve statvfs")?; let total = (statvfs.blocks() as u64) * (statvfs.fragment_size() as u64); let used = ((statvfs.blocks() as u64) - (statvfs.blocks_free() as u64)) * (statvfs.fragment_size() as u64); let available = (statvfs.blocks_available() as u64) * (statvfs.block_size() as u64); let free = (statvfs.blocks_free() as u64) * (statvfs.block_size() as u64); let result; let alert_type; match self.info_type { InfoType::Available => { result = available as f64; alert_type = AlertType::Below; } InfoType::Free => { result = free as f64; alert_type = AlertType::Below; } InfoType::Used => { result = used as f64; alert_type = AlertType::Above; } } let percentage = result / (total as f64) * 100.; let values = map!( "percentage" => Value::from_float(percentage).percents(), "path" => Value::from_string(self.path.clone()), "total" => Value::from_float(total as f64).bytes(), "used" => Value::from_float(used as f64).bytes(), "available" => Value::from_float(available as f64).bytes(), "free" => Value::from_float(free as f64).bytes(), "icon" => Value::from_string(self.icon.to_string()), //TODO remove "alias" => Value::from_string(self.alias.clone()), ); self.disk_space.set_texts(self.format.render(&values)?); // Send percentage to alert check if we don't want absolute alerts let alert_val = if self.alert_absolute { result / match self.unit { Prefix::Tera => 1u64 << 40, Prefix::Giga => 1u64 << 30, Prefix::Mega => 1u64 << 20, Prefix::Kilo => 1u64 << 10, Prefix::One => 1u64, _ => unreachable!(), } as f64 } else
; let state = self.compute_state(alert_val, self.warning, self.alert, alert_type); self.disk_space.set_state(state); Ok(Some(self.update_interval.into())) } fn view(&self) -> Vec<&dyn I3BarWidget> { vec![&self.disk_space] } fn id(&self) -> usize { self.id } }
{ percentage }
conditional_block
disk_space.rs
use std::path::Path; use std::time::Duration; use crossbeam_channel::Sender; use nix::sys::statvfs::statvfs; use serde_derive::Deserialize; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::errors::*; use crate::formatting::FormatTemplate; use crate::formatting::{prefix::Prefix, value::Value}; use crate::scheduler::Task; use crate::widgets::text::TextWidget; use crate::widgets::{I3BarWidget, State}; #[derive(Copy, Clone, Debug, Deserialize)] #[serde(rename_all = "lowercase")] pub enum InfoType { Available, Free, Used, } pub struct DiskSpace { id: usize, disk_space: TextWidget, update_interval: Duration, path: String, unit: Prefix, info_type: InfoType, warning: f64, alert: f64, alert_absolute: bool, format: FormatTemplate, icon: String, // DEPRECATED // TODO remove alias: String, } #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields, default)] pub struct DiskSpaceConfig { /// Path to collect information from pub path: String, /// Currently supported options are available, free, total and used /// Sets value used for {percentage} calculation /// total is the same as used, use format to set format string for output pub info_type: InfoType, /// Format string for output pub format: FormatTemplate, /// Unit that is used to display disk space. Options are B, KB, MB, GB and TB pub unit: String, /// Update interval in seconds #[serde(deserialize_with = "deserialize_duration")] pub interval: Duration, /// Diskspace warning (yellow) pub warning: f64, /// Diskspace alert (red) pub alert: f64, /// use absolute (unit) values for disk space alerts pub alert_absolute: bool, /// Alias that is displayed for path // DEPRECATED // TODO remove pub alias: String, } impl Default for DiskSpaceConfig { fn default() -> Self { Self { path: "/".to_string(), info_type: InfoType::Available, format: FormatTemplate::default(), unit: "GB".to_string(), interval: Duration::from_secs(20), warning: 20., alert: 10., alert_absolute: false, alias: "/".to_string(), } } } enum AlertType { Above, Below, } impl DiskSpace { fn compute_state(&self, value: f64, warning: f64, alert: f64, alert_type: AlertType) -> State { match alert_type { AlertType::Above => { if value > alert { State::Critical } else if value <= alert && value > warning { State::Warning } else { State::Idle } } AlertType::Below => { if 0. <= value && value < alert { State::Critical } else if alert <= value && value < warning { State::Warning } else { State::Idle } } } } } impl ConfigBlock for DiskSpace { type Config = DiskSpaceConfig; fn new( id: usize, block_config: Self::Config, shared_config: SharedConfig, _tx_update_request: Sender<Task>, ) -> Result<Self> { let icon = shared_config.get_icon("disk_drive")?; Ok(DiskSpace { id, update_interval: block_config.interval, disk_space: TextWidget::new(id, 0, shared_config), path: block_config.path, format: block_config.format.with_default("{available}")?, info_type: block_config.info_type, unit: match block_config.unit.as_str() { "TB" => Prefix::Tera, "GB" => Prefix::Giga, "MB" => Prefix::Mega, "KB" => Prefix::Kilo, "B" => Prefix::One, x => { return Err(BlockError( "disk_space".to_string(), format!("cannot set unit to '{}'", x), )) } }, warning: block_config.warning, alert: block_config.alert, alert_absolute: block_config.alert_absolute, icon: icon.trim().to_string(), alias: block_config.alias, }) }
impl Block for DiskSpace { fn update(&mut self) -> Result<Option<Update>> { let statvfs = statvfs(Path::new(self.path.as_str())) .block_error("disk_space", "failed to retrieve statvfs")?; let total = (statvfs.blocks() as u64) * (statvfs.fragment_size() as u64); let used = ((statvfs.blocks() as u64) - (statvfs.blocks_free() as u64)) * (statvfs.fragment_size() as u64); let available = (statvfs.blocks_available() as u64) * (statvfs.block_size() as u64); let free = (statvfs.blocks_free() as u64) * (statvfs.block_size() as u64); let result; let alert_type; match self.info_type { InfoType::Available => { result = available as f64; alert_type = AlertType::Below; } InfoType::Free => { result = free as f64; alert_type = AlertType::Below; } InfoType::Used => { result = used as f64; alert_type = AlertType::Above; } } let percentage = result / (total as f64) * 100.; let values = map!( "percentage" => Value::from_float(percentage).percents(), "path" => Value::from_string(self.path.clone()), "total" => Value::from_float(total as f64).bytes(), "used" => Value::from_float(used as f64).bytes(), "available" => Value::from_float(available as f64).bytes(), "free" => Value::from_float(free as f64).bytes(), "icon" => Value::from_string(self.icon.to_string()), //TODO remove "alias" => Value::from_string(self.alias.clone()), ); self.disk_space.set_texts(self.format.render(&values)?); // Send percentage to alert check if we don't want absolute alerts let alert_val = if self.alert_absolute { result / match self.unit { Prefix::Tera => 1u64 << 40, Prefix::Giga => 1u64 << 30, Prefix::Mega => 1u64 << 20, Prefix::Kilo => 1u64 << 10, Prefix::One => 1u64, _ => unreachable!(), } as f64 } else { percentage }; let state = self.compute_state(alert_val, self.warning, self.alert, alert_type); self.disk_space.set_state(state); Ok(Some(self.update_interval.into())) } fn view(&self) -> Vec<&dyn I3BarWidget> { vec![&self.disk_space] } fn id(&self) -> usize { self.id } }
}
random_line_split
async-fn-multiple-lifetimes.rs
// Copyright 2018 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. // edition:2018 #![feature(arbitrary_self_types, async_await, await_macro, futures_api, pin)] use std::ops::Add; async fn multiple_named_lifetimes<'a, 'b>(_: &'a u8, _: &'b u8) {} //~^ ERROR multiple different lifetimes used in arguments of `async fn`
_: impl for<'b> Add<&'b u8>, _: &'c u8, ) {} async fn multiple_elided_lifetimes(_: &u8, _: &u8) {} //~^ ERROR multiple elided lifetimes used //~^^ ERROR missing lifetime specifier fn main() {}
async fn multiple_hrtb_and_single_named_lifetime_ok<'c>( _: impl for<'a> Add<&'a u8>,
random_line_split
async-fn-multiple-lifetimes.rs
// Copyright 2018 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. // edition:2018 #![feature(arbitrary_self_types, async_await, await_macro, futures_api, pin)] use std::ops::Add; async fn multiple_named_lifetimes<'a, 'b>(_: &'a u8, _: &'b u8) {} //~^ ERROR multiple different lifetimes used in arguments of `async fn` async fn multiple_hrtb_and_single_named_lifetime_ok<'c>( _: impl for<'a> Add<&'a u8>, _: impl for<'b> Add<&'b u8>, _: &'c u8, )
async fn multiple_elided_lifetimes(_: &u8, _: &u8) {} //~^ ERROR multiple elided lifetimes used //~^^ ERROR missing lifetime specifier fn main() {}
{}
identifier_body
async-fn-multiple-lifetimes.rs
// Copyright 2018 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. // edition:2018 #![feature(arbitrary_self_types, async_await, await_macro, futures_api, pin)] use std::ops::Add; async fn multiple_named_lifetimes<'a, 'b>(_: &'a u8, _: &'b u8) {} //~^ ERROR multiple different lifetimes used in arguments of `async fn` async fn multiple_hrtb_and_single_named_lifetime_ok<'c>( _: impl for<'a> Add<&'a u8>, _: impl for<'b> Add<&'b u8>, _: &'c u8, ) {} async fn
(_: &u8, _: &u8) {} //~^ ERROR multiple elided lifetimes used //~^^ ERROR missing lifetime specifier fn main() {}
multiple_elided_lifetimes
identifier_name
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn incr(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main() { let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; println!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x { assert!((true)); } else
}
{ assert!((false)); }
conditional_block
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// except according to those terms. fn incr(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main() { let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; println!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x { assert!((true)); } else { assert!((false)); } }
// // 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
random_line_split
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn incr(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main()
{ let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; println!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x { assert!((true)); } else { assert!((false)); } }
identifier_body
lazy-and-or.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn
(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main() { let x = 1 == 2 || 3 == 3; assert!((x)); let mut y: int = 10; println!("{:?}", x || incr(&mut y)); assert_eq!(y, 10); if true && x { assert!((true)); } else { assert!((false)); } }
incr
identifier_name
cube.rs
#[macro_use] extern crate glium; extern crate arcball; extern crate cgmath; use arcball::ArcballCamera; use cgmath::{Vector2, Vector3}; use glium::index::PrimitiveType; use glium::{glutin, Surface}; #[derive(Copy, Clone)] struct
{ pos: [f32; 3], color: [f32; 3], } implement_vertex!(Vertex, pos, color); // NOTE: This is still provided as an example of how to hook up mouse events // to the camera, however it should eventually be replaced by one using // device events (I think) since window events don't seem to fire often fn main() { let window = glutin::window::WindowBuilder::new().with_title("Arcball Camera Cube Example"); let context = glutin::ContextBuilder::new() .with_vsync(true); let event_loop = glutin::event_loop::EventLoop::new(); let display = glium::Display::new(window, context, &event_loop).expect("failed to create display"); // Hard-coded cube triangle strip let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { pos: [1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, ], ) .unwrap(); let index_buffer = glium::index::NoIndices(PrimitiveType::TriangleStrip); let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 proj_view; in vec3 pos; in vec3 color; out vec3 vcolor; void main(void) { gl_Position = proj_view * vec4(pos, 1.0); vcolor = color; } ", fragment: " #version 140 in vec3 vcolor; out vec4 color; void main(void) { color = vec4(vcolor, 1.0); } " }, ) .unwrap(); let display_dims = display.get_framebuffer_dimensions(); let persp_proj = cgmath::perspective( cgmath::Deg(65.0), display_dims.0 as f32 / display_dims.1 as f32, 1.0, 200.0, ); let mut arcball_camera = ArcballCamera::new( Vector3::new(0.0, 0.0, 0.0), 1.0, [display_dims.0 as f32, display_dims.1 as f32], ); // Track if left/right mouse is down let mut mouse_pressed = [false, false]; let mut prev_mouse = None; event_loop.run(move |event, _, control_flow| { let mut should_quit = false; println!("running"); match event { glutin::event::Event::WindowEvent { event,.. } => match event { glutin::event::WindowEvent::CloseRequested => should_quit = true, glutin::event::WindowEvent::KeyboardInput { input,.. } => match input.virtual_keycode { Some(glutin::event::VirtualKeyCode::Escape) => should_quit = true, _ => {} }, glutin::event::WindowEvent::CursorMoved { position,.. } if prev_mouse.is_none() => { prev_mouse = Some(position); println!("init mouse = {:?}", prev_mouse); } glutin::event::WindowEvent::CursorMoved { position,.. } => { let prev = prev_mouse.unwrap(); if mouse_pressed[0] { arcball_camera.rotate( Vector2::new(prev.x as f32, prev.y as f32), Vector2::new(position.x as f32, position.y as f32), ); } else if mouse_pressed[1] { let mouse_delta = Vector2::new( (position.x - prev.x) as f32, (position.y - prev.y) as f32, ); arcball_camera.pan(mouse_delta); } prev_mouse = Some(position); println!("prev = {:?}", prev_mouse); } glutin::event::WindowEvent::MouseInput { state, button,.. } => { if button == glutin::event::MouseButton::Left { mouse_pressed[0] = state == glutin::event::ElementState::Pressed; } else if button == glutin::event::MouseButton::Right { mouse_pressed[1] = state == glutin::event::ElementState::Pressed; } } glutin::event::WindowEvent::MouseWheel { delta,.. } => { let y = match delta { glutin::event::MouseScrollDelta::LineDelta(_, y) => y, glutin::event::MouseScrollDelta::PixelDelta(p) => p.y as f32, }; arcball_camera.zoom(y, 0.16); } _ => {} }, _ => {} } *control_flow = if should_quit { glutin::event_loop::ControlFlow::Exit } else { glutin::event_loop::ControlFlow::Poll }; let proj_view: [[f32; 4]; 4] = (persp_proj * arcball_camera.get_mat4()).into(); let uniforms = uniform! { proj_view: proj_view, }; let draw_params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ..Default::default() }, ..Default::default() }; let mut target = display.draw(); target.clear_color(0.1, 0.1, 0.1, 0.0); target.clear_depth(1.0); target .draw( &vertex_buffer, &index_buffer, &program, &uniforms, &draw_params, ) .unwrap(); target.finish().unwrap(); }); }
Vertex
identifier_name
cube.rs
#[macro_use] extern crate glium; extern crate arcball; extern crate cgmath; use arcball::ArcballCamera; use cgmath::{Vector2, Vector3}; use glium::index::PrimitiveType; use glium::{glutin, Surface}; #[derive(Copy, Clone)] struct Vertex { pos: [f32; 3], color: [f32; 3], } implement_vertex!(Vertex, pos, color); // NOTE: This is still provided as an example of how to hook up mouse events // to the camera, however it should eventually be replaced by one using // device events (I think) since window events don't seem to fire often fn main() { let window = glutin::window::WindowBuilder::new().with_title("Arcball Camera Cube Example"); let context = glutin::ContextBuilder::new() .with_vsync(true); let event_loop = glutin::event_loop::EventLoop::new(); let display = glium::Display::new(window, context, &event_loop).expect("failed to create display"); // Hard-coded cube triangle strip let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { pos: [1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, ], ) .unwrap(); let index_buffer = glium::index::NoIndices(PrimitiveType::TriangleStrip); let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 proj_view; in vec3 pos; in vec3 color; out vec3 vcolor; void main(void) { gl_Position = proj_view * vec4(pos, 1.0); vcolor = color; } ", fragment: " #version 140 in vec3 vcolor; out vec4 color; void main(void) { color = vec4(vcolor, 1.0); } " }, ) .unwrap(); let display_dims = display.get_framebuffer_dimensions(); let persp_proj = cgmath::perspective( cgmath::Deg(65.0), display_dims.0 as f32 / display_dims.1 as f32, 1.0, 200.0, ); let mut arcball_camera = ArcballCamera::new( Vector3::new(0.0, 0.0, 0.0), 1.0, [display_dims.0 as f32, display_dims.1 as f32], ); // Track if left/right mouse is down let mut mouse_pressed = [false, false]; let mut prev_mouse = None; event_loop.run(move |event, _, control_flow| { let mut should_quit = false; println!("running"); match event { glutin::event::Event::WindowEvent { event,.. } => match event { glutin::event::WindowEvent::CloseRequested => should_quit = true, glutin::event::WindowEvent::KeyboardInput { input,.. } => match input.virtual_keycode { Some(glutin::event::VirtualKeyCode::Escape) => should_quit = true, _ => {} }, glutin::event::WindowEvent::CursorMoved { position,.. } if prev_mouse.is_none() => { prev_mouse = Some(position); println!("init mouse = {:?}", prev_mouse); } glutin::event::WindowEvent::CursorMoved { position,.. } => { let prev = prev_mouse.unwrap(); if mouse_pressed[0] { arcball_camera.rotate( Vector2::new(prev.x as f32, prev.y as f32), Vector2::new(position.x as f32, position.y as f32), ); } else if mouse_pressed[1] { let mouse_delta = Vector2::new( (position.x - prev.x) as f32, (position.y - prev.y) as f32, );
println!("prev = {:?}", prev_mouse); } glutin::event::WindowEvent::MouseInput { state, button,.. } => { if button == glutin::event::MouseButton::Left { mouse_pressed[0] = state == glutin::event::ElementState::Pressed; } else if button == glutin::event::MouseButton::Right { mouse_pressed[1] = state == glutin::event::ElementState::Pressed; } } glutin::event::WindowEvent::MouseWheel { delta,.. } => { let y = match delta { glutin::event::MouseScrollDelta::LineDelta(_, y) => y, glutin::event::MouseScrollDelta::PixelDelta(p) => p.y as f32, }; arcball_camera.zoom(y, 0.16); } _ => {} }, _ => {} } *control_flow = if should_quit { glutin::event_loop::ControlFlow::Exit } else { glutin::event_loop::ControlFlow::Poll }; let proj_view: [[f32; 4]; 4] = (persp_proj * arcball_camera.get_mat4()).into(); let uniforms = uniform! { proj_view: proj_view, }; let draw_params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ..Default::default() }, ..Default::default() }; let mut target = display.draw(); target.clear_color(0.1, 0.1, 0.1, 0.0); target.clear_depth(1.0); target .draw( &vertex_buffer, &index_buffer, &program, &uniforms, &draw_params, ) .unwrap(); target.finish().unwrap(); }); }
arcball_camera.pan(mouse_delta); } prev_mouse = Some(position);
random_line_split
cube.rs
#[macro_use] extern crate glium; extern crate arcball; extern crate cgmath; use arcball::ArcballCamera; use cgmath::{Vector2, Vector3}; use glium::index::PrimitiveType; use glium::{glutin, Surface}; #[derive(Copy, Clone)] struct Vertex { pos: [f32; 3], color: [f32; 3], } implement_vertex!(Vertex, pos, color); // NOTE: This is still provided as an example of how to hook up mouse events // to the camera, however it should eventually be replaced by one using // device events (I think) since window events don't seem to fire often fn main() { let window = glutin::window::WindowBuilder::new().with_title("Arcball Camera Cube Example"); let context = glutin::ContextBuilder::new() .with_vsync(true); let event_loop = glutin::event_loop::EventLoop::new(); let display = glium::Display::new(window, context, &event_loop).expect("failed to create display"); // Hard-coded cube triangle strip let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { pos: [1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, ], ) .unwrap(); let index_buffer = glium::index::NoIndices(PrimitiveType::TriangleStrip); let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 proj_view; in vec3 pos; in vec3 color; out vec3 vcolor; void main(void) { gl_Position = proj_view * vec4(pos, 1.0); vcolor = color; } ", fragment: " #version 140 in vec3 vcolor; out vec4 color; void main(void) { color = vec4(vcolor, 1.0); } " }, ) .unwrap(); let display_dims = display.get_framebuffer_dimensions(); let persp_proj = cgmath::perspective( cgmath::Deg(65.0), display_dims.0 as f32 / display_dims.1 as f32, 1.0, 200.0, ); let mut arcball_camera = ArcballCamera::new( Vector3::new(0.0, 0.0, 0.0), 1.0, [display_dims.0 as f32, display_dims.1 as f32], ); // Track if left/right mouse is down let mut mouse_pressed = [false, false]; let mut prev_mouse = None; event_loop.run(move |event, _, control_flow| { let mut should_quit = false; println!("running"); match event { glutin::event::Event::WindowEvent { event,.. } => match event { glutin::event::WindowEvent::CloseRequested => should_quit = true, glutin::event::WindowEvent::KeyboardInput { input,.. } => match input.virtual_keycode { Some(glutin::event::VirtualKeyCode::Escape) => should_quit = true, _ => {} }, glutin::event::WindowEvent::CursorMoved { position,.. } if prev_mouse.is_none() => { prev_mouse = Some(position); println!("init mouse = {:?}", prev_mouse); } glutin::event::WindowEvent::CursorMoved { position,.. } =>
glutin::event::WindowEvent::MouseInput { state, button,.. } => { if button == glutin::event::MouseButton::Left { mouse_pressed[0] = state == glutin::event::ElementState::Pressed; } else if button == glutin::event::MouseButton::Right { mouse_pressed[1] = state == glutin::event::ElementState::Pressed; } } glutin::event::WindowEvent::MouseWheel { delta,.. } => { let y = match delta { glutin::event::MouseScrollDelta::LineDelta(_, y) => y, glutin::event::MouseScrollDelta::PixelDelta(p) => p.y as f32, }; arcball_camera.zoom(y, 0.16); } _ => {} }, _ => {} } *control_flow = if should_quit { glutin::event_loop::ControlFlow::Exit } else { glutin::event_loop::ControlFlow::Poll }; let proj_view: [[f32; 4]; 4] = (persp_proj * arcball_camera.get_mat4()).into(); let uniforms = uniform! { proj_view: proj_view, }; let draw_params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ..Default::default() }, ..Default::default() }; let mut target = display.draw(); target.clear_color(0.1, 0.1, 0.1, 0.0); target.clear_depth(1.0); target .draw( &vertex_buffer, &index_buffer, &program, &uniforms, &draw_params, ) .unwrap(); target.finish().unwrap(); }); }
{ let prev = prev_mouse.unwrap(); if mouse_pressed[0] { arcball_camera.rotate( Vector2::new(prev.x as f32, prev.y as f32), Vector2::new(position.x as f32, position.y as f32), ); } else if mouse_pressed[1] { let mouse_delta = Vector2::new( (position.x - prev.x) as f32, (position.y - prev.y) as f32, ); arcball_camera.pan(mouse_delta); } prev_mouse = Some(position); println!("prev = {:?}", prev_mouse); }
conditional_block
cube.rs
#[macro_use] extern crate glium; extern crate arcball; extern crate cgmath; use arcball::ArcballCamera; use cgmath::{Vector2, Vector3}; use glium::index::PrimitiveType; use glium::{glutin, Surface}; #[derive(Copy, Clone)] struct Vertex { pos: [f32; 3], color: [f32; 3], } implement_vertex!(Vertex, pos, color); // NOTE: This is still provided as an example of how to hook up mouse events // to the camera, however it should eventually be replaced by one using // device events (I think) since window events don't seem to fire often fn main()
}, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [0.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0], }, Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [-1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0], }, Vertex { pos: [1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, Vertex { pos: [-1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0], }, ], ) .unwrap(); let index_buffer = glium::index::NoIndices(PrimitiveType::TriangleStrip); let program = program!(&display, 140 => { vertex: " #version 140 uniform mat4 proj_view; in vec3 pos; in vec3 color; out vec3 vcolor; void main(void) { gl_Position = proj_view * vec4(pos, 1.0); vcolor = color; } ", fragment: " #version 140 in vec3 vcolor; out vec4 color; void main(void) { color = vec4(vcolor, 1.0); } " }, ) .unwrap(); let display_dims = display.get_framebuffer_dimensions(); let persp_proj = cgmath::perspective( cgmath::Deg(65.0), display_dims.0 as f32 / display_dims.1 as f32, 1.0, 200.0, ); let mut arcball_camera = ArcballCamera::new( Vector3::new(0.0, 0.0, 0.0), 1.0, [display_dims.0 as f32, display_dims.1 as f32], ); // Track if left/right mouse is down let mut mouse_pressed = [false, false]; let mut prev_mouse = None; event_loop.run(move |event, _, control_flow| { let mut should_quit = false; println!("running"); match event { glutin::event::Event::WindowEvent { event,.. } => match event { glutin::event::WindowEvent::CloseRequested => should_quit = true, glutin::event::WindowEvent::KeyboardInput { input,.. } => match input.virtual_keycode { Some(glutin::event::VirtualKeyCode::Escape) => should_quit = true, _ => {} }, glutin::event::WindowEvent::CursorMoved { position,.. } if prev_mouse.is_none() => { prev_mouse = Some(position); println!("init mouse = {:?}", prev_mouse); } glutin::event::WindowEvent::CursorMoved { position,.. } => { let prev = prev_mouse.unwrap(); if mouse_pressed[0] { arcball_camera.rotate( Vector2::new(prev.x as f32, prev.y as f32), Vector2::new(position.x as f32, position.y as f32), ); } else if mouse_pressed[1] { let mouse_delta = Vector2::new( (position.x - prev.x) as f32, (position.y - prev.y) as f32, ); arcball_camera.pan(mouse_delta); } prev_mouse = Some(position); println!("prev = {:?}", prev_mouse); } glutin::event::WindowEvent::MouseInput { state, button,.. } => { if button == glutin::event::MouseButton::Left { mouse_pressed[0] = state == glutin::event::ElementState::Pressed; } else if button == glutin::event::MouseButton::Right { mouse_pressed[1] = state == glutin::event::ElementState::Pressed; } } glutin::event::WindowEvent::MouseWheel { delta,.. } => { let y = match delta { glutin::event::MouseScrollDelta::LineDelta(_, y) => y, glutin::event::MouseScrollDelta::PixelDelta(p) => p.y as f32, }; arcball_camera.zoom(y, 0.16); } _ => {} }, _ => {} } *control_flow = if should_quit { glutin::event_loop::ControlFlow::Exit } else { glutin::event_loop::ControlFlow::Poll }; let proj_view: [[f32; 4]; 4] = (persp_proj * arcball_camera.get_mat4()).into(); let uniforms = uniform! { proj_view: proj_view, }; let draw_params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ..Default::default() }, ..Default::default() }; let mut target = display.draw(); target.clear_color(0.1, 0.1, 0.1, 0.0); target.clear_depth(1.0); target .draw( &vertex_buffer, &index_buffer, &program, &uniforms, &draw_params, ) .unwrap(); target.finish().unwrap(); }); }
{ let window = glutin::window::WindowBuilder::new().with_title("Arcball Camera Cube Example"); let context = glutin::ContextBuilder::new() .with_vsync(true); let event_loop = glutin::event_loop::EventLoop::new(); let display = glium::Display::new(window, context, &event_loop).expect("failed to create display"); // Hard-coded cube triangle strip let vertex_buffer = glium::VertexBuffer::new( &display, &[ Vertex { pos: [1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0], }, Vertex { pos: [-1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0],
identifier_body
errors.rs
use std::convert::{self, From}; use std::error; use std::fmt; use std::io; use std::string; use std::sync; use rusty_leveldb::Status; use crate::blockchain::proto::script; /// Returns a string with filename, current code line and column macro_rules! line_mark { () => { format!("Marked line: {} @ {}:{}", file!(), line!(), column!()) }; } /// Transforms a Option to Result /// If the Option contains None, a line mark will be placed along with OpErrorKind::None macro_rules! transform { ($e:expr) => {{ $e.ok_or(OpError::new(OpErrorKind::None).join_msg(&line_mark!()))? }}; } pub type OpResult<T> = Result<T, OpError>; #[derive(Debug)] /// Custom error type pub struct OpError { pub kind: OpErrorKind, pub message: String, } impl OpError { pub fn new(kind: OpErrorKind) -> Self { OpError { kind, message: String::new(), } } /// Joins the Error with a new message and returns it pub fn join_msg(mut self, msg: &str) -> Self { self.message.push_str(msg); OpError { kind: self.kind, message: self.message, } } } impl fmt::Display for OpError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.message.is_empty() { write!(f, "{}", &self.kind) } else { write!(f, "{} {}", &self.message, &self.kind) } } } impl error::Error for OpError { fn description(&self) -> &str {
} } #[derive(Debug)] pub enum OpErrorKind { None, IoError(io::Error), ByteOrderError(io::Error), Utf8Error(string::FromUtf8Error), ScriptError(script::ScriptError), InvalidArgsError, CallbackError, ValidateError, RuntimeError, PoisonError, SendError, LevelDBError(String), } impl fmt::Display for OpErrorKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpErrorKind::IoError(ref err) => write!(f, "I/O Error: {}", err), OpErrorKind::ByteOrderError(ref err) => write!(f, "ByteOrder: {}", err), OpErrorKind::Utf8Error(ref err) => write!(f, "Utf8 Conversion: {}", err), OpErrorKind::ScriptError(ref err) => write!(f, "Script: {}", err), OpErrorKind::LevelDBError(ref err) => write!(f, "LevelDB: {}", err), ref err @ OpErrorKind::PoisonError => write!(f, "Threading Error: {}", err), ref err @ OpErrorKind::SendError => write!(f, "Sync: {}", err), ref err @ OpErrorKind::InvalidArgsError => write!(f, "InvalidArgs: {}", err), ref err @ OpErrorKind::CallbackError => write!(f, "Callback: {}", err), ref err @ OpErrorKind::ValidateError => write!(f, "Validation: {}", err), ref err @ OpErrorKind::RuntimeError => write!(f, "RuntimeError: {}", err), OpErrorKind::None => write!(f, ""), } } } impl error::Error for OpErrorKind { fn source(&self) -> Option<&(dyn error::Error +'static)> { match *self { OpErrorKind::IoError(ref err) => Some(err), OpErrorKind::ByteOrderError(ref err) => Some(err), OpErrorKind::Utf8Error(ref err) => Some(err), OpErrorKind::ScriptError(ref err) => Some(err), ref err @ OpErrorKind::PoisonError => Some(err), ref err @ OpErrorKind::SendError => Some(err), _ => None, } } } impl From<io::Error> for OpError { fn from(err: io::Error) -> Self { Self::new(OpErrorKind::IoError(err)) } } impl convert::From<i32> for OpError { fn from(err_code: i32) -> Self { Self::from(io::Error::from_raw_os_error(err_code)) } } impl convert::From<String> for OpError { fn from(err: String) -> Self { Self::new(OpErrorKind::None).join_msg(&err) } } impl<T> convert::From<sync::PoisonError<T>> for OpError { fn from(_: sync::PoisonError<T>) -> Self { Self::new(OpErrorKind::PoisonError) } } impl<T> convert::From<sync::mpsc::SendError<T>> for OpError { fn from(_: sync::mpsc::SendError<T>) -> Self { Self::new(OpErrorKind::SendError) } } impl convert::From<string::FromUtf8Error> for OpError { fn from(err: string::FromUtf8Error) -> Self { Self::new(OpErrorKind::Utf8Error(err)) } } impl convert::From<rusty_leveldb::Status> for OpError { fn from(status: Status) -> Self { Self::new(OpErrorKind::LevelDBError(status.err)) } } #[cfg(test)] mod tests { use super::*; use std::io; #[test] fn test_op_error() { let kind = io::Error::new(io::ErrorKind::BrokenPipe, "oh no!"); let err = OpError::from(kind); assert_eq!(format!("{}", err), "I/O Error: oh no!"); let err = err.join_msg("Cannot proceed."); assert_eq!(format!("{}", err), "Cannot proceed. I/O Error: oh no!"); } }
self.message.as_ref() } fn cause(&self) -> Option<&dyn error::Error> { self.kind.source()
random_line_split
errors.rs
use std::convert::{self, From}; use std::error; use std::fmt; use std::io; use std::string; use std::sync; use rusty_leveldb::Status; use crate::blockchain::proto::script; /// Returns a string with filename, current code line and column macro_rules! line_mark { () => { format!("Marked line: {} @ {}:{}", file!(), line!(), column!()) }; } /// Transforms a Option to Result /// If the Option contains None, a line mark will be placed along with OpErrorKind::None macro_rules! transform { ($e:expr) => {{ $e.ok_or(OpError::new(OpErrorKind::None).join_msg(&line_mark!()))? }}; } pub type OpResult<T> = Result<T, OpError>; #[derive(Debug)] /// Custom error type pub struct OpError { pub kind: OpErrorKind, pub message: String, } impl OpError { pub fn new(kind: OpErrorKind) -> Self { OpError { kind, message: String::new(), } } /// Joins the Error with a new message and returns it pub fn join_msg(mut self, msg: &str) -> Self { self.message.push_str(msg); OpError { kind: self.kind, message: self.message, } } } impl fmt::Display for OpError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.message.is_empty() { write!(f, "{}", &self.kind) } else { write!(f, "{} {}", &self.message, &self.kind) } } } impl error::Error for OpError { fn description(&self) -> &str { self.message.as_ref() } fn cause(&self) -> Option<&dyn error::Error> { self.kind.source() } } #[derive(Debug)] pub enum OpErrorKind { None, IoError(io::Error), ByteOrderError(io::Error), Utf8Error(string::FromUtf8Error), ScriptError(script::ScriptError), InvalidArgsError, CallbackError, ValidateError, RuntimeError, PoisonError, SendError, LevelDBError(String), } impl fmt::Display for OpErrorKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpErrorKind::IoError(ref err) => write!(f, "I/O Error: {}", err), OpErrorKind::ByteOrderError(ref err) => write!(f, "ByteOrder: {}", err), OpErrorKind::Utf8Error(ref err) => write!(f, "Utf8 Conversion: {}", err), OpErrorKind::ScriptError(ref err) => write!(f, "Script: {}", err), OpErrorKind::LevelDBError(ref err) => write!(f, "LevelDB: {}", err), ref err @ OpErrorKind::PoisonError => write!(f, "Threading Error: {}", err), ref err @ OpErrorKind::SendError => write!(f, "Sync: {}", err), ref err @ OpErrorKind::InvalidArgsError => write!(f, "InvalidArgs: {}", err), ref err @ OpErrorKind::CallbackError => write!(f, "Callback: {}", err), ref err @ OpErrorKind::ValidateError => write!(f, "Validation: {}", err), ref err @ OpErrorKind::RuntimeError => write!(f, "RuntimeError: {}", err), OpErrorKind::None => write!(f, ""), } } } impl error::Error for OpErrorKind { fn source(&self) -> Option<&(dyn error::Error +'static)> { match *self { OpErrorKind::IoError(ref err) => Some(err), OpErrorKind::ByteOrderError(ref err) => Some(err), OpErrorKind::Utf8Error(ref err) => Some(err), OpErrorKind::ScriptError(ref err) => Some(err), ref err @ OpErrorKind::PoisonError => Some(err), ref err @ OpErrorKind::SendError => Some(err), _ => None, } } } impl From<io::Error> for OpError { fn from(err: io::Error) -> Self { Self::new(OpErrorKind::IoError(err)) } } impl convert::From<i32> for OpError { fn from(err_code: i32) -> Self { Self::from(io::Error::from_raw_os_error(err_code)) } } impl convert::From<String> for OpError { fn
(err: String) -> Self { Self::new(OpErrorKind::None).join_msg(&err) } } impl<T> convert::From<sync::PoisonError<T>> for OpError { fn from(_: sync::PoisonError<T>) -> Self { Self::new(OpErrorKind::PoisonError) } } impl<T> convert::From<sync::mpsc::SendError<T>> for OpError { fn from(_: sync::mpsc::SendError<T>) -> Self { Self::new(OpErrorKind::SendError) } } impl convert::From<string::FromUtf8Error> for OpError { fn from(err: string::FromUtf8Error) -> Self { Self::new(OpErrorKind::Utf8Error(err)) } } impl convert::From<rusty_leveldb::Status> for OpError { fn from(status: Status) -> Self { Self::new(OpErrorKind::LevelDBError(status.err)) } } #[cfg(test)] mod tests { use super::*; use std::io; #[test] fn test_op_error() { let kind = io::Error::new(io::ErrorKind::BrokenPipe, "oh no!"); let err = OpError::from(kind); assert_eq!(format!("{}", err), "I/O Error: oh no!"); let err = err.join_msg("Cannot proceed."); assert_eq!(format!("{}", err), "Cannot proceed. I/O Error: oh no!"); } }
from
identifier_name
errors.rs
use std::convert::{self, From}; use std::error; use std::fmt; use std::io; use std::string; use std::sync; use rusty_leveldb::Status; use crate::blockchain::proto::script; /// Returns a string with filename, current code line and column macro_rules! line_mark { () => { format!("Marked line: {} @ {}:{}", file!(), line!(), column!()) }; } /// Transforms a Option to Result /// If the Option contains None, a line mark will be placed along with OpErrorKind::None macro_rules! transform { ($e:expr) => {{ $e.ok_or(OpError::new(OpErrorKind::None).join_msg(&line_mark!()))? }}; } pub type OpResult<T> = Result<T, OpError>; #[derive(Debug)] /// Custom error type pub struct OpError { pub kind: OpErrorKind, pub message: String, } impl OpError { pub fn new(kind: OpErrorKind) -> Self { OpError { kind, message: String::new(), } } /// Joins the Error with a new message and returns it pub fn join_msg(mut self, msg: &str) -> Self { self.message.push_str(msg); OpError { kind: self.kind, message: self.message, } } } impl fmt::Display for OpError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.message.is_empty() { write!(f, "{}", &self.kind) } else { write!(f, "{} {}", &self.message, &self.kind) } } } impl error::Error for OpError { fn description(&self) -> &str { self.message.as_ref() } fn cause(&self) -> Option<&dyn error::Error> { self.kind.source() } } #[derive(Debug)] pub enum OpErrorKind { None, IoError(io::Error), ByteOrderError(io::Error), Utf8Error(string::FromUtf8Error), ScriptError(script::ScriptError), InvalidArgsError, CallbackError, ValidateError, RuntimeError, PoisonError, SendError, LevelDBError(String), } impl fmt::Display for OpErrorKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpErrorKind::IoError(ref err) => write!(f, "I/O Error: {}", err), OpErrorKind::ByteOrderError(ref err) => write!(f, "ByteOrder: {}", err), OpErrorKind::Utf8Error(ref err) => write!(f, "Utf8 Conversion: {}", err), OpErrorKind::ScriptError(ref err) => write!(f, "Script: {}", err), OpErrorKind::LevelDBError(ref err) => write!(f, "LevelDB: {}", err), ref err @ OpErrorKind::PoisonError => write!(f, "Threading Error: {}", err), ref err @ OpErrorKind::SendError => write!(f, "Sync: {}", err), ref err @ OpErrorKind::InvalidArgsError => write!(f, "InvalidArgs: {}", err), ref err @ OpErrorKind::CallbackError => write!(f, "Callback: {}", err), ref err @ OpErrorKind::ValidateError => write!(f, "Validation: {}", err), ref err @ OpErrorKind::RuntimeError => write!(f, "RuntimeError: {}", err), OpErrorKind::None => write!(f, ""), } } } impl error::Error for OpErrorKind { fn source(&self) -> Option<&(dyn error::Error +'static)> { match *self { OpErrorKind::IoError(ref err) => Some(err), OpErrorKind::ByteOrderError(ref err) => Some(err), OpErrorKind::Utf8Error(ref err) => Some(err), OpErrorKind::ScriptError(ref err) => Some(err), ref err @ OpErrorKind::PoisonError => Some(err), ref err @ OpErrorKind::SendError => Some(err), _ => None, } } } impl From<io::Error> for OpError { fn from(err: io::Error) -> Self { Self::new(OpErrorKind::IoError(err)) } } impl convert::From<i32> for OpError { fn from(err_code: i32) -> Self { Self::from(io::Error::from_raw_os_error(err_code)) } } impl convert::From<String> for OpError { fn from(err: String) -> Self { Self::new(OpErrorKind::None).join_msg(&err) } } impl<T> convert::From<sync::PoisonError<T>> for OpError { fn from(_: sync::PoisonError<T>) -> Self { Self::new(OpErrorKind::PoisonError) } } impl<T> convert::From<sync::mpsc::SendError<T>> for OpError { fn from(_: sync::mpsc::SendError<T>) -> Self { Self::new(OpErrorKind::SendError) } } impl convert::From<string::FromUtf8Error> for OpError { fn from(err: string::FromUtf8Error) -> Self
} impl convert::From<rusty_leveldb::Status> for OpError { fn from(status: Status) -> Self { Self::new(OpErrorKind::LevelDBError(status.err)) } } #[cfg(test)] mod tests { use super::*; use std::io; #[test] fn test_op_error() { let kind = io::Error::new(io::ErrorKind::BrokenPipe, "oh no!"); let err = OpError::from(kind); assert_eq!(format!("{}", err), "I/O Error: oh no!"); let err = err.join_msg("Cannot proceed."); assert_eq!(format!("{}", err), "Cannot proceed. I/O Error: oh no!"); } }
{ Self::new(OpErrorKind::Utf8Error(err)) }
identifier_body
cursor.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle, Thickness}, }; /// The `CursorRenderObject` is used to render the `Cursor` widget. /// /// [`Cursor`]:../../widgets/struct.Cursor.html #[derive(Debug, IntoRenderObject)] pub struct
; impl RenderObject for CursorRenderObject { fn render_self(&self, ctx: &mut Context, global_position: &Point) { let ( bounds, background, border_width, border_brush, background_opacity, cursor_x, selection_width, selection_x, offset, ) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.get::<Brush>("background").clone(), *widget.get::<Thickness>("border_width"), widget.clone_or_default::<Brush>("border_brush"), *widget.get::<f32>("background_opacity"), *widget.get::<f64>("cursor_x"), *widget.get::<f64>("selection_width"), *widget.get::<f64>("selection_x"), *widget.get::<f64>("offset"), ) }; let border_width = border_width.right(); // background ctx.render_context_2_d().set_alpha(background_opacity); ctx.render_context_2_d().set_fill_style(background); ctx.render_context_2_d().fill_rect( global_position.x() + bounds.x() + offset + selection_x - border_width / 2., global_position.y() + bounds.y(), selection_width, bounds.height(), ); ctx.render_context_2_d().set_alpha(1.); // border ctx.render_context_2_d().set_fill_style(border_brush); ctx.render_context_2_d().fill_rect( global_position.x() + bounds.x() + offset + cursor_x - border_width / 2., global_position.y() + bounds.y(), border_width, bounds.height(), ); } }
CursorRenderObject
identifier_name
cursor.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle, Thickness}, }; /// The `CursorRenderObject` is used to render the `Cursor` widget. /// /// [`Cursor`]:../../widgets/struct.Cursor.html #[derive(Debug, IntoRenderObject)] pub struct CursorRenderObject; impl RenderObject for CursorRenderObject { fn render_self(&self, ctx: &mut Context, global_position: &Point)
*widget.get::<f64>("selection_width"), *widget.get::<f64>("selection_x"), *widget.get::<f64>("offset"), ) }; let border_width = border_width.right(); // background ctx.render_context_2_d().set_alpha(background_opacity); ctx.render_context_2_d().set_fill_style(background); ctx.render_context_2_d().fill_rect( global_position.x() + bounds.x() + offset + selection_x - border_width / 2., global_position.y() + bounds.y(), selection_width, bounds.height(), ); ctx.render_context_2_d().set_alpha(1.); // border ctx.render_context_2_d().set_fill_style(border_brush); ctx.render_context_2_d().fill_rect( global_position.x() + bounds.x() + offset + cursor_x - border_width / 2., global_position.y() + bounds.y(), border_width, bounds.height(), ); } }
{ let ( bounds, background, border_width, border_brush, background_opacity, cursor_x, selection_width, selection_x, offset, ) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.get::<Brush>("background").clone(), *widget.get::<Thickness>("border_width"), widget.clone_or_default::<Brush>("border_brush"), *widget.get::<f32>("background_opacity"), *widget.get::<f64>("cursor_x"),
identifier_body
cursor.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle, Thickness}, }; /// The `CursorRenderObject` is used to render the `Cursor` widget. /// /// [`Cursor`]:../../widgets/struct.Cursor.html #[derive(Debug, IntoRenderObject)] pub struct CursorRenderObject; impl RenderObject for CursorRenderObject { fn render_self(&self, ctx: &mut Context, global_position: &Point) { let ( bounds, background, border_width, border_brush, background_opacity, cursor_x, selection_width,
*widget.get::<Rectangle>("bounds"), widget.get::<Brush>("background").clone(), *widget.get::<Thickness>("border_width"), widget.clone_or_default::<Brush>("border_brush"), *widget.get::<f32>("background_opacity"), *widget.get::<f64>("cursor_x"), *widget.get::<f64>("selection_width"), *widget.get::<f64>("selection_x"), *widget.get::<f64>("offset"), ) }; let border_width = border_width.right(); // background ctx.render_context_2_d().set_alpha(background_opacity); ctx.render_context_2_d().set_fill_style(background); ctx.render_context_2_d().fill_rect( global_position.x() + bounds.x() + offset + selection_x - border_width / 2., global_position.y() + bounds.y(), selection_width, bounds.height(), ); ctx.render_context_2_d().set_alpha(1.); // border ctx.render_context_2_d().set_fill_style(border_brush); ctx.render_context_2_d().fill_rect( global_position.x() + bounds.x() + offset + cursor_x - border_width / 2., global_position.y() + bounds.y(), border_width, bounds.height(), ); } }
selection_x, offset, ) = { let widget = ctx.widget(); (
random_line_split
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress}; use app_units::Au; use euclid::{Point2D, Rect}; use gfx_traits::Epoch; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use metrics::PaintTimeMetrics; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use profile_traits::mem::ReportsChan; use rpc::LayoutRPC; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData}; use script_traits::Painter; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_url::ServoUrl; use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender}; use style::context::QuirksMode; use style::properties::PropertyId; use style::selector_parser::PseudoElement; use style::stylesheets::Stylesheet; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. The second stylesheet is the /// insertion point (if it exists, the sheet needs to be inserted before /// it). AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>), /// Removes a stylesheet from the document. RemoveStylesheet(ServoArc<Stylesheet>), /// Change the quirks mode. SetQuirksMode(QuirksMode), /// Requests a reflow. Reflow(ScriptReflow), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout thread render the next frame of all animations. TickAnimations, /// Updates layout's timer for animation testing from script. /// /// The inner field is the number of *milliseconds* to advance, and the bool /// field is whether animations should be force-ticked. AdvanceClockMs(i32, bool), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapStyleAndLayoutData(OpaqueStyleAndLayoutData), /// Requests that the layout thread measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout thread enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout thread immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow, /// Get the last epoch counter for this layout thread. GetCurrentEpoch(IpcSender<Epoch>), /// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending; /// false otherwise). GetWebFontLoadState(IpcSender<bool>), /// Creates a new layout thread. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutThread(NewLayoutThreadInfo), /// Set the final Url. SetFinalUrl(ServoUrl), /// Tells layout about the new scrolling offsets of each scrollable stacking context. SetScrollStates(Vec<ScrollState>), /// Tells layout about a single new scrolling offset from the script. The rest will /// remain untouched and layout won't forward this back to script. UpdateScrollStateFromScript(ScrollState), /// Tells layout that script has added some paint worklet modules. RegisterPaint(Atom, Vec<Atom>, Box<Painter>), /// Send to layout the precise time when the navigation started. SetNavigationStart(u64), } #[derive(Debug, PartialEq)] pub enum NodesFromPointQueryType { All, Topmost, } #[derive(Debug, PartialEq)] pub enum QueryMsg { ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeScrollIdQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), NodeScrollGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId), OffsetParentQuery(TrustedNodeAddress), StyleQuery(TrustedNodeAddress), TextIndexQuery(TrustedNodeAddress, Point2D<f32>), NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType), ElementInnerTextQuery(TrustedNodeAddress), } /// Any query to perform with this reflow. #[derive(Debug, PartialEq)] pub enum ReflowGoal { Full, TickAnimations, LayoutQuery(QueryMsg, u64), } impl ReflowGoal { /// Returns true if the given ReflowQuery needs a full, up-to-date display list to /// be present or false if it only needs stacking-relative positions. pub fn needs_display_list(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } /// Returns true if the given ReflowQuery needs its display list send to WebRender or /// false if a layout_thread display list is sufficient. pub fn needs_display(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } } /// Information needed for a reflow. pub struct Reflow { /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information derived from a layout pass that needs to be returned to the script thread. #[derive(Default)] pub struct ReflowComplete { /// The list of images that were encountered that are in progress. pub pending_images: Vec<PendingImage>, /// The list of nodes that initiated a CSS transition. pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>, } /// Information needed for a script-initiated reflow. pub struct
{ /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document: TrustedNodeAddress, /// Whether the document's stylesheets have changed since the last script reflow. pub stylesheets_changed: bool, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<ReflowComplete>, /// The goal of this reflow. pub reflow_goal: ReflowGoal, /// The number of objects in the dom #10110 pub dom_count: u32, } pub struct NewLayoutThreadInfo { pub id: PipelineId, pub url: ServoUrl, pub is_parent: bool, pub layout_pair: (Sender<Msg>, Receiver<Msg>), pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: IpcSender<ConstellationMsg>, pub script_chan: IpcSender<ConstellationControlMsg>, pub image_cache: Arc<ImageCache>, pub content_process_shutdown_chan: Option<IpcSender<()>>, pub layout_threads: usize, pub paint_time_metrics: PaintTimeMetrics, }
ScriptReflow
identifier_name
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress}; use app_units::Au; use euclid::{Point2D, Rect}; use gfx_traits::Epoch; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use metrics::PaintTimeMetrics; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use profile_traits::mem::ReportsChan; use rpc::LayoutRPC; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData}; use script_traits::Painter; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_url::ServoUrl; use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender}; use style::context::QuirksMode; use style::properties::PropertyId; use style::selector_parser::PseudoElement; use style::stylesheets::Stylesheet; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. The second stylesheet is the /// insertion point (if it exists, the sheet needs to be inserted before /// it). AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>), /// Removes a stylesheet from the document. RemoveStylesheet(ServoArc<Stylesheet>), /// Change the quirks mode. SetQuirksMode(QuirksMode), /// Requests a reflow. Reflow(ScriptReflow), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout thread render the next frame of all animations. TickAnimations, /// Updates layout's timer for animation testing from script. /// /// The inner field is the number of *milliseconds* to advance, and the bool /// field is whether animations should be force-ticked. AdvanceClockMs(i32, bool), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapStyleAndLayoutData(OpaqueStyleAndLayoutData), /// Requests that the layout thread measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout thread enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout thread immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow, /// Get the last epoch counter for this layout thread. GetCurrentEpoch(IpcSender<Epoch>), /// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending; /// false otherwise). GetWebFontLoadState(IpcSender<bool>), /// Creates a new layout thread. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutThread(NewLayoutThreadInfo), /// Set the final Url. SetFinalUrl(ServoUrl), /// Tells layout about the new scrolling offsets of each scrollable stacking context. SetScrollStates(Vec<ScrollState>), /// Tells layout about a single new scrolling offset from the script. The rest will /// remain untouched and layout won't forward this back to script. UpdateScrollStateFromScript(ScrollState), /// Tells layout that script has added some paint worklet modules. RegisterPaint(Atom, Vec<Atom>, Box<Painter>), /// Send to layout the precise time when the navigation started. SetNavigationStart(u64), } #[derive(Debug, PartialEq)] pub enum NodesFromPointQueryType { All, Topmost, } #[derive(Debug, PartialEq)] pub enum QueryMsg { ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeScrollIdQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), NodeScrollGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId), OffsetParentQuery(TrustedNodeAddress), StyleQuery(TrustedNodeAddress), TextIndexQuery(TrustedNodeAddress, Point2D<f32>), NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType), ElementInnerTextQuery(TrustedNodeAddress), } /// Any query to perform with this reflow. #[derive(Debug, PartialEq)] pub enum ReflowGoal { Full, TickAnimations, LayoutQuery(QueryMsg, u64), } impl ReflowGoal { /// Returns true if the given ReflowQuery needs a full, up-to-date display list to /// be present or false if it only needs stacking-relative positions. pub fn needs_display_list(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } /// Returns true if the given ReflowQuery needs its display list send to WebRender or /// false if a layout_thread display list is sufficient. pub fn needs_display(&self) -> bool
} /// Information needed for a reflow. pub struct Reflow { /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information derived from a layout pass that needs to be returned to the script thread. #[derive(Default)] pub struct ReflowComplete { /// The list of images that were encountered that are in progress. pub pending_images: Vec<PendingImage>, /// The list of nodes that initiated a CSS transition. pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document: TrustedNodeAddress, /// Whether the document's stylesheets have changed since the last script reflow. pub stylesheets_changed: bool, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<ReflowComplete>, /// The goal of this reflow. pub reflow_goal: ReflowGoal, /// The number of objects in the dom #10110 pub dom_count: u32, } pub struct NewLayoutThreadInfo { pub id: PipelineId, pub url: ServoUrl, pub is_parent: bool, pub layout_pair: (Sender<Msg>, Receiver<Msg>), pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: IpcSender<ConstellationMsg>, pub script_chan: IpcSender<ConstellationControlMsg>, pub image_cache: Arc<ImageCache>, pub content_process_shutdown_chan: Option<IpcSender<()>>, pub layout_threads: usize, pub paint_time_metrics: PaintTimeMetrics, }
{ match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } }
identifier_body
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress}; use app_units::Au; use euclid::{Point2D, Rect}; use gfx_traits::Epoch; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use metrics::PaintTimeMetrics; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use profile_traits::mem::ReportsChan; use rpc::LayoutRPC; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData}; use script_traits::Painter; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_url::ServoUrl; use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender}; use style::context::QuirksMode; use style::properties::PropertyId; use style::selector_parser::PseudoElement; use style::stylesheets::Stylesheet; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. The second stylesheet is the /// insertion point (if it exists, the sheet needs to be inserted before /// it). AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>), /// Removes a stylesheet from the document. RemoveStylesheet(ServoArc<Stylesheet>), /// Change the quirks mode. SetQuirksMode(QuirksMode), /// Requests a reflow. Reflow(ScriptReflow), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout thread render the next frame of all animations. TickAnimations, /// Updates layout's timer for animation testing from script. /// /// The inner field is the number of *milliseconds* to advance, and the bool /// field is whether animations should be force-ticked. AdvanceClockMs(i32, bool), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapStyleAndLayoutData(OpaqueStyleAndLayoutData), /// Requests that the layout thread measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout thread enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout thread immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow, /// Get the last epoch counter for this layout thread. GetCurrentEpoch(IpcSender<Epoch>), /// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending; /// false otherwise). GetWebFontLoadState(IpcSender<bool>), /// Creates a new layout thread. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutThread(NewLayoutThreadInfo), /// Set the final Url. SetFinalUrl(ServoUrl), /// Tells layout about the new scrolling offsets of each scrollable stacking context. SetScrollStates(Vec<ScrollState>), /// Tells layout about a single new scrolling offset from the script. The rest will /// remain untouched and layout won't forward this back to script. UpdateScrollStateFromScript(ScrollState), /// Tells layout that script has added some paint worklet modules. RegisterPaint(Atom, Vec<Atom>, Box<Painter>), /// Send to layout the precise time when the navigation started. SetNavigationStart(u64), } #[derive(Debug, PartialEq)] pub enum NodesFromPointQueryType { All, Topmost, } #[derive(Debug, PartialEq)] pub enum QueryMsg { ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeScrollIdQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), NodeScrollGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId), OffsetParentQuery(TrustedNodeAddress), StyleQuery(TrustedNodeAddress), TextIndexQuery(TrustedNodeAddress, Point2D<f32>), NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType), ElementInnerTextQuery(TrustedNodeAddress), } /// Any query to perform with this reflow. #[derive(Debug, PartialEq)] pub enum ReflowGoal { Full, TickAnimations, LayoutQuery(QueryMsg, u64), } impl ReflowGoal { /// Returns true if the given ReflowQuery needs a full, up-to-date display list to /// be present or false if it only needs stacking-relative positions. pub fn needs_display_list(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } /// Returns true if the given ReflowQuery needs its display list send to WebRender or /// false if a layout_thread display list is sufficient. pub fn needs_display(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) |
} /// Information needed for a reflow. pub struct Reflow { /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information derived from a layout pass that needs to be returned to the script thread. #[derive(Default)] pub struct ReflowComplete { /// The list of images that were encountered that are in progress. pub pending_images: Vec<PendingImage>, /// The list of nodes that initiated a CSS transition. pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document: TrustedNodeAddress, /// Whether the document's stylesheets have changed since the last script reflow. pub stylesheets_changed: bool, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<ReflowComplete>, /// The goal of this reflow. pub reflow_goal: ReflowGoal, /// The number of objects in the dom #10110 pub dom_count: u32, } pub struct NewLayoutThreadInfo { pub id: PipelineId, pub url: ServoUrl, pub is_parent: bool, pub layout_pair: (Sender<Msg>, Receiver<Msg>), pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: IpcSender<ConstellationMsg>, pub script_chan: IpcSender<ConstellationControlMsg>, pub image_cache: Arc<ImageCache>, pub content_process_shutdown_chan: Option<IpcSender<()>>, pub layout_threads: usize, pub paint_time_metrics: PaintTimeMetrics, }
&QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } }
random_line_split
terrain.rs
use building_blocks::storage; use building_blocks::{ mesh::{IsOpaque, MergeVoxel, SignedDistance}, storage::IsEmpty, }; pub const EMPTY_VOXEL: Voxel = Voxel { voxel_type: VoxelType::Air, distance: VoxelDistance(1), }; pub const NUM_VOXEL_TYPES: usize = 5; #[derive(Clone, Copy, Debug)] pub struct Voxel { voxel_type: VoxelType, distance: VoxelDistance, } impl Voxel { pub fn new(voxel_type: VoxelType, distance: VoxelDistance) -> Self { Self { voxel_type, distance, } } pub fn voxel_type(&self) -> &VoxelType { &self.voxel_type } pub fn distance(&self) -> &VoxelDistance { &self.distance } } impl SignedDistance for Voxel { fn distance(&self) -> f32 { self.distance.0 as f32 } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum VoxelType { Air, Stone, Grass, Gold, Water, } impl VoxelType { pub fn index(&self) -> usize { match self { VoxelType::Air => 0, VoxelType::Stone => 1, VoxelType::Grass => 2, VoxelType::Gold => 3, VoxelType::Water => 4, } } pub fn collidable(&self) -> bool { match self { VoxelType::Air | VoxelType::Water => false, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold => true, } } } impl MergeVoxel for VoxelType { type VoxelValue = Self; fn voxel_merge_value(&self) -> Self::VoxelValue { *self } } impl IsOpaque for VoxelType { fn is_opaque(&self) -> bool { match self { VoxelType::Air | VoxelType::Water => false, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold => true, } } } impl IsEmpty for VoxelType {
VoxelType::Air => true, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold | VoxelType::Water => false, } } } #[derive(Clone, Copy, Debug)] pub struct VoxelDistance(pub i8);
fn is_empty(&self) -> bool { match self {
random_line_split
terrain.rs
use building_blocks::storage; use building_blocks::{ mesh::{IsOpaque, MergeVoxel, SignedDistance}, storage::IsEmpty, }; pub const EMPTY_VOXEL: Voxel = Voxel { voxel_type: VoxelType::Air, distance: VoxelDistance(1), }; pub const NUM_VOXEL_TYPES: usize = 5; #[derive(Clone, Copy, Debug)] pub struct Voxel { voxel_type: VoxelType, distance: VoxelDistance, } impl Voxel { pub fn new(voxel_type: VoxelType, distance: VoxelDistance) -> Self { Self { voxel_type, distance, } } pub fn voxel_type(&self) -> &VoxelType { &self.voxel_type } pub fn distance(&self) -> &VoxelDistance { &self.distance } } impl SignedDistance for Voxel { fn distance(&self) -> f32 { self.distance.0 as f32 } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum VoxelType { Air, Stone, Grass, Gold, Water, } impl VoxelType { pub fn index(&self) -> usize
pub fn collidable(&self) -> bool { match self { VoxelType::Air | VoxelType::Water => false, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold => true, } } } impl MergeVoxel for VoxelType { type VoxelValue = Self; fn voxel_merge_value(&self) -> Self::VoxelValue { *self } } impl IsOpaque for VoxelType { fn is_opaque(&self) -> bool { match self { VoxelType::Air | VoxelType::Water => false, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold => true, } } } impl IsEmpty for VoxelType { fn is_empty(&self) -> bool { match self { VoxelType::Air => true, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold | VoxelType::Water => false, } } } #[derive(Clone, Copy, Debug)] pub struct VoxelDistance(pub i8);
{ match self { VoxelType::Air => 0, VoxelType::Stone => 1, VoxelType::Grass => 2, VoxelType::Gold => 3, VoxelType::Water => 4, } }
identifier_body
terrain.rs
use building_blocks::storage; use building_blocks::{ mesh::{IsOpaque, MergeVoxel, SignedDistance}, storage::IsEmpty, }; pub const EMPTY_VOXEL: Voxel = Voxel { voxel_type: VoxelType::Air, distance: VoxelDistance(1), }; pub const NUM_VOXEL_TYPES: usize = 5; #[derive(Clone, Copy, Debug)] pub struct Voxel { voxel_type: VoxelType, distance: VoxelDistance, } impl Voxel { pub fn new(voxel_type: VoxelType, distance: VoxelDistance) -> Self { Self { voxel_type, distance, } } pub fn voxel_type(&self) -> &VoxelType { &self.voxel_type } pub fn distance(&self) -> &VoxelDistance { &self.distance } } impl SignedDistance for Voxel { fn distance(&self) -> f32 { self.distance.0 as f32 } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum VoxelType { Air, Stone, Grass, Gold, Water, } impl VoxelType { pub fn index(&self) -> usize { match self { VoxelType::Air => 0, VoxelType::Stone => 1, VoxelType::Grass => 2, VoxelType::Gold => 3, VoxelType::Water => 4, } } pub fn
(&self) -> bool { match self { VoxelType::Air | VoxelType::Water => false, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold => true, } } } impl MergeVoxel for VoxelType { type VoxelValue = Self; fn voxel_merge_value(&self) -> Self::VoxelValue { *self } } impl IsOpaque for VoxelType { fn is_opaque(&self) -> bool { match self { VoxelType::Air | VoxelType::Water => false, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold => true, } } } impl IsEmpty for VoxelType { fn is_empty(&self) -> bool { match self { VoxelType::Air => true, VoxelType::Stone | VoxelType::Grass | VoxelType::Gold | VoxelType::Water => false, } } } #[derive(Clone, Copy, Debug)] pub struct VoxelDistance(pub i8);
collidable
identifier_name
use.rs
// ignore-fast // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast #[allow(unused_imports)]; #[no_std]; extern crate std;
use x = zed::str; mod baz { pub use bar::str; pub use x = std::str; } #[start] pub fn start(_: int, _: **u8) -> int { 0 }
extern crate zed = "std"; extern crate bar = "std#0.10"; use std::str;
random_line_split
use.rs
// ignore-fast // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast #[allow(unused_imports)]; #[no_std]; extern crate std; extern crate zed = "std"; extern crate bar = "std#0.10"; use std::str; use x = zed::str; mod baz { pub use bar::str; pub use x = std::str; } #[start] pub fn start(_: int, _: **u8) -> int
{ 0 }
identifier_body
use.rs
// ignore-fast // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast #[allow(unused_imports)]; #[no_std]; extern crate std; extern crate zed = "std"; extern crate bar = "std#0.10"; use std::str; use x = zed::str; mod baz { pub use bar::str; pub use x = std::str; } #[start] pub fn
(_: int, _: **u8) -> int { 0 }
start
identifier_name
misc.rs
//! Miscellaneous type-system utilities that are too small to deserve their own modules. use crate::infer::InferCtxtExt as _; use crate::traits::{self, ObligationCause}; use rustc_hir as hir; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use crate::traits::error_reporting::InferCtxtExt; #[derive(Clone)] pub enum CopyImplementationError<'tcx> { InfrigingFields(Vec<&'tcx ty::FieldDef>), NotAnAdt, HasDestructor, } pub fn can_type_implement_copy( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, self_type: Ty<'tcx>,
let (adt, substs) = match self_type.kind() { // These types used to have a builtin impl. // Now libcore provides that impl. ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) | ty::Char | ty::RawPtr(..) | ty::Never | ty::Ref(_, _, hir::Mutability::Not) | ty::Array(..) => return Ok(()), ty::Adt(adt, substs) => (adt, substs), _ => return Err(CopyImplementationError::NotAnAdt), }; let mut infringing = Vec::new(); for variant in &adt.variants { for field in &variant.fields { let ty = field.ty(tcx, substs); if ty.references_error() { continue; } let span = tcx.def_span(field.did); let cause = ObligationCause::dummy_with_span(span); let ctx = traits::FulfillmentContext::new(); match traits::fully_normalize(&infcx, ctx, cause, param_env, ty) { Ok(ty) => { if!infcx.type_is_copy_modulo_regions(param_env, ty, span) { infringing.push(field); } } Err(errors) => { infcx.report_fulfillment_errors(&errors, None, false); } }; } } if!infringing.is_empty() { return Err(CopyImplementationError::InfrigingFields(infringing)); } if adt.has_dtor(tcx) { return Err(CopyImplementationError::HasDestructor); } Ok(()) }) }
) -> Result<(), CopyImplementationError<'tcx>> { // FIXME: (@jroesch) float this code up tcx.infer_ctxt().enter(|infcx| {
random_line_split
misc.rs
//! Miscellaneous type-system utilities that are too small to deserve their own modules. use crate::infer::InferCtxtExt as _; use crate::traits::{self, ObligationCause}; use rustc_hir as hir; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use crate::traits::error_reporting::InferCtxtExt; #[derive(Clone)] pub enum CopyImplementationError<'tcx> { InfrigingFields(Vec<&'tcx ty::FieldDef>), NotAnAdt, HasDestructor, } pub fn
( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, self_type: Ty<'tcx>, ) -> Result<(), CopyImplementationError<'tcx>> { // FIXME: (@jroesch) float this code up tcx.infer_ctxt().enter(|infcx| { let (adt, substs) = match self_type.kind() { // These types used to have a builtin impl. // Now libcore provides that impl. ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) | ty::Char | ty::RawPtr(..) | ty::Never | ty::Ref(_, _, hir::Mutability::Not) | ty::Array(..) => return Ok(()), ty::Adt(adt, substs) => (adt, substs), _ => return Err(CopyImplementationError::NotAnAdt), }; let mut infringing = Vec::new(); for variant in &adt.variants { for field in &variant.fields { let ty = field.ty(tcx, substs); if ty.references_error() { continue; } let span = tcx.def_span(field.did); let cause = ObligationCause::dummy_with_span(span); let ctx = traits::FulfillmentContext::new(); match traits::fully_normalize(&infcx, ctx, cause, param_env, ty) { Ok(ty) => { if!infcx.type_is_copy_modulo_regions(param_env, ty, span) { infringing.push(field); } } Err(errors) => { infcx.report_fulfillment_errors(&errors, None, false); } }; } } if!infringing.is_empty() { return Err(CopyImplementationError::InfrigingFields(infringing)); } if adt.has_dtor(tcx) { return Err(CopyImplementationError::HasDestructor); } Ok(()) }) }
can_type_implement_copy
identifier_name
misc.rs
//! Miscellaneous type-system utilities that are too small to deserve their own modules. use crate::infer::InferCtxtExt as _; use crate::traits::{self, ObligationCause}; use rustc_hir as hir; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use crate::traits::error_reporting::InferCtxtExt; #[derive(Clone)] pub enum CopyImplementationError<'tcx> { InfrigingFields(Vec<&'tcx ty::FieldDef>), NotAnAdt, HasDestructor, } pub fn can_type_implement_copy( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, self_type: Ty<'tcx>, ) -> Result<(), CopyImplementationError<'tcx>>
let mut infringing = Vec::new(); for variant in &adt.variants { for field in &variant.fields { let ty = field.ty(tcx, substs); if ty.references_error() { continue; } let span = tcx.def_span(field.did); let cause = ObligationCause::dummy_with_span(span); let ctx = traits::FulfillmentContext::new(); match traits::fully_normalize(&infcx, ctx, cause, param_env, ty) { Ok(ty) => { if!infcx.type_is_copy_modulo_regions(param_env, ty, span) { infringing.push(field); } } Err(errors) => { infcx.report_fulfillment_errors(&errors, None, false); } }; } } if!infringing.is_empty() { return Err(CopyImplementationError::InfrigingFields(infringing)); } if adt.has_dtor(tcx) { return Err(CopyImplementationError::HasDestructor); } Ok(()) }) }
{ // FIXME: (@jroesch) float this code up tcx.infer_ctxt().enter(|infcx| { let (adt, substs) = match self_type.kind() { // These types used to have a builtin impl. // Now libcore provides that impl. ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) | ty::Char | ty::RawPtr(..) | ty::Never | ty::Ref(_, _, hir::Mutability::Not) | ty::Array(..) => return Ok(()), ty::Adt(adt, substs) => (adt, substs), _ => return Err(CopyImplementationError::NotAnAdt), };
identifier_body
match_wildcard_for_single_variants.rs
// run-rustfix #![warn(clippy::match_wildcard_for_single_variants)] #![allow(dead_code)] enum Foo { A, B, C, } enum Color { Red, Green, Blue, Rgb(u8, u8, u8), } impl Color { fn f(self) { match self { Self::Red => (), Self::Green => (), Self::Blue => (), _ => (), }; } } fn
() { let f = Foo::A; match f { Foo::A => {}, Foo::B => {}, _ => {}, } let color = Color::Red; // check exhaustive bindings match color { Color::Red => {}, Color::Green => {}, Color::Rgb(_r, _g, _b) => {}, _ => {}, } // check exhaustive wild match color { Color::Red => {}, Color::Green => {}, Color::Rgb(..) => {}, _ => {}, } match color { Color::Red => {}, Color::Green => {}, Color::Rgb(_, _, _) => {}, _ => {}, } // shouldn't lint as there is one missing variant // and one that isn't exhaustively covered match color { Color::Red => {}, Color::Green => {}, Color::Rgb(255, _, _) => {}, _ => {}, } // References shouldn't change anything match &color { &Color::Red => (), Color::Green => (), &Color::Rgb(..) => (), &_ => (), } use self::Color as C; match color { C::Red => (), C::Green => (), C::Rgb(..) => (), _ => (), } match color { C::Red => (), Color::Green => (), Color::Rgb(..) => (), _ => (), } match Some(0) { Some(0) => 0, Some(_) => 1, _ => 2, }; #[non_exhaustive] enum Bar { A, B, C, } match Bar::A { Bar::A => (), Bar::B => (), _ => (), }; //#6984 { #![allow(clippy::manual_non_exhaustive)] pub enum Enum { A, B, C, #[doc(hidden)] __Private, } match Enum::A { Enum::A => (), Enum::B => (), Enum::C => (), _ => (), } match Enum::A { Enum::A => (), Enum::B => (), _ => (), } } }
main
identifier_name
match_wildcard_for_single_variants.rs
// run-rustfix #![warn(clippy::match_wildcard_for_single_variants)] #![allow(dead_code)] enum Foo { A, B, C, } enum Color { Red, Green, Blue, Rgb(u8, u8, u8), } impl Color { fn f(self) { match self { Self::Red => (), Self::Green => (), Self::Blue => (), _ => (), }; } } fn main() { let f = Foo::A; match f { Foo::A => {}, Foo::B => {}, _ => {}, } let color = Color::Red; // check exhaustive bindings match color { Color::Red => {}, Color::Green => {}, Color::Rgb(_r, _g, _b) => {}, _ => {}, } // check exhaustive wild match color { Color::Red => {}, Color::Green => {}, Color::Rgb(..) => {}, _ => {}, } match color { Color::Red => {}, Color::Green => {}, Color::Rgb(_, _, _) => {}, _ => {}, } // shouldn't lint as there is one missing variant // and one that isn't exhaustively covered match color { Color::Red => {}, Color::Green => {}, Color::Rgb(255, _, _) => {}, _ => {}, } // References shouldn't change anything match &color { &Color::Red => (), Color::Green => (), &Color::Rgb(..) => (),
use self::Color as C; match color { C::Red => (), C::Green => (), C::Rgb(..) => (), _ => (), } match color { C::Red => (), Color::Green => (), Color::Rgb(..) => (), _ => (), } match Some(0) { Some(0) => 0, Some(_) => 1, _ => 2, }; #[non_exhaustive] enum Bar { A, B, C, } match Bar::A { Bar::A => (), Bar::B => (), _ => (), }; //#6984 { #![allow(clippy::manual_non_exhaustive)] pub enum Enum { A, B, C, #[doc(hidden)] __Private, } match Enum::A { Enum::A => (), Enum::B => (), Enum::C => (), _ => (), } match Enum::A { Enum::A => (), Enum::B => (), _ => (), } } }
&_ => (), }
random_line_split
match_wildcard_for_single_variants.rs
// run-rustfix #![warn(clippy::match_wildcard_for_single_variants)] #![allow(dead_code)] enum Foo { A, B, C, } enum Color { Red, Green, Blue, Rgb(u8, u8, u8), } impl Color { fn f(self)
} fn main() { let f = Foo::A; match f { Foo::A => {}, Foo::B => {}, _ => {}, } let color = Color::Red; // check exhaustive bindings match color { Color::Red => {}, Color::Green => {}, Color::Rgb(_r, _g, _b) => {}, _ => {}, } // check exhaustive wild match color { Color::Red => {}, Color::Green => {}, Color::Rgb(..) => {}, _ => {}, } match color { Color::Red => {}, Color::Green => {}, Color::Rgb(_, _, _) => {}, _ => {}, } // shouldn't lint as there is one missing variant // and one that isn't exhaustively covered match color { Color::Red => {}, Color::Green => {}, Color::Rgb(255, _, _) => {}, _ => {}, } // References shouldn't change anything match &color { &Color::Red => (), Color::Green => (), &Color::Rgb(..) => (), &_ => (), } use self::Color as C; match color { C::Red => (), C::Green => (), C::Rgb(..) => (), _ => (), } match color { C::Red => (), Color::Green => (), Color::Rgb(..) => (), _ => (), } match Some(0) { Some(0) => 0, Some(_) => 1, _ => 2, }; #[non_exhaustive] enum Bar { A, B, C, } match Bar::A { Bar::A => (), Bar::B => (), _ => (), }; //#6984 { #![allow(clippy::manual_non_exhaustive)] pub enum Enum { A, B, C, #[doc(hidden)] __Private, } match Enum::A { Enum::A => (), Enum::B => (), Enum::C => (), _ => (), } match Enum::A { Enum::A => (), Enum::B => (), _ => (), } } }
{ match self { Self::Red => (), Self::Green => (), Self::Blue => (), _ => (), }; }
identifier_body
absolute.rs
use std::{cell::RefCell, collections::BTreeMap}; use dces::prelude::*; use crate::{ proc_macros::IntoLayout, render::RenderContext2D, theming::*, tree::Tree, utils::prelude::*, widget_base::mark_as_dirty, }; use super::{component, component_try_mut, Layout}; /// Place widgets absolute on the screen. #[derive(Default, IntoLayout)] pub struct AbsoluteLayout { desired_size: RefCell<DirtySize>, } impl AbsoluteLayout { /// Preset the defaults. pub fn new() -> Self { AbsoluteLayout::default() } } impl Layout for AbsoluteLayout { fn measure( &self, render_context_2_d: &mut RenderContext2D, entity: Entity, ecm: &mut EntityComponentManager<Tree>, layouts: &BTreeMap<Entity, Box<dyn Layout>>, theme: &Theme, ) -> DirtySize { // collapsed entities don't consume any size if component::<Visibility>(ecm, entity, "visibility") == Visibility::Collapsed { self.desired_size.borrow_mut().set_size(0.0, 0.0); return *self.desired_size.borrow(); } let window = ecm.entity_store().root(); if let Ok(bounds) = ecm.component_store().get::<Rectangle>("bounds", window) { self.desired_size .borrow_mut() .set_size(bounds.width(), bounds.height()); } // walk down and arrange the addressed childs for index in 0..ecm.entity_store().children[&entity].len() { let child = ecm.entity_store().children[&entity][index]; if let Some(child_layout) = layouts.get(&child)
} *self.desired_size.borrow() } fn arrange( &self, render_context_2_d: &mut RenderContext2D, _parent_size: (f64, f64), entity: Entity, ecm: &mut EntityComponentManager<Tree>, layouts: &BTreeMap<Entity, Box<dyn Layout>>, theme: &Theme, ) -> (f64, f64) { if component::<Visibility>(ecm, entity, "visibility") == Visibility::Collapsed { self.desired_size.borrow_mut().set_size(0.0, 0.0); return (0.0, 0.0); } if let Some(bounds) = component_try_mut::<Rectangle>(ecm, entity, "bounds") { bounds.set_width(self.desired_size.borrow().width()); bounds.set_height(self.desired_size.borrow().height()); } mark_as_dirty("bounds", entity, ecm); for index in 0..ecm.entity_store().children[&entity].len() { let child = ecm.entity_store().children[&entity][index]; if let Some(child_layout) = layouts.get(&child) { child_layout.arrange( render_context_2_d, ( self.desired_size.borrow().width(), self.desired_size.borrow().height(), ), child, ecm, layouts, theme, ); } } self.desired_size.borrow_mut().set_dirty(false); self.desired_size.borrow().size() } }
{ let dirty = child_layout .measure(render_context_2_d, child, ecm, layouts, theme) .dirty() || self.desired_size.borrow().dirty(); self.desired_size.borrow_mut().set_dirty(dirty); }
conditional_block
absolute.rs
use std::{cell::RefCell, collections::BTreeMap}; use dces::prelude::*; use crate::{ proc_macros::IntoLayout, render::RenderContext2D, theming::*, tree::Tree, utils::prelude::*, widget_base::mark_as_dirty, }; use super::{component, component_try_mut, Layout}; /// Place widgets absolute on the screen. #[derive(Default, IntoLayout)] pub struct AbsoluteLayout { desired_size: RefCell<DirtySize>, } impl AbsoluteLayout { /// Preset the defaults. pub fn new() -> Self { AbsoluteLayout::default() } } impl Layout for AbsoluteLayout { fn measure( &self, render_context_2_d: &mut RenderContext2D, entity: Entity, ecm: &mut EntityComponentManager<Tree>, layouts: &BTreeMap<Entity, Box<dyn Layout>>, theme: &Theme, ) -> DirtySize { // collapsed entities don't consume any size if component::<Visibility>(ecm, entity, "visibility") == Visibility::Collapsed { self.desired_size.borrow_mut().set_size(0.0, 0.0); return *self.desired_size.borrow(); } let window = ecm.entity_store().root(); if let Ok(bounds) = ecm.component_store().get::<Rectangle>("bounds", window) { self.desired_size .borrow_mut()
.set_size(bounds.width(), bounds.height()); } // walk down and arrange the addressed childs for index in 0..ecm.entity_store().children[&entity].len() { let child = ecm.entity_store().children[&entity][index]; if let Some(child_layout) = layouts.get(&child) { let dirty = child_layout .measure(render_context_2_d, child, ecm, layouts, theme) .dirty() || self.desired_size.borrow().dirty(); self.desired_size.borrow_mut().set_dirty(dirty); } } *self.desired_size.borrow() } fn arrange( &self, render_context_2_d: &mut RenderContext2D, _parent_size: (f64, f64), entity: Entity, ecm: &mut EntityComponentManager<Tree>, layouts: &BTreeMap<Entity, Box<dyn Layout>>, theme: &Theme, ) -> (f64, f64) { if component::<Visibility>(ecm, entity, "visibility") == Visibility::Collapsed { self.desired_size.borrow_mut().set_size(0.0, 0.0); return (0.0, 0.0); } if let Some(bounds) = component_try_mut::<Rectangle>(ecm, entity, "bounds") { bounds.set_width(self.desired_size.borrow().width()); bounds.set_height(self.desired_size.borrow().height()); } mark_as_dirty("bounds", entity, ecm); for index in 0..ecm.entity_store().children[&entity].len() { let child = ecm.entity_store().children[&entity][index]; if let Some(child_layout) = layouts.get(&child) { child_layout.arrange( render_context_2_d, ( self.desired_size.borrow().width(), self.desired_size.borrow().height(), ), child, ecm, layouts, theme, ); } } self.desired_size.borrow_mut().set_dirty(false); self.desired_size.borrow().size() } }
random_line_split
absolute.rs
use std::{cell::RefCell, collections::BTreeMap}; use dces::prelude::*; use crate::{ proc_macros::IntoLayout, render::RenderContext2D, theming::*, tree::Tree, utils::prelude::*, widget_base::mark_as_dirty, }; use super::{component, component_try_mut, Layout}; /// Place widgets absolute on the screen. #[derive(Default, IntoLayout)] pub struct AbsoluteLayout { desired_size: RefCell<DirtySize>, } impl AbsoluteLayout { /// Preset the defaults. pub fn
() -> Self { AbsoluteLayout::default() } } impl Layout for AbsoluteLayout { fn measure( &self, render_context_2_d: &mut RenderContext2D, entity: Entity, ecm: &mut EntityComponentManager<Tree>, layouts: &BTreeMap<Entity, Box<dyn Layout>>, theme: &Theme, ) -> DirtySize { // collapsed entities don't consume any size if component::<Visibility>(ecm, entity, "visibility") == Visibility::Collapsed { self.desired_size.borrow_mut().set_size(0.0, 0.0); return *self.desired_size.borrow(); } let window = ecm.entity_store().root(); if let Ok(bounds) = ecm.component_store().get::<Rectangle>("bounds", window) { self.desired_size .borrow_mut() .set_size(bounds.width(), bounds.height()); } // walk down and arrange the addressed childs for index in 0..ecm.entity_store().children[&entity].len() { let child = ecm.entity_store().children[&entity][index]; if let Some(child_layout) = layouts.get(&child) { let dirty = child_layout .measure(render_context_2_d, child, ecm, layouts, theme) .dirty() || self.desired_size.borrow().dirty(); self.desired_size.borrow_mut().set_dirty(dirty); } } *self.desired_size.borrow() } fn arrange( &self, render_context_2_d: &mut RenderContext2D, _parent_size: (f64, f64), entity: Entity, ecm: &mut EntityComponentManager<Tree>, layouts: &BTreeMap<Entity, Box<dyn Layout>>, theme: &Theme, ) -> (f64, f64) { if component::<Visibility>(ecm, entity, "visibility") == Visibility::Collapsed { self.desired_size.borrow_mut().set_size(0.0, 0.0); return (0.0, 0.0); } if let Some(bounds) = component_try_mut::<Rectangle>(ecm, entity, "bounds") { bounds.set_width(self.desired_size.borrow().width()); bounds.set_height(self.desired_size.borrow().height()); } mark_as_dirty("bounds", entity, ecm); for index in 0..ecm.entity_store().children[&entity].len() { let child = ecm.entity_store().children[&entity][index]; if let Some(child_layout) = layouts.get(&child) { child_layout.arrange( render_context_2_d, ( self.desired_size.borrow().width(), self.desired_size.borrow().height(), ), child, ecm, layouts, theme, ); } } self.desired_size.borrow_mut().set_dirty(false); self.desired_size.borrow().size() } }
new
identifier_name
dump_process_registers.rs
//! A script to read and dump to stdout the current register values of a //! process. extern crate libc; extern crate mach; use std::io; use std::mem; use std::ptr; use mach::kern_return::{KERN_SUCCESS}; use mach::message::{mach_msg_type_number_t}; use mach::port::{mach_port_name_t}; use mach::structs::{x86_thread_state64_t}; use mach::task::{task_resume, task_suspend, task_threads}; use mach::thread_act::{thread_get_state}; use mach::thread_status::{x86_THREAD_STATE64}; use mach::traps::{mach_task_self, task_for_pid}; use mach::types::{task_t, thread_act_array_t}; use std::io::prelude::*; fn read_int() -> Result<::libc::c_int, ()> { let stdin = io::stdin(); let mut line = String::new(); stdin.read_line(&mut line).ok().unwrap(); let mut value : ::libc::c_int = 0; for c in line.chars().take_while(|&c| c!= '\n') { if let Some(d) = c.to_digit(10) { value = value * 10 + (d as ::libc::c_int); } else { return Err(()); } } return Ok(value); } fn resume(task: task_t) { unsafe { let kret = task_resume(task); if kret!= KERN_SUCCESS { println!("Did not succeed in resuming task."); println!("kern_return_t error {}", kret); panic!(); } } } fn main() { print!("Enter pid: "); io::stdout().flush().ok(); let pid = match read_int() { Ok(v) => v, Err(_) => { println!("Bad pid!"); return; }, }; println!("pid = {}", &pid); let task : mach_port_name_t = 0; unsafe { let kret = task_for_pid(mach_task_self() as mach_port_name_t, pid, mem::transmute(&task)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task for pid {}", pid); println!("kern_return_t error {}", kret); println!(""); println!("Did you forget to run with'sudo'? This script will"); println!("probably fail without it."); return; } } println!("task = 0x{:x}", &task); unsafe { let kret = task_suspend(task as task_t); if kret!= KERN_SUCCESS { println!("Did not succeed in suspending task."); println!("kern_return_t error {}", kret); return; } } let thread_list : thread_act_array_t = ptr::null_mut(); let thread_count : mach_msg_type_number_t = 0; unsafe { let kret = task_threads(task as task_t, mem::transmute(&thread_list), mem::transmute(&thread_count)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task's threads"); println!("kern_return_t error {}", kret); resume(task as task_t); return; } } println!("Task is running {} threads", &thread_count); unsafe { let threads = Vec::from_raw_parts(thread_list, thread_count as usize, thread_count as usize); let state = x86_thread_state64_t::new(); let state_count = x86_thread_state64_t::count(); for (idx, &thread) in threads.iter().enumerate() { println!("Thread {}:", idx);
if kret!= KERN_SUCCESS { println!("Did not succeed in getting task's thread state"); println!("kern_return_t error {}", kret); continue; } println!("{:?}", state); } } resume(task as task_t); println!("Success!"); }
let kret = thread_get_state(thread, x86_THREAD_STATE64, mem::transmute(&state), mem::transmute(&state_count));
random_line_split
dump_process_registers.rs
//! A script to read and dump to stdout the current register values of a //! process. extern crate libc; extern crate mach; use std::io; use std::mem; use std::ptr; use mach::kern_return::{KERN_SUCCESS}; use mach::message::{mach_msg_type_number_t}; use mach::port::{mach_port_name_t}; use mach::structs::{x86_thread_state64_t}; use mach::task::{task_resume, task_suspend, task_threads}; use mach::thread_act::{thread_get_state}; use mach::thread_status::{x86_THREAD_STATE64}; use mach::traps::{mach_task_self, task_for_pid}; use mach::types::{task_t, thread_act_array_t}; use std::io::prelude::*; fn read_int() -> Result<::libc::c_int, ()> { let stdin = io::stdin(); let mut line = String::new(); stdin.read_line(&mut line).ok().unwrap(); let mut value : ::libc::c_int = 0; for c in line.chars().take_while(|&c| c!= '\n') { if let Some(d) = c.to_digit(10) { value = value * 10 + (d as ::libc::c_int); } else { return Err(()); } } return Ok(value); } fn resume(task: task_t) { unsafe { let kret = task_resume(task); if kret!= KERN_SUCCESS { println!("Did not succeed in resuming task."); println!("kern_return_t error {}", kret); panic!(); } } } fn
() { print!("Enter pid: "); io::stdout().flush().ok(); let pid = match read_int() { Ok(v) => v, Err(_) => { println!("Bad pid!"); return; }, }; println!("pid = {}", &pid); let task : mach_port_name_t = 0; unsafe { let kret = task_for_pid(mach_task_self() as mach_port_name_t, pid, mem::transmute(&task)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task for pid {}", pid); println!("kern_return_t error {}", kret); println!(""); println!("Did you forget to run with'sudo'? This script will"); println!("probably fail without it."); return; } } println!("task = 0x{:x}", &task); unsafe { let kret = task_suspend(task as task_t); if kret!= KERN_SUCCESS { println!("Did not succeed in suspending task."); println!("kern_return_t error {}", kret); return; } } let thread_list : thread_act_array_t = ptr::null_mut(); let thread_count : mach_msg_type_number_t = 0; unsafe { let kret = task_threads(task as task_t, mem::transmute(&thread_list), mem::transmute(&thread_count)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task's threads"); println!("kern_return_t error {}", kret); resume(task as task_t); return; } } println!("Task is running {} threads", &thread_count); unsafe { let threads = Vec::from_raw_parts(thread_list, thread_count as usize, thread_count as usize); let state = x86_thread_state64_t::new(); let state_count = x86_thread_state64_t::count(); for (idx, &thread) in threads.iter().enumerate() { println!("Thread {}:", idx); let kret = thread_get_state(thread, x86_THREAD_STATE64, mem::transmute(&state), mem::transmute(&state_count)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task's thread state"); println!("kern_return_t error {}", kret); continue; } println!("{:?}", state); } } resume(task as task_t); println!("Success!"); }
main
identifier_name
dump_process_registers.rs
//! A script to read and dump to stdout the current register values of a //! process. extern crate libc; extern crate mach; use std::io; use std::mem; use std::ptr; use mach::kern_return::{KERN_SUCCESS}; use mach::message::{mach_msg_type_number_t}; use mach::port::{mach_port_name_t}; use mach::structs::{x86_thread_state64_t}; use mach::task::{task_resume, task_suspend, task_threads}; use mach::thread_act::{thread_get_state}; use mach::thread_status::{x86_THREAD_STATE64}; use mach::traps::{mach_task_self, task_for_pid}; use mach::types::{task_t, thread_act_array_t}; use std::io::prelude::*; fn read_int() -> Result<::libc::c_int, ()>
fn resume(task: task_t) { unsafe { let kret = task_resume(task); if kret!= KERN_SUCCESS { println!("Did not succeed in resuming task."); println!("kern_return_t error {}", kret); panic!(); } } } fn main() { print!("Enter pid: "); io::stdout().flush().ok(); let pid = match read_int() { Ok(v) => v, Err(_) => { println!("Bad pid!"); return; }, }; println!("pid = {}", &pid); let task : mach_port_name_t = 0; unsafe { let kret = task_for_pid(mach_task_self() as mach_port_name_t, pid, mem::transmute(&task)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task for pid {}", pid); println!("kern_return_t error {}", kret); println!(""); println!("Did you forget to run with'sudo'? This script will"); println!("probably fail without it."); return; } } println!("task = 0x{:x}", &task); unsafe { let kret = task_suspend(task as task_t); if kret!= KERN_SUCCESS { println!("Did not succeed in suspending task."); println!("kern_return_t error {}", kret); return; } } let thread_list : thread_act_array_t = ptr::null_mut(); let thread_count : mach_msg_type_number_t = 0; unsafe { let kret = task_threads(task as task_t, mem::transmute(&thread_list), mem::transmute(&thread_count)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task's threads"); println!("kern_return_t error {}", kret); resume(task as task_t); return; } } println!("Task is running {} threads", &thread_count); unsafe { let threads = Vec::from_raw_parts(thread_list, thread_count as usize, thread_count as usize); let state = x86_thread_state64_t::new(); let state_count = x86_thread_state64_t::count(); for (idx, &thread) in threads.iter().enumerate() { println!("Thread {}:", idx); let kret = thread_get_state(thread, x86_THREAD_STATE64, mem::transmute(&state), mem::transmute(&state_count)); if kret!= KERN_SUCCESS { println!("Did not succeed in getting task's thread state"); println!("kern_return_t error {}", kret); continue; } println!("{:?}", state); } } resume(task as task_t); println!("Success!"); }
{ let stdin = io::stdin(); let mut line = String::new(); stdin.read_line(&mut line).ok().unwrap(); let mut value : ::libc::c_int = 0; for c in line.chars().take_while(|&c| c != '\n') { if let Some(d) = c.to_digit(10) { value = value * 10 + (d as ::libc::c_int); } else { return Err(()); } } return Ok(value); }
identifier_body
output.rs
/// The types used by the generated parser to convert C4 into something usable /// by the accessor. /// Key-Value #[derive(Clone)] pub struct Property { id: String, value: String } impl Property { pub fn new(_id: String, _value: String) -> Self { Property { id: _id, value: _value } } } /// An invocation of a selector, with the id of the selector and the value it /// must have to match. #[derive(Clone)] pub struct Selection { id: String, value: String } impl Selection { pub fn new(_id: String, _value: String) -> Self { Selection { id: _id, value: _value } } } /// The set of selections for a specific rule. These are the selections that are /// AND'd together in evaluation. #[derive(Clone)] pub struct SelectionSet { selections: Vec<Selection> } impl SelectionSet { pub fn new(_selections: Vec<Selection>) -> Self { SelectionSet { selections: _selections } } pub fn add_selection(&mut self, s: Selection) { self.selections.push(s) } pub fn with_selection(&self, s: Selection) -> Self { let mut ss = self.selections.clone(); ss.push(s); SelectionSet { selections: ss,.. *self } } } /// An expression is either a vector of selection sets surrounding some expressions /// or a property pub enum Expression { Select { selections: Vec<SelectionSet>, expressions: Vec<Expression> }, Property(Property) } pub struct Configuration { pub expressions: Vec<Expression> } impl Configuration { pub fn new(_expressions: Vec<Expression>) -> Self { Configuration { expressions: _expressions } } } #[cfg(test)] mod tests { use parser::generated::*; use parser::output::*; fn dump_error_and_fail(e: ParseError) { println!("At line: {}, column: {}, offset: {}", e.line, e.column, e.offset); for exp in &e.expected { println!("expected to match {}", exp); } assert!(false, "failed to parse!");
fn check_cfg<F>(c: &str, f: F) where F: Fn(Configuration) { match configuration(c) { Ok(c) => f(c), Err(e) => dump_error_and_fail(e) } } #[test] fn test_simple_config() { check_cfg( r##" $country="us" $region="west" { taxRate: "8.0"; } "##, |c: Configuration| { assert_eq!(1, c.expressions.len()); } ); } #[test] fn test_multi_selection() { check_cfg( r##" $country="us" $region="west", $country="ca" $region="ca" { taxRate: "8.0"; } "##, |c: Configuration| { assert_eq!(1, c.expressions.len()); } ); } }
}
random_line_split
output.rs
/// The types used by the generated parser to convert C4 into something usable /// by the accessor. /// Key-Value #[derive(Clone)] pub struct Property { id: String, value: String } impl Property { pub fn new(_id: String, _value: String) -> Self
} /// An invocation of a selector, with the id of the selector and the value it /// must have to match. #[derive(Clone)] pub struct Selection { id: String, value: String } impl Selection { pub fn new(_id: String, _value: String) -> Self { Selection { id: _id, value: _value } } } /// The set of selections for a specific rule. These are the selections that are /// AND'd together in evaluation. #[derive(Clone)] pub struct SelectionSet { selections: Vec<Selection> } impl SelectionSet { pub fn new(_selections: Vec<Selection>) -> Self { SelectionSet { selections: _selections } } pub fn add_selection(&mut self, s: Selection) { self.selections.push(s) } pub fn with_selection(&self, s: Selection) -> Self { let mut ss = self.selections.clone(); ss.push(s); SelectionSet { selections: ss,.. *self } } } /// An expression is either a vector of selection sets surrounding some expressions /// or a property pub enum Expression { Select { selections: Vec<SelectionSet>, expressions: Vec<Expression> }, Property(Property) } pub struct Configuration { pub expressions: Vec<Expression> } impl Configuration { pub fn new(_expressions: Vec<Expression>) -> Self { Configuration { expressions: _expressions } } } #[cfg(test)] mod tests { use parser::generated::*; use parser::output::*; fn dump_error_and_fail(e: ParseError) { println!("At line: {}, column: {}, offset: {}", e.line, e.column, e.offset); for exp in &e.expected { println!("expected to match {}", exp); } assert!(false, "failed to parse!"); } fn check_cfg<F>(c: &str, f: F) where F: Fn(Configuration) { match configuration(c) { Ok(c) => f(c), Err(e) => dump_error_and_fail(e) } } #[test] fn test_simple_config() { check_cfg( r##" $country="us" $region="west" { taxRate: "8.0"; } "##, |c: Configuration| { assert_eq!(1, c.expressions.len()); } ); } #[test] fn test_multi_selection() { check_cfg( r##" $country="us" $region="west", $country="ca" $region="ca" { taxRate: "8.0"; } "##, |c: Configuration| { assert_eq!(1, c.expressions.len()); } ); } }
{ Property { id: _id, value: _value } }
identifier_body
output.rs
/// The types used by the generated parser to convert C4 into something usable /// by the accessor. /// Key-Value #[derive(Clone)] pub struct Property { id: String, value: String } impl Property { pub fn new(_id: String, _value: String) -> Self { Property { id: _id, value: _value } } } /// An invocation of a selector, with the id of the selector and the value it /// must have to match. #[derive(Clone)] pub struct Selection { id: String, value: String } impl Selection { pub fn new(_id: String, _value: String) -> Self { Selection { id: _id, value: _value } } } /// The set of selections for a specific rule. These are the selections that are /// AND'd together in evaluation. #[derive(Clone)] pub struct SelectionSet { selections: Vec<Selection> } impl SelectionSet { pub fn new(_selections: Vec<Selection>) -> Self { SelectionSet { selections: _selections } } pub fn
(&mut self, s: Selection) { self.selections.push(s) } pub fn with_selection(&self, s: Selection) -> Self { let mut ss = self.selections.clone(); ss.push(s); SelectionSet { selections: ss,.. *self } } } /// An expression is either a vector of selection sets surrounding some expressions /// or a property pub enum Expression { Select { selections: Vec<SelectionSet>, expressions: Vec<Expression> }, Property(Property) } pub struct Configuration { pub expressions: Vec<Expression> } impl Configuration { pub fn new(_expressions: Vec<Expression>) -> Self { Configuration { expressions: _expressions } } } #[cfg(test)] mod tests { use parser::generated::*; use parser::output::*; fn dump_error_and_fail(e: ParseError) { println!("At line: {}, column: {}, offset: {}", e.line, e.column, e.offset); for exp in &e.expected { println!("expected to match {}", exp); } assert!(false, "failed to parse!"); } fn check_cfg<F>(c: &str, f: F) where F: Fn(Configuration) { match configuration(c) { Ok(c) => f(c), Err(e) => dump_error_and_fail(e) } } #[test] fn test_simple_config() { check_cfg( r##" $country="us" $region="west" { taxRate: "8.0"; } "##, |c: Configuration| { assert_eq!(1, c.expressions.len()); } ); } #[test] fn test_multi_selection() { check_cfg( r##" $country="us" $region="west", $country="ca" $region="ca" { taxRate: "8.0"; } "##, |c: Configuration| { assert_eq!(1, c.expressions.len()); } ); } }
add_selection
identifier_name
problems.rs
//! Test Driven Learning Project. //! Desenvolva TDD e programação com TDD e programação! //! Módulo novice. //! //! The MIT License (MIT) //! //! Copyright (c) 2016 Paulo Henrique Rodrigues Pinheiro <[email protected]> //! //! Permission is hereby granted, free of charge, to any person obtaining a copy //! of this software and associated documentation files (the "Software"), to deal //! in the Software without restriction, including without limitation the rights //! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //! copies of the Software, and to permit persons to whom the Software is //! furnished to do so, subject to the following conditions: //! //! The above copyright notice and this permission notice shall be included in all //! copies or substantial portions of the Software. //! //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //! SOFTWARE. // Inclua os módulos que precisar aqui: /// A função `negue` deve receber um valor boleano (verdadeiro ou falso) e /// retornar a negação desse valor. /// /// # Examples /// /// ``` /// extern crate rust; /// assert_eq!(true, rust::problems::negue(false)); /// assert_eq!(false, rust::problems::negue(true)); /// ``` pub fn negue(value:bool) -> bool { false } /// A função `diga_ola` deve ser escrita de tal forma que receba como /// parâmetro um argumento *string*. Deve retornar a *string* "Olá, ", seguida /// do argumento recebido, mais um ponto final. A *string* recebida deve estar /// limpa, ou seja, sem caracteres de espaço no começo ou no fim. Se a *string* /// estiver vazia, retorna apenas "Olá!" /// /// # Examples /// /// ``` /// extern crate rust; /// /// assert_eq!("Olá!", rust::problems::diga_ola("")); /// assert_eq!("Olá!", rust::problems::diga_ola(" ")); /// assert_eq!("Olá, Paulo.", rust::problems::diga_ola("Paulo")); /// assert_eq!("Olá, Paulo.", rust::problems::diga_ola(" Paulo ")); /// assert_eq!("Olá, Paulo Henrique.", rust::problems::diga_ola(" Paulo Henrique ")); /// ``` pub fn diga_ola(nome:&str) -> String { "".to_string() } /// A função `lista_numeros_pares` deve receber um parâmetro numérico /// inteiro que determina quantos números pares devem estar em um array que /// será o retorno da função. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::lista_numeros_pares(0).len()); /// assert_eq!(vec![2], rust::problems::lista_numeros_pares(1)); /// assert_eq!(vec![2, 4, 6, 8], rust::problems::lista_numeros_pares(4)); /// assert_eq!(vec![2, 4, 6, 8, 10], rust::problems::lista_numeros_pares(5)); /// assert_eq!(0, rust::problems::lista_numeros_pares(-1).len()); /// ``` pub fn lista_numeros_pares(quantos:i32) -> Vec<i32> { vec![] } /// A função `lista_multiplos` deve receber dois parâmetros numéricos /// inteiros e retornar uma lista de números inteiros. O tamanho da lista é /// determinado pelo primeiro parâmetro, e o número base será o segundo /// parâmetro. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::lista_multiplos(0, 10).len()); /// assert_eq!(0, rust::problems::lista_multiplos(-1, 10).len()); /// assert_eq!(vec![-3, -2, -1], rust::problems::lista_multiplos(3, -1)); /// assert_eq!(0, rust::problems::lista_multiplos(3, 0).len()); /// assert_eq!(vec![10, 20, 30], rust::problems::lista_multiplos(3, 10)); /// ``` pub fn lista_multiplos(quantos:i32, base:i32) -> Vec<i32> { vec![] } /// A função `soma` deve receber um *array* de números inteiros, e retornar /// a sua soma. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::soma(vec![])); /// assert_eq!(1, rust::problems::soma(vec![1])); /// assert_eq!(3, rust::problems::soma(vec![1, 2])); /// ``` pub fn soma(lista:Vec<i32>) -> i32 { -1 } /// A função `subtracao` deve receber um *array* de números inteiros, e /// retornar a subtração de todos os elementos em sequência. Por exemplo, /// subtracao([3,2,1]) deve retornar 0, e subtracao([10,2,3]) deve retornar 5. /// Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::subtracao(vec![3, 2, 1])); /// assert_eq!(5, rust::problems::subtracao(vec![10, 2, 3])); /// assert_eq!(0, rust::problems::subtracao(vec![])); /// assert_eq!(-1, rust::problems::subtracao(vec![1, 2])); /// assert_eq!(4, rust::problems::subtracao(vec![-1, -2, -3])); /// assert_eq!(3, rust::problems::subtracao(vec![9, 3, 2, 1])); /// ``` pub fn subtracao(lista:Vec<i32>) -> i32 { -1 } /// A função `multiplicação` deve receber um *array* de números inteiros, e /// retornar o seu produto. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(6, rust::problems::multiplicacao(vec![1, 2, 3])); /// assert_eq!(0, rust::problems::multiplicacao(vec![])); /// assert_eq!(-8, rust::problems::multiplicacao(vec![-2, 1, 4])); /// assert_eq!(8, rust::problems::multiplicacao(vec![-2, -1, 4])); pub fn multiplicacao(lista:Vec<i32>) -> i32 { -1 } /// A função `divisao` deve receber um *array* de números inteiros, e /// retornar o resultado da sequência de divisões por cada elemento. Por /// exemplo, divisão([16, 4, 2]) deve retornar 2, e divisão([100,2,10]) deve /// retornar 5. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(2, rust::problems::divisao(vec![5, 2])); /// assert_eq!(0, rust::problems::divisao(vec![])); /// assert_eq!(0, rust::problems::divisao(vec![0])); /// assert_eq!(2, rust::problems::divisao(vec![16, 4, 2])); /// assert_eq!(5, rust::problems::divisao(vec![100, 2, 10])); /// assert_eq!(0, rust::problems::divisao(vec![0, 1])); /// //assert_eq!(0, rust::problems::divisao(vec![1, 0])); pub fn divisao(lista:Vec<i32>) ->i32 { -1 } /// A função `maior` deve receber um *array* de números inteiros e retornar /// qual é o maior deles. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(100, rust::problems::maior(vec![0, 1,100])); /// assert_eq!(0, rust::problems::maior(vec![0])); pub fn maior(lista:Vec<i32>)-> i32 { -1 } /// A função `intersecao` deve receber dois *arrays* contendo números /// inteiros, e retornar a interseção entre os conjuntos, ou seja, um *array* /// que contenha apenas os números que estejam contidos nos dois *arrays* /// passados para a função. /// /// Examples /// /// ``` /// assert_eq!(0, rust::problems::intersecao(vec![], vec![]).len()); /// assert_eq!(0, rust::problems::intersecao(vec![1, 2], vec![3, 4]).len()); /// assert_eq!(vec![2], rust::problems::intersecao(vec![1, 2], vec![2, 3])); pub fn intersecao(a:Vec<i32>, b:Vec<i32>) -> Vec<i32> { vec![] }
identifier_name
problems.rs
//! Test Driven Learning Project. //! Desenvolva TDD e programação com TDD e programação! //! Módulo novice. //! //! The MIT License (MIT) //! //! Copyright (c) 2016 Paulo Henrique Rodrigues Pinheiro <[email protected]> //! //! Permission is hereby granted, free of charge, to any person obtaining a copy //! of this software and associated documentation files (the "Software"), to deal //! in the Software without restriction, including without limitation the rights //! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //! copies of the Software, and to permit persons to whom the Software is //! furnished to do so, subject to the following conditions: //! //! The above copyright notice and this permission notice shall be included in all //! copies or substantial portions of the Software. //! //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //! SOFTWARE. // Inclua os módulos que precisar aqui: /// A função `negue` deve receber um valor boleano (verdadeiro ou falso) e /// retornar a negação desse valor. /// /// # Examples /// /// ``` /// extern crate rust; /// assert_eq!(true, rust::problems::negue(false)); /// assert_eq!(false, rust::problems::negue(true)); /// ``` pub fn negue(value:bool) -> bool { false } /// A função `diga_ola` deve ser escrita de tal forma que receba como /// parâmetro um argumento *string*. Deve retornar a *string* "Olá, ", seguida /// do argumento recebido, mais um ponto final. A *string* recebida deve estar /// limpa, ou seja, sem caracteres de espaço no começo ou no fim. Se a *string* /// estiver vazia, retorna apenas "Olá!" /// /// # Examples /// /// ``` /// extern crate rust; /// /// assert_eq!("Olá!", rust::problems::diga_ola("")); /// assert_eq!("Olá!", rust::problems::diga_ola(" ")); /// assert_eq!("Olá, Paulo.", rust::problems::diga_ola("Paulo")); /// assert_eq!("Olá, Paulo.", rust::problems::diga_ola(" Paulo ")); /// assert_eq!("Olá, Paulo Henrique.", rust::problems::diga_ola(" Paulo Henrique ")); /// ``` pub fn diga_ola(nome:&str) -> String { "".to_string() } /// A função `lista_numeros_pares` deve receber um parâmetro numérico /// inteiro que determina quantos números pares devem estar em um array que /// será o retorno da função. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::lista_numeros_pares(0).len()); /// assert_eq!(vec![2], rust::problems::lista_numeros_pares(1)); /// assert_eq!(vec![2, 4, 6, 8], rust::problems::lista_numeros_pares(4)); /// assert_eq!(vec![2, 4, 6, 8, 10], rust::problems::lista_numeros_pares(5)); /// assert_eq!(0, rust::problems::lista_numeros_pares(-1).len()); /// ``` pub fn lista_numeros_pares(quantos:i32) -> Vec<i32> { vec![] } /// A função `lista_multiplos` deve receber dois parâmetros numéricos /// inteiros e retornar uma lista de números inteiros. O tamanho da lista é /// determinado pelo primeiro parâmetro, e o número base será o segundo /// parâmetro. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::lista_multiplos(0, 10).len()); /// assert_eq!(0, rust::problems::lista_multiplos(-1, 10).len()); /// assert_eq!(vec![-3, -2, -1], rust::problems::lista_multiplos(3, -1)); /// assert_eq!(0, rust::problems::lista_multiplos(3, 0).len()); /// assert_eq!(vec![10, 20, 30], rust::problems::lista_multiplos(3, 10)); /// ``` pub fn lista_multiplos(quantos:i32, base:i32) -> Vec<i32> { vec![] } /// A função `soma` deve receber um *array* de números inteiros, e retornar /// a sua soma. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::soma(vec![])); /// assert_eq!(1, rust::problems::soma(vec![1])); /// assert_eq!(3, rust::problems::soma(vec![1, 2])); /// ``` pub fn soma(lista:Vec<i32>) -> i32 { -1 } /// A função `subtracao` deve receber um *array* de números inteiros, e /// retornar a subtração de todos os elementos em sequência. Por exemplo, /// subtracao([3,2,1]) deve retornar 0, e subtracao([10,2,3]) deve retornar 5. /// Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::subtracao(vec![3, 2, 1])); /// assert_eq!(5, rust::problems::subtracao(vec![10, 2, 3])); /// assert_eq!(0, rust::problems::subtracao(vec![])); /// assert_eq!(-1, rust::problems::subtracao(vec![1, 2])); /// assert_eq!(4, rust::problems::subtracao(vec![-1, -2, -3])); /// assert_eq!(3, rust::problems::subtracao(vec![9, 3, 2, 1])); /// ``` pub fn subtracao(lista:Vec<i32>) -> i32 { -1 } /// A função `multiplicação` deve receber um *array* de números inteiros, e /// retornar o seu produto. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(6, rust::problems::multiplicacao(vec![1, 2, 3]));
-1 } /// A função `divisao` deve receber um *array* de números inteiros, e /// retornar o resultado da sequência de divisões por cada elemento. Por /// exemplo, divisão([16, 4, 2]) deve retornar 2, e divisão([100,2,10]) deve /// retornar 5. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(2, rust::problems::divisao(vec![5, 2])); /// assert_eq!(0, rust::problems::divisao(vec![])); /// assert_eq!(0, rust::problems::divisao(vec![0])); /// assert_eq!(2, rust::problems::divisao(vec![16, 4, 2])); /// assert_eq!(5, rust::problems::divisao(vec![100, 2, 10])); /// assert_eq!(0, rust::problems::divisao(vec![0, 1])); /// //assert_eq!(0, rust::problems::divisao(vec![1, 0])); pub fn divisao(lista:Vec<i32>) ->i32 { -1 } /// A função `maior` deve receber um *array* de números inteiros e retornar /// qual é o maior deles. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(100, rust::problems::maior(vec![0, 1,100])); /// assert_eq!(0, rust::problems::maior(vec![0])); pub fn maior(lista:Vec<i32>)-> i32 { -1 } /// A função `intersecao` deve receber dois *arrays* contendo números /// inteiros, e retornar a interseção entre os conjuntos, ou seja, um *array* /// que contenha apenas os números que estejam contidos nos dois *arrays* /// passados para a função. /// /// Examples /// /// ``` /// assert_eq!(0, rust::problems::intersecao(vec![], vec![]).len()); /// assert_eq!(0, rust::problems::intersecao(vec![1, 2], vec![3, 4]).len()); /// assert_eq!(vec![2], rust::problems::intersecao(vec![1, 2], vec![2, 3])); pub fn intersecao(a:Vec<i32>, b:Vec<i32>) -> Vec<i32> { vec![] }
/// assert_eq!(0, rust::problems::multiplicacao(vec![])); /// assert_eq!(-8, rust::problems::multiplicacao(vec![-2, 1, 4])); /// assert_eq!(8, rust::problems::multiplicacao(vec![-2, -1, 4])); pub fn multiplicacao(lista:Vec<i32>) -> i32 {
random_line_split
problems.rs
//! Test Driven Learning Project. //! Desenvolva TDD e programação com TDD e programação! //! Módulo novice. //! //! The MIT License (MIT) //! //! Copyright (c) 2016 Paulo Henrique Rodrigues Pinheiro <[email protected]> //! //! Permission is hereby granted, free of charge, to any person obtaining a copy //! of this software and associated documentation files (the "Software"), to deal //! in the Software without restriction, including without limitation the rights //! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //! copies of the Software, and to permit persons to whom the Software is //! furnished to do so, subject to the following conditions: //! //! The above copyright notice and this permission notice shall be included in all //! copies or substantial portions of the Software. //! //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //! SOFTWARE. // Inclua os módulos que precisar aqui: /// A função `negue` deve receber um valor boleano (verdadeiro ou falso) e /// retornar a negação desse valor. /// /// # Examples /// /// ``` /// extern crate rust; /// assert_eq!(true, rust::problems::negue(false)); /// assert_eq!(false, rust::problems::negue(true)); /// ``` pub fn negue(value:bool) -> bool { fals
unção `diga_ola` deve ser escrita de tal forma que receba como /// parâmetro um argumento *string*. Deve retornar a *string* "Olá, ", seguida /// do argumento recebido, mais um ponto final. A *string* recebida deve estar /// limpa, ou seja, sem caracteres de espaço no começo ou no fim. Se a *string* /// estiver vazia, retorna apenas "Olá!" /// /// # Examples /// /// ``` /// extern crate rust; /// /// assert_eq!("Olá!", rust::problems::diga_ola("")); /// assert_eq!("Olá!", rust::problems::diga_ola(" ")); /// assert_eq!("Olá, Paulo.", rust::problems::diga_ola("Paulo")); /// assert_eq!("Olá, Paulo.", rust::problems::diga_ola(" Paulo ")); /// assert_eq!("Olá, Paulo Henrique.", rust::problems::diga_ola(" Paulo Henrique ")); /// ``` pub fn diga_ola(nome:&str) -> String { "".to_string() } /// A função `lista_numeros_pares` deve receber um parâmetro numérico /// inteiro que determina quantos números pares devem estar em um array que /// será o retorno da função. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::lista_numeros_pares(0).len()); /// assert_eq!(vec![2], rust::problems::lista_numeros_pares(1)); /// assert_eq!(vec![2, 4, 6, 8], rust::problems::lista_numeros_pares(4)); /// assert_eq!(vec![2, 4, 6, 8, 10], rust::problems::lista_numeros_pares(5)); /// assert_eq!(0, rust::problems::lista_numeros_pares(-1).len()); /// ``` pub fn lista_numeros_pares(quantos:i32) -> Vec<i32> { vec![] } /// A função `lista_multiplos` deve receber dois parâmetros numéricos /// inteiros e retornar uma lista de números inteiros. O tamanho da lista é /// determinado pelo primeiro parâmetro, e o número base será o segundo /// parâmetro. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::lista_multiplos(0, 10).len()); /// assert_eq!(0, rust::problems::lista_multiplos(-1, 10).len()); /// assert_eq!(vec![-3, -2, -1], rust::problems::lista_multiplos(3, -1)); /// assert_eq!(0, rust::problems::lista_multiplos(3, 0).len()); /// assert_eq!(vec![10, 20, 30], rust::problems::lista_multiplos(3, 10)); /// ``` pub fn lista_multiplos(quantos:i32, base:i32) -> Vec<i32> { vec![] } /// A função `soma` deve receber um *array* de números inteiros, e retornar /// a sua soma. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::soma(vec![])); /// assert_eq!(1, rust::problems::soma(vec![1])); /// assert_eq!(3, rust::problems::soma(vec![1, 2])); /// ``` pub fn soma(lista:Vec<i32>) -> i32 { -1 } /// A função `subtracao` deve receber um *array* de números inteiros, e /// retornar a subtração de todos os elementos em sequência. Por exemplo, /// subtracao([3,2,1]) deve retornar 0, e subtracao([10,2,3]) deve retornar 5. /// Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(0, rust::problems::subtracao(vec![3, 2, 1])); /// assert_eq!(5, rust::problems::subtracao(vec![10, 2, 3])); /// assert_eq!(0, rust::problems::subtracao(vec![])); /// assert_eq!(-1, rust::problems::subtracao(vec![1, 2])); /// assert_eq!(4, rust::problems::subtracao(vec![-1, -2, -3])); /// assert_eq!(3, rust::problems::subtracao(vec![9, 3, 2, 1])); /// ``` pub fn subtracao(lista:Vec<i32>) -> i32 { -1 } /// A função `multiplicação` deve receber um *array* de números inteiros, e /// retornar o seu produto. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(6, rust::problems::multiplicacao(vec![1, 2, 3])); /// assert_eq!(0, rust::problems::multiplicacao(vec![])); /// assert_eq!(-8, rust::problems::multiplicacao(vec![-2, 1, 4])); /// assert_eq!(8, rust::problems::multiplicacao(vec![-2, -1, 4])); pub fn multiplicacao(lista:Vec<i32>) -> i32 { -1 } /// A função `divisao` deve receber um *array* de números inteiros, e /// retornar o resultado da sequência de divisões por cada elemento. Por /// exemplo, divisão([16, 4, 2]) deve retornar 2, e divisão([100,2,10]) deve /// retornar 5. Se a lista for vazia, deve retornar zero. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(2, rust::problems::divisao(vec![5, 2])); /// assert_eq!(0, rust::problems::divisao(vec![])); /// assert_eq!(0, rust::problems::divisao(vec![0])); /// assert_eq!(2, rust::problems::divisao(vec![16, 4, 2])); /// assert_eq!(5, rust::problems::divisao(vec![100, 2, 10])); /// assert_eq!(0, rust::problems::divisao(vec![0, 1])); /// //assert_eq!(0, rust::problems::divisao(vec![1, 0])); pub fn divisao(lista:Vec<i32>) ->i32 { -1 } /// A função `maior` deve receber um *array* de números inteiros e retornar /// qual é o maior deles. /// /// Examples /// /// ``` /// extern crate rust; /// /// assert_eq!(100, rust::problems::maior(vec![0, 1,100])); /// assert_eq!(0, rust::problems::maior(vec![0])); pub fn maior(lista:Vec<i32>)-> i32 { -1 } /// A função `intersecao` deve receber dois *arrays* contendo números /// inteiros, e retornar a interseção entre os conjuntos, ou seja, um *array* /// que contenha apenas os números que estejam contidos nos dois *arrays* /// passados para a função. /// /// Examples /// /// ``` /// assert_eq!(0, rust::problems::intersecao(vec![], vec![]).len()); /// assert_eq!(0, rust::problems::intersecao(vec![1, 2], vec![3, 4]).len()); /// assert_eq!(vec![2], rust::problems::intersecao(vec![1, 2], vec![2, 3])); pub fn intersecao(a:Vec<i32>, b:Vec<i32>) -> Vec<i32> { vec![] }
e } /// A f
identifier_body
framerate.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 actor::{Actor, ActorRegistry, ActorMessageStatus}; use actors::timeline::HighResolutionStamp; use devtools_traits::DevtoolScriptControlMsg; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use rustc_serialize::json; use std::mem; use std::net::TcpStream; use time::precise_time_ns; pub struct FramerateActor { name: String, pipeline: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>, start_time: Option<u64>, is_recording: bool, ticks: Vec<HighResolutionStamp>, } impl Actor for FramerateActor { fn name(&self) -> String { self.name.clone() } fn handle_message(&self, _registry: &ActorRegistry, _msg_type: &str, _msg: &json::Object, _stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> { Ok(ActorMessageStatus::Ignored) } } impl FramerateActor { /// return name of actor pub fn create(registry: &ActorRegistry, pipeline_id: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>) -> String
pub fn add_tick(&mut self, tick: f64) { self.ticks.push(HighResolutionStamp::wrap(tick)); if self.is_recording { let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } } pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> { mem::replace(&mut self.ticks, Vec::new()) } fn start_recording(&mut self) { if self.is_recording { return; } self.start_time = Some(precise_time_ns()); self.is_recording = true; let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } fn stop_recording(&mut self) { if!self.is_recording { return; } self.is_recording = false; self.start_time = None; } } impl Drop for FramerateActor { fn drop(&mut self) { self.stop_recording(); } }
{ let actor_name = registry.new_name("framerate"); let mut actor = FramerateActor { name: actor_name.clone(), pipeline: pipeline_id, script_sender: script_sender, start_time: None, is_recording: false, ticks: Vec::new(), }; actor.start_recording(); registry.register_later(box actor); actor_name }
identifier_body
framerate.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 actor::{Actor, ActorRegistry, ActorMessageStatus}; use actors::timeline::HighResolutionStamp; use devtools_traits::DevtoolScriptControlMsg; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use rustc_serialize::json; use std::mem; use std::net::TcpStream; use time::precise_time_ns; pub struct FramerateActor { name: String, pipeline: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>, start_time: Option<u64>, is_recording: bool, ticks: Vec<HighResolutionStamp>, } impl Actor for FramerateActor { fn name(&self) -> String { self.name.clone() } fn handle_message(&self, _registry: &ActorRegistry, _msg_type: &str, _msg: &json::Object, _stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> { Ok(ActorMessageStatus::Ignored) } } impl FramerateActor { /// return name of actor pub fn create(registry: &ActorRegistry, pipeline_id: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>) -> String { let actor_name = registry.new_name("framerate"); let mut actor = FramerateActor { name: actor_name.clone(), pipeline: pipeline_id, script_sender: script_sender, start_time: None, is_recording: false, ticks: Vec::new(), }; actor.start_recording(); registry.register_later(box actor); actor_name } pub fn add_tick(&mut self, tick: f64) { self.ticks.push(HighResolutionStamp::wrap(tick)); if self.is_recording { let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } } pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> { mem::replace(&mut self.ticks, Vec::new()) } fn
(&mut self) { if self.is_recording { return; } self.start_time = Some(precise_time_ns()); self.is_recording = true; let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } fn stop_recording(&mut self) { if!self.is_recording { return; } self.is_recording = false; self.start_time = None; } } impl Drop for FramerateActor { fn drop(&mut self) { self.stop_recording(); } }
start_recording
identifier_name
framerate.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 actor::{Actor, ActorRegistry, ActorMessageStatus}; use actors::timeline::HighResolutionStamp; use devtools_traits::DevtoolScriptControlMsg; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use rustc_serialize::json; use std::mem; use std::net::TcpStream; use time::precise_time_ns; pub struct FramerateActor { name: String, pipeline: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>, start_time: Option<u64>, is_recording: bool, ticks: Vec<HighResolutionStamp>, } impl Actor for FramerateActor { fn name(&self) -> String { self.name.clone() } fn handle_message(&self, _registry: &ActorRegistry, _msg_type: &str, _msg: &json::Object, _stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> { Ok(ActorMessageStatus::Ignored) } } impl FramerateActor { /// return name of actor pub fn create(registry: &ActorRegistry, pipeline_id: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>) -> String { let actor_name = registry.new_name("framerate"); let mut actor = FramerateActor { name: actor_name.clone(), pipeline: pipeline_id, script_sender: script_sender, start_time: None, is_recording: false, ticks: Vec::new(), }; actor.start_recording(); registry.register_later(box actor); actor_name } pub fn add_tick(&mut self, tick: f64) { self.ticks.push(HighResolutionStamp::wrap(tick)); if self.is_recording { let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } } pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> {
return; } self.start_time = Some(precise_time_ns()); self.is_recording = true; let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } fn stop_recording(&mut self) { if!self.is_recording { return; } self.is_recording = false; self.start_time = None; } } impl Drop for FramerateActor { fn drop(&mut self) { self.stop_recording(); } }
mem::replace(&mut self.ticks, Vec::new()) } fn start_recording(&mut self) { if self.is_recording {
random_line_split
framerate.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 actor::{Actor, ActorRegistry, ActorMessageStatus}; use actors::timeline::HighResolutionStamp; use devtools_traits::DevtoolScriptControlMsg; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use rustc_serialize::json; use std::mem; use std::net::TcpStream; use time::precise_time_ns; pub struct FramerateActor { name: String, pipeline: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>, start_time: Option<u64>, is_recording: bool, ticks: Vec<HighResolutionStamp>, } impl Actor for FramerateActor { fn name(&self) -> String { self.name.clone() } fn handle_message(&self, _registry: &ActorRegistry, _msg_type: &str, _msg: &json::Object, _stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> { Ok(ActorMessageStatus::Ignored) } } impl FramerateActor { /// return name of actor pub fn create(registry: &ActorRegistry, pipeline_id: PipelineId, script_sender: IpcSender<DevtoolScriptControlMsg>) -> String { let actor_name = registry.new_name("framerate"); let mut actor = FramerateActor { name: actor_name.clone(), pipeline: pipeline_id, script_sender: script_sender, start_time: None, is_recording: false, ticks: Vec::new(), }; actor.start_recording(); registry.register_later(box actor); actor_name } pub fn add_tick(&mut self, tick: f64) { self.ticks.push(HighResolutionStamp::wrap(tick)); if self.is_recording { let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } } pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> { mem::replace(&mut self.ticks, Vec::new()) } fn start_recording(&mut self) { if self.is_recording
self.start_time = Some(precise_time_ns()); self.is_recording = true; let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, self.name()); self.script_sender.send(msg).unwrap(); } fn stop_recording(&mut self) { if!self.is_recording { return; } self.is_recording = false; self.start_time = None; } } impl Drop for FramerateActor { fn drop(&mut self) { self.stop_recording(); } }
{ return; }
conditional_block
cci_impl_exe.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
extern mod cci_impl_lib; use cci_impl_lib::uint_helpers; pub fn main() { //let bt0 = sys::frame_address(); //info!("%?", bt0); 3u.to(10u, |i| { println!("{}", i); //let bt1 = sys::frame_address(); //info!("%?", bt1); //assert!(bt0 == bt1); }) }
// except according to those terms. // xfail-fast - check-fast doesn't understand aux-build // aux-build:cci_impl_lib.rs
random_line_split
cci_impl_exe.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast - check-fast doesn't understand aux-build // aux-build:cci_impl_lib.rs extern mod cci_impl_lib; use cci_impl_lib::uint_helpers; pub fn main()
{ //let bt0 = sys::frame_address(); //info!("%?", bt0); 3u.to(10u, |i| { println!("{}", i); //let bt1 = sys::frame_address(); //info!("%?", bt1); //assert!(bt0 == bt1); }) }
identifier_body
cci_impl_exe.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast - check-fast doesn't understand aux-build // aux-build:cci_impl_lib.rs extern mod cci_impl_lib; use cci_impl_lib::uint_helpers; pub fn
() { //let bt0 = sys::frame_address(); //info!("%?", bt0); 3u.to(10u, |i| { println!("{}", i); //let bt1 = sys::frame_address(); //info!("%?", bt1); //assert!(bt0 == bt1); }) }
main
identifier_name
image_cache_task.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 image::base::Image; use url::Url; use std::sync::Arc; use std::sync::mpsc::{channel, Sender}; /// This is optionally passed to the image cache when requesting /// and image, and returned to the specified event loop when the /// image load completes. It is typically used to trigger a reflow /// and/or repaint. pub trait ImageResponder : Send { fn respond(&self, ImageResponse); } /// The current state of an image in the cache. #[derive(PartialEq, Copy, Clone)] pub enum ImageState { Pending, LoadError, NotRequested, } /// The returned image. #[derive(Clone)] pub enum ImageResponse { /// The requested image was loaded. Loaded(Arc<Image>), /// The requested image failed to load, so a placeholder was loaded instead. PlaceholderLoaded(Arc<Image>), /// Neither the requested image nor the placeholder could be loaded. None
#[derive(Clone)] pub struct ImageCacheChan(pub Sender<ImageCacheResult>); /// The result of an image cache command that is returned to the /// caller. pub struct ImageCacheResult { pub responder: Option<Box<ImageResponder>>, pub image_response: ImageResponse, } /// Commands that the image cache understands. pub enum ImageCacheCommand { /// Request an image asynchronously from the cache. Supply a channel /// to receive the result, and optionally an image responder /// that is passed to the result channel. RequestImage(Url, ImageCacheChan, Option<Box<ImageResponder>>), /// Synchronously check the state of an image in the cache. /// TODO(gw): Profile this on some real world sites and see /// if it's worth caching the results of this locally in each /// layout / paint task. GetImageIfAvailable(Url, UsePlaceholder, Sender<Result<Arc<Image>, ImageState>>), /// Clients must wait for a response before shutting down the ResourceTask Exit(Sender<()>), } #[derive(Copy, Clone, PartialEq)] pub enum UsePlaceholder { No, Yes, } /// The client side of the image cache task. This can be safely cloned /// and passed to different tasks. #[derive(Clone)] pub struct ImageCacheTask { chan: Sender<ImageCacheCommand>, } /// The public API for the image cache task. impl ImageCacheTask { /// Construct a new image cache pub fn new(chan: Sender<ImageCacheCommand>) -> ImageCacheTask { ImageCacheTask { chan: chan, } } /// Asynchronously request and image. See ImageCacheCommand::RequestImage. pub fn request_image(&self, url: Url, result_chan: ImageCacheChan, responder: Option<Box<ImageResponder>>) { let msg = ImageCacheCommand::RequestImage(url, result_chan, responder); self.chan.send(msg).unwrap(); } /// Get the current state of an image. See ImageCacheCommand::GetImageIfAvailable. pub fn get_image_if_available(&self, url: Url, use_placeholder: UsePlaceholder) -> Result<Arc<Image>, ImageState> { let (sender, receiver) = channel(); let msg = ImageCacheCommand::GetImageIfAvailable(url, use_placeholder, sender); self.chan.send(msg).unwrap(); receiver.recv().unwrap() } /// Shutdown the image cache task. pub fn exit(&self) { let (response_chan, response_port) = channel(); self.chan.send(ImageCacheCommand::Exit(response_chan)).unwrap(); response_port.recv().unwrap(); } }
} /// Channel for sending commands to the image cache.
random_line_split
image_cache_task.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 image::base::Image; use url::Url; use std::sync::Arc; use std::sync::mpsc::{channel, Sender}; /// This is optionally passed to the image cache when requesting /// and image, and returned to the specified event loop when the /// image load completes. It is typically used to trigger a reflow /// and/or repaint. pub trait ImageResponder : Send { fn respond(&self, ImageResponse); } /// The current state of an image in the cache. #[derive(PartialEq, Copy, Clone)] pub enum ImageState { Pending, LoadError, NotRequested, } /// The returned image. #[derive(Clone)] pub enum ImageResponse { /// The requested image was loaded. Loaded(Arc<Image>), /// The requested image failed to load, so a placeholder was loaded instead. PlaceholderLoaded(Arc<Image>), /// Neither the requested image nor the placeholder could be loaded. None } /// Channel for sending commands to the image cache. #[derive(Clone)] pub struct ImageCacheChan(pub Sender<ImageCacheResult>); /// The result of an image cache command that is returned to the /// caller. pub struct
{ pub responder: Option<Box<ImageResponder>>, pub image_response: ImageResponse, } /// Commands that the image cache understands. pub enum ImageCacheCommand { /// Request an image asynchronously from the cache. Supply a channel /// to receive the result, and optionally an image responder /// that is passed to the result channel. RequestImage(Url, ImageCacheChan, Option<Box<ImageResponder>>), /// Synchronously check the state of an image in the cache. /// TODO(gw): Profile this on some real world sites and see /// if it's worth caching the results of this locally in each /// layout / paint task. GetImageIfAvailable(Url, UsePlaceholder, Sender<Result<Arc<Image>, ImageState>>), /// Clients must wait for a response before shutting down the ResourceTask Exit(Sender<()>), } #[derive(Copy, Clone, PartialEq)] pub enum UsePlaceholder { No, Yes, } /// The client side of the image cache task. This can be safely cloned /// and passed to different tasks. #[derive(Clone)] pub struct ImageCacheTask { chan: Sender<ImageCacheCommand>, } /// The public API for the image cache task. impl ImageCacheTask { /// Construct a new image cache pub fn new(chan: Sender<ImageCacheCommand>) -> ImageCacheTask { ImageCacheTask { chan: chan, } } /// Asynchronously request and image. See ImageCacheCommand::RequestImage. pub fn request_image(&self, url: Url, result_chan: ImageCacheChan, responder: Option<Box<ImageResponder>>) { let msg = ImageCacheCommand::RequestImage(url, result_chan, responder); self.chan.send(msg).unwrap(); } /// Get the current state of an image. See ImageCacheCommand::GetImageIfAvailable. pub fn get_image_if_available(&self, url: Url, use_placeholder: UsePlaceholder) -> Result<Arc<Image>, ImageState> { let (sender, receiver) = channel(); let msg = ImageCacheCommand::GetImageIfAvailable(url, use_placeholder, sender); self.chan.send(msg).unwrap(); receiver.recv().unwrap() } /// Shutdown the image cache task. pub fn exit(&self) { let (response_chan, response_port) = channel(); self.chan.send(ImageCacheCommand::Exit(response_chan)).unwrap(); response_port.recv().unwrap(); } }
ImageCacheResult
identifier_name
day19.rs
use std::fs::File; use std::io::BufReader; use std::io::BufRead; use std::collections::HashSet; struct Replacement { before: String, after: String, } fn replace(med: &str, rep: &Replacement) -> Vec<String> { let mut meds: Vec<String> = Vec::new(); let parts: Vec<&str> = med.split(&rep.before).collect(); for i in 1..parts.len() { let mut new_med = parts[0].to_string(); for j in 1..parts.len() { if i == j { new_med = new_med + &rep.after; } else { new_med = new_med + &rep.before; } new_med = new_med + parts[j]; } meds.push(new_med); } meds } fn search(med: &str, reps: &Vec<Replacement>) -> u32 { struct State { molecule: String, steps: u32 } let mut queue: Vec<State> = Vec::new(); queue.push( State{ molecule: med.to_string(), steps: 0, } ); while!queue.is_empty() { let s = queue.pop().unwrap(); if s.molecule == "e" { return s.steps } for r in reps { for m in replace(&s.molecule, &r) { queue.push( State{ molecule: m.clone(), steps: s.steps + 1, } ); } } queue.sort_by(|a, b| b.molecule.len().cmp(&a.molecule.len())); } unreachable!(); } fn main() { let f = File::open("day19.in") .ok() .expect("Error opening input"); let file = BufReader::new(&f); let mut in_replacements = true; let mut replacements: Vec<Replacement> = Vec::new(); let mut medecine: String = String::new(); for l in file.lines() { let l = l.unwrap(); if in_replacements { if l == "" { in_replacements = false; } else { let parts: Vec<&str> = l.trim().split(" => ").collect(); replacements.push(Replacement{ before: parts[0].to_string(), after: parts[1].to_string(), }); } } else { medecine = l.trim().to_string(); } }
let mut meds = HashSet::new(); for r in &replacements { for m in replace(&medecine, &r) { meds.insert(m); } } println!("{}", meds.len()); let mut reversed: Vec<Replacement> = Vec::new(); for r in &replacements { reversed.push(Replacement{ before: r.after.clone(), after: r.before.clone(), }); } let steps = search(&medecine, &reversed); println!("{}", steps) }
random_line_split
day19.rs
use std::fs::File; use std::io::BufReader; use std::io::BufRead; use std::collections::HashSet; struct Replacement { before: String, after: String, } fn replace(med: &str, rep: &Replacement) -> Vec<String> { let mut meds: Vec<String> = Vec::new(); let parts: Vec<&str> = med.split(&rep.before).collect(); for i in 1..parts.len() { let mut new_med = parts[0].to_string(); for j in 1..parts.len() { if i == j { new_med = new_med + &rep.after; } else
new_med = new_med + parts[j]; } meds.push(new_med); } meds } fn search(med: &str, reps: &Vec<Replacement>) -> u32 { struct State { molecule: String, steps: u32 } let mut queue: Vec<State> = Vec::new(); queue.push( State{ molecule: med.to_string(), steps: 0, } ); while!queue.is_empty() { let s = queue.pop().unwrap(); if s.molecule == "e" { return s.steps } for r in reps { for m in replace(&s.molecule, &r) { queue.push( State{ molecule: m.clone(), steps: s.steps + 1, } ); } } queue.sort_by(|a, b| b.molecule.len().cmp(&a.molecule.len())); } unreachable!(); } fn main() { let f = File::open("day19.in") .ok() .expect("Error opening input"); let file = BufReader::new(&f); let mut in_replacements = true; let mut replacements: Vec<Replacement> = Vec::new(); let mut medecine: String = String::new(); for l in file.lines() { let l = l.unwrap(); if in_replacements { if l == "" { in_replacements = false; } else { let parts: Vec<&str> = l.trim().split(" => ").collect(); replacements.push(Replacement{ before: parts[0].to_string(), after: parts[1].to_string(), }); } } else { medecine = l.trim().to_string(); } } let mut meds = HashSet::new(); for r in &replacements { for m in replace(&medecine, &r) { meds.insert(m); } } println!("{}", meds.len()); let mut reversed: Vec<Replacement> = Vec::new(); for r in &replacements { reversed.push(Replacement{ before: r.after.clone(), after: r.before.clone(), }); } let steps = search(&medecine, &reversed); println!("{}", steps) }
{ new_med = new_med + &rep.before; }
conditional_block
day19.rs
use std::fs::File; use std::io::BufReader; use std::io::BufRead; use std::collections::HashSet; struct Replacement { before: String, after: String, } fn replace(med: &str, rep: &Replacement) -> Vec<String> { let mut meds: Vec<String> = Vec::new(); let parts: Vec<&str> = med.split(&rep.before).collect(); for i in 1..parts.len() { let mut new_med = parts[0].to_string(); for j in 1..parts.len() { if i == j { new_med = new_med + &rep.after; } else { new_med = new_med + &rep.before; } new_med = new_med + parts[j]; } meds.push(new_med); } meds } fn
(med: &str, reps: &Vec<Replacement>) -> u32 { struct State { molecule: String, steps: u32 } let mut queue: Vec<State> = Vec::new(); queue.push( State{ molecule: med.to_string(), steps: 0, } ); while!queue.is_empty() { let s = queue.pop().unwrap(); if s.molecule == "e" { return s.steps } for r in reps { for m in replace(&s.molecule, &r) { queue.push( State{ molecule: m.clone(), steps: s.steps + 1, } ); } } queue.sort_by(|a, b| b.molecule.len().cmp(&a.molecule.len())); } unreachable!(); } fn main() { let f = File::open("day19.in") .ok() .expect("Error opening input"); let file = BufReader::new(&f); let mut in_replacements = true; let mut replacements: Vec<Replacement> = Vec::new(); let mut medecine: String = String::new(); for l in file.lines() { let l = l.unwrap(); if in_replacements { if l == "" { in_replacements = false; } else { let parts: Vec<&str> = l.trim().split(" => ").collect(); replacements.push(Replacement{ before: parts[0].to_string(), after: parts[1].to_string(), }); } } else { medecine = l.trim().to_string(); } } let mut meds = HashSet::new(); for r in &replacements { for m in replace(&medecine, &r) { meds.insert(m); } } println!("{}", meds.len()); let mut reversed: Vec<Replacement> = Vec::new(); for r in &replacements { reversed.push(Replacement{ before: r.after.clone(), after: r.before.clone(), }); } let steps = search(&medecine, &reversed); println!("{}", steps) }
search
identifier_name
issue-31948-2.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:rustdoc-nonreachable-impls.rs // build-aux-docs // ignore-cross-compile extern crate rustdoc_nonreachable_impls; // @has issue_31948_2/struct.Wobble.html // @has - '//*[@class="impl"]//code' 'Qux for' // @has - '//*[@class="impl"]//code' 'Bark for' // @has - '//*[@class="impl"]//code' 'Woof for' // @!has - '//*[@class="impl"]//code' 'Bar for' pub use rustdoc_nonreachable_impls::hidden::Wobble; // @has issue_31948_2/trait.Qux.html // @has - '//code' 'for Foo' // @has - '//code' 'for Wobble' pub use rustdoc_nonreachable_impls::hidden::Qux; // @!has issue_31948_2/trait.Bar.html // @!has issue_31948_2/trait.Woof.html
// @!has issue_31948_2/trait.Bark.html
random_line_split
term.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Simple ANSI color library #[allow(missing_doc)]; use std::os; use terminfo::*; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; // FIXME (#2807): Windows support. pub mod color { pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16; pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; } pub mod attr { /// Terminal attributes for use with term.attr(). /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(super::color::Color), /// Convenience attribute to set the background color BackgroundColor(super::color::Color) } } fn cap_for_attr(attr: attr::Attr) -> &'static str { match attr { attr::Bold => "bold", attr::Dim => "dim", attr::Italic(true) => "sitm", attr::Italic(false) => "ritm", attr::Underline(true) => "smul", attr::Underline(false) => "rmul", attr::Blink => "blink", attr::Standout(true) => "smso", attr::Standout(false) => "rmso", attr::Reverse => "rev", attr::Secure => "invis", attr::ForegroundColor(_) => "setaf", attr::BackgroundColor(_) => "setab" } } pub struct Terminal<T> { priv num_colors: u16, priv out: T, priv ti: ~TermInfo } impl<T: Writer> Terminal<T> { pub fn new(out: T) -> Result<Terminal<T>, ~str> { let term = match os::getenv("TERM") { Some(t) => t, None => return Err(~"TERM environment variable undefined") }; let entry = open(term); if entry.is_err() { if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); } let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc}); } /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns true if the color was set, false otherwise. pub fn fg(&mut self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(*self.ti.strings.find_equiv(&("setaf")).unwrap(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns true if the color was set, false otherwise. pub fn bg(&mut self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(*self.ti.strings.find_equiv(&("setab")).unwrap(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } /// Sets the given terminal attribute, if supported. /// Returns true if the attribute was supported, false otherwise. pub fn attr(&mut self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { let s = expand(*parm.unwrap(), [], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } } } /// Returns whether the given terminal attribute is supported. pub fn supports_attr(&self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => { self.num_colors > 0 } _ => { let cap = cap_for_attr(attr); self.ti.strings.find_equiv(&cap).is_some() } } } /// Resets all terminal attributes and color to the default. pub fn reset(&mut self) { let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap = self.ti.strings.find_equiv(&("op")); } } let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| { expand(*op, [], &mut Variables::new()) }); if s.is_ok() { self.out.write(s.unwrap()); } else if self.num_colors > 0 { warn!("{}", s.unwrap_err()); } else { // if we support attributes but not color, it would be nice to still warn!() // but it's not worth testing all known attributes just for this. debug!("{}", s.unwrap_err()); } } fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else
} pub fn unwrap(self) -> T { self.out } pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } impl<T: Writer> Writer for Terminal<T> { fn write(&mut self, buf: &[u8]) { self.out.write(buf); } fn flush(&mut self) { self.out.flush(); } }
{ color }
conditional_block
term.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Simple ANSI color library #[allow(missing_doc)]; use std::os; use terminfo::*; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; // FIXME (#2807): Windows support. pub mod color { pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16; pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; } pub mod attr { /// Terminal attributes for use with term.attr(). /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(super::color::Color), /// Convenience attribute to set the background color BackgroundColor(super::color::Color) } } fn cap_for_attr(attr: attr::Attr) -> &'static str { match attr { attr::Bold => "bold", attr::Dim => "dim", attr::Italic(true) => "sitm", attr::Italic(false) => "ritm", attr::Underline(true) => "smul", attr::Underline(false) => "rmul", attr::Blink => "blink", attr::Standout(true) => "smso", attr::Standout(false) => "rmso", attr::Reverse => "rev", attr::Secure => "invis", attr::ForegroundColor(_) => "setaf", attr::BackgroundColor(_) => "setab" } } pub struct Terminal<T> { priv num_colors: u16, priv out: T, priv ti: ~TermInfo } impl<T: Writer> Terminal<T> { pub fn new(out: T) -> Result<Terminal<T>, ~str> { let term = match os::getenv("TERM") { Some(t) => t, None => return Err(~"TERM environment variable undefined") }; let entry = open(term); if entry.is_err() { if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); } let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc});
/// the corresponding normal color will be used instead. /// /// Returns true if the color was set, false otherwise. pub fn fg(&mut self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(*self.ti.strings.find_equiv(&("setaf")).unwrap(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns true if the color was set, false otherwise. pub fn bg(&mut self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(*self.ti.strings.find_equiv(&("setab")).unwrap(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } /// Sets the given terminal attribute, if supported. /// Returns true if the attribute was supported, false otherwise. pub fn attr(&mut self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { let s = expand(*parm.unwrap(), [], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } } } /// Returns whether the given terminal attribute is supported. pub fn supports_attr(&self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => { self.num_colors > 0 } _ => { let cap = cap_for_attr(attr); self.ti.strings.find_equiv(&cap).is_some() } } } /// Resets all terminal attributes and color to the default. pub fn reset(&mut self) { let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap = self.ti.strings.find_equiv(&("op")); } } let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| { expand(*op, [], &mut Variables::new()) }); if s.is_ok() { self.out.write(s.unwrap()); } else if self.num_colors > 0 { warn!("{}", s.unwrap_err()); } else { // if we support attributes but not color, it would be nice to still warn!() // but it's not worth testing all known attributes just for this. debug!("{}", s.unwrap_err()); } } fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else { color } } pub fn unwrap(self) -> T { self.out } pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } impl<T: Writer> Writer for Terminal<T> { fn write(&mut self, buf: &[u8]) { self.out.write(buf); } fn flush(&mut self) { self.out.flush(); } }
} /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors,
random_line_split
term.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Simple ANSI color library #[allow(missing_doc)]; use std::os; use terminfo::*; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use terminfo::parm::{expand, Number, Variables}; // FIXME (#2807): Windows support. pub mod color { pub type Color = u16; pub static BLACK: Color = 0u16; pub static RED: Color = 1u16; pub static GREEN: Color = 2u16; pub static YELLOW: Color = 3u16; pub static BLUE: Color = 4u16; pub static MAGENTA: Color = 5u16; pub static CYAN: Color = 6u16; pub static WHITE: Color = 7u16; pub static BRIGHT_BLACK: Color = 8u16; pub static BRIGHT_RED: Color = 9u16; pub static BRIGHT_GREEN: Color = 10u16; pub static BRIGHT_YELLOW: Color = 11u16; pub static BRIGHT_BLUE: Color = 12u16; pub static BRIGHT_MAGENTA: Color = 13u16; pub static BRIGHT_CYAN: Color = 14u16; pub static BRIGHT_WHITE: Color = 15u16; } pub mod attr { /// Terminal attributes for use with term.attr(). /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. pub enum Attr { /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold Standout(bool), /// Reverse mode, inverts the foreground and background colors Reverse, /// Secure mode, also called invis mode. Hides the printed text Secure, /// Convenience attribute to set the foreground color ForegroundColor(super::color::Color), /// Convenience attribute to set the background color BackgroundColor(super::color::Color) } } fn cap_for_attr(attr: attr::Attr) -> &'static str { match attr { attr::Bold => "bold", attr::Dim => "dim", attr::Italic(true) => "sitm", attr::Italic(false) => "ritm", attr::Underline(true) => "smul", attr::Underline(false) => "rmul", attr::Blink => "blink", attr::Standout(true) => "smso", attr::Standout(false) => "rmso", attr::Reverse => "rev", attr::Secure => "invis", attr::ForegroundColor(_) => "setaf", attr::BackgroundColor(_) => "setab" } } pub struct Terminal<T> { priv num_colors: u16, priv out: T, priv ti: ~TermInfo } impl<T: Writer> Terminal<T> { pub fn new(out: T) -> Result<Terminal<T>, ~str> { let term = match os::getenv("TERM") { Some(t) => t, None => return Err(~"TERM environment variable undefined") }; let entry = open(term); if entry.is_err() { if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); } let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc}); } /// Sets the foreground color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns true if the color was set, false otherwise. pub fn fg(&mut self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(*self.ti.strings.find_equiv(&("setaf")).unwrap(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } /// Sets the background color to the given color. /// /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// /// Returns true if the color was set, false otherwise. pub fn bg(&mut self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(*self.ti.strings.find_equiv(&("setab")).unwrap(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } /// Sets the given terminal attribute, if supported. /// Returns true if the attribute was supported, false otherwise. pub fn attr(&mut self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { let s = expand(*parm.unwrap(), [], &mut Variables::new()); if s.is_ok() { self.out.write(s.unwrap()); return true } else { warn!("{}", s.unwrap_err()); } } false } } } /// Returns whether the given terminal attribute is supported. pub fn supports_attr(&self, attr: attr::Attr) -> bool { match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => { self.num_colors > 0 } _ => { let cap = cap_for_attr(attr); self.ti.strings.find_equiv(&cap).is_some() } } } /// Resets all terminal attributes and color to the default. pub fn reset(&mut self) { let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap = self.ti.strings.find_equiv(&("op")); } } let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| { expand(*op, [], &mut Variables::new()) }); if s.is_ok() { self.out.write(s.unwrap()); } else if self.num_colors > 0 { warn!("{}", s.unwrap_err()); } else { // if we support attributes but not color, it would be nice to still warn!() // but it's not worth testing all known attributes just for this. debug!("{}", s.unwrap_err()); } } fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else { color } } pub fn unwrap(self) -> T { self.out } pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } impl<T: Writer> Writer for Terminal<T> { fn write(&mut self, buf: &[u8]) { self.out.write(buf); } fn
(&mut self) { self.out.flush(); } }
flush
identifier_name
properties.rs
extern crate dbus; use dbus::{Connection, BusType, stdintf}; fn
() { // Connect to server and create a ConnPath. A ConnPath implements several interfaces, // in this case we'll use OrgFreedesktopDBusProperties, which allows us to call "get". let c = Connection::get_private(BusType::Session).unwrap(); let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000); use stdintf::OrgFreedesktopDBusProperties; let metadata = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap(); // The Metadata property is a Dict<String, Variant>, we can get the values out by iterating over it. // When using "as_iter()" for a dict, we'll get one key, it's value, next key, it's value, etc. // The ".0" is needed to traverse into the variant. let mut iter = metadata.0.as_iter().unwrap(); while let Some(key) = iter.next() { // Printing the key is easy, since we know it's a String. print!("{}: ", key.as_str().unwrap()); // We don't know what type the value is. We'll try a few and fall back to // debug printing if the value is more complex than that. let value = iter.next().unwrap(); if let Some(s) = value.as_str() { println!("{}", s); } else if let Some(i) = value.as_i64() { println!("{}", i); } else { println!("{:?}", value); } } }
main
identifier_name
properties.rs
extern crate dbus; use dbus::{Connection, BusType, stdintf}; fn main()
if let Some(s) = value.as_str() { println!("{}", s); } else if let Some(i) = value.as_i64() { println!("{}", i); } else { println!("{:?}", value); } } }
{ // Connect to server and create a ConnPath. A ConnPath implements several interfaces, // in this case we'll use OrgFreedesktopDBusProperties, which allows us to call "get". let c = Connection::get_private(BusType::Session).unwrap(); let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000); use stdintf::OrgFreedesktopDBusProperties; let metadata = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap(); // The Metadata property is a Dict<String, Variant>, we can get the values out by iterating over it. // When using "as_iter()" for a dict, we'll get one key, it's value, next key, it's value, etc. // The ".0" is needed to traverse into the variant. let mut iter = metadata.0.as_iter().unwrap(); while let Some(key) = iter.next() { // Printing the key is easy, since we know it's a String. print!("{}: ", key.as_str().unwrap()); // We don't know what type the value is. We'll try a few and fall back to // debug printing if the value is more complex than that. let value = iter.next().unwrap();
identifier_body
properties.rs
extern crate dbus; use dbus::{Connection, BusType, stdintf}; fn main() { // Connect to server and create a ConnPath. A ConnPath implements several interfaces, // in this case we'll use OrgFreedesktopDBusProperties, which allows us to call "get". let c = Connection::get_private(BusType::Session).unwrap(); let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000); use stdintf::OrgFreedesktopDBusProperties;
// When using "as_iter()" for a dict, we'll get one key, it's value, next key, it's value, etc. // The ".0" is needed to traverse into the variant. let mut iter = metadata.0.as_iter().unwrap(); while let Some(key) = iter.next() { // Printing the key is easy, since we know it's a String. print!("{}: ", key.as_str().unwrap()); // We don't know what type the value is. We'll try a few and fall back to // debug printing if the value is more complex than that. let value = iter.next().unwrap(); if let Some(s) = value.as_str() { println!("{}", s); } else if let Some(i) = value.as_i64() { println!("{}", i); } else { println!("{:?}", value); } } }
let metadata = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap(); // The Metadata property is a Dict<String, Variant>, we can get the values out by iterating over it.
random_line_split
properties.rs
extern crate dbus; use dbus::{Connection, BusType, stdintf}; fn main() { // Connect to server and create a ConnPath. A ConnPath implements several interfaces, // in this case we'll use OrgFreedesktopDBusProperties, which allows us to call "get". let c = Connection::get_private(BusType::Session).unwrap(); let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000); use stdintf::OrgFreedesktopDBusProperties; let metadata = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap(); // The Metadata property is a Dict<String, Variant>, we can get the values out by iterating over it. // When using "as_iter()" for a dict, we'll get one key, it's value, next key, it's value, etc. // The ".0" is needed to traverse into the variant. let mut iter = metadata.0.as_iter().unwrap(); while let Some(key) = iter.next() { // Printing the key is easy, since we know it's a String. print!("{}: ", key.as_str().unwrap()); // We don't know what type the value is. We'll try a few and fall back to // debug printing if the value is more complex than that. let value = iter.next().unwrap(); if let Some(s) = value.as_str()
else if let Some(i) = value.as_i64() { println!("{}", i); } else { println!("{:?}", value); } } }
{ println!("{}", s); }
conditional_block
generic-object.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Foo<T> { fn get(&self) -> T; } struct S { x: int } impl Foo<int> for S { fn get(&self) -> int { self.x } } pub fn main() { let x = ~S { x: 1 };
let y = x as ~Foo<int>; assert_eq!(y.get(), 1); }
random_line_split
generic-object.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Foo<T> { fn get(&self) -> T; } struct S { x: int } impl Foo<int> for S { fn
(&self) -> int { self.x } } pub fn main() { let x = ~S { x: 1 }; let y = x as ~Foo<int>; assert_eq!(y.get(), 1); }
get
identifier_name
generic-object.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Foo<T> { fn get(&self) -> T; } struct S { x: int } impl Foo<int> for S { fn get(&self) -> int { self.x } } pub fn main()
{ let x = ~S { x: 1 }; let y = x as ~Foo<int>; assert_eq!(y.get(), 1); }
identifier_body
build-assets.rs
use anyhow::Context; use std::{ path::{Path, PathBuf}, process::Command, }; const DOCKER_IMAGE_REPO: &str = "https://github.com/z88dk/z88dk.git"; const DOCKER_IMAGE_COMMIT: &str = "d61f6bb46ec15775cccf543f5941b6a2d6864ecf"; const DOCKER_IMAGE_NAME: &str = "rustzx/z88dk"; const DOCKER_IMAGE_FILE: &str = "z88dk.Dockerfile"; const HEX_ALPHABET: [char; 16] = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', ]; const SHORTENED_COMMIT_LENGTH: usize = 7; fn image_tagged_name(name: impl AsRef<str>, tag: impl Into<String>) -> String { let mut tag = tag.into(); tag.truncate(SHORTENED_COMMIT_LENGTH); format!("{}:{}", name.as_ref(), tag) } // Running docker container OS may differ from the host, therefore // we can't use Path/PathBuf struct ForeignOsPath(String); impl ForeignOsPath { fn new(path: impl Into<String>) -> Self { Self(path.into()) } } struct DockerMountPoint { dir: PathBuf, mount: ForeignOsPath, } enum DockerAction { ShellScript { path: ForeignOsPath }, } struct DockerContainer { image: String, name: Option<String>, mount_points: Vec<DockerMountPoint>, remove_after_run: bool, action: Option<DockerAction>, } impl DockerContainer { pub fn from_image(image: impl Into<String>) -> Self { Self { image: image.into(), remove_after_run: false, mount_points: vec![], name: None, action: None, } } pub fn name(mut self, name: impl Into<String>) -> Self
pub fn mount(mut self, mount_point: DockerMountPoint) -> Self { self.mount_points.push(mount_point); self } pub fn remove_after_run(mut self) -> Self { self.remove_after_run = true; self } pub fn startup_script(mut self, path: ForeignOsPath) -> Self { self.action.replace(DockerAction::ShellScript { path }); self } pub fn run(self) -> Result<(), anyhow::Error> { let mut cmd = Command::new("docker"); cmd.arg("run"); if let Some(name) = self.name { cmd.args(&["--name", &name]); } for mount_point in self.mount_points { cmd.args(&[ "-v", &format!("{}:{}", mount_point.dir.display(), mount_point.mount.0), ]); } if self.remove_after_run { cmd.arg("--rm"); } if matches!(&self.action, Some(DockerAction::ShellScript {.. })) { cmd.arg("-it"); } cmd.arg(self.image); if let Some(action) = self.action { match action { DockerAction::ShellScript { path } => { cmd.args(&["sh", &path.0]); } } } execute_command_transparent(cmd)?; Ok(()) } } struct DockerImage { url: String, name: Option<String>, dockerfile: Option<String>, } impl DockerImage { pub fn present_on_machine(image_name: &str) -> Result<bool, anyhow::Error> { let mut cmd = Command::new("docker"); cmd.args(["images", "-q", image_name]); let output = cmd .output() .with_context(|| "Failed to query docker images") .and_then(|out| { String::from_utf8(out.stdout).with_context(|| "Failed to parse docker stdout") })?; Ok(!output.is_empty()) } pub fn from_git(repo: impl AsRef<str>, commit: impl AsRef<str>) -> Self { let url = format!("{}#{}", repo.as_ref(), commit.as_ref()); Self { url, name: None, dockerfile: None, } } pub fn with_name(mut self, name: impl Into<String>) -> Self { self.name.replace(name.into()); self } pub fn with_dockerfile(mut self, dockerfile: impl Into<String>) -> Self { self.dockerfile.replace(dockerfile.into()); self } pub fn build(self) -> anyhow::Result<()> { let mut cmd = Command::new("docker"); cmd.arg("build"); if let Some(dockerfile) = self.dockerfile { cmd.args(["-f", &dockerfile]); } if let Some(name) = self.name { cmd.args(["-t", &name]); } cmd.arg(self.url); cmd.spawn()?.wait()?; execute_command_transparent(cmd)?; Ok(()) } } fn to_container_name(prefix: &str) -> String { format!("{}-{}", prefix, nanoid::nanoid!(8, &HEX_ALPHABET)) } fn execute_command_transparent(mut cmd: Command) -> anyhow::Result<()> { println!("Running command with args: {:#?}", cmd); let status = cmd.spawn()?.wait()?; if!status.success() { anyhow::anyhow!( "Command execution failed with code {}", status.code().unwrap_or(1) ); } Ok(()) } fn main() -> anyhow::Result<()> { if!DockerImage::present_on_machine(DOCKER_IMAGE_NAME) .with_context(|| "Failed to check for docker image presence")? { DockerImage::from_git(DOCKER_IMAGE_REPO, DOCKER_IMAGE_COMMIT) .with_name(image_tagged_name(DOCKER_IMAGE_NAME, DOCKER_IMAGE_COMMIT)) .with_dockerfile(DOCKER_IMAGE_FILE) .build() .with_context(|| "Failed to build docker image")?; } let mut assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); assets_dir.push(Path::new("test_data")); DockerContainer::from_image(image_tagged_name(DOCKER_IMAGE_NAME, DOCKER_IMAGE_COMMIT)) .name(to_container_name("rustzx-assets")) .mount(DockerMountPoint { dir: assets_dir, mount: ForeignOsPath::new("/src/"), }) .remove_after_run() .startup_script(ForeignOsPath::new("/src/make.sh")) .run() .expect("Failed to build assets"); Ok(()) }
{ self.name.replace(name.into()); self }
identifier_body
build-assets.rs
use anyhow::Context; use std::{ path::{Path, PathBuf}, process::Command, }; const DOCKER_IMAGE_REPO: &str = "https://github.com/z88dk/z88dk.git"; const DOCKER_IMAGE_COMMIT: &str = "d61f6bb46ec15775cccf543f5941b6a2d6864ecf"; const DOCKER_IMAGE_NAME: &str = "rustzx/z88dk"; const DOCKER_IMAGE_FILE: &str = "z88dk.Dockerfile"; const HEX_ALPHABET: [char; 16] = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', ]; const SHORTENED_COMMIT_LENGTH: usize = 7; fn image_tagged_name(name: impl AsRef<str>, tag: impl Into<String>) -> String { let mut tag = tag.into(); tag.truncate(SHORTENED_COMMIT_LENGTH); format!("{}:{}", name.as_ref(), tag) } // Running docker container OS may differ from the host, therefore // we can't use Path/PathBuf struct ForeignOsPath(String); impl ForeignOsPath { fn new(path: impl Into<String>) -> Self { Self(path.into()) } } struct DockerMountPoint { dir: PathBuf, mount: ForeignOsPath, } enum DockerAction { ShellScript { path: ForeignOsPath }, } struct DockerContainer { image: String, name: Option<String>, mount_points: Vec<DockerMountPoint>, remove_after_run: bool, action: Option<DockerAction>, } impl DockerContainer { pub fn from_image(image: impl Into<String>) -> Self { Self { image: image.into(), remove_after_run: false, mount_points: vec![], name: None, action: None, } } pub fn name(mut self, name: impl Into<String>) -> Self { self.name.replace(name.into()); self } pub fn mount(mut self, mount_point: DockerMountPoint) -> Self { self.mount_points.push(mount_point); self } pub fn remove_after_run(mut self) -> Self { self.remove_after_run = true; self } pub fn startup_script(mut self, path: ForeignOsPath) -> Self { self.action.replace(DockerAction::ShellScript { path }); self } pub fn run(self) -> Result<(), anyhow::Error> { let mut cmd = Command::new("docker"); cmd.arg("run"); if let Some(name) = self.name { cmd.args(&["--name", &name]); } for mount_point in self.mount_points { cmd.args(&[ "-v", &format!("{}:{}", mount_point.dir.display(), mount_point.mount.0), ]); } if self.remove_after_run { cmd.arg("--rm"); } if matches!(&self.action, Some(DockerAction::ShellScript {.. })) { cmd.arg("-it"); } cmd.arg(self.image); if let Some(action) = self.action { match action { DockerAction::ShellScript { path } => { cmd.args(&["sh", &path.0]); } } } execute_command_transparent(cmd)?; Ok(()) } } struct DockerImage { url: String, name: Option<String>, dockerfile: Option<String>, } impl DockerImage { pub fn present_on_machine(image_name: &str) -> Result<bool, anyhow::Error> { let mut cmd = Command::new("docker"); cmd.args(["images", "-q", image_name]); let output = cmd .output() .with_context(|| "Failed to query docker images") .and_then(|out| { String::from_utf8(out.stdout).with_context(|| "Failed to parse docker stdout") })?; Ok(!output.is_empty()) } pub fn from_git(repo: impl AsRef<str>, commit: impl AsRef<str>) -> Self { let url = format!("{}#{}", repo.as_ref(), commit.as_ref()); Self { url, name: None, dockerfile: None, } } pub fn with_name(mut self, name: impl Into<String>) -> Self { self.name.replace(name.into()); self } pub fn with_dockerfile(mut self, dockerfile: impl Into<String>) -> Self { self.dockerfile.replace(dockerfile.into()); self } pub fn build(self) -> anyhow::Result<()> { let mut cmd = Command::new("docker"); cmd.arg("build"); if let Some(dockerfile) = self.dockerfile { cmd.args(["-f", &dockerfile]); } if let Some(name) = self.name {
cmd.arg(self.url); cmd.spawn()?.wait()?; execute_command_transparent(cmd)?; Ok(()) } } fn to_container_name(prefix: &str) -> String { format!("{}-{}", prefix, nanoid::nanoid!(8, &HEX_ALPHABET)) } fn execute_command_transparent(mut cmd: Command) -> anyhow::Result<()> { println!("Running command with args: {:#?}", cmd); let status = cmd.spawn()?.wait()?; if!status.success() { anyhow::anyhow!( "Command execution failed with code {}", status.code().unwrap_or(1) ); } Ok(()) } fn main() -> anyhow::Result<()> { if!DockerImage::present_on_machine(DOCKER_IMAGE_NAME) .with_context(|| "Failed to check for docker image presence")? { DockerImage::from_git(DOCKER_IMAGE_REPO, DOCKER_IMAGE_COMMIT) .with_name(image_tagged_name(DOCKER_IMAGE_NAME, DOCKER_IMAGE_COMMIT)) .with_dockerfile(DOCKER_IMAGE_FILE) .build() .with_context(|| "Failed to build docker image")?; } let mut assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); assets_dir.push(Path::new("test_data")); DockerContainer::from_image(image_tagged_name(DOCKER_IMAGE_NAME, DOCKER_IMAGE_COMMIT)) .name(to_container_name("rustzx-assets")) .mount(DockerMountPoint { dir: assets_dir, mount: ForeignOsPath::new("/src/"), }) .remove_after_run() .startup_script(ForeignOsPath::new("/src/make.sh")) .run() .expect("Failed to build assets"); Ok(()) }
cmd.args(["-t", &name]); }
random_line_split
build-assets.rs
use anyhow::Context; use std::{ path::{Path, PathBuf}, process::Command, }; const DOCKER_IMAGE_REPO: &str = "https://github.com/z88dk/z88dk.git"; const DOCKER_IMAGE_COMMIT: &str = "d61f6bb46ec15775cccf543f5941b6a2d6864ecf"; const DOCKER_IMAGE_NAME: &str = "rustzx/z88dk"; const DOCKER_IMAGE_FILE: &str = "z88dk.Dockerfile"; const HEX_ALPHABET: [char; 16] = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', ]; const SHORTENED_COMMIT_LENGTH: usize = 7; fn image_tagged_name(name: impl AsRef<str>, tag: impl Into<String>) -> String { let mut tag = tag.into(); tag.truncate(SHORTENED_COMMIT_LENGTH); format!("{}:{}", name.as_ref(), tag) } // Running docker container OS may differ from the host, therefore // we can't use Path/PathBuf struct ForeignOsPath(String); impl ForeignOsPath { fn new(path: impl Into<String>) -> Self { Self(path.into()) } } struct DockerMountPoint { dir: PathBuf, mount: ForeignOsPath, } enum DockerAction { ShellScript { path: ForeignOsPath }, } struct DockerContainer { image: String, name: Option<String>, mount_points: Vec<DockerMountPoint>, remove_after_run: bool, action: Option<DockerAction>, } impl DockerContainer { pub fn from_image(image: impl Into<String>) -> Self { Self { image: image.into(), remove_after_run: false, mount_points: vec![], name: None, action: None, } } pub fn
(mut self, name: impl Into<String>) -> Self { self.name.replace(name.into()); self } pub fn mount(mut self, mount_point: DockerMountPoint) -> Self { self.mount_points.push(mount_point); self } pub fn remove_after_run(mut self) -> Self { self.remove_after_run = true; self } pub fn startup_script(mut self, path: ForeignOsPath) -> Self { self.action.replace(DockerAction::ShellScript { path }); self } pub fn run(self) -> Result<(), anyhow::Error> { let mut cmd = Command::new("docker"); cmd.arg("run"); if let Some(name) = self.name { cmd.args(&["--name", &name]); } for mount_point in self.mount_points { cmd.args(&[ "-v", &format!("{}:{}", mount_point.dir.display(), mount_point.mount.0), ]); } if self.remove_after_run { cmd.arg("--rm"); } if matches!(&self.action, Some(DockerAction::ShellScript {.. })) { cmd.arg("-it"); } cmd.arg(self.image); if let Some(action) = self.action { match action { DockerAction::ShellScript { path } => { cmd.args(&["sh", &path.0]); } } } execute_command_transparent(cmd)?; Ok(()) } } struct DockerImage { url: String, name: Option<String>, dockerfile: Option<String>, } impl DockerImage { pub fn present_on_machine(image_name: &str) -> Result<bool, anyhow::Error> { let mut cmd = Command::new("docker"); cmd.args(["images", "-q", image_name]); let output = cmd .output() .with_context(|| "Failed to query docker images") .and_then(|out| { String::from_utf8(out.stdout).with_context(|| "Failed to parse docker stdout") })?; Ok(!output.is_empty()) } pub fn from_git(repo: impl AsRef<str>, commit: impl AsRef<str>) -> Self { let url = format!("{}#{}", repo.as_ref(), commit.as_ref()); Self { url, name: None, dockerfile: None, } } pub fn with_name(mut self, name: impl Into<String>) -> Self { self.name.replace(name.into()); self } pub fn with_dockerfile(mut self, dockerfile: impl Into<String>) -> Self { self.dockerfile.replace(dockerfile.into()); self } pub fn build(self) -> anyhow::Result<()> { let mut cmd = Command::new("docker"); cmd.arg("build"); if let Some(dockerfile) = self.dockerfile { cmd.args(["-f", &dockerfile]); } if let Some(name) = self.name { cmd.args(["-t", &name]); } cmd.arg(self.url); cmd.spawn()?.wait()?; execute_command_transparent(cmd)?; Ok(()) } } fn to_container_name(prefix: &str) -> String { format!("{}-{}", prefix, nanoid::nanoid!(8, &HEX_ALPHABET)) } fn execute_command_transparent(mut cmd: Command) -> anyhow::Result<()> { println!("Running command with args: {:#?}", cmd); let status = cmd.spawn()?.wait()?; if!status.success() { anyhow::anyhow!( "Command execution failed with code {}", status.code().unwrap_or(1) ); } Ok(()) } fn main() -> anyhow::Result<()> { if!DockerImage::present_on_machine(DOCKER_IMAGE_NAME) .with_context(|| "Failed to check for docker image presence")? { DockerImage::from_git(DOCKER_IMAGE_REPO, DOCKER_IMAGE_COMMIT) .with_name(image_tagged_name(DOCKER_IMAGE_NAME, DOCKER_IMAGE_COMMIT)) .with_dockerfile(DOCKER_IMAGE_FILE) .build() .with_context(|| "Failed to build docker image")?; } let mut assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); assets_dir.push(Path::new("test_data")); DockerContainer::from_image(image_tagged_name(DOCKER_IMAGE_NAME, DOCKER_IMAGE_COMMIT)) .name(to_container_name("rustzx-assets")) .mount(DockerMountPoint { dir: assets_dir, mount: ForeignOsPath::new("/src/"), }) .remove_after_run() .startup_script(ForeignOsPath::new("/src/make.sh")) .run() .expect("Failed to build assets"); Ok(()) }
name
identifier_name
TestAtanh.rs
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh. #pragma version(1) #pragma rs java_package_name(android.renderscript.cts) float __attribute__((kernel)) testAtanhFloatFloat(float inV) { return atanh(inV);
float3 __attribute__((kernel)) testAtanhFloat3Float3(float3 inV) { return atanh(inV); } float4 __attribute__((kernel)) testAtanhFloat4Float4(float4 inV) { return atanh(inV); } half __attribute__((kernel)) testAtanhHalfHalf(half inV) { return atanh(inV); } half2 __attribute__((kernel)) testAtanhHalf2Half2(half2 inV) { return atanh(inV); } half3 __attribute__((kernel)) testAtanhHalf3Half3(half3 inV) { return atanh(inV); } half4 __attribute__((kernel)) testAtanhHalf4Half4(half4 inV) { return atanh(inV); }
} float2 __attribute__((kernel)) testAtanhFloat2Float2(float2 inV) { return atanh(inV); }
random_line_split