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
cargo_clean.rs
use crate::core::InternedString; use std::collections::HashMap; use std::fs; use std::path::Path; use crate::core::compiler::unit_dependencies; use crate::core::compiler::{BuildConfig, BuildContext, CompileKind, CompileMode, Context}; use crate::core::compiler::{RustcTargetData, UnitInterner}; use crate::core::profile...
use crate::core::{PackageIdSpec, Workspace}; use crate::ops; use crate::ops::resolve::WorkspaceResolve; use crate::util::errors::{CargoResult, CargoResultExt}; use crate::util::paths; use crate::util::Config; pub struct CleanOptions<'a> { pub config: &'a Config, /// A list of packages to clean. If empty, every...
use crate::core::resolver::features::HasDevUnits; use crate::core::resolver::ResolveOpts;
random_line_split
cargo_clean.rs
use crate::core::InternedString; use std::collections::HashMap; use std::fs; use std::path::Path; use crate::core::compiler::unit_dependencies; use crate::core::compiler::{BuildConfig, BuildContext, CompileKind, CompileMode, Context}; use crate::core::compiler::{RustcTargetData, UnitInterner}; use crate::core::profile...
(ws: &Workspace<'_>, opts: &CleanOptions<'_>) -> CargoResult<()> { let mut target_dir = ws.target_dir(); let config = ws.config(); // If the doc option is set, we just want to delete the doc directory. if opts.doc { target_dir = target_dir.join("doc"); return rm_rf(&target_dir.into_path...
clean
identifier_name
example.rs
use std::rand::{task_rng, Rng}; use std::str; struct Robot { name: ~str } fn generateName() -> ~str { let mut rng = task_rng(); let mut s = str::with_capacity(6); static LETTERS: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); static NUMBERS: &'static [u8] = bytes!("0123456789"); for _ i...
} pub fn resetName(&mut self) { self.name = generateName(); } }
self.name.as_slice()
random_line_split
example.rs
use std::rand::{task_rng, Rng}; use std::str; struct Robot { name: ~str } fn generateName() -> ~str { let mut rng = task_rng(); let mut s = str::with_capacity(6); static LETTERS: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); static NUMBERS: &'static [u8] = bytes!("0123456789"); for _ i...
() -> Robot { Robot { name: generateName() } } pub fn name<'a>(&'a self) -> &'a str { self.name.as_slice() } pub fn resetName(&mut self) { self.name = generateName(); } }
new
identifier_name
example.rs
use std::rand::{task_rng, Rng}; use std::str; struct Robot { name: ~str } fn generateName() -> ~str
impl Robot { pub fn new() -> Robot { Robot { name: generateName() } } pub fn name<'a>(&'a self) -> &'a str { self.name.as_slice() } pub fn resetName(&mut self) { self.name = generateName(); } }
{ let mut rng = task_rng(); let mut s = str::with_capacity(6); static LETTERS: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); static NUMBERS: &'static [u8] = bytes!("0123456789"); for _ in range(0, 3) { s.push_char(rng.choose(LETTERS) as char); } for _ in range(0, 3) { ...
identifier_body
helper.rs
use std::io::Read; use std::io::Result as IoResult; pub fn int_to_vec(number: i32) -> Vec<u8> { let number = number.to_string(); let mut result = Vec::with_capacity(number.len()); for &c in number.as_bytes().iter() { result.push(c); } result } fn try_read<T: Read>(reader: &mut T, buf : &mut [u8], min_by...
} return Ok(pos); } fn read<T: Read>(reader: &mut T, buf : &mut [u8], min_bytes : usize) -> IoResult<usize> { let n = try!(try_read(reader, buf, min_bytes)); if n < min_bytes { Err(::std::io::Error::new(::std::io::ErrorKind::Other, "Could not read enough byt...
{ return Ok(pos); }
conditional_block
helper.rs
use std::io::Read; use std::io::Result as IoResult; pub fn int_to_vec(number: i32) -> Vec<u8> { let number = number.to_string(); let mut result = Vec::with_capacity(number.len()); for &c in number.as_bytes().iter() { result.push(c); } result } fn try_read<T: Read>(reader: &mut T, buf : &mut [u8], min_by...
fn read<T: Read>(reader: &mut T, buf : &mut [u8], min_bytes : usize) -> IoResult<usize> { let n = try!(try_read(reader, buf, min_bytes)); if n < min_bytes { Err(::std::io::Error::new(::std::io::ErrorKind::Other, "Could not read enough bytes from Reader")) } else {...
{ let mut pos = 0; let buf_len = buf.len(); while pos < min_bytes { let buf1 = &mut buf[pos .. buf_len]; let n = try!(reader.read(buf1)); pos += n; if n == 0 { return Ok(pos); } } return Ok(pos); }
identifier_body
helper.rs
use std::io::Read; use std::io::Result as IoResult; pub fn int_to_vec(number: i32) -> Vec<u8> { let number = number.to_string(); let mut result = Vec::with_capacity(number.len()); for &c in number.as_bytes().iter() { result.push(c); } result } fn try_read<T: Read>(reader: &mut T, buf : &mut [u8], min_by...
<T: Read>(reader: &mut T, len: usize) -> IoResult<Vec<u8>> { let mut buf = Vec::with_capacity(len); unsafe { buf.set_len(len); } try!(read(reader, &mut buf, len)); Ok(buf) }
read_exact
identifier_name
helper.rs
use std::io::Read; use std::io::Result as IoResult; pub fn int_to_vec(number: i32) -> Vec<u8> { let number = number.to_string(); let mut result = Vec::with_capacity(number.len()); for &c in number.as_bytes().iter() { result.push(c); }
} fn try_read<T: Read>(reader: &mut T, buf : &mut [u8], min_bytes : usize) -> IoResult<usize> { let mut pos = 0; let buf_len = buf.len(); while pos < min_bytes { let buf1 = &mut buf[pos.. buf_len]; let n = try!(reader.read(buf1)); pos += n; if n == 0 { return Ok(pos); } ...
result
random_line_split
showcase.rs
/* Copyright 2016 Jordan Miner * * Licensed under the MIT license <LICENSE or * http://opensource.org/licenses/MIT>. This file may not be copied, * modified, or distributed except according to those terms. */ #[macro_use] extern crate clear_coat; extern crate iup_sys; extern crate smallvec; use std::rc::Rc; use ...
dialog.popup(ScreenPosition::CenterParent, ScreenPosition::CenterParent) .expect("couldn't show file dialog"); }); let grid = grid_box!( type_check_box, type_radio, dir_check_box, dir_text_box, multiple_files_check_box, fill!(), fill!(), show_dialog, );...
{ dialog.set_multiple_files(true); }
conditional_block
showcase.rs
/* Copyright 2016 Jordan Miner * * Licensed under the MIT license <LICENSE or * http://opensource.org/licenses/MIT>. This file may not be copied, * modified, or distributed except according to those terms. */ #[macro_use] extern crate clear_coat; extern crate iup_sys; extern crate smallvec; use std::rc::Rc; use ...
(&self) -> *mut Ihandle { self.canvas.handle() } } fn create_cursors_page() -> Box<Control> { let cursors_canvas = Rc::new(CursorsCanvas::new()); cursors_canvas.canvas.set_min_size(300, 200); let radios_info = [ ("None", Cursor::None), ("Arrow", Cursor::Arrow), ("Busy",...
handle
identifier_name
showcase.rs
/* Copyright 2016 Jordan Miner * * Licensed under the MIT license <LICENSE or * http://opensource.org/licenses/MIT>. This file may not be copied, * modified, or distributed except according to those terms. */ #[macro_use] extern crate clear_coat; extern crate iup_sys; extern crate smallvec; use std::rc::Rc; use ...
let page = vbox!( &label, hbox!(&start_button, &stop_button), ); let page_capt = page.clone(); let label_capt = label.clone(); let mut counter = 1; timer.action_event().add(move || { label_capt.set_title(&counter.to_string()); page_capt.refresh_children(); ...
let start_button = Button::with_title("Start"); let stop_button = Button::with_title("Stop"); let timer = Timer::new();
random_line_split
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ cli::{Options, INLINE_PRELUDE}, prelude_template_helpers::StratificationHelper, }; use abigen::Abigen; use anyhow::anyhow; use boogie_backend::{boogie_wrapper::BoogieWrapper, bytecode_transl...
<W: WriteColor>( error_writer: &mut W, options: Options, ) -> anyhow::Result<()> { let now = Instant::now(); let target_sources = find_move_filenames(&options.move_sources, true)?; let all_sources = collect_all_sources( &target_sources, &find_move_filenames(&options.move_deps, true)?...
run_move_prover
identifier_name
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ cli::{Options, INLINE_PRELUDE}, prelude_template_helpers::StratificationHelper, }; use abigen::Abigen; use anyhow::anyhow; use boogie_backend::{boogie_wrapper::BoogieWrapper, bytecode_transl...
Ord::cmp(fa.file_name().unwrap(), fb.file_name().unwrap()) }); Ok(deps) } fn canonicalize(s: &str) -> String { match fs::canonicalize(s) { Ok(p) => p.to_string_lossy().to_string(), Err(_) => s.to_string(), } } /// Recursively calculate dependencies. fn calculate_deps_recursive...
{ let file_map = calculate_file_map(input_deps)?; let mut deps = vec![]; let mut visited = BTreeSet::new(); for src in sources.iter() { calculate_deps_recursively(Path::new(src), &file_map, &mut visited, &mut deps, regex)?; } // Remove input sources from deps. They can end here because o...
identifier_body
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ cli::{Options, INLINE_PRELUDE}, prelude_template_helpers::StratificationHelper, }; use abigen::Abigen; use anyhow::anyhow; use boogie_backend::{boogie_wrapper::BoogieWrapper, bytecode_transl...
, )?; all_sources.extend(friend_sources); let friend_deps = calculate_deps(&all_sources, input_deps, &DEP_REGEX)?; all_sources.extend(friend_deps); Ok(all_sources) } /// Calculates transitive dependencies of the given Move sources. This function /// is also used to calculate transitive friends d...
{ &FRIEND_REGEX }
conditional_block
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ cli::{Options, INLINE_PRELUDE}, prelude_template_helpers::StratificationHelper, }; use abigen::Abigen; use anyhow::anyhow; use boogie_backend::{boogie_wrapper::BoogieWrapper, bytecode_transl...
return Ok(run_errmapgen(&env, &options, now)); } // Same for read/write set analysis if options.run_read_write_set { return Ok(run_read_write_set(&env, &options, now)); } let targets = create_and_process_bytecode(&options, &env); if env.has_errors() { env.report_errors(e...
} // Same for the error map generator if options.run_errmapgen {
random_line_split
routes.rs
//! # Request handlers //! //! Iron's [`router`]() will accept a function closure that takes //! a mutable `Request` and returns an `IronResult<Response>`. //! The application specifies two handlers: //! //! - `get_person` handles `GET /person/:id`, and will get a `Person` //! from Redis and return them as json. //! - ...
() -> Result<redis::Connection> { let client = redis::Client::open("redis://127.0.0.1/")?; client.get_connection().map_err(|e| e.into()) } /// Get the data for a `Person` from Redis. fn get_person_data(conn: redis::Connection, id: &Id) -> Result<String> { let person_data: Option<String> = conn.get(id.as_re...
get_conn
identifier_name
routes.rs
//! # Request handlers //! //! Iron's [`router`]() will accept a function closure that takes //! a mutable `Request` and returns an `IronResult<Response>`. //! The application specifies two handlers: //! //! - `get_person` handles `GET /person/:id`, and will get a `Person`
use serde_json; use redis::{self, Commands}; use iron::prelude::*; use iron::status; use router::Router; use errors::*; use model::*; /// Get a person by id. /// /// This handler takes an id from the query parameters and gets /// the corresponding person, or returns a `HTTP 404`. pub fn get_person(req: &mut Request) ...
//! from Redis and return them as json. //! - `post_person` handles `POST /person/:id`, and will update a //! `Person` in Redis with a new name.
random_line_split
routes.rs
//! # Request handlers //! //! Iron's [`router`]() will accept a function closure that takes //! a mutable `Request` and returns an `IronResult<Response>`. //! The application specifies two handlers: //! //! - `get_person` handles `GET /person/:id`, and will get a `Person` //! from Redis and return them as json. //! - ...
/// Set the data for a `Person` in Redis. fn set_person_data(conn: redis::Connection, person: Person) -> Result<()> { let person_data = serde_json::to_string(&person)?; conn.set(person.id.as_ref(), person_data)?; Ok(()) } /// Get a person from the request body with an id. fn make_person(req: &mut Reque...
{ let person_data: Option<String> = conn.get(id.as_ref())?; person_data.ok_or(Error::from(ErrorKind::PersonNotFound)) }
identifier_body
bytes.rs
struct Unit<'a> { value: f32, name: &'a str, } impl<'a> Unit<'a> { const fn new(value: f32, name: &str) -> Unit { Unit { value, name } } } const BYTE_UNITS: [Unit; 6] = [ Unit::new(1e3, "k"), Unit::new(1e6, "M"), Unit::new(1e9, "G"), Unit::new(1e12, "T"), Unit::new(1e15, "P...
; format!( "{:.*}{} {}", n_decimals, bytes / unit.value, decimal_point, unit.name ) }
{ "" }
conditional_block
bytes.rs
struct
<'a> { value: f32, name: &'a str, } impl<'a> Unit<'a> { const fn new(value: f32, name: &str) -> Unit { Unit { value, name } } } const BYTE_UNITS: [Unit; 6] = [ Unit::new(1e3, "k"), Unit::new(1e6, "M"), Unit::new(1e9, "G"), Unit::new(1e12, "T"), Unit::new(1e15, "P"), Uni...
Unit
identifier_name
bytes.rs
struct Unit<'a> { value: f32, name: &'a str, } impl<'a> Unit<'a> { const fn new(value: f32, name: &str) -> Unit { Unit { value, name } } } const BYTE_UNITS: [Unit; 6] = [ Unit::new(1e3, "k"), Unit::new(1e6, "M"), Unit::new(1e9, "G"), Unit::new(1e12, "T"), Unit::new(1e15, "P...
decimal_point, unit.name ) }
random_line_split
bytes.rs
struct Unit<'a> { value: f32, name: &'a str, } impl<'a> Unit<'a> { const fn new(value: f32, name: &str) -> Unit { Unit { value, name } } } const BYTE_UNITS: [Unit; 6] = [ Unit::new(1e3, "k"), Unit::new(1e6, "M"), Unit::new(1e9, "G"), Unit::new(1e12, "T"), Unit::new(1e15, "P...
bytes / unit.value, decimal_point, unit.name ) }
{ let bytes = bytes as f32; let unit = BYTE_UNITS .iter() .take_while(|unit| unit.value <= bytes) .last() .unwrap_or(&BYTE_UNITS[0]); let value = bytes / unit.value; let n_decimals = if value < 10.0 { 2 } else if value < 100.0 { 1 } else { ...
identifier_body
macros.rs
//! Various macros /// Generates an integer type `Name` where computations are done modulo `m` #[macro_export] macro_rules! define_modulo_ring( ($Name:ident, $m:expr) => ( #[deriving(PartialEq,Clone)] struct $Name { value: i64 } impl $Name { fn new(v: i64) -> $Name { let x=v%$m; if x < 0 { ...
) )
random_line_split
htmltrackelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; use dom::bindings::js::Root; use dom::document::Doc...
} } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLTrackElement> { let element = HTMLTrackElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, doc...
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLTrackElement { HTMLTrackElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document)
random_line_split
htmltrackelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; use dom::bindings::js::Root; use dom::document::Doc...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLTrackElement> { let element = HTMLTrackElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTrac...
{ HTMLTrackElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
htmltrackelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; use dom::bindings::js::Root; use dom::document::Doc...
{ htmlelement: HTMLElement, } impl HTMLTrackElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLTrackElement { HTMLTrackElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_m...
HTMLTrackElement
identifier_name
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen:...
(&self) -> Root<HTMLCollection> { #[derive(HeapSizeOf, JSTraceable)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { elem.downcast::<HTMLElement>() .map_or(false, H...
Elements
identifier_name
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen:...
} }); let fields = children.flat_map(|child| { child.traverse_preorder().filter(|descendant| { match descendant.type_id() { NodeTypeId::Element( ElementTypeId::...
} else if node.is::<HTMLLegendElement>() { found_legend = true; false } else { true
random_line_split
main.rs
#![feature(drain_filter)] #![feature(result_flattening)] #![feature(trace_macros)] #![feature(try_blocks)] #![feature(never_type)] use std::env; use std::time::Duration; use err_derive::Error; use getopts::Options; use futures::future; mod utils; mod feeds; mod config; use config::Config; mod providers; use providers...
let interfaces = Interfaces::new(config.interfaces); let state = State::new(config.feeds); let fetch_interval = Duration::from_secs(config.fetch_interval_secs); future::try_join(providers.fetch_loop(state.clone(), fetch_interval), interfaces.serve(state.clone())).await?; Ok(()) } fn print_us...
println!("Loading config..."); let config = Config::load(config).await?; println!("Config Loaded"); let mut providers = Providers::new(config.providers);
random_line_split
main.rs
#![feature(drain_filter)] #![feature(result_flattening)] #![feature(trace_macros)] #![feature(try_blocks)] #![feature(never_type)] use std::env; use std::time::Duration; use err_derive::Error; use getopts::Options; use futures::future; mod utils; mod feeds; mod config; use config::Config; mod providers; use providers...
() -> Result<(), Error> { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("c", "config", "Select fallback device to use", "config.json"); opts.optflag("h", "help", "Print this help menu"); let matches = opts.parse(&args[1..])?; if mat...
main
identifier_name
main.rs
#![feature(drain_filter)] #![feature(result_flattening)] #![feature(trace_macros)] #![feature(try_blocks)] #![feature(never_type)] use std::env; use std::time::Duration; use err_derive::Error; use getopts::Options; use futures::future; mod utils; mod feeds; mod config; use config::Config; mod providers; use providers...
let config = matches.opt_get("c")? .unwrap_or("config.json".to_string()); println!("Loading config..."); let config = Config::load(config).await?; println!("Config Loaded"); let mut providers = Providers::new(config.providers); let interfaces = Interfaces::new(config.interfaces); let s...
{ print_usage(&program, opts); return Ok(()); }
conditional_block
liquid.rs
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; pub static FIXTURES: &[&str] = &["Hello World"]; fn bench_fixtures(c: &mut Criterion) { let mut group = c.benchmark_group("liquid_bench_fixtures"); for fixture in FIXTURES { group.bench_function(BenchmarkId::new("parse", fixture...
let template = parser .parse(fixture) .expect("Benchmark template parsing failed"); let data = liquid::Object::new(); template.render(&data).unwrap(); b.iter(|| template.render(&data)); }); } group.finish(); } criterion_gro...
group.bench_function(BenchmarkId::new("render", fixture), |b| { let parser = liquid::ParserBuilder::with_stdlib().build().unwrap();
random_line_split
liquid.rs
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; pub static FIXTURES: &[&str] = &["Hello World"]; fn bench_fixtures(c: &mut Criterion)
} criterion_group!(benches, bench_fixtures); criterion_main!(benches);
{ let mut group = c.benchmark_group("liquid_bench_fixtures"); for fixture in FIXTURES { group.bench_function(BenchmarkId::new("parse", fixture), |b| { let parser = liquid::ParserBuilder::with_stdlib().build().unwrap(); b.iter(|| parser.parse(fixture)); }); group.b...
identifier_body
liquid.rs
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; pub static FIXTURES: &[&str] = &["Hello World"]; fn
(c: &mut Criterion) { let mut group = c.benchmark_group("liquid_bench_fixtures"); for fixture in FIXTURES { group.bench_function(BenchmarkId::new("parse", fixture), |b| { let parser = liquid::ParserBuilder::with_stdlib().build().unwrap(); b.iter(|| parser.parse(fixture)); ...
bench_fixtures
identifier_name
io.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....
{ file: File, state_hashes: HashMap<H256, (u64, u64)>, // len, offset block_hashes: HashMap<H256, (u64, u64)>, // len, offset manifest: ManifestData, } impl PackedReader { /// Create a new `PackedReader` for the file at the given path. /// This will fail if any io errors are encountered or the file /// is not ...
PackedReader
identifier_name
io.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....
state_hashes: state_hashes, block_hashes: block_hashes, state_root: b"notarealroot".sha3(), block_number: 12345678987654321, block_hash: b"notarealblock".sha3(), }; writer.finish(manifest.clone()).unwrap(); let reader = PackedReader::new(path.as_path()).unwrap().unwrap(); assert_eq!(reader.mani...
{ let path = RandomTempPath::new(); let mut writer = PackedWriter::new(path.as_path()).unwrap(); let mut state_hashes = Vec::new(); let mut block_hashes = Vec::new(); for chunk in STATE_CHUNKS { let hash = chunk.sha3(); state_hashes.push(hash.clone()); writer.write_state_chunk(hash, chunk).unwrap()...
identifier_body
io.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....
try!(file.seek(SeekFrom::End(-8))); let mut off_bytes = [0u8; 8]; try!(file.read_exact(&mut off_bytes[..])); let manifest_off: u64 = ((off_bytes[7] as u64) << 56) + ((off_bytes[6] as u64) << 48) + ((off_bytes[5] as u64) << 40) + ((off_bytes[4] as u64) << 32) + ((off_bytes[3] as u64) << 24) +...
{ // ensure we don't seek before beginning. return Ok(None); }
conditional_block
io.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....
// writing logic is the same for both kinds of chunks. fn write_chunk(&mut self, hash: H256, chunk: &[u8]) -> io::Result<()> { let mut file_path = self.dir.clone(); file_path.push(hash.hex()); let mut file = try!(File::create(file_path)); try!(file.write_all(chunk)); Ok(()) } } impl SnapshotWriter for L...
Ok(LooseWriter { dir: path, }) }
random_line_split
glue.rs
ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>, source_location: Option<NodeInfo>) -> Block<'blk, 'tcx> { // NB: v is an *alias* of type t here, not a direct value. debug!("drop_ty(t={})"...
; match source_location { Some(sl) => debuginfo::set_source_location(bcx.fcx, sl.id, sl.span), None => debuginfo::clear_source_location(bcx.fcx) }; Call(bcx, glue, &[ptr], None); } bcx } pub fn drop_ty_immediate<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ...
{ v }
conditional_block
glue.rs
<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, content_ty: Ty<'tcx>) -> Block<'blk, 'tcx> { assert!(ty::type_is_sized(bcx.ccx().tcx(), content_ty)); let sizing_type = sizing_type_of(bcx.ccx(), content_ty); let content_size = llsize_of_alloc(bcx.ccx(), sizing_ty...
trans_exchange_free_ty
identifier_name
glue.rs
use middle::subst; use middle::subst::{Subst, Substs}; use trans::adt; use trans::base::*; use trans::build::*; use trans::callee; use trans::cleanup; use trans::cleanup::CleanupMethods; use trans::common::*; use trans::datum; use trans::debuginfo; use trans::expr; use trans::machine::*; use trans::tvec; use trans::typ...
use llvm::{ValueRef, True, get_param}; use llvm; use middle::lang_items::ExchangeFreeFnLangItem;
random_line_split
glue.rs
ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>, source_location: Option<NodeInfo>) -> Block<'blk, 'tcx> { // NB: v is an *alias* of type t here, not a direct value. debug!("drop_ty(t={})"...
bcx.ty_to_string(fty)).as_slice()) }; let (struct_data, info) = if ty::type_is_sized(bcx.tcx(), t) { (v0, None) } else { let data = GEPi(bcx, v0, &[0, abi::slice_elt_base]); let info = GEPi(bcx, v0, &[0, abi::slice_elt_len]); (Load(bcx, da...
{ let repr = adt::represent_type(bcx.ccx(), t); // Find and call the actual destructor let dtor_addr = get_res_dtor(bcx.ccx(), dtor_did, t, class_did, substs); // The first argument is the "self" argument for drop let params = unsafe { let ty = Type::from_r...
identifier_body
errors.rs
// Copyright 2021 Google LLC // // 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 ...
(_: http::uri::InvalidUri) -> Self { HttpError::Uri } } impl From<http::Error> for HttpError { fn from(err: http::Error) -> Self { HttpError::Generic(err) } } impl HttpError { // Encode the GCS rules on retrying. pub fn should_retry_gcs(&self) -> bool { match self { ...
from
identifier_name
errors.rs
// Copyright 2021 Google LLC // // 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 ...
_ => false, }, // TODO(boulos): Add more here. As we need them. _ => { debug!("Asked for should_retry_gcs({:#?}). Saying no", self); false } } } }
{ match self { // If hyper says this is a user or parse error, it won't // change on a retry. Self::Hyper(e) => !e.is_parse() && !e.is_user(), // https://cloud.google.com/storage/docs/json_api/v1/status-codes // come in handy as a guide. In fact, it li...
identifier_body
errors.rs
// Copyright 2021 Google LLC // // 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 ...
fn from(err: hyper::Error) -> Self { HttpError::Hyper(err) } } impl From<http::uri::InvalidUri> for HttpError { fn from(_: http::uri::InvalidUri) -> Self { HttpError::Uri } } impl From<http::Error> for HttpError { fn from(err: http::Error) -> Self { HttpError::Generic(err) ...
impl From<hyper::Error> for HttpError {
random_line_split
rechunker.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. */ #![deny(warnings)] use anyhow::{format_err, Error}; use blobrepo::BlobRepo; use blobstore::{Loadable, PutBehaviour}; use clap_old::Arg; us...
(fb: FacebookInit) -> Result<(), Error> { let matches = args::MononokeAppBuilder::new(NAME) .with_advanced_args_hidden() .with_special_put_behaviour(PutBehaviour::Overwrite) .build() .about("Rechunk blobs using the filestore") .arg( Arg::with_name("filenodes") ...
main
identifier_name
rechunker.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. */ #![deny(warnings)] use anyhow::{format_err, Error}; use blobrepo::BlobRepo; use blobstore::{Loadable, PutBehaviour}; use clap_old::Arg; us...
.help("The number of filenodes to rechunk in parallel"), ) .get_matches(fb)?; let logger = matches.logger(); let ctx = CoreContext::new_with_logger(fb, logger.clone()); let jobs: usize = matches .value_of("jobs") .map_or(Ok(DEFAULT_NUM_JOBS), |j| j.parse()) ...
{ let matches = args::MononokeAppBuilder::new(NAME) .with_advanced_args_hidden() .with_special_put_behaviour(PutBehaviour::Overwrite) .build() .about("Rechunk blobs using the filestore") .arg( Arg::with_name("filenodes") .value_name("FILENODES") ...
identifier_body
rechunker.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. */ #![deny(warnings)] use anyhow::{format_err, Error}; use blobrepo::BlobRepo; use blobstore::{Loadable, PutBehaviour}; use clap_old::Arg; us...
.arg( Arg::with_name("filenodes") .value_name("FILENODES") .takes_value(true) .required(true) .min_values(1) .help("filenode IDs for blobs to be rechunked"), ) .arg( Arg::with_name("jobs") ...
.about("Rechunk blobs using the filestore")
random_line_split
main.rs
use std::io; use std::io::Write; fn
(a: &str, b: &str) -> bool { if a.len()!= b.len() { return false; } for c in a.chars() { if!b.contains(c) { return false; } } true } fn main() -> Result<(), std::io::Error> { print!("Enter two strings and I'll tell you if then are anagrams: "); io::stdout...
is_anagram
identifier_name
main.rs
use std::io; use std::io::Write; fn is_anagram(a: &str, b: &str) -> bool { if a.len()!= b.len() { return false; } for c in a.chars() { if!b.contains(c) { return false; } } true } fn main() -> Result<(), std::io::Error> { print!("Enter two strings and I'll te...
println!(r#"{} and {} are {}anagrams."#, first, second, not); Ok(()) }
{ not = "not " }
conditional_block
main.rs
use std::io; use std::io::Write; fn is_anagram(a: &str, b: &str) -> bool
fn main() -> Result<(), std::io::Error> { print!("Enter two strings and I'll tell you if then are anagrams: "); io::stdout().flush()?; let mut first = String::new(); io::stdin().read_line(&mut first)?; let first = first.trim(); print!("Enter the second string: "); io::stdout().flush()?; ...
{ if a.len() != b.len() { return false; } for c in a.chars() { if !b.contains(c) { return false; } } true }
identifier_body
main.rs
use std::io; use std::io::Write; fn is_anagram(a: &str, b: &str) -> bool { if a.len()!= b.len() { return false; } for c in a.chars() { if!b.contains(c) { return false; } } true } fn main() -> Result<(), std::io::Error> { print!("Enter two strings and I'll te...
Ok(()) }
if !ok { not = "not " } println!(r#"{} and {} are {}anagrams."#, first, second, not);
random_line_split
mod.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
Ok(ClosedInterval { lower_bound: bounds[0].parse()?, upper_bound: bounds[1].parse()?, }) } } /// Convenience trait to get a CellID from a Point3. /// `From<Point3<S>>` cannot be used because of orphan rules. pub trait FromPoint3<S: Scalar> { fn from_point(p: &Point3<S>)...
{ return Err(ParseClosedIntervalError( "An interval needs to be defined by exactly 2 bounds.".into(), )); }
conditional_block
mod.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
pub use sat::*; pub use web_mercator::*; /// Lower bound for distance from earth's center. /// See https://en.wikipedia.org/wiki/Earth_radius#Geophysical_extremes pub const EARTH_RADIUS_MIN_M: f64 = 6_352_800.0; /// Upper bound for distance from earth's center. /// See https://en.wikipedia.org/wiki/Earth_radius#Geophy...
#[macro_use] pub mod base; pub mod sat; pub mod web_mercator; pub use base::*;
random_line_split
mod.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
(p: &Point3<S>) -> Self { s2::cellid::CellID::from(s2::point::Point::from_coords( f64::from(p.x.clone()), f64::from(p.y.clone()), f64::from(p.z.clone()), )) } } impl<S: RealField> FromPoint3<S> for ECEF<S> { fn from_point(p: &Point3<S>) -> Self { ECEF...
from_point
identifier_name
salsa20.rs
use Error; use super::ProtectedStream; use util::{decrypt, sha256}; use crypto::salsa20::Salsa20 as SalsaDecryptor; use rustc_serialize::base64::FromBase64; const IV: [u8; 8] = [0xE8, 0x30, 0x09, 0x4B, 0x97, 0x20, 0x5D, 0x2A]; pub struct Salsa20 { decryptor: SalsaDecryptor, } impl Salsa20 { pub fn new(key:...
() { let key = [0xE4, 0x70, 0xC4, 0xEF, 0x95, 0x61, 0x22, 0xDF, 0x2C, 0x0D, 0xD1, 0x42, 0x4A, 0x24, 0xE6, 0x87, 0x79, 0x29, 0xB9, 0xAD, 0x47, 0x9C, 0x0E, 0xA5, 0xA0, 0x5D, 0xB1, 0x27, 0x7A, 0xDF, 0xBD, 0xCD]; let mut salsa20 = Salsa20::new(&key); let result...
should_decrypt_password
identifier_name
salsa20.rs
use Error; use super::ProtectedStream; use util::{decrypt, sha256}; use crypto::salsa20::Salsa20 as SalsaDecryptor; use rustc_serialize::base64::FromBase64; const IV: [u8; 8] = [0xE8, 0x30, 0x09, 0x4B, 0x97, 0x20, 0x5D, 0x2A]; pub struct Salsa20 { decryptor: SalsaDecryptor,
pub fn new(key: &[u8; 32]) -> Salsa20 { Salsa20 { decryptor: SalsaDecryptor::new(&sha256(key), &IV) } } } impl ProtectedStream for Salsa20 { fn decrypt(&mut self, value: &str) -> Result<String, Error> { let in_buffer = try!(value.from_base64().map_err(|e| Error::Base64(e))); let res...
} impl Salsa20 {
random_line_split
main.rs
#[macro_use] extern crate error_chain; #[macro_use] extern crate prettytable; #[macro_use] extern crate stderr; extern crate chan; extern crate clap; extern crate filetime; extern crate globset; extern crate pretty_bytes; extern crate separator; #[macro_use] mod errors; mod compression; mod lists; mod structs; use cl...
let local_stats_tx = stats_tx.clone(); let local_wg = wg.clone(); wg.add(1); std::thread::spawn(move || { worker_thread(local_params, local_stats_tx, local_rx); local_wg.done(); }); } (tx, stats_rx, wg) } fn yield_file<F>(path: PathBuf, globset: ...
let local_rx = rx.clone();
random_line_split
main.rs
#[macro_use] extern crate error_chain; #[macro_use] extern crate prettytable; #[macro_use] extern crate stderr; extern crate chan; extern crate clap; extern crate filetime; extern crate globset; extern crate pretty_bytes; extern crate separator; #[macro_use] mod errors; mod compression; mod lists; mod structs; use cl...
//pre-pends./ to relative paths fn fix_filters(filters: &mut Vec<String>) { for i in 0..filters.len() { let new_path; { let ref path = filters[i]; match path.chars().next().expect("Received blank filter!") { '.' | '/' => continue, _ => new_pa...
{ let r = match path.extension() { Some(x) => { let ext = x.to_str().ok_or(ErrorKind::InvalidCharactersInPath)?; str_search(COMP_EXTS, &ext, false).is_ok() }, None => false, }; return Ok(r); }
identifier_body
main.rs
#[macro_use] extern crate error_chain; #[macro_use] extern crate prettytable; #[macro_use] extern crate stderr; extern crate chan; extern crate clap; extern crate filetime; extern crate globset; extern crate pretty_bytes; extern crate separator; #[macro_use] mod errors; mod compression; mod lists; mod structs; use cl...
<F>(path: PathBuf, globset: &GlobSet, callback: &F) -> Result<()> where F: Fn(PathBuf) -> Result<()> { if is_hidden(&path)? { //we are ignoring.files and.directories //we may add a command-line switch to control this behavior in the future return Ok(()); } if path.is_dir() { ...
yield_file
identifier_name
hashdb.rs
// Copyright 2015-2017 Parity Technologies (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 lat...
/// Check for the existance of a hash-key. /// /// # Examples /// ```rust /// extern crate ethcore_util; /// use ethcore_util::hashdb::*; /// use ethcore_util::memorydb::*; /// use ethcore_util::sha3::*; /// fn main() { /// let mut m = MemoryDB::new(); /// let hello_bytes = "Hello world!".as_bytes(); //...
random_line_split
hashdb.rs
// Copyright 2015-2017 Parity Technologies (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 lat...
fn as_hashdb_mut(&mut self) -> &mut HashDB { self } }
{ self }
identifier_body
hashdb.rs
// Copyright 2015-2017 Parity Technologies (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 lat...
(&self) -> &HashDB { self } fn as_hashdb_mut(&mut self) -> &mut HashDB { self } }
as_hashdb
identifier_name
lub.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 ...
} this.get_ref().infcx.tcx.sess.span_bug( this.get_ref().trace.origin.span(), format!("region {:?} is not associated with \ any bound region from A!", r0).as_slice()) } } fn tys(&self, a: ty::t, b...
{ debug!("generalize_region(r0={:?}): \ replacing with {:?}, tainted={:?}", r0, *a_br, tainted); return ty::ReLateBound(new_scope, *a_br); }
conditional_block
lub.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 ...
new_scope: NodeId, a_map: &HashMap<ty::BoundRegion, ty::Region>, r0: ty::Region) -> ty::Region { // Regions that pre-dated the LUB computation stay as they are. if!is_var_in_set(ne...
mark: RegionMark, new_vars: &[RegionVid],
random_line_split
lub.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, a: Onceness, b: Onceness) -> cres<Onceness> { match (a, b) { (Once, _) | (_, Once) => Ok(Once), (Many, Many) => Ok(Many) } } fn bounds(&self, a: BuiltinBounds, b: BuiltinBounds) -> cres<BuiltinBounds> { // More bounds is a subtype of fewer bounds, so ...
oncenesses
identifier_name
lub.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 ...
fn bounds(&self, a: BuiltinBounds, b: BuiltinBounds) -> cres<BuiltinBounds> { // More bounds is a subtype of fewer bounds, so // the LUB (mutual supertype) is the intersection. Ok(a.intersection(b)) } fn contraregions(&self, a: ty::Region, b: ty::Region) -> cre...
{ match (a, b) { (Once, _) | (_, Once) => Ok(Once), (Many, Many) => Ok(Many) } }
identifier_body
mocking.rs
use crate::mock_store::{MockLayer, MockStore}; use std::any::{Any, TypeId}; use std::marker::PhantomData; use std::mem::transmute; /// Trait for setting up mocks /// /// The trait is implemented for all functions, so its methods can be called on any function. /// /// Note: methods have any effect only if called on fun...
/// /// ``` /// #[mockable] /// fn get_string() -> String { /// "not mocked".to_string() /// } /// /// #[test] /// fn get_string_test() { /// get_string.mock_safe(|| MockResult::Return("mocked".to_string())); /// /// assert_eq!("mocked", get_string()); ///...
/// This eliminates the problem of using non-static values, which may not live long enough.
random_line_split
mocking.rs
use crate::mock_store::{MockLayer, MockStore}; use std::any::{Any, TypeId}; use std::marker::PhantomData; use std::mem::transmute; /// Trait for setting up mocks /// /// The trait is implemented for all functions, so its methods can be called on any function. /// /// Note: methods have any effect only if called on fun...
fn mock_safe<M: FnMut<T, Output = MockResult<T, O>> +'static>(&self, mock: M) { unsafe { self.mock_raw(mock) } } fn clear_mock(&self) { let id = unsafe { self.get_mock_id() }; MOCK_STORE.with(|mock_store| mock_store.clear_id(id)) } fn call_mock(&self, input: T) -> MockRes...
{ let id = self.get_mock_id(); let boxed = Box::new(mock) as Box<dyn FnMut<_, Output = _>>; let static_boxed: Box<dyn FnMut<T, Output = MockResult<T, O>> + 'static> = transmute(boxed); MOCK_STORE.with(|mock_store| mock_store.add_to_thread_layer(id, static_boxed)) }
identifier_body
mocking.rs
use crate::mock_store::{MockLayer, MockStore}; use std::any::{Any, TypeId}; use std::marker::PhantomData; use std::mem::transmute; /// Trait for setting up mocks /// /// The trait is implemented for all functions, so its methods can be called on any function. /// /// Note: methods have any effect only if called on fun...
<M: FnMut<T, Output = MockResult<T, O>>>(&self, mock: M) { let id = self.get_mock_id(); let boxed = Box::new(mock) as Box<dyn FnMut<_, Output = _>>; let static_boxed: Box<dyn FnMut<T, Output = MockResult<T, O>> +'static> = transmute(boxed); MOCK_STORE.with(|mock_store| mock_store.add_to_...
mock_raw
identifier_name
bench.rs
#![feature(test)] extern crate test; use std::mem::replace; use test::Bencher; // bench: find the `BENCH_SIZE` first terms of the fibonacci sequence static BENCH_SIZE: usize = 20; // recursive fibonacci fn fibonacci(n: usize) -> u32 { if n < 2
else { fibonacci(n - 1) + fibonacci(n - 2) } } // iterative fibonacci struct Fibonacci { curr: u32, next: u32, } impl Iterator for Fibonacci { type Item = u32; fn next(&mut self) -> Option<u32> { let new_next = self.curr + self.next; let new_curr = replace(&mut self.next, ...
{ 1 }
conditional_block
bench.rs
#![feature(test)] extern crate test; use std::mem::replace; use test::Bencher; // bench: find the `BENCH_SIZE` first terms of the fibonacci sequence static BENCH_SIZE: usize = 20; // recursive fibonacci fn fibonacci(n: usize) -> u32 { if n < 2 { 1 } else { fibonacci(n - 1) + fibonacci(n - 2)...
}) }
random_line_split
bench.rs
#![feature(test)] extern crate test; use std::mem::replace; use test::Bencher; // bench: find the `BENCH_SIZE` first terms of the fibonacci sequence static BENCH_SIZE: usize = 20; // recursive fibonacci fn fibonacci(n: usize) -> u32 { if n < 2 { 1 } else { fibonacci(n - 1) + fibonacci(n - 2)...
} fn fibonacci_sequence() -> Fibonacci { Fibonacci { curr: 1, next: 1 } } // function to benchmark must be annotated with `#[bench]` #[bench] fn recursive_fibonacci(b: &mut Bencher) { // exact code to benchmark must be passed as a closure to the iter // method of Bencher b.iter(|| { (0..BENCH...
{ let new_next = self.curr + self.next; let new_curr = replace(&mut self.next, new_next); Some(replace(&mut self.curr, new_curr)) }
identifier_body
bench.rs
#![feature(test)] extern crate test; use std::mem::replace; use test::Bencher; // bench: find the `BENCH_SIZE` first terms of the fibonacci sequence static BENCH_SIZE: usize = 20; // recursive fibonacci fn
(n: usize) -> u32 { if n < 2 { 1 } else { fibonacci(n - 1) + fibonacci(n - 2) } } // iterative fibonacci struct Fibonacci { curr: u32, next: u32, } impl Iterator for Fibonacci { type Item = u32; fn next(&mut self) -> Option<u32> { let new_next = self.curr + self.nex...
fibonacci
identifier_name
series.rs
use std::ops::{Add, Div, Mul}; pub fn sum_of_i<T, R, Q>(n: T) -> Q::Output where T: Add<Output = R> + Copy + Mul<R, Output = Q> + From<u8>, Q: Div + From<u8>, { ((n) * (n + T::from(1_u8))) / Q::from(2_u8) } pub fn sum_of_squares_i<T>(n: T) -> T where T: Add<Output = T> + Copy + Mul<Output = T> + From<...
#[test] fn sum_of_squares_base_cases() { assert_eq!(sum_of_squares_i(1), 1); assert_eq!(sum_of_squares_i(0), 0); assert_eq!(sum_of_squares_i(2), 5); assert_eq!(sum_of_squares_i(5), 55); } #[test] fn sum_of_squares_is_correct_for_some_mid_sized_numbers() { a...
{ assert_eq!(sum_of_i(100_u64), naive_sum_of_i(100)); assert_eq!(sum_of_i(200_u64), naive_sum_of_i(200)); }
identifier_body
series.rs
use std::ops::{Add, Div, Mul}; pub fn sum_of_i<T, R, Q>(n: T) -> Q::Output where T: Add<Output = R> + Copy + Mul<R, Output = Q> + From<u8>, Q: Div + From<u8>, { ((n) * (n + T::from(1_u8))) / Q::from(2_u8) } pub fn sum_of_squares_i<T>(n: T) -> T where T: Add<Output = T> + Copy + Mul<Output = T> + From<...
() { assert_eq!(sum_of_squares_i(100), naive_sum_of_squares(100)); assert_eq!(sum_of_squares_i(200), naive_sum_of_squares(200)); } }
sum_of_squares_is_correct_for_some_mid_sized_numbers
identifier_name
series.rs
use std::ops::{Add, Div, Mul}; pub fn sum_of_i<T, R, Q>(n: T) -> Q::Output where T: Add<Output = R> + Copy + Mul<R, Output = Q> + From<u8>, Q: Div + From<u8>, { ((n) * (n + T::from(1_u8))) / Q::from(2_u8) } pub fn sum_of_squares_i<T>(n: T) -> T where T: Add<Output = T> + Copy + Mul<Output = T> + From<...
fn sum_of_i_is_correct_for_some_mid_size_numbers() { assert_eq!(sum_of_i(100_u64), naive_sum_of_i(100)); assert_eq!(sum_of_i(200_u64), naive_sum_of_i(200)); } #[test] fn sum_of_squares_base_cases() { assert_eq!(sum_of_squares_i(1), 1); assert_eq!(sum_of_squares_i(0), 0);...
} #[test]
random_line_split
eq_and_partial_eq.rs
// Why is this trait called PartialEq? // The traditional mathematical definition of an equivalence relation, of which equality is one instance, imposes three requirements. // For any values x and y: // • If x == y is true, then y == x must be true as well. // In other words, swapping the two sides of an equality c...
// PartialEq is Eq, but without x == x guarantee. (Wow, spirit of Haskell I feel).
// Eq is full equlality constraint.
random_line_split
intobject.rs
use libc::{c_char, c_int, c_long, c_ulong, c_ulonglong, size_t}; use crate::object::*; use crate::pyport::Py_ssize_t; #[repr(C)] #[derive(Copy, Clone)] pub struct PyIntObject { #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_next: *mut PyObject, #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_prev: *m...
{ (*(io as *mut PyIntObject)).ob_ival }
identifier_body
intobject.rs
use libc::{c_char, c_int, c_long, c_ulong, c_ulonglong, size_t}; use crate::object::*; use crate::pyport::Py_ssize_t; #[repr(C)] #[derive(Copy, Clone)] pub struct PyIntObject { #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_next: *mut PyObject, #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_prev: *m...
(io: *mut PyObject) -> c_long { (*(io as *mut PyIntObject)).ob_ival }
PyInt_AS_LONG
identifier_name
intobject.rs
use libc::{c_char, c_int, c_long, c_ulong, c_ulonglong, size_t}; use crate::object::*; use crate::pyport::Py_ssize_t; #[repr(C)] #[derive(Copy, Clone)] pub struct PyIntObject { #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_next: *mut PyObject, #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_prev: *m...
} pub unsafe fn PyInt_AS_LONG(io: *mut PyObject) -> c_long { (*(io as *mut PyIntObject)).ob_ival }
obj: *mut PyObject, format_spec: *mut c_char, format_spec_len: Py_ssize_t, ) -> *mut PyObject; }
random_line_split
method-on-generic-struct.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...
(self: Box<Struct<T>>, arg1: int, arg2: int) -> int { zzz(); // #break arg1 + arg2 } } fn main() { let stack = Struct { x: (8888_u32, -8888_i32) }; let _ = stack.self_by_ref(-1, -2); let _ = stack.self_by_val(-3, -4); let owned = box Struct { x: 1234.5f64 }; let _ = owned.self_...
self_owned
identifier_name
method-on-generic-struct.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...
{()}
identifier_body
method-on-generic-struct.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...
impl<T> Struct<T> { fn self_by_ref(&self, arg1: int, arg2: int) -> int { zzz(); // #break arg1 + arg2 } fn self_by_val(self, arg1: int, arg2: int) -> int { zzz(); // #break arg1 + arg2 } fn self_owned(self: Box<Struct<T>>, arg1: int, arg2: int) -> int { zzz...
}
random_line_split
header.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...
fn parse_aux_build(line: &str) -> Option<~str> { parse_name_value_directive(line, ~"aux-build") } fn parse_compile_flags(line: &str) -> Option<~str> { parse_name_value_directive(line, ~"compile-flags") } fn parse_debugger_cmd(line: &str) -> Option<~str> { parse_name_value_directive(line, ~"debugger") } ...
{ parse_name_value_directive(line, ~"error-pattern") }
identifier_body
header.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...
(line: &str, directive: ~str) -> Option<~str> { let keycolon = directive + ":"; match line.find_str(keycolon) { Some(colon) => { let value = line.slice(colon + keycolon.len(), line.len()).to_owned(); debug!("{}: {}"...
parse_name_value_directive
identifier_name
header.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 parse_debugger_cmd(ln) { Some(dc) => debugger_cmds.push(dc), None => () }; match parse_check_line(ln) { Some(cl) => check_lines.push(cl), None => () }; true }); return TestProps { error_patterns: ...
{}
conditional_block
header.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...
Some(colon) => { let value = line.slice(colon + keycolon.len(), line.len()).to_owned(); debug!("{}: {}", directive, value); Some(value) } None => None } }
fn parse_name_value_directive(line: &str, directive: ~str) -> Option<~str> { let keycolon = directive + ":"; match line.find_str(keycolon) {
random_line_split
room.rs
use diesel; use diesel::pg::PgConnection; use regex::Regex; use rocket::http::Status; use rocket::response::Failure; use super::schema::rooms;
#[derive(Clone, Serialize, Deserialize, Queryable, Identifiable)] pub struct Room { pub id: i64, pub name: String, pub description: Option<String>, pub is_public: bool, } #[derive(Insertable, Deserialize)] #[table_name = "rooms"] pub struct NewRoom { pub name: String, pub description: Option<S...
use player::play_video_thread;
random_line_split
room.rs
use diesel; use diesel::pg::PgConnection; use regex::Regex; use rocket::http::Status; use rocket::response::Failure; use super::schema::rooms; use player::play_video_thread; #[derive(Clone, Serialize, Deserialize, Queryable, Identifiable)] pub struct Room { pub id: i64, pub name: String, pub description: O...
Err(e) => { println!("Error while fetching the rooms: {}", e); Err(Failure(Status::InternalServerError)) } } } }
{ use diesel::prelude::*; use schema::rooms::dsl::*; let result; match query { Some(query) => { result = rooms .filter(name.ilike(format!("%{}%", query.to_lowercase()))) .order(name.desc()) .load::<...
identifier_body
room.rs
use diesel; use diesel::pg::PgConnection; use regex::Regex; use rocket::http::Status; use rocket::response::Failure; use super::schema::rooms; use player::play_video_thread; #[derive(Clone, Serialize, Deserialize, Queryable, Identifiable)] pub struct Room { pub id: i64, pub name: String, pub description: O...
{ pub name: String, pub description: Option<String>, pub is_public: bool, } #[derive(FromForm)] pub struct SearchRoom { pub name: String, } impl Room { #[inline] pub fn create(conn: &PgConnection, mut new_room: NewRoom) -> Result<Room, Failure> { use diesel::prelude::*; use di...
NewRoom
identifier_name
object-lifetime-default-from-box-error.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) { } } struct SomeStruct<'a> { r: Box<SomeTrait+'a> } fn load(ss: &mut SomeStruct) -> Box<SomeTrait> { // `Box<SomeTrait>` defaults to a `'static` bound, so this return // is illegal. ss.r //~ ERROR mismatched types } fn store(ss: &mut SomeStruct, b: Box<SomeTrait>) { // No error: b is bo...
dummy
identifier_name
object-lifetime-default-from-box-error.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} struct SomeStruct<'a> { r: Box<SomeTrait+'a> } fn load(ss: &mut SomeStruct) -> Box<SomeTrait> { // `Box<SomeTrait>` defaults to a `'static` bound, so this return // is illegal. ss.r //~ ERROR mismatched types } fn store(ss: &mut SomeStruct, b: Box<SomeTrait>) { // No error: b is bounded by'st...
{ }
identifier_body
object-lifetime-default-from-box-error.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn store1<'b>(ss: &mut SomeStruct, b: Box<SomeTrait+'b>) { // Here we override the lifetimes explicitly, and so naturally we get an error. ss.r = b; //~ ERROR mismatched types } fn main() { }
}
random_line_split
once-cant-call-twice-on-stack.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 ...
() { let x = arc::ARC(true); do foo { assert!(*x.get()); util::ignore(x); } }
main
identifier_name
once-cant-call-twice-on-stack.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
// except according to those terms. // Testing guarantees provided by once functions. // This program would segfault if it were legal. // compile-flags:-Z once-fns extern mod extra; use extra::arc; use std::util; fn foo(blk: &once fn()) { blk(); blk(); //~ ERROR use of moved value } fn main() { let x = ...
// 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
once-cant-call-twice-on-stack.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 ...
fn main() { let x = arc::ARC(true); do foo { assert!(*x.get()); util::ignore(x); } }
{ blk(); blk(); //~ ERROR use of moved value }
identifier_body
cloudformation.rs
#![cfg(feature = "cloudformation")] extern crate rusoto; use rusoto::cloudformation::{CloudFormationClient, ListStacksInput}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_list_stacks()
#[test] fn should_list_stacks_with_status_filter() { let client = CloudFormationClient::new(default_tls_client().unwrap(), DefaultCredentialsProvider::new().unwrap(), Region::UsEast1); let filters = vec!["CREATE_COMPLETE".to_owned()]; let request = ListStacksInput { stack_status_filter: Some(filters...
{ let client = CloudFormationClient::new(default_tls_client().unwrap(), DefaultCredentialsProvider::new().unwrap(), Region::UsEast1); let request = ListStacksInput::default(); let result = client.list_stacks(&request).unwrap(); println!("{:#?}", result); }
identifier_body
cloudformation.rs
#![cfg(feature = "cloudformation")] extern crate rusoto; use rusoto::cloudformation::{CloudFormationClient, ListStacksInput}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_list_stacks() { let client = CloudFormationClient::new(default_tls_client().unwrap(), D...
#[test] fn should_list_stacks_with_status_filter() { let client = CloudFormationClient::new(default_tls_client().unwrap(), DefaultCredentialsProvider::new().unwrap(), Region::UsEast1); let filters = vec!["CREATE_COMPLETE".to_owned()]; let request = ListStacksInput { stack_status_filter: Some(filters)...
let request = ListStacksInput::default(); let result = client.list_stacks(&request).unwrap(); println!("{:#?}", result); }
random_line_split