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
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
Ok(content) => content, Err(e) => { writeln!(stderr(), "{}", e).unwrap(); return; } } } // Open output let writer: Box<Write>; match matches.value_of("out") { None | Some("-") => { writer = Box::new(stdout()...
{ let matches = clap_app!(leafmt => (version: lea::version_str()) (about: "Lea source code formatter / pretty printer") (@arg FILE: +required "The file to format (`-` to read from stdin)") (@arg out: -o --out +takes_value "Write output to <out> (`-` to write to stdout).") (af...
identifier_body
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
else { source_name = file; code = match read_file(&source_name) { Ok(content) => content, Err(e) => { writeln!(stderr(), "{}", e).unwrap(); return; } } } // Open output let writer: Box<Write>; match matches.val...
{ stdin().read_to_string(&mut code).unwrap(); source_name = "<stdin>"; }
conditional_block
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
fn prettyprint<W: Write>(code: &str, source_name: &str, mut target: W) -> io::Result<()> { match parser::block(code) { Ok(main) => { let mut pp = PrettyPrinter::new(&mut target); try!(pp.print_block(&main)); } Err(e) => { try!(e.format(code, source_name, &...
random_line_split
mod.rs
// library of matrix and vector functions // a 3 component vector pub struct Vec3{ pub x: f32, pub y: f32, pub z: f32 } // associated functions of Vec3 impl Vec3{ // used for constructing Vec3 nicely pub fn new(x:f32,y:f32,z:f32) -> Vec3 { Vec3{x: x, y: y, z: z} } } // a 3x3 matrix pub...
(mat1: &Mat3,mat2: &Mat3) -> Mat3{ let mut result = Mat3::new_empty(); // go by row for i in 0..3{ // go by column for j in 0..3{ let mut sum :f32 = 0.0; // get the result of the row,column pair (i,j) for k in 0..3{ sum = sum + (mat1.valu...
MatXMat3
identifier_name
mod.rs
// library of matrix and vector functions // a 3 component vector pub struct Vec3{ pub x: f32, pub y: f32, pub z: f32 } // associated functions of Vec3
} } // a 3x3 matrix pub struct Mat3{ pub values: [[f32;3];3] } impl Mat3{ // used for constructing an empty matrix pub fn new_empty() -> Mat3{ Mat3{values: [[0.0,0.0,0.0], [0.0,0.0,0.0], [0.0,0.0,0.0]] } } } pub fn dot(vec1:&Vec3,vec2:&Vec3) -> ...
impl Vec3{ // used for constructing Vec3 nicely pub fn new(x:f32,y:f32,z:f32) -> Vec3 { Vec3{x: x, y: y, z: z}
random_line_split
quickcheck_types.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. */ //! QuickCheck support for wire packs. use quickcheck::{empty_shrinker, Arbitrary, Gen}; use mercurial_types::{Delta, HgNodeHash, MPath, ...
else { None }; // 50% chance of size being present let size = if bool::arbitrary(g) { Some(2) } else { None }; Some(Metadata { flags, size }) } else { None }; Self { node: HgNodeHash::arbitrary(g), delta_base, ...
{ Some(1) }
conditional_block
quickcheck_types.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. */ //! QuickCheck support for wire packs. use quickcheck::{empty_shrinker, Arbitrary, Gen}; use mercurial_types::{Delta, HgNodeHash, MPath, ...
// Not going to get anything out of shrinking this since MPath is not shrinkable. } impl Arbitrary for DataEntry { fn arbitrary(g: &mut Gen) -> Self { // 20% chance of a fulltext revision let (delta_base, delta) = if *g.choose(&[0, 1, 2, 3, 4]).unwrap() == 0 { (NULL_HASH, Delta::ne...
// HistoryEntry depends on the kind of the overall wirepack, so this can't be implemented. unimplemented!("use WirePackPartSequence::arbitrary instead") }
random_line_split
quickcheck_types.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. */ //! QuickCheck support for wire packs. use quickcheck::{empty_shrinker, Arbitrary, Gen}; use mercurial_types::{Delta, HgNodeHash, MPath, ...
(g: &mut Gen) -> Self { let size = g.size(); let kind = if bool::arbitrary(g) { Kind::Tree } else { Kind::File }; let file_count = usize::arbitrary(g) % size; let files = (0..file_count) .map(|_| FileEntries::arbitrary_params(g, kind))...
arbitrary
identifier_name
quickcheck_types.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. */ //! QuickCheck support for wire packs. use quickcheck::{empty_shrinker, Arbitrary, Gen}; use mercurial_types::{Delta, HgNodeHash, MPath, ...
// Not going to get anything out of shrinking this since MPath is not shrinkable. } impl Arbitrary for DataEntry { fn arbitrary(g: &mut Gen) -> Self { // 20% chance of a fulltext revision let (delta_base, delta) = if *g.choose(&[0, 1, 2, 3, 4]).unwrap() == 0 { (NULL_HASH, Delta::n...
{ // HistoryEntry depends on the kind of the overall wirepack, so this can't be implemented. unimplemented!("use WirePackPartSequence::arbitrary instead") }
identifier_body
i64.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 ...
impl CheckedSub for i64 { #[inline] fn checked_sub(&self, v: &i64) -> Option<i64> { unsafe { let (x, y) = intrinsics::i64_sub_with_overflow(*self, *v); if y { None } else { Some(x) } } } } // FIXME: #8449: should not be disabled on 32-bit #[cfg(target_word_size = "6...
} }
random_line_split
i64.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 ...
(&self, v: &i64) -> Option<i64> { unsafe { let (x, y) = intrinsics::i64_sub_with_overflow(*self, *v); if y { None } else { Some(x) } } } } // FIXME: #8449: should not be disabled on 32-bit #[cfg(target_word_size = "64")] impl CheckedMul for i64 { #[inline] fn checked...
checked_sub
identifier_name
i64.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 ...
}
{ unsafe { let (x, y) = intrinsics::i64_mul_with_overflow(*self, *v); if y { None } else { Some(x) } } }
identifier_body
i64.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 ...
else { Some(x) } } } } impl CheckedSub for i64 { #[inline] fn checked_sub(&self, v: &i64) -> Option<i64> { unsafe { let (x, y) = intrinsics::i64_sub_with_overflow(*self, *v); if y { None } else { Some(x) } } } } // FIXME: #8449: should not be disabled o...
{ None }
conditional_block
test_main.rs
#![feature(test)] #![feature(conservative_impl_trait)] #![feature(specialization)] #[macro_use] extern crate ndarray; extern crate test; extern crate rand; extern crate ndarray_rand; extern crate num; extern crate chrono; extern crate error_chain; extern crate itertools; extern crate rustc_serialize; extern crate csv...
() { let mut btree: BTreeMap<String, Row<f64>> = BTreeMap::new(); btree.insert("a".to_string(), arr1(&[2., 3., 2.])); if let Err(ref e) = run() { use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {...
main
identifier_name
test_main.rs
#![feature(test)] #![feature(conservative_impl_trait)] #![feature(specialization)] #[macro_use] extern crate ndarray; extern crate test; extern crate rand; extern crate ndarray_rand; extern crate num; extern crate chrono; extern crate error_chain; extern crate itertools; extern crate rustc_serialize; extern crate csv...
} fn run() -> Result<()> { let df: Result<DataFrame<InnerType, OuterType>> = DataFrame::read_csv("/Users/suchin/Github/rust-dataframe/src/tests/test.\ csv"); let a = arr2(&[[2., 7.], [3., NAN], [2., 4.]]); // let b = arr2(&[[2., 6...
{ use ::std::io::Write; let stderr = &mut ::std::io::stderr(); let errmsg = "Error writing to stderr"; writeln!(stderr, "error: {}", e).expect(errmsg); for e in e.iter().skip(1) { writeln!(stderr, "caused by: {}", e).expect(errmsg); } // The backtra...
conditional_block
test_main.rs
#![feature(test)] #![feature(conservative_impl_trait)] #![feature(specialization)] #[macro_use] extern crate ndarray; extern crate test; extern crate rand; extern crate ndarray_rand; extern crate num; extern crate chrono; extern crate error_chain; extern crate itertools; extern crate rustc_serialize; extern crate csv...
.as_df()?; let res_1: DataFrame<f64, String> = df.inner_left_join(&df_1).as_df()?; let concat = df.concat(&df_1, UtahAxis::Row).as_df(); // let b = arr1(&[2., 3., 2.]); let k: DataFrame<f64, String> = dataframe!( { "a" => col!([2., 3., 2.]), "b" => col!([2., NAN, 2.]) }...
{ let df: Result<DataFrame<InnerType, OuterType>> = DataFrame::read_csv("/Users/suchin/Github/rust-dataframe/src/tests/test.\ csv"); let a = arr2(&[[2., 7.], [3., NAN], [2., 4.]]); // let b = arr2(&[[2., 6.], [3., 4.]]); let c =...
identifier_body
test_main.rs
#![feature(test)] #![feature(conservative_impl_trait)] #![feature(specialization)] #[macro_use] extern crate ndarray; extern crate test; extern crate rand; extern crate ndarray_rand; extern crate num; extern crate chrono; extern crate error_chain; extern crate itertools; extern crate rustc_serialize; extern crate csv;...
let mut df: DataFrame<f64, String> = DataFrame::new(a).columns(&["a", "b"])? .index(&["1", "2", "3"])?; let df_1 = DataFrame::new(c).columns(&["c", "d"])?.index(&["1", "2", "3"])?; let new_data = df.select(&["2"], UtahAxis::Row).as_array()?; // let df_iter: DataFrameIterator = df_1.df_iter(UtahA...
let a = arr2(&[[2., 7.], [3., NAN], [2., 4.]]); // let b = arr2(&[[2., 6.], [3., 4.]]); let c = arr2(&[[2., 6.], [3., 4.], [2., 1.]]);
random_line_split
logname.rs
extern crate libc; extern crate getopts; extern crate coreutils; use libc::funcs::posix88::unistd::getlogin; use std::c_str::CString; use std::os; fn
() { let args = os::args(); let program = args[0].clone(); let opts = &[ getopts::optflag("h", "help", "display this help and exit"), getopts::optflag("V", "version", "output version information and exit"), ]; let matches = match getopts::getopts(args.tail(), opts) { Ok(m)...
main
identifier_name
logname.rs
extern crate libc; extern crate getopts; extern crate coreutils; use libc::funcs::posix88::unistd::getlogin; use std::c_str::CString; use std::os; fn main()
if matches.opt_present("help") { println!("Usage: {}", getopts::usage(program.as_slice(), opts)); return; } if matches.opt_present("version") { println!("{}: {}", program, coreutils::version()); return; } let login = unsafe { CString::new( getlog...
{ let args = os::args(); let program = args[0].clone(); let opts = &[ getopts::optflag("h", "help", "display this help and exit"), getopts::optflag("V", "version", "output version information and exit"), ]; let matches = match getopts::getopts(args.tail(), opts) { Ok(m) =>...
identifier_body
logname.rs
extern crate libc; extern crate getopts; extern crate coreutils; use libc::funcs::posix88::unistd::getlogin; use std::c_str::CString; use std::os; fn main() { let args = os::args(); let program = args[0].clone(); let opts = &[ getopts::optflag("h", "help", "display this help and exit"), ...
return; } if matches.opt_present("version") { println!("{}: {}", program, coreutils::version()); return; } let login = unsafe { CString::new( getlogin() as *const libc::c_char, false ) }; match login.as_str() { Some(usern...
}; if matches.opt_present("help") { println!("Usage: {}", getopts::usage(program.as_slice(), opts));
random_line_split
args.rs
use clap::{arg_enum, Clap}; arg_enum! { #[derive(Debug)] pub enum RenderDevice { Cpu, Gpu } } impl RenderDevice { pub fn to_str(&self) -> &str
} #[clap(version = env!("CARGO_PKG_VERSION"))] #[derive(Clap, Debug)] pub struct Args { /// Which address to listen on. #[clap(default_value = "0.0.0.0", long = "address", short = "a")] pub address: String, /// By default elmyra uses a bundled version of blender (strongly recommended), you can overr...
{ match self { Self::Cpu => "CPU", Self::Gpu => "GPU" } }
identifier_body
args.rs
use clap::{arg_enum, Clap}; arg_enum! { #[derive(Debug)] pub enum RenderDevice { Cpu, Gpu } } impl RenderDevice { pub fn to_str(&self) -> &str { match self { Self::Cpu => "CPU", Self::Gpu => "GPU" } } } #[clap(version = env!("CARGO_PKG_VERSI...
{ /// Which address to listen on. #[clap(default_value = "0.0.0.0", long = "address", short = "a")] pub address: String, /// By default elmyra uses a bundled version of blender (strongly recommended), you can override it with this if you know what you're doing or if would like to play and learn. ...
Args
identifier_name
args.rs
use clap::{arg_enum, Clap}; arg_enum! { #[derive(Debug)] pub enum RenderDevice { Cpu, Gpu } } impl RenderDevice { pub fn to_str(&self) -> &str { match self { Self::Cpu => "CPU", Self::Gpu => "GPU" } } } #[clap(version = env!("CARGO_PKG_VERSI...
}
random_line_split
issue-14308.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
A(..) => 1i }; assert_eq!(x, 1); let x = match A(4) { A(1) => 1i, A(..) => 2i }; assert_eq!(x, 2); // This next test uses a (..) wildcard match on a nullary struct. // There's no particularly good reason to support this, but it's currently allowed, // and this ma...
struct A(int); struct B; fn main() { let x = match A(3) {
random_line_split
issue-14308.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = match A(3) { A(..) => 1i }; assert_eq!(x, 1); let x = match A(4) { A(1) => 1i, A(..) => 2i }; assert_eq!(x, 2); // This next test uses a (..) wildcard match on a nullary struct. // There's no particularly good reason to support this, but it's currently ...
identifier_body
issue-14308.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
; fn main() { let x = match A(3) { A(..) => 1i }; assert_eq!(x, 1); let x = match A(4) { A(1) => 1i, A(..) => 2i }; assert_eq!(x, 2); // This next test uses a (..) wildcard match on a nullary struct. // There's no particularly good reason to support this, but it...
B
identifier_name
event_content.rs
//! Implementations of the MessageEventContent and StateEventContent derive macro. use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse::{Parse, ParseStream}, DeriveInput, LitStr, Token, }; /// Parses attributes for `*EventContent` derives. /// /// `#[ruma_event(type = "m.room.alias")]` en...
(input: ParseStream) -> syn::Result<Self> { input.parse::<Token![type]>()?; input.parse::<Token![=]>()?; Ok(EventMeta::Type(input.parse::<LitStr>()?)) } } /// Create an `EventContent` implementation for a struct. pub fn expand_event_content(input: DeriveInput) -> syn::Result<TokenStream> { ...
parse
identifier_name
event_content.rs
//! Implementations of the MessageEventContent and StateEventContent derive macro. use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse::{Parse, ParseStream}, DeriveInput, LitStr, Token, }; /// Parses attributes for `*EventContent` derives. /// /// `#[ruma_event(type = "m.room.alias")]` en...
let event_type = { let event_meta = event_type_attr.parse_args::<EventMeta>()?; let EventMeta::Type(lit) = event_meta; lit }; Ok(quote! { impl ::ruma_events::EventContent for #ident { fn event_type(&self) -> &str { #event_type } ...
syn::Error::new(Span::call_site(), msg) })?;
random_line_split
event_content.rs
//! Implementations of the MessageEventContent and StateEventContent derive macro. use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse::{Parse, ParseStream}, DeriveInput, LitStr, Token, }; /// Parses attributes for `*EventContent` derives. /// /// `#[ruma_event(type = "m.room.alias")]` en...
{ let ident = input.ident.clone(); let room_ev_content = expand_room_event_content(input)?; Ok(quote! { #room_ev_content impl ::ruma_events::StateEventContent for #ident { } }) }
identifier_body
server.rs
use mio::{Handler, Token, EventLoop, EventSet, PollOpt}; use mio::tcp::TcpListener; use mio::util::Slab; use std::net::SocketAddr; use connection::Connection; use error::Result; const SERVER: Token = Token(0); struct Server { listener: TcpListener, connections: Slab<Connection>, } impl Server { fn new(li...
} } } } impl Handler for Server { type Timeout = (); type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<Server>, token: Token, events: EventSet) { match token { SERVER => self.accept_new(event_loop), _ => { if events.is...
} Ok(None) => {} Err(e) => { // TODO handle event_loop.shutdown();
random_line_split
server.rs
use mio::{Handler, Token, EventLoop, EventSet, PollOpt}; use mio::tcp::TcpListener; use mio::util::Slab; use std::net::SocketAddr; use connection::Connection; use error::Result; const SERVER: Token = Token(0); struct Server { listener: TcpListener, connections: Slab<Connection>, } impl Server { fn new(li...
} impl Handler for Server { type Timeout = (); type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<Server>, token: Token, events: EventSet) { match token { SERVER => self.accept_new(event_loop), _ => { if events.is_readable() { ...
{ match self.listener.accept() { Ok(Some((socket, addr))) => { info!("New Connection from {}", addr); let token = self.connections .insert_with(|token| Connection::new(socket, token)) .unwrap(); event_loop.regist...
identifier_body
server.rs
use mio::{Handler, Token, EventLoop, EventSet, PollOpt}; use mio::tcp::TcpListener; use mio::util::Slab; use std::net::SocketAddr; use connection::Connection; use error::Result; const SERVER: Token = Token(0); struct Server { listener: TcpListener, connections: Slab<Connection>, } impl Server { fn new(li...
if events.is_hup() {} if events.is_error() {} if self.connections[token].is_closed() { event_loop.deregister(&self.connections[token].socket); let _ = self.connections.remove(token); } } } } ...
{ self.connections[token].write() }
conditional_block
server.rs
use mio::{Handler, Token, EventLoop, EventSet, PollOpt}; use mio::tcp::TcpListener; use mio::util::Slab; use std::net::SocketAddr; use connection::Connection; use error::Result; const SERVER: Token = Token(0); struct Server { listener: TcpListener, connections: Slab<Connection>, } impl Server { fn new(li...
(addr: SocketAddr) -> Result<()> { let listener = try!(TcpListener::bind(&addr)); let mut event_loop = try!(EventLoop::new()); try!(event_loop.register(&listener, SERVER, EventSet::readable(), PollOpt::edge())); let mut server = Self::new(listener); event_loop.run(&mut server); ...
run
identifier_name
Concurrent.rs
extern crate sync; use sync::{Arc, Mutex}; fn main ()
// spawn(proc() { // let numbers = rx.recv(); // println!("{}", numbers[num]); // }) // } // let numbers = ~[1,2,3]; // let numbers = Arc::new(numbers); // for num in range(0, 3) { // let (tx, rx) = channel(); // tx.send(numbers.clone()); // spawn(proc() { // let number...
{ // let mut numbers = ~[1, 2, 3, 4]; // let (tx, rx) = channel (); // numbers[0] = 4; // tx.send(numbers); // spawn (proc () { // let mut numbers = rx.recv (); // println! ("{}", numbers[0]); // numbers[0] = 5; // println! ("{}", numbers[0]); // tx.send(numbers); // }) // let numbe...
identifier_body
Concurrent.rs
extern crate sync; use sync::{Arc, Mutex}; fn main () { // let mut numbers = ~[1, 2, 3, 4]; // let (tx, rx) = channel (); // numbers[0] = 4; // tx.send(numbers); // spawn (proc () { // let mut numbers = rx.recv ();
// println! ("{}", numbers[0]); // numbers[0] = 5; // println! ("{}", numbers[0]); // tx.send(numbers); // }) // let numbers = ~[1,2,3]; // for num in range(0, 3) { // let (tx, rx) = channel(); // tx.send(numbers.clone()); // spawn(proc() { // let numbers = rx.recv(); // ...
random_line_split
Concurrent.rs
extern crate sync; use sync::{Arc, Mutex}; fn
() { // let mut numbers = ~[1, 2, 3, 4]; // let (tx, rx) = channel (); // numbers[0] = 4; // tx.send(numbers); // spawn (proc () { // let mut numbers = rx.recv (); // println! ("{}", numbers[0]); // numbers[0] = 5; // println! ("{}", numbers[0]); // tx.send(numbers); // }) // let n...
main
identifier_name
cksum.rs
#![crate_name = "uu_cksum"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[macro_use] extern crate uucore; use std::fs::File; use s...
() -> [u8; 1024 * 1024] { unsafe { mem::uninitialized() } } #[inline] fn cksum(fname: &str) -> io::Result<(u32, usize)> { let mut crc = 0u32; let mut size = 0usize; let file; let mut rd: Box<Read> = match fname { "-" => Box::new(stdin()), _ => { file = try!(File::open(&...
init_byte_array
identifier_name
cksum.rs
#![crate_name = "uu_cksum"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[macro_use] extern crate uucore; use std::fs::File; use s...
#[cfg(not(windows))] fn init_byte_array() -> [u8; 1024 * 1024] { unsafe { mem::uninitialized() } } #[inline] fn cksum(fname: &str) -> io::Result<(u32, usize)> { let mut crc = 0u32; let mut size = 0usize; let file; let mut rd: Box<Read> = match fname { "-" => Box::new(stdin()), _ ...
{ vec![0; 1024 * 1024] }
identifier_body
cksum.rs
#![crate_name = "uu_cksum"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[macro_use] extern crate uucore; use std::fs::File; use s...
let mut rd: Box<Read> = match fname { "-" => Box::new(stdin()), _ => { file = try!(File::open(&Path::new(fname))); Box::new(BufReader::new(file)) } }; let mut bytes = init_byte_array(); loop { match rd.read(&mut bytes) { Ok(num_bytes) ...
let file;
random_line_split
traversal.rs
let parent = node.traversal_parent().unwrap(); let remaining = parent.did_process_child(); if remaining!= 0 { // The parent has other unprocessed descendants. We only // perform postorder processing after the last descendant ...
// If we are in a forgetful traversal, drop the existing restyle // data here, since we won't need to perform a post-traversal to pick up // any change hints. if flags.contains(Forgetful) { data.clear_restyle_flags_and_damage(); } // Optionally clear the descendants bit for the traver...
{ note_children::<E, D, F>( context, element, data, propagated_hint, data.restyle.reconstructed_self_or_ancestor(), note_child ); }
conditional_block
traversal.rs
mut node: E::ConcreteNode, children_to_process: isize ) { // If the postorder step is a no-op, don't bother. if!Self::needs_postorder_traversal() { return; } if children_to_process == 0 { // We are a leaf. Walk up the chain. loop {...
root: OpaqueNode,
random_line_split
traversal.rs
let parent = node.traversal_parent().unwrap(); let remaining = parent.did_process_child(); if remaining!= 0 { // The parent has other unprocessed descendants. We only // perform postorder processing after the last descendant ...
// To avoid wasting work, we defer initial styling of XBL subtrees until // frame construction, which does an explicit traversal of the unstyled // children after shuffling the subtree. That explicit traversal may in // turn find other bound elements, which get handled in the same way. ...
{ debug_assert!(cfg!(feature = "gecko") || parent.has_current_styles_for_traversal(parent_data, context.shared.traversal_flags)); // If the parent computed display:none, we don't style the subtree. if parent_data.styles.is_display_none() { debug!("Parent {:?} i...
identifier_body
traversal.rs
let parent = node.traversal_parent().unwrap(); let remaining = parent.did_process_child(); if remaining!= 0 { // The parent has other unprocessed descendants. We only // perform postorder processing after the last descendant ...
( root: E, shared_context: &SharedStyleContext, traversal_flags: TraversalFlags ) -> PreTraverseToken { // If this is an unstyled-only traversal, the caller has already verified // that there's something to traverse, and we don't need to do any // invalidation since w...
pre_traverse
identifier_name
16853_H1.rs
Per(s)PSA @ damp 02% PSA @ damp 05% PSA @ damp 07% PSA @ damp 10% PSA @ damp 20% PSA @ damp 30% (m/s/s) 0.000 9.4427940E-002 9.4423000E-002 9.4423000E-002 9.4423000E-002 9.4423000E-002 9.4423000E-002 0.010 9.5077590E-002 9.4428840E-002 9.4429890E-002 9.4431070E-002 9.4431960E-002 9.4428650E-002 0.020 9.5591330E-002 ...
0.650 2.1797280E-001 1.8877083E-001 1.7303199E-001 1.5523672E-001 1.1628085E-001 9.2407720E-002 0.700 1.4387584E-001 2.1101710E-001 1.7496218E-001 1.4056417E-001 1.0735576E-001 8.4936020E-002 0.750 2.1221133E-001 1.6501458E-001 1.4778031E-001 1.3065909E-001 9.7020360E-002 7.7791750E-002 0.800 2.4024567E-001 1.320355...
0.550 2.2443265E-001 2.0542115E-001 1.7928344E-001 1.5216398E-001 1.2084850E-001 1.0293319E-001 0.600 3.2437012E-001 2.1653445E-001 1.8949097E-001 1.6210338E-001 1.2160170E-001 9.8512280E-002
random_line_split
wl_buffer.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_int, c_void, uint32_t}; use raw; use raw::types::listeners; use raw::types::objects; pub const WL_BUFFER_DESTROY: uint32_t = 0; #[inline(always)] pub unsafe fn wl_buffer_add_listener( wl_buffer: *mut objects::wl_buffer, listener: *const listeners::wl_buffer_l...
( wl_buffer: *mut objects::wl_buffer, user_data: *mut c_void ) { raw::wl_proxy_set_user_data( wl_buffer as *mut objects::wl_proxy, user_data ) } #[inline(always)] pub unsafe fn wl_buffer_get_user_data( wl_buffer: *mut objects::wl_buffer ) -> *mut c_void { raw::wl_proxy_get_user_...
wl_buffer_set_user_data
identifier_name
wl_buffer.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_int, c_void, uint32_t}; use raw; use raw::types::listeners; use raw::types::objects; pub const WL_BUFFER_DESTROY: uint32_t = 0; #[inline(always)] pub unsafe fn wl_buffer_add_listener( wl_buffer: *mut objects::wl_buffer, listener: *const listeners::wl_buffer_l...
listener as *mut extern fn(), data ) } #[inline(always)] pub unsafe fn wl_buffer_set_user_data( wl_buffer: *mut objects::wl_buffer, user_data: *mut c_void ) { raw::wl_proxy_set_user_data( wl_buffer as *mut objects::wl_proxy, user_data ) } #[inline(always)] pub unsaf...
wl_buffer as *mut objects::wl_proxy,
random_line_split
wl_buffer.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_int, c_void, uint32_t}; use raw; use raw::types::listeners; use raw::types::objects; pub const WL_BUFFER_DESTROY: uint32_t = 0; #[inline(always)] pub unsafe fn wl_buffer_add_listener( wl_buffer: *mut objects::wl_buffer, listener: *const listeners::wl_buffer_l...
{ raw::wl_proxy_marshal( wl_buffer as *mut objects::wl_proxy, WL_BUFFER_DESTROY ); raw::wl_proxy_destroy(wl_buffer as *mut objects::wl_proxy) }
identifier_body
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*;
// This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the printed stats: // // ``` // cargo test --package concurrency_manager --test memory_usage --features jemalloc --release -- test_memory_usage --exact --ignored --nocapture // ``` #[test] #[igno...
use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType};
random_line_split
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*; use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType}; // This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the p...
let guard = block_on(cm.lock_key(&key)); guard.with_lock(|l| { *l = Some(lock); }); forget(guard); } }); ths.push(th); } ths.into_iter().for_each(|th| th.join().unwrap()); println!("{:?}", tik...
{ continue; }
conditional_block
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*; use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType}; // This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the p...
let lock = Lock::new( LockType::Put, raw, 10.into(), 1000, None, 10.into(), 1, 20.into(), ); // Key already exi...
{ // Make key as small as possible, so concurrent writes in the scheduler // can be as many as possible. Then, we can maximize the amplication // caused by the data structure. const KEY_LEN: usize = 16; // We allow 100MB pending writes in the scheduler. const LOCK_COUNT: usize = 100 * 1024 * 102...
identifier_body
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*; use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType}; // This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the p...
() { // Make key as small as possible, so concurrent writes in the scheduler // can be as many as possible. Then, we can maximize the amplication // caused by the data structure. const KEY_LEN: usize = 16; // We allow 100MB pending writes in the scheduler. const LOCK_COUNT: usize = 100 * 1024 * ...
test_memory_usage
identifier_name
print.rs
// TODO: get num cols of terminal dynamically // TODO: care about the given print options use super::{Report, ReportKind, RemarkKind, Snippet}; use code::{FileMap, LineIdx, Span}; use term_painter::ToStyle; use term_painter::Color::*; use std::default::Default; /// Options for printing on the terminal. By `default()`...
let line = line_orig.replace("\t", " "); let num_tabs = line_orig[..start.col.0 as usize] .chars() .filter(|&c| c == '\t') .count(); // adjust cols in case of replaced tabs let startcol = start.col.0 as usize + 3*num_tabs; let endcol = end.col...
{ let start = src.get_loc(span.lo); let end = src.get_loc(span.hi); trace!("Span is from {:?} to {:?}", start, end); // ----- Dummyspan ----- if span.is_dummy() { println!(" {} {} ! no snippet due to <dummy-span>, this is a bug !", Magenta.bold().paint("?"), Magen...
identifier_body
print.rs
// TODO: get num cols of terminal dynamically // TODO: care about the given print options use super::{Report, ReportKind, RemarkKind, Snippet}; use code::{FileMap, LineIdx, Span}; use term_painter::ToStyle; use term_painter::Color::*; use std::default::Default; /// Options for printing on the terminal. By `default()`...
(rep: &Report, src: &FileMap, _: PrintOptions) { trace!("Printing report: {:#?}", rep); trace!("Printing with filemap: {:#?}", src); // print header let title = match rep.kind { ReportKind::Error => White.bold().bg(Red).paint("ERROR"), ReportKind::Warning => White.bold().bg(Yellow).pain...
print
identifier_name
print.rs
// TODO: get num cols of terminal dynamically // TODO: care about the given print options use super::{Report, ReportKind, RemarkKind, Snippet}; use code::{FileMap, LineIdx, Span}; use term_painter::ToStyle; use term_painter::Color::*; use std::default::Default; /// Options for printing on the terminal. By `default()`...
); }); } // ----- Multiline ----- else { let (lines, color) = match *snippet { Snippet::Replace { ref with,.. } => { let mut lines = Vec::new(); if let Some(first_break) = with.find("\n") { // we can unwrap, becau...
println!(" {: <2$}{:^<3$}", " ", "^", startcol + 1, underline_len,
random_line_split
magic_square.rs
extern crate magic_square; use magic_square::*; #[test] pub fn magic_square_contains_the_postage_stamp_values() { let mut values = create_magic_square().values; values.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(POSTAGE_STAMP_VALUES, values); }
pub fn rows_sum_to_the_same_value() { let values = create_magic_square().values; let magic_number = magic_number(); for &sum in sum_rows(values).iter() { assert_eq!(magic_number, sum); } } #[test] pub fn columns_sum_to_the_same_value() { let values = create_magic_square().values; let ma...
#[test]
random_line_split
magic_square.rs
extern crate magic_square; use magic_square::*; #[test] pub fn magic_square_contains_the_postage_stamp_values() { let mut values = create_magic_square().values; values.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(POSTAGE_STAMP_VALUES, values); } #[test] pub fn rows_sum_to_the_same_value() { ...
(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); } fn sum_diagonals(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); }
sum_columns
identifier_name
magic_square.rs
extern crate magic_square; use magic_square::*; #[test] pub fn magic_square_contains_the_postage_stamp_values() { let mut values = create_magic_square().values; values.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(POSTAGE_STAMP_VALUES, values); } #[test] pub fn rows_sum_to_the_same_value() { ...
fn sum_columns(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); } fn sum_diagonals(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); }
{ panic!("For you to do"); }
identifier_body
transport.rs
// Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com> // // 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, modifi...
<T : Packet>(&mut self, packet: T, dst: net::IpAddr) -> io::Result<usize> { use packet::ipv4::MutableIpv4Packet; // FreeBSD and OS X expect total length and fragment offset fields of IPv4 packets to be in // host byte order rather than network byte order (man 4 ip/Raw IP Sockets) if mat...
send_to_impl
identifier_name
transport.rs
// Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com> // // 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, modifi...
macro_rules! transport_channel_iterator { ($ty:ident, $iter:ident, $func:ident) => ( /// An iterator over packets of type $ty pub struct $iter<'a> { tr: &'a mut TransportReceiver } /// Return a packet iterator with packets of type $ty for some transport receiver p...
/// ipv4_packet_iter) // Name of function to create iterator /// ``` #[macro_export]
random_line_split
crypto.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
} /// ECDH functions #[cfg_attr(feature="dev", allow(similar_names))] pub mod ecdh { use crypto::*; use crypto; /// Agree on a shared secret pub fn agree(secret: &Secret, public: &Public) -> Result<Secret, CryptoError> { use secp256k1::*; let context = &crypto::SECP256K1; let mut pdata: [u8; 65] = [4u8; 65...
{ sig[64] <= 1 && H256::from_slice(&sig[0..32]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) >= h256_from_u64(1) && H256::from_...
identifier_body
crypto.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
(sig: &Signature) -> bool { sig[64] <= 1 && H256::from_slice(&sig[0..32]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) >= h256_...
is_valid
identifier_name
crypto.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
/// Invalid EC signature InvalidSignature, /// Invalid AES message InvalidMessage, /// IO Error Io(::std::io::Error), } impl From<::secp256k1::Error> for CryptoError { fn from(e: ::secp256k1::Error) -> CryptoError { match e { ::secp256k1::Error::InvalidMessage => CryptoError::InvalidMessage, ::secp256k1...
pub enum CryptoError { /// Invalid secret key InvalidSecret, /// Invalid public key InvalidPublic,
random_line_split
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
pub num_events: i32, pub num_fatalities: i32, } impl Country { pub fn new(t_link: String, t_name: String, num_eve: i32, num_fat: i32) -> Country { Country { events: Vec::new(), link: t_link, name: t_name, num_events: num_eve, num_fatalitie...
pub link: String, pub name: String,
random_line_split
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
{ pub events: Vec<Event>, pub link: String, pub name: String, pub num_events: i32, pub num_fatalities: i32, } impl Country { pub fn new(t_link: String, t_name: String, num_eve: i32, num_fat: i32) -> Country { Country { events: Vec::new(), link: t_link, ...
Country
identifier_name
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
} YearPageData { eve_vec: t_eve, name: self.name.clone(), year: inp_year, } } }
{ t_eve.push(EventTruncRenderable::from_event(elem)); }
conditional_block
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
}
{ let mut t_eve: Vec<EventTruncRenderable> = Vec::new(); for elem in &self.events { if elem.year == inp_year { t_eve.push(EventTruncRenderable::from_event(elem)); } } YearPageData { eve_vec: t_eve, name: self.name.clone(), ...
identifier_body
lights.rs
use cgmath::Point2; use layer::LayerId; #[derive(Clone, Debug)] pub struct AmbientLight { pub color: LightColor, pub intensity: f32, } #[derive(Clone, Debug)] pub struct Light { pub center: Point2<f32>, pub radius: f32, pub source_radius: f32, pub source_layer: LayerId, pu...
([r, g, b]: [f32; 3]) -> Self { use color::component_srgb_to_linear as conv; LightColor { r: conv(r), g: conv(g), b: conv(b), } } pub fn from_array([r, g, b]: [f32; 3]) -> Self { LightColor { r: r, g: g, b: b } } pub fn t...
from_srgb
identifier_name
lights.rs
use cgmath::Point2; use layer::LayerId; #[derive(Clone, Debug)] pub struct AmbientLight { pub color: LightColor, pub intensity: f32, } #[derive(Clone, Debug)] pub struct Light { pub center: Point2<f32>, pub radius: f32, pub source_radius: f32, pub source_layer: LayerId, pu...
#[derive(Clone, Copy, Debug)] pub struct LightColor { pub r: f32, pub g: f32, pub b: f32, } impl LightColor { pub fn from_srgb([r, g, b]: [f32; 3]) -> Self { use color::component_srgb_to_linear as conv; LightColor { r: conv(r), g: conv(g), ...
pub intensity: f32, }
random_line_split
tile.rs
use std::f64::{self, consts}; const EARTH_RADIUS: f64 = 6378137.0; const PERIMETER: f64 = EARTH_RADIUS * 2. * consts::PI; #[allow(dead_code)] /** * Turns WGS 84 coordinates into WebMercator * tiles numbering */ pub fn lon_lat_to_tile(lon: f64, lat: f64, zoom: u32) -> (u32, u32, u32) { let lat = lat.to_radians...
{ let bbox = LonLatBbox { west: 78.75, south: 66.51326044311186, east: 90.0, north: 70.61261423801925 }; let tile = Tile { x: 23, y: 7, z: 5, }; assert_eq!(bbox, tile.bounds()); }
identifier_body
tile.rs
use std::f64::{self, consts}; const EARTH_RADIUS: f64 = 6378137.0; const PERIMETER: f64 = EARTH_RADIUS * 2. * consts::PI;
* tiles numbering */ pub fn lon_lat_to_tile(lon: f64, lat: f64, zoom: u32) -> (u32, u32, u32) { let lat = lat.to_radians(); let n = 2_f64.powf(zoom as f64); let xtile: f64 = ((lon + 180.0) / 360.0) * n; let ytile: f64 = (1.0 - (lat.tan() + (1.0 / lat.cos())).ln() / consts::PI) / 2.0 * n; (xtile.fl...
#[allow(dead_code)] /** * Turns WGS 84 coordinates into WebMercator
random_line_split
tile.rs
use std::f64::{self, consts}; const EARTH_RADIUS: f64 = 6378137.0; const PERIMETER: f64 = EARTH_RADIUS * 2. * consts::PI; #[allow(dead_code)] /** * Turns WGS 84 coordinates into WebMercator * tiles numbering */ pub fn lon_lat_to_tile(lon: f64, lat: f64, zoom: u32) -> (u32, u32, u32) { let lat = lat.to_radians...
(&self) -> Bbox { let (west, north) = wgs84_to_meters(self.west, self.north); let (east, south) = wgs84_to_meters(self.east, self.south); Bbox {west, south, east, north} } } #[derive(Debug, PartialEq)] pub struct Bbox { /// meters pub west: f64, /// meters pub south: f64, ...
xy
identifier_name
rect.rs
use std::convert::From; use graphics::math::{ self, Scalar }; use { Point, Size }; /// A rectangle. #[derive(Clone, Copy, Debug)] pub struct Rect { /// The position of the top left corner of the rectangle. pub pos: Point, /// The width and height of the rectangle. pub size: Size, } impl<P: Into<Point...
/// Computes a scaled rectangle with the same position as self. pub fn scaled<T: Into<Size>>(self, v: T) -> Rect { let v: Size = v.into(); Rect { pos: self.pos, size: self.size * v, } } /// Returns the position of the top side of the rectangle. pub fn...
/// Returns the position of the right side of the rectangle. pub fn right(&self) -> Scalar { self.pos.x + self.size.w }
random_line_split
rect.rs
use std::convert::From; use graphics::math::{ self, Scalar }; use { Point, Size }; /// A rectangle. #[derive(Clone, Copy, Debug)] pub struct Rect { /// The position of the top left corner of the rectangle. pub pos: Point, /// The width and height of the rectangle. pub size: Size, } impl<P: Into<Point...
} impl Rect { /// Returns the position of the bottom side of the rectangle. pub fn bottom(&self) -> Scalar { self.pos.y + self.size.h } /// Computes a rectangle with quadruple the surface area of self and with center /// (self.x, self.y). pub fn centered(self) -> Rect { Rect {...
{ Rect { pos: Point { x: x, y: y }, size: Size { w: w, h: h }, } }
identifier_body
rect.rs
use std::convert::From; use graphics::math::{ self, Scalar }; use { Point, Size }; /// A rectangle. #[derive(Clone, Copy, Debug)] pub struct Rect { /// The position of the top left corner of the rectangle. pub pos: Point, /// The width and height of the rectangle. pub size: Size, } impl<P: Into<Point...
(v: [Scalar; 4]) -> Rect { Rect { pos: Point { x: v[0], y: v[1] }, size: Size { w: v[2], h: v[3] }, } } } impl From<(Scalar, Scalar, Scalar, Scalar)> for Rect { fn from((x, y, w, h): (Scalar, Scalar, Scalar, Scalar)) -> Rect { Rect { pos: Point { x: x...
from
identifier_name
token.rs
delim="#".repeat(n), string=ident_to_str(s)) } /* Name components */ IDENT(s, _) => input.get(s.name).to_owned(), LIFETIME(s) => format!("'{}", input.get(s.name)), UNDERSCORE => ~"_", /* Other */ DOC_COMMENT(ref s) => ident_to_str(s).to_owned(), EOF => ~"<eof>", ...
mtwt_token_eq_test
identifier_name
token.rs
UNDERSCORE, LIFETIME(ast::Ident), /* For interpolation */ INTERPOLATED(Nonterminal), DOC_COMMENT(ast::Ident), EOF, } #[deriving(Clone, Encodable, Decodable, Eq, IterBytes)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(@ast::Item), NtBlock(P<ast::Block>), ...
impl Keyword { pub fn to_ident(&self) -> Ident { match *self { $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )* $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )* } } } } fn mk_fresh_iden...
random_line_split
token.rs
UNDERSCORE, LIFETIME(ast::Ident), /* For interpolation */ INTERPOLATED(Nonterminal), DOC_COMMENT(ast::Ident), EOF, } #[deriving(Clone, Encodable, Decodable, Eq, IterBytes)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(@ast::Item), NtBlock(P<ast::Block>), ...
// maps a string to its interned representation pub fn intern(str : &str) -> Name { let interner = get_ident_interner(); interner.intern(str) } // gensyms a new uint, using the current interner pub fn gensym(str : &str) -> Name { let interner = get_ident_interner(); interner.gensym(str) } // map an ...
{ @interner::StrInterner::new() }
identifier_body
mod.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
pub mod field_path; pub mod field_predicate; pub mod version;
pub mod field_isempty; pub mod field_istype; pub mod field_lt;
random_line_split
dynamic_lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> { unsafe { SetLastError(0); let result = f(); let error = os::errno(); if 0 == error { Ok(result) } else { Err(format!("Error code {}", error)) ...
{ let mut handle = ptr::null_mut(); GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle); handle as *mut u8 }
identifier_body
dynamic_lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
if result!= expected_result { panic!("cos({})!= {} but equaled {} instead", argument, expected_result, result) } } #[test] #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "dragonf...
let expected_result = 1.0; let result = cosine(argument);
random_line_split
dynamic_lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(path: &[Path]) -> Vec<u8> { let mut newvar = Vec::new(); for (i, path) in path.iter().enumerate() { if i > 0 { newvar.push(DynamicLibrary::separator()); } newvar.push_all(path.as_vec()); } return newvar; } /// Returns the environment variable for this pr...
create_path
identifier_name
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use super::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() }
else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { while!serial_status.readf(0x20) {} serial_data.write(*byte); if *byte == 8 { while!serial_status.readf(0x20) {} ...
{ ::env().console.lock().write(bytes); }
conditional_block
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use super::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status =...
if *byte == 8 { while!serial_status.readf(0x20) {} serial_data.write(0x20); while!serial_status.readf(0x20) {} serial_data.write(8); } } } Ok(len) }
for byte in bytes.iter() { while !serial_status.readf(0x20) {} serial_data.write(*byte);
random_line_split
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use super::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize>
} } Ok(len) }
{ let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { whi...
identifier_body
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use super::Result; pub fn
(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); ...
do_sys_debug
identifier_name
lpurge.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use futures::future::TryFutureExt; use std::{collections::HashMap, path::PathBuf}; use tokio::fs; #[derive(serde::Deseri...
}
{ let cfg = Config { fs: "lima".to_string(), pool: "santiago".to_string(), ost: 16, freehi: 123, freelo: 60, mailbox: "foobar".to_string(), }; let file = conf_name(&cfg, "/etc/lpurge/{fs}/{ost}-{pool}.conf") .awa...
identifier_body
lpurge.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use futures::future::TryFutureExt; use std::{collections::HashMap, path::PathBuf}; use tokio::fs; #[derive(serde::Deseri...
() { let cfg = Config { fs: "lima".to_string(), pool: "santiago".to_string(), ost: 16, freehi: 123, freelo: 60, mailbox: "foobar".to_string(), }; let file = conf_name(&cfg, "/etc/lpurge/{fs}/{ost}-{pool}.conf") .a...
config_name
identifier_name
lpurge.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use futures::future::TryFutureExt; use std::{collections::HashMap, path::PathBuf}; use tokio::fs; #[derive(serde::Deseri...
let cnt = c.generate_unit(socket); fs::write(file, cnt.as_bytes()).await } #[cfg(test)] mod lpurge_conf_tests { use super::*; use insta::assert_display_snapshot; use std::env; use tempfile::tempdir; #[tokio::test] async fn works() { let cfg = Config { fs: "lima"....
{ fs::create_dir_all(&parent).await?; }
conditional_block
lpurge.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use futures::future::TryFutureExt; use std::{collections::HashMap, path::PathBuf}; use tokio::fs; #[derive(serde::Deseri...
.await .expect("name could not be created"); assert_eq!( file, PathBuf::from("/etc/lpurge/lima/OST0010-santiago.conf") ); } }
random_line_split
check_const.rs
// Copyright 2012-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-MI...
match expr.node { ExprLit(ref lit) => ast_util::lit_is_str(&**lit), _ => false, } } _ => false, } } match p.node { // Let through plain ~-string literals here PatLit(ref a) => if!is_str(&**a) ...
random_line_split
check_const.rs
// Copyright 2012-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-MI...
(&mut self, p: &Pat) { check_pat(self, p); } fn visit_expr(&mut self, ex: &Expr) { if check_expr(self, ex) { visit::walk_expr(self, ex); } } } pub fn check_crate(tcx: &ty::ctxt) { visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx, in_const: false }, ...
visit_pat
identifier_name
check_const.rs
// Copyright 2012-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-MI...
ExprPath(ref pth) => { // NB: In the future you might wish to relax this slightly // to handle on-demand instantiation of functions via // foo::<bar> in a const. Currently that is only done on // a path in trans::callee that only works in block contexts. ...
{ let ety = ty::expr_ty(v.tcx, e); if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) { span_err!(v.tcx.sess, e.span, E0012, "can not cast to `{}` in a constant expression", ppaux::ty_to_string(v.tcx, ety)); ...
conditional_block
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
// ========================================================================= //
{ let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().column_as_icy_em, ) }; run_puzzle(window, save_data, view) }
identifier_body
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
( window: &mut Window, save_data: &mut SaveData, ) -> Mode { let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().column_as_icy_em, ) }; run_puzzle(window, save_data,...
run_column_as_icy_em
identifier_name
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
save_data: &mut SaveData, ) -> Mode { let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().column_as_icy_em, ) }; run_puzzle(window, save_data, view) } // ==============...
// ========================================================================= // pub fn run_column_as_icy_em( window: &mut Window,
random_line_split
slow.rs
//! Slow, fallback cases where we cannot unambiguously round a float. //! //! This occurs when we cannot determine the exact representation using //! both the fast path (native) cases nor the Lemire/Bellerophon algorithms, //! and therefore must fallback to a slow, arbitrary-precision representation. #![doc(hidden)] ...
<F: Float>(mut bigmant: Bigint, exponent: i32) -> ExtendedFloat { // Simple, we just need to multiply by the power of the radix. // Now, we can calculate the mantissa and the exponent from this. // The binary exponent is the binary exponent for the mantissa // shifted to the hidden bit. bigmant.pow(...
positive_digit_comp
identifier_name
slow.rs
//! Slow, fallback cases where we cannot unambiguously round a float. //! //! This occurs when we cannot determine the exact representation using //! both the fast path (native) cases nor the Lemire/Bellerophon algorithms, //! and therefore must fallback to a slow, arbitrary-precision representation. #![doc(hidden)] ...
exp, }; // Shift the digits into position and determine if we need to round-up. round::<F, _>(&mut fp, |f, s| { round_nearest_tie_even(f, s, |is_odd, is_halfway, is_above| { is_above || (is_halfway && is_truncated) || (is_odd && is_halfway) }); }); fp } /// Gene...
let mut fp = ExtendedFloat { mant,
random_line_split
slow.rs
//! Slow, fallback cases where we cannot unambiguously round a float. //! //! This occurs when we cannot determine the exact representation using //! both the fast path (native) cases nor the Lemire/Bellerophon algorithms, //! and therefore must fallback to a slow, arbitrary-precision representation. #![doc(hidden)] ...
is_above || (is_halfway && is_truncated) || (is_odd && is_halfway) }); }); fp } /// Generate the significant digits with a negative exponent relative to mantissa. /// /// This algorithm is quite simple: we have the significant digits `m1 * b^N1`, /// where `m1` is the bigint mantissa, `b` ...
{ // Simple, we just need to multiply by the power of the radix. // Now, we can calculate the mantissa and the exponent from this. // The binary exponent is the binary exponent for the mantissa // shifted to the hidden bit. bigmant.pow(10, exponent as u32).unwrap(); // Get the exact representat...
identifier_body
specialization_graph.rs
StableHasherResult}; use traits; use ty::{self, TyCtxt, TypeFoldable}; use ty::fast_reject::{self, SimplifiedType}; use rustc_data_structures::sync::Lrc; use syntax::ast::Ident; use util::captures::Captures; use util::nodemap::{DefIdMap, FxHashMap}; /// A per-trait graph of impls in spe...
{ Impl(DefId), Trait(DefId), } impl<'a, 'gcx, 'tcx> Node { pub fn is_from_trait(&self) -> bool { match *self { Node::Trait(..) => true, _ => false, } } /// Iterate over the items defined directly by the given (impl or trait) node. pub fn items( ...
Node
identifier_name
specialization_graph.rs
/// Children of a given impl, grouped into blanket/non-blanket varieties as is /// done in `TraitDef`. #[derive(Default, RustcEncodable, RustcDecodable)] struct Children { // Impls of a trait (or specializations of a given impl). To allow for // quicker lookup, the impls are indexed by a simplified version of...
} }
random_line_split