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
export_common.rs
use std::ffi::OsString; use crate::common::ui::UI; use crate::error::Result; pub async fn start(ui: &mut UI, args: &[OsString], export_cmd: &str, export_pkg_ident: &str, export_pkg_ident_envvar: &str) -> Result<()> { i...
pub async fn start(ui: &mut UI, _args: &[OsString], export_cmd: &str, _export_pkg_ident: &str, _export_pkg_ident_envvar: &str) -> Result<()> { let cmd = export_cmd.replace("hab", "").replace("-...
UI}; use crate::error::{Error, Result};
random_line_split
export_common.rs
use std::ffi::OsString; use crate::common::ui::UI; use crate::error::Result; pub async fn start(ui: &mut UI, args: &[OsString], export_cmd: &str, export_pkg_ident: &str, export_pkg_ident_envvar: &str) -> Result<()> { i...
(ui: &mut UI, _args: &[OsString], export_cmd: &str, _export_pkg_ident: &str, _export_pkg_ident_envvar: &str) -> Result<()> { let cmd = export_cmd.replace("hab", "").replace("-", " "); ui.wa...
start
identifier_name
export_common.rs
use std::ffi::OsString; use crate::common::ui::UI; use crate::error::Result; pub async fn start(ui: &mut UI, args: &[OsString], export_cmd: &str, export_pkg_ident: &str, export_pkg_ident_envvar: &str) -> Result<()> { i...
else { Err(Error::ExecCommandNotFound(command)) } } } #[cfg(target_os = "macos")] mod inner { use std::ffi::OsString; use crate::common::ui::{UIWriter, UI}; use crate::error::{Error, Result}; pub async fn start(ui: &mut UI, ...
{ command::pkg::exec::start(&ident, cmd, args) }
conditional_block
adapter.rs
use api::{ Error, Operation, User }; use channel::Channel; use io::*; use services::*; use values::*; use transformable_channels::mpsc::*; use std::collections::HashMap; use std::sync::Arc; pub type ResultMap<K, T, E> = HashMap<K, Result<T, E>>; /// A witness that we are currently watching for a value. /// Watching...
/// Signal the adapter that it is time to stop. /// /// Ideally, the adapter should not return until all its threads have been stopped. fn stop(&self) { // By default, do nothing. } } /// API that adapters must implement. /// /// # Requirements /// /// Channels and Services are expected...
{ target.drain(..).map(|(id, _, _, _)| { (id.clone(), Err(Error::OperationNotSupported(Operation::Watch, id))) }).collect() }
identifier_body
adapter.rs
use api::{ Error, Operation, User }; use channel::Channel; use io::*; use services::*; use values::*; use transformable_channels::mpsc::*; use std::collections::HashMap; use std::sync::Arc; pub type ResultMap<K, T, E> = HashMap<K, Result<T, E>>; /// A witness that we are currently watching for a value. /// Watching...
(&self) { // By default, do nothing. } } pub type RawWatchTarget = (Id<Channel>, /*condition*/Option<(Payload, Type)>, /*values*/Type, Box<ExtSender<WatchEvent</*result*/(Payload, Type)>>>); pub type WatchTarget = (Id<Channel>, /*condition*/Option<Value>, Box<ExtSender<WatchEvent</*result*/Value>>>); pub ...
stop
identifier_name
adapter.rs
use api::{ Error, Operation, User }; use channel::Channel; use io::*; use services::*; use values::*; use transformable_channels::mpsc::*; use std::collections::HashMap; use std::sync::Arc; pub type ResultMap<K, T, E> = HashMap<K, Result<T, E>>; /// A witness that we are currently watching for a value. /// Watching...
pub type WatchResult = Vec<(Id<Channel>, Result<Box<AdapterWatchGuard>, Error>)>;
random_line_split
banning_queue.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...
#[test] fn should_not_accept_transactions_from_banned_sender() { // given let tx = transaction(Action::Create); let mut txq = queue(); // Banlist once (threshold not reached) let banlist1 = txq.ban_sender(tx.sender()); assert!(!banlist1, "Threshold not reached yet."); // Insert once let import1 = tx...
{ // given let tx = transaction(Action::Create); let mut txq = queue(); // when txq.queue().add(tx, TransactionOrigin::External, 0, None, &default_tx_provider()).unwrap(); // then // should also deref to queue assert_eq!(txq.status().pending, 1); }
identifier_body
banning_queue.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...
} impl DerefMut for BanningTransactionQueue { fn deref_mut(&mut self) -> &mut Self::Target { self.queue() } } #[cfg(test)] mod tests { use std::time::Duration; use super::{BanningTransactionQueue, Threshold}; use ethkey::{Random, Generator}; use transaction::{Transaction, SignedTransaction, Action}; use error...
fn deref(&self) -> &Self::Target { &self.queue }
random_line_split
banning_queue.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...
(&mut self) -> &mut TransactionQueue { &mut self.queue } /// Add to the queue taking bans into consideration. /// May reject transaction because of the banlist. pub fn add_with_banlist( &mut self, transaction: SignedTransaction, time: QueuingInstant, details_provider: &TransactionQueueDetailsProvider, )...
queue
identifier_name
internal_crypto.rs
// internal_crypto.rs - internal cryptographic functions // Copyright (C) 2018 David Anthony Stainton. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the Licen...
(input: &[u8; KEY_SIZE]) -> PacketKeys { let mut output = [0u8; KDF_OUTPUT_SIZE]; let hk = Hkdf::<Sha256>::extract(None, &input[..]); hk.expand(String::from(KDF_INFO_STR).into_bytes().as_slice(), &mut output).unwrap(); let (a1,a2,a3,a4,a5,a6) = array_refs![&output,MAC_KEY_SIZE,STREAM_KEY_SIZE,STREAM_IV...
kdf
identifier_name
internal_crypto.rs
// internal_crypto.rs - internal cryptographic functions // Copyright (C) 2018 David Anthony Stainton. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the Licen...
pub const SPRP_IV_SIZE: usize = AEZ_NONCE_SIZE; /// the size of the DH group element in bytes. pub const GROUP_ELEMENT_SIZE: usize = KEY_SIZE; const KDF_OUTPUT_SIZE: usize = MAC_KEY_SIZE + STREAM_KEY_SIZE + STREAM_IV_SIZE + SPRP_KEY_SIZE + SPRP_IV_SIZE + KEY_SIZE; const KDF_INFO_STR: &str = "panoramix-kdf-v0-hkdf-sh...
/// the key size of the SPRP in bytes. pub const SPRP_KEY_SIZE: usize = AEZ_KEY_SIZE; /// the IV size of the SPRP in bytes.
random_line_split
main.rs
extern crate serde_json; use serde_json::Value; use std::path::Path; use std::io::prelude::*; use std::fs::File; use serde_json::Value::*; fn add_up_numbers_part1(json: &Value) -> isize { match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Ar...
fn parse_and_add_up_numbers_part2(input: &str) -> isize { serde_json::from_str::<Value>(input).map(|json| add_up_numbers_part2(&json)).unwrap_or(0) } fn read_file(path: &Path) -> String { let mut input = String::new(); let mut file = File::open(path).expect("File could not be found"); file.read_to_st...
{ serde_json::from_str::<Value>(input).map(|json| add_up_numbers_part1(&json)).unwrap_or(0) }
identifier_body
main.rs
extern crate serde_json; use serde_json::Value; use std::path::Path; use std::io::prelude::*; use std::fs::File; use serde_json::Value::*; fn add_up_numbers_part1(json: &Value) -> isize { match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Ar...
match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Array(ref vec) => vec.into_iter().fold(0, |a, i| a + add_up_numbers_part2(i)), Object(ref map) => { if map.values().any(|v| { match *v { ...
fn add_up_numbers_part2(json: &Value) -> isize {
random_line_split
main.rs
extern crate serde_json; use serde_json::Value; use std::path::Path; use std::io::prelude::*; use std::fs::File; use serde_json::Value::*; fn add_up_numbers_part1(json: &Value) -> isize { match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Ar...
(path: &Path) -> String { let mut input = String::new(); let mut file = File::open(path).expect("File could not be found"); file.read_to_string(&mut input).expect("File could not be read"); input } fn main() { let input = read_file(Path::new("input.txt")); let number_part1 = parse_and_add_up_n...
read_file
identifier_name
condition.rs
use num::FromPrimitive; enum_from_primitive! { #[derive(Debug)] pub enum Cond{ Equal = 0b0000, NotEqual = 0b0001, UnsignedHigherOrSame = 0b0010, UnsignedLower = 0b0011, Negative = 0b0100, PositiveOrZero = 0b0101, Overflow...
(insn: u32) -> Cond { Cond::from_u8((insn >> 28) as u8).unwrap() } }
from
identifier_name
condition.rs
use num::FromPrimitive; enum_from_primitive! { #[derive(Debug)] pub enum Cond{ Equal = 0b0000, NotEqual = 0b0001, UnsignedHigherOrSame = 0b0010, UnsignedLower = 0b0011, Negative = 0b0100, PositiveOrZero = 0b0101, Overflow...
}
{ Cond::from_u8((insn >> 28) as u8).unwrap() }
identifier_body
condition.rs
use num::FromPrimitive; enum_from_primitive! { #[derive(Debug)] pub enum Cond{ Equal = 0b0000, NotEqual = 0b0001, UnsignedHigherOrSame = 0b0010, UnsignedLower = 0b0011, Negative = 0b0100, PositiveOrZero = 0b0101,
LessThan = 0b1011, GreaterThan = 0b1100, LessThanOrEqual = 0b1101, Always = 0b1110, Undefined = 0b1111 } } impl From<u32> for Cond { fn from (insn: u32) -> Cond { Cond::from_u8((insn >> 28) as u8).unwrap() } }
Overflow = 0b0110, NoOverflow = 0b0111, UnsignedHigher = 0b1000, UnsignedLowerOrSame = 0b1001, GreaterOrEqual = 0b1010,
random_line_split
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= e...
if pivot!= 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot { swap...
let pivot = partition(nums, start, end);
random_line_split
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= e...
println!("{:?}", quick_sort(nums)); }
];
identifier_name
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; }
i32>, start: usize, end: usize) { if start >= end { return; } // 分区点 let pivot = partition(nums, start, end); if pivot!= 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize ...
let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<
identifier_body
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= e...
s, start, end); if pivot!= 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot { ...
rtition(num
conditional_block
dynamic_lib.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 ...
<T>(&self, symbol: &str) -> Result<T, ~str> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented let maybe_symbol_value = dl::check_for_errors_in(|| { symbol.with_c_str(|raw_string| { dl::symbol(self.handle, raw_s...
symbol
identifier_name
dynamic_lib.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 maybe_symbol_value = dl::check_for_errors_in(|| { symbol.with_c_str(|raw_string| { dl::symbol(self.handle, raw_string) }) }); // The value must not be constructed if there is an error so // the destructor does not run. match maybe_symb...
random_line_split
dynamic_lib.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 ...
pub unsafe fn open_internal() -> *u8 { dlopen(ptr::null(), Lazy as libc::c_int) as *u8 } pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> { use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT}; static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT; unsa...
{ filename.with_c_str(|raw_name| { dlopen(raw_name, Lazy as libc::c_int) as *u8 }) }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive, plugin)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![crate_name = "gfx_traits...
extern crate azure; extern crate euclid; extern crate heapsize; extern crate layers; extern crate msg; extern crate serde; pub mod color; mod paint_listener; pub use paint_listener::PaintListener; use azure::azure_hl::Color; use euclid::Matrix4D; use euclid::rect::Rect; use msg::constellation_msg::PipelineId; use std...
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive, plugin)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![crate_name = "gfx_traits...
{ /// A layer for the fragment body itself. FragmentBody, /// An extra layer created for a DOM fragments with overflow:scroll. OverflowScroll, /// A layer created to contain ::before pseudo-element content. BeforePseudoContent, /// A layer created to contain ::after pseudo-element content. ...
LayerType
identifier_name
web.rs
use actix::Addr; use actix_web::{http, middleware}; use actix_web::{web, App, HttpServer}; use diesel::r2d2::{self, ConnectionManager}; use diesel::PgConnection; use crate::database::DbExecutor; use badge::handlers::badge_handler; // use run::handlers::run_handler; use status::handlers::status_handler; pub type Poo...
{ use actix_web::middleware::cors::Cors; HttpServer::new(move || { App::new() .data(state.clone()) .wrap(middleware::Logger::default()) .wrap( Cors::new() // <- Construct CORS middleware builder .allowed_methods(vec!["GET", "POST", ...
identifier_body
web.rs
use actix::Addr; use actix_web::{http, middleware}; use actix_web::{web, App, HttpServer}; use diesel::r2d2::{self, ConnectionManager}; use diesel::PgConnection; use crate::database::DbExecutor; use badge::handlers::badge_handler; // use run::handlers::run_handler; use status::handlers::status_handler; pub type Poo...
(state: WebState, http_bind: String, http_port: String) { use actix_web::middleware::cors::Cors; HttpServer::new(move || { App::new() .data(state.clone()) .wrap(middleware::Logger::default()) .wrap( Cors::new() // <- Construct CORS middleware builder ...
http_server
identifier_name
web.rs
use actix::Addr; use actix_web::{http, middleware}; use actix_web::{web, App, HttpServer}; use diesel::r2d2::{self, ConnectionManager}; use diesel::PgConnection; use crate::database::DbExecutor; use badge::handlers::badge_handler; // use run::handlers::run_handler;
#[derive(Clone)] pub struct WebState { pub db: Pool, pub db_actor: Addr<DbExecutor>, } pub fn http_server(state: WebState, http_bind: String, http_port: String) { use actix_web::middleware::cors::Cors; HttpServer::new(move || { App::new() .data(state.clone()) .wrap(middlew...
use status::handlers::status_handler; pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
random_line_split
cell.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::trace::JSTraceable; use js::jsapi::{JSTracer}; use servo_util::task_state; use servo_util::tas...
<'a>(&'a self) -> &'a T { debug_assert!(task_state::get().contains(SCRIPT | IN_GC)); &*self.value.as_unsafe_cell().get() } /// Is the cell mutably borrowed? /// /// For safety checks in debug builds only. pub fn is_mutably_borrowed(&self) -> bool { self.value.try_borrow().is...
borrow_for_gc_trace
identifier_name
cell.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::trace::JSTraceable; use js::jsapi::{JSTracer}; use servo_util::task_state; use servo_util::tas...
pub fn unwrap(self) -> T { self.value.unwrap() } pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => panic!("DOMRefCell<T> already mutably borrowed") } } pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {...
{ DOMRefCell { value: RefCell::new(value), } }
identifier_body
cell.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::trace::JSTraceable; use js::jsapi::{JSTracer}; use servo_util::task_state; use servo_util::tas...
value: RefCell::new(value), } } pub fn unwrap(self) -> T { self.value.unwrap() } pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => panic!("DOMRefCell<T> already mutably borrowed") } } ...
impl<T> DOMRefCell<T> { pub fn new(value: T) -> DOMRefCell<T> { DOMRefCell {
random_line_split
rt.rs
// This file is part of rgtk. // // rgtk 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 Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
pub fn events_pending() -> bool { unsafe { ffi::to_bool(ffi::gtk_events_pending()) } } pub fn get_major_version() -> u32 { unsafe { ffi::gtk_get_major_version() as u32 } } pub fn get_minor_version() -> u32 { unsafe { ffi::gtk_get_minor_version() as u32 } } pub fn ge...
{ let c_blocking = if blocking { ffi::GTRUE } else { ffi::GFALSE }; match unsafe { ffi::gtk_main_iteration_do(c_blocking) } { ffi::GFALSE => false, _ => true } }
identifier_body
rt.rs
// This file is part of rgtk. // // rgtk 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 Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
() -> u32 { unsafe { ffi::gtk_get_major_version() as u32 } } pub fn get_minor_version() -> u32 { unsafe { ffi::gtk_get_minor_version() as u32 } } pub fn get_micro_version() -> u32 { unsafe { ffi::gtk_get_micro_version() as u32 } } pub fn get_binary_age() -> u32 { u...
get_major_version
identifier_name
rt.rs
// This file is part of rgtk. // // rgtk 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 Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
unsafe { ffi::gtk_get_interface_age() as u32 } } pub fn check_version(required_major: u32, required_minor: u32, required_micro: u32) -> Option<String> { let c_str = unsafe { ffi::gtk_check_version(required_major as c_uint, required_mino...
} } pub fn get_interface_age() -> u32 {
random_line_split
lv.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/. //! Logical Volumes use std::collections::BTreeMap; use std::io; use std::io::ErrorKind::Other; use devicemapper::{...
/// Construct an LV from an LvmTextMap. pub fn from_textmap( name: &str, vg_name: &str, map: &LvmTextMap, pvs: &BTreeMap<String, PV>, ) -> Result<LV> { let err = || Error::Io(io::Error::new(Other, "lv textmap parsing error")); let id = map.string_from_textmap("id").ok_or_else(err)?; let c...
{ let mut v = Vec::new(); for seg in &lv.segments { v.extend(seg.used_areas()) } v }
identifier_body
lv.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/. //! Logical Volumes use std::collections::BTreeMap; use std::io; use std::io::ErrorKind::Other; use devicemapper::{...
(map: &LvmTextMap, pvs: &BTreeMap<String, PV>) -> Result<Box<dyn Segment>> { match map.string_from_textmap("type") { Some("striped") => StripedSegment::from_textmap(map, pvs), _ => unimplemented!(), } } /// A striped Logical Volume Segment. #[derive(Debug, PartialEq)...
from_textmap
identifier_name
lv.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/. //! Logical Volumes use std::collections::BTreeMap; use std::io; use std::io::ErrorKind::Other; use devicemapper::{...
pub creation_host: String, /// Created at this Unix time. pub creation_time: i64, /// A list of the segments comprising the LV. pub segments: Vec<Box<dyn segment::Segment>>, /// The major/minor number of the LV. pub device: LinearDev, } impl LV { /// The total number of extents used by ...
/// The status. pub status: Vec<String>, /// Flags. pub flags: Vec<String>, /// Created by this host.
random_line_split
lv.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/. //! Logical Volumes use std::collections::BTreeMap; use std::io; use std::io::ErrorKind::Other; use devicemapper::{...
map.insert( "stripes".to_string(), Entry::List( self.stripes .iter() .map(|&(k, v)| { let name = format!("pv{}", dev_to_idx.get(&k).unwrap()); vec![Entr...
{ map.insert("stripe_size".to_string(), Entry::Number(stripe_size as i64)); }
conditional_block
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
MySqlPool { type Value = MySqlPool; } pub struct RedisConfig { pub connect_string: String, pub expire: u64 } pub fn get_redis_config(config: &Config) -> RedisConfig { let table = config.value(); let redis_config = table.get("redis").unwrap().as_table().unwrap(); let protocol = redis_config....
0.clone() } } impl Key for
identifier_body
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
g { connect_string: connect_string, expire: max_age as u64 } }
ct_string = format!("{}://{}:{}@{}:{}", protocol, username, password, host, &*port) } RedisConfi
conditional_block
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
ct_string: String, pub expire: u64 } pub fn get_redis_config(config: &Config) -> RedisConfig { let table = config.value(); let redis_config = table.get("redis").unwrap().as_table().unwrap(); let protocol = redis_config.get("protocol").unwrap().as_str().unwrap(); let host = redis_config.get("host")...
pub conne
identifier_name
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
let table = config.value(); let redis_config = table.get("redis").unwrap().as_table().unwrap(); let protocol = redis_config.get("protocol").unwrap().as_str().unwrap(); let host = redis_config.get("host").unwrap().as_str().unwrap(); let port = redis_config.get("port").unwrap().as_integer().unwrap().t...
} pub fn get_redis_config(config: &Config) -> RedisConfig {
random_line_split
truncated_type.rs
#[derive(Clone, Debug, PartialEq)] pub enum TruncatedType { Length, Time, Disconnect, Unspecified, Unknown(String), } impl ToString for TruncatedType { fn to_string(&self) -> String { let stringified = match *self { TruncatedType::Length => "length", TruncatedTyp...
impl<S: AsRef<str>> From<S> for TruncatedType { fn from(string: S) -> Self { let lower: String = string.as_ref().to_lowercase(); match lower.as_str() { "length" => TruncatedType::Length, "time" => TruncatedType::Time, "disconnect" => TruncatedType::Disconnect, ...
}
random_line_split
truncated_type.rs
#[derive(Clone, Debug, PartialEq)] pub enum TruncatedType { Length, Time, Disconnect, Unspecified, Unknown(String), } impl ToString for TruncatedType { fn to_string(&self) -> String { let stringified = match *self { TruncatedType::Length => "length", TruncatedTyp...
}
{ let lower: String = string.as_ref().to_lowercase(); match lower.as_str() { "length" => TruncatedType::Length, "time" => TruncatedType::Time, "disconnect" => TruncatedType::Disconnect, "unspecified" => TruncatedType::Unspecified, _ => Truncate...
identifier_body
truncated_type.rs
#[derive(Clone, Debug, PartialEq)] pub enum TruncatedType { Length, Time, Disconnect, Unspecified, Unknown(String), } impl ToString for TruncatedType { fn
(&self) -> String { let stringified = match *self { TruncatedType::Length => "length", TruncatedType::Time => "time", TruncatedType::Disconnect => "disconnect", TruncatedType::Unspecified => "unspecified", TruncatedType::Unknown(ref val) => val.as_ref(...
to_string
identifier_name
f64.rs
use std::ops::{Add, Div, Mul, Sub}; use traits::{Simd, Vector}; use f64x2; impl Simd for f64 { type Vector = f64x2; } impl Add for f64x2 { type Output = f64x2; fn add(self, rhs: f64x2) -> f64x2 { self + rhs } } impl Div for f64x2 { type Output = f64x2; fn div(self, rhs: f64x2) -> ...
}
{ self.0 + self.1 }
identifier_body
f64.rs
use std::ops::{Add, Div, Mul, Sub}; use traits::{Simd, Vector}; use f64x2; impl Simd for f64 { type Vector = f64x2; } impl Add for f64x2 { type Output = f64x2; fn add(self, rhs: f64x2) -> f64x2 { self + rhs
impl Div for f64x2 { type Output = f64x2; fn div(self, rhs: f64x2) -> f64x2 { self / rhs } } impl Mul for f64x2 { type Output = f64x2; fn mul(self, rhs: f64x2) -> f64x2 { self * rhs } } impl Sub for f64x2 { type Output = f64x2; fn sub(self, rhs: f64x2) -> f64x2 { ...
} }
random_line_split
f64.rs
use std::ops::{Add, Div, Mul, Sub}; use traits::{Simd, Vector}; use f64x2; impl Simd for f64 { type Vector = f64x2; } impl Add for f64x2 { type Output = f64x2; fn add(self, rhs: f64x2) -> f64x2 { self + rhs } } impl Div for f64x2 { type Output = f64x2; fn
(self, rhs: f64x2) -> f64x2 { self / rhs } } impl Mul for f64x2 { type Output = f64x2; fn mul(self, rhs: f64x2) -> f64x2 { self * rhs } } impl Sub for f64x2 { type Output = f64x2; fn sub(self, rhs: f64x2) -> f64x2 { self - rhs } } impl Vector for f64x2 { type...
div
identifier_name
c-style-enum-in-composite.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...
(&mut self) {()} } fn main() { let tuple_interior_padding = (0_i16, OneHundred); // It will depend on the machine architecture if any padding is actually involved here let tuple_padding_at_end = ((1_u64, OneThousand), 2_u64); let tuple_different_enums = (OneThousand, MountainView, OneMillion, Vienna);...
drop
identifier_name
c-style-enum-in-composite.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
c-style-enum-in-composite.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print tuple_inter...
random_line_split
gauge.rs
use super::*; /// A gauge metric for floating point values with helper methods /// for incrementing and decrementing it's value /// /// Internally uses a `Metric<f64>` with `Semantics::Instant`, /// `Count::One` scale, and `1` count dimension pub struct Gauge { metric: Metric<f64>, init_val: f64 } impl Gauge ...
pub fn set(&mut self, val: f64) -> io::Result<()> { self.metric.set_val(val) } /// Increments the gauge by the given value pub fn inc(&mut self, increment: f64) -> io::Result<()> { let val = self.metric.val(); self.metric.set_val(val + increment) } /// Decrements the ga...
/// Sets the value of the gauge
random_line_split
gauge.rs
use super::*; /// A gauge metric for floating point values with helper methods /// for incrementing and decrementing it's value /// /// Internally uses a `Metric<f64>` with `Semantics::Instant`, /// `Count::One` scale, and `1` count dimension pub struct Gauge { metric: Metric<f64>, init_val: f64 } impl Gauge ...
(name: &str, init_val: f64, shorthelp_text: &str, longhelp_text: &str) -> Result<Self, String> { let metric = Metric::new( name, init_val, Semantics::Instant, Unit::new().count(Count::One, 1)?, shorthelp_text, longhelp_text )?; ...
new
identifier_name
mod.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
(name: XorName, tag: u64) -> Self { DataId::Mutable(MutableDataId(name, tag)) } /// Get name of this identifier. pub fn name(&self) -> &XorName { match *self { DataId::Immutable(ref id) => id.name(), DataId::Mutable(ref id) => id.name(), } } }
mutable
identifier_name
mod.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
impl DataId { /// Create `DataId` for immutable data. pub fn immutable(name: XorName) -> Self { DataId::Immutable(ImmutableDataId(name)) } /// Create `DataId` for mutable data. pub fn mutable(name: XorName, tag: u64) -> Self { DataId::Mutable(MutableDataId(name, tag)) } //...
random_line_split
math.rs
use std::ops::{Add, Div, Sub}; pub fn min<T>(nums: &Vec<T>) -> Option<T> where T: Ord + Copy, { nums.iter().fold(None, |min, x| match min { None => Some(*x), Some(y) => Some(if *x < y { *x } else { y }), }) } pub fn max<T>(nums: &Vec<T>) -> Option<T> where T: Ord + Copy, { nums.iter...
(nums: &Vec<u64>) -> Option<u64> { if nums.len() > 0 { let count = nums.len() as u64; //let max_num = max(nums).unwrap(); let min_num = min(nums).unwrap(); let sum: u64 = nums.iter().sum(); let mid_abs = (sum - (min_num * count)) / count; return Some(min_num + mid_abs...
avg_scale
identifier_name
math.rs
use std::ops::{Add, Div, Sub}; pub fn min<T>(nums: &Vec<T>) -> Option<T> where T: Ord + Copy, { nums.iter().fold(None, |min, x| match min { None => Some(*x), Some(y) => Some(if *x < y { *x } else { y }), }) } pub fn max<T>(nums: &Vec<T>) -> Option<T> where T: Ord + Copy, { nums.iter...
}) } pub fn avg_scale(nums: &Vec<u64>) -> Option<u64> { if nums.len() > 0 { let count = nums.len() as u64; //let max_num = max(nums).unwrap(); let min_num = min(nums).unwrap(); let sum: u64 = nums.iter().sum(); let mid_abs = (sum - (min_num * count)) / count; retu...
random_line_split
math.rs
use std::ops::{Add, Div, Sub}; pub fn min<T>(nums: &Vec<T>) -> Option<T> where T: Ord + Copy,
pub fn max<T>(nums: &Vec<T>) -> Option<T> where T: Ord + Copy, { nums.iter().fold(None, |max, x| match max { None => Some(*x), Some(y) => Some(if *x > y { *x } else { y }), }) } pub fn avg_scale(nums: &Vec<u64>) -> Option<u64> { if nums.len() > 0 { let count = nums.len() as u64;...
{ nums.iter().fold(None, |min, x| match min { None => Some(*x), Some(y) => Some(if *x < y { *x } else { y }), }) }
identifier_body
lib.rs
pub fn to_bytes(values: &[u32]) -> Vec<u8> {
let mut per_stream_vec = Vec::new(); let mut per_byte_vec: Vec<u8> = Vec::new(); for value in values { rb = *value; loop { let mut b = rb & 0x7F; if idx == 0 { b &= 0x7F; } else { b |= 0x80; } per_by...
let mut idx = 0; let mut rb: u32;
random_line_split
lib.rs
pub fn to_bytes(values: &[u32]) -> Vec<u8> { let mut idx = 0; let mut rb: u32; let mut per_stream_vec = Vec::new(); let mut per_byte_vec: Vec<u8> = Vec::new(); for value in values { rb = *value; loop { let mut b = rb & 0x7F; if idx == 0 { b &=...
else { incomplete_byte_seq = false; no_bytes += 1; // check for overflow if no_bytes > 4 { return Err("value overflowed!"); } u32_val |= (byte & 0x7F) as u32; v.push(u32_val); u32_val = 0; no_byt...
{ incomplete_byte_seq = true; no_bytes += 1; u32_val |= (byte & 0x7F) as u32; u32_val <<= 7; }
conditional_block
lib.rs
pub fn to_bytes(values: &[u32]) -> Vec<u8> { let mut idx = 0; let mut rb: u32; let mut per_stream_vec = Vec::new(); let mut per_byte_vec: Vec<u8> = Vec::new(); for value in values { rb = *value; loop { let mut b = rb & 0x7F; if idx == 0 { b &=...
v.push(u32_val); u32_val = 0; no_bytes = 0; } } if incomplete_byte_seq { return Err("incomplete sequence!"); } Ok(v) }
{ let mut v: Vec<u32> = Vec::new(); let mut no_bytes = 0; let mut u32_val = 0u32; let mut incomplete_byte_seq = false; for byte in bytes { if byte & 0x80 != 0 { incomplete_byte_seq = true; no_bytes += 1; u32_val |= (byte & 0x7F) as u32; u32_va...
identifier_body
lib.rs
pub fn
(values: &[u32]) -> Vec<u8> { let mut idx = 0; let mut rb: u32; let mut per_stream_vec = Vec::new(); let mut per_byte_vec: Vec<u8> = Vec::new(); for value in values { rb = *value; loop { let mut b = rb & 0x7F; if idx == 0 { b &= 0x7F; ...
to_bytes
identifier_name
env.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....
use uint::Uint; /// Vm environment. #[derive(Debug, PartialEq, Deserialize)] pub struct Env { /// Address. #[serde(rename="currentCoinbase")] pub author: Address, /// Difficulty #[serde(rename="currentDifficulty")] pub difficulty: Uint, /// Gas limit. #[serde(rename="currentGasLimit")] pub gas_limit: Uint, /...
random_line_split
env.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....
() { let s = r#"{ "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", "currentDifficulty" : "0x0100", "currentGasLimit" : "0x0f4240", "currentNumber" : "0x00", "currentTimestamp" : "0x01" }"#; let _deserialized: Env = serde_json::from_str(s).unwrap(); // TODO: validate all fields } }...
env_deserialization
identifier_name
env.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....
}
{ let s = r#"{ "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", "currentDifficulty" : "0x0100", "currentGasLimit" : "0x0f4240", "currentNumber" : "0x00", "currentTimestamp" : "0x01" }"#; let _deserialized: Env = serde_json::from_str(s).unwrap(); // TODO: validate all fields }
identifier_body
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
(&self, f: &mut fmt::Formatter) -> fmt::Result { let str = match *self { Red => "red", Yellow => "yellow", Blue => "blue", }; write!(f, "{}", str) } } #[derive(Copy)] struct CreatureInfo { name: uint, color: Color } fn show_color_list(set: Vec<Co...
fmt
identifier_name
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
to_rendezvous_log); }); to_creature }).collect(); let mut creatures_met = 0; // set up meetings... for _ in 0..nn { let fst_creature = from_creatures.recv().unwrap(); let snd_creature = from_creatures.recv().unwrap(); creatu...
{ // these ports will allow us to hear from the creatures let (to_rendezvous, from_creatures) = channel::<CreatureInfo>(); // these channels will be passed to the creatures so they can talk to us let (to_rendezvous_log, from_creatures_log) = channel::<String>(); // these channels will allow us to ...
identifier_body
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
println!("{}", show_color_list(set)); // print each creature's stats drop(to_rendezvous_log); for rep in from_creatures_log.iter() { println!("{}", rep); } // print the total number of creatures met println!("{:?}\n", Number(creatures_met)); } fn main() { let nn = if std::env:...
drop(to_creature); // print each color in the set
random_line_split
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
else { std::env::args() .nth(1) .and_then(|arg| arg.parse().ok()) .unwrap_or(600) }; print_complements(); println!(""); rendezvous(nn, vec!(Blue, Red, Yellow)); rendezvous(nn, vec!(Blue, Red, Yellow, Red, Yellow, B...
{ 200000 }
conditional_block
mod.rs
mod parse; use std::cmp::min; #[derive(Debug)] pub struct
{ name: String, speed: u32, fly_time: u32, rest_time: u32 } impl Reindeer { fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer { Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, rest_time: rest_time } } pub fn parse(input: &str) -> Reinde...
Reindeer
identifier_name
mod.rs
mod parse; use std::cmp::min;
#[derive(Debug)] pub struct Reindeer { name: String, speed: u32, fly_time: u32, rest_time: u32 } impl Reindeer { fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer { Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, rest_time: rest_time } } ...
random_line_split
mod.rs
mod parse; use std::cmp::min; #[derive(Debug)] pub struct Reindeer { name: String, speed: u32, fly_time: u32, rest_time: u32 } impl Reindeer { fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer { Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, r...
} #[cfg(test)] mod tests { use super::Reindeer; #[test] fn test_parse_reindeer() { let reindeer = Reindeer::parse("Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds."); assert_eq!(reindeer.speed, 16); assert_eq!(reindeer.fly_time, 11); assert_eq!(re...
{ self.name.clone() }
identifier_body
mod.rs
mod parse; use std::cmp::min; #[derive(Debug)] pub struct Reindeer { name: String, speed: u32, fly_time: u32, rest_time: u32 } impl Reindeer { fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer { Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, r...
time_left -= self.fly_time + self.rest_time; } distance } pub fn name(&self) -> String { self.name.clone() } } #[cfg(test)] mod tests { use super::Reindeer; #[test] fn test_parse_reindeer() { let reindeer = Reindeer::parse("Dancer can fly 16 km/s...
{ break; }
conditional_block
forge.rs
use atom::header::AtomType; use atom::types::{AtomSequence, UnknownAtomSequence}; use urid::{URID, URIDCache, URIDCacheMapping}; use std::slice; use units::Unit; use std::marker::PhantomData; use atom::header::Atom; use atom::into::ToAtom; use std::mem; pub trait Forger<'c, C: 'c> : Sized{ fn cache(&self) -> &'c ...
impl<'c, C: URIDCache> Forge<'c, C> { #[inline] pub fn new(buffer: &'c mut [u8], cache: &'c C) -> Forge<'c, C> { Forge { buffer, cache, position: 0 } } #[inline] pub fn begin_sequence<'a, U: Unit + 'c>(&'a mut self) -> ForgeSequence<'a, 'c, C, U, Self> where C: URIDCac...
{ let size = atom.get_total_size() as usize; let data = atom as *const A as *const u8; &mut *(forge.write_raw_padded(data, size) as *mut A) }
identifier_body
forge.rs
use atom::header::AtomType; use atom::types::{AtomSequence, UnknownAtomSequence}; use urid::{URID, URIDCache, URIDCacheMapping}; use std::slice; use units::Unit; use std::marker::PhantomData; use atom::header::Atom; use atom::into::ToAtom; use std::mem; pub trait Forger<'c, C: 'c> : Sized{ fn cache(&self) -> &'c ...
<'b, U2: Unit + 'c>(&'b mut self, time: &U) -> ForgeSequence<'b, 'c, C, U2, Self> where C: URIDCacheMapping<U2> + URIDCacheMapping<UnknownAtomSequence> + 'b { unsafe { self.write_raw_padded(time as *const U as *const u8, mem::size_of::<U>()); } ForgeSequence::new(self) ...
begin_sequence
identifier_name
forge.rs
use atom::header::AtomType; use atom::types::{AtomSequence, UnknownAtomSequence}; use urid::{URID, URIDCache, URIDCacheMapping}; use std::slice; use units::Unit; use std::marker::PhantomData; use atom::header::Atom; use atom::into::ToAtom; use std::mem; pub trait Forger<'c, C: 'c> : Sized{ fn cache(&self) -> &'c ...
pub struct ForgeSequence<'a, 'c, C: 'c, U: Unit, F: Forger<'c, C> + 'a> { parent: &'a mut F, atom: &'a mut Atom, _unit_type: PhantomData<U>, _cache_type: PhantomData<&'c C> } impl<'a, 'c, C: URIDCache + 'c, U: Unit + 'c, F: Forger<'c, C> + 'a> ForgeSequence<'a, 'c, C, U, F> { #[inline] fn new<'...
}
random_line_split
lib.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] use std::sync::Arc; use parking...
// It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty,
random_line_split
lib.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
/// /// Mark this latch triggered, releasing all threads that are waiting for it to trigger. /// /// All calls to trigger after the first one are noops. /// pub fn trigger(&self) { // To trigger the latch, we drop the Sender. self.sender.lock().take(); } /// /// Wait for another thread to t...
{ let (sender, receiver) = watch::channel(()); AsyncLatch { sender: Arc::new(Mutex::new(Some(sender))), receiver, } }
identifier_body
lib.rs
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
(&self) { // To see whether the latch is triggered, we clone the receiver, and then wait for our clone to // return None, indicating that the Sender has been dropped. let mut receiver = self.receiver.clone(); while receiver.recv().await.is_some() {} } /// /// Return true if the latch has been tri...
triggered
identifier_name
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
(self: Box<WorkerEventHandler>) { let this = *self; Worker::dispatch_simple_error(this.addr); } } pub struct WorkerErrorHandler { addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32, } impl WorkerErrorHandler { pub fn new(addr: Trus...
handler
identifier_name
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
// https://www.whatwg.org/html/#dom-worker pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> { // Step 2-4. let worker_url = match UrlParser::new().base_url(&global.get_url()).parse(&script_url) { Ok(url) => url, Err(_) => return Err(S...
reflect_dom_object(box Worker::new_inherited(global, sender), global, WorkerBinding::Wrap) }
random_line_split
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
}
{ let this = *self; Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num); }
identifier_body
file.rs
use nix::unistd; use std::os::unix::io::RawFd; #[derive(Debug)] pub struct Fd { pub raw_fd: RawFd, is_closed: bool, } impl Fd { /// Wraps an existing `fd` in our file descriptor object pub fn new(fd: RawFd) -> Fd
/// Duplicates the file descriptor pub fn dup(fd: RawFd) -> Result<Fd, String> { let new_fd = try!(unistd::dup(fd).or(Err(format!("{}: bad file descriptor", fd)))); Ok(Fd::new(new_fd)) } pub fn close(&mut self) { if self.is_closed { return; } unist...
{ Fd { raw_fd: fd, is_closed: false, } }
identifier_body
file.rs
use nix::unistd; use std::os::unix::io::RawFd; #[derive(Debug)] pub struct Fd { pub raw_fd: RawFd, is_closed: bool, } impl Fd { /// Wraps an existing `fd` in our file descriptor object pub fn new(fd: RawFd) -> Fd { Fd { raw_fd: fd, is_closed: false, } }
} pub fn close(&mut self) { if self.is_closed { return; } unistd::close(self.raw_fd).unwrap(); self.is_closed = true; } } impl Drop for Fd { fn drop(&mut self) { // Don't automatically drop any of the default file descriptors if self.raw_fd ...
/// Duplicates the file descriptor pub fn dup(fd: RawFd) -> Result<Fd, String> { let new_fd = try!(unistd::dup(fd).or(Err(format!("{}: bad file descriptor", fd)))); Ok(Fd::new(new_fd))
random_line_split
file.rs
use nix::unistd; use std::os::unix::io::RawFd; #[derive(Debug)] pub struct Fd { pub raw_fd: RawFd, is_closed: bool, } impl Fd { /// Wraps an existing `fd` in our file descriptor object pub fn new(fd: RawFd) -> Fd { Fd { raw_fd: fd, is_closed: false, } } ...
(&mut self) { if self.is_closed { return; } unistd::close(self.raw_fd).unwrap(); self.is_closed = true; } } impl Drop for Fd { fn drop(&mut self) { // Don't automatically drop any of the default file descriptors if self.raw_fd > 2 &&!self.is_closed {...
close
identifier_name
file.rs
use nix::unistd; use std::os::unix::io::RawFd; #[derive(Debug)] pub struct Fd { pub raw_fd: RawFd, is_closed: bool, } impl Fd { /// Wraps an existing `fd` in our file descriptor object pub fn new(fd: RawFd) -> Fd { Fd { raw_fd: fd, is_closed: false, } } ...
unistd::close(self.raw_fd).unwrap(); self.is_closed = true; } } impl Drop for Fd { fn drop(&mut self) { // Don't automatically drop any of the default file descriptors if self.raw_fd > 2 &&!self.is_closed { self.close(); } } }
{ return; }
conditional_block
pipe.rs
unsafe { let _ = libc::CloseHandle(self.handle()); } } } struct Inner { handle: libc::HANDLE, lock: mutex::NativeMutex, read_closed: atomic::AtomicBool, write_closed: atomic::AtomicBool, } impl Inner { fn new(handle: libc::HANDLE) -> Inner { Inner { handle: handle,...
return Err(epipe()) } let ret = unsafe { libc::WriteFile(self.handle(), buf[offset..].as_ptr() as libc::LPVOID, (buf.len() - offset) as libc::DWORD, &mut bytes_written,...
{ if self.write.is_none() { self.write = Some(try!(Event::new(true, false))); } let mut offset = 0; let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.write.as_ref().unwrap().handle(); while offset < buf.len() { ...
identifier_body
pipe.rs
) { unsafe { let _ = libc::CloseHandle(self.handle()); } } } struct Inner { handle: libc::HANDLE, lock: mutex::NativeMutex, read_closed: atomic::AtomicBool, write_closed: atomic::AtomicBool, } impl Inner { fn new(handle: libc::HANDLE) -> Inner { Inner { handle: hand...
pub fn handle(&self) -> libc::HANDLE { self.inner.handle } fn read_closed(&self) -> bool { self.inner.read_closed.load(atomic::SeqCst) } fn write_closed(&self) -> bool { self.inner.write_closed.load(atomic::SeqCst) } fn cancel_io(&self) -> IoResult<()> { match unsafe ...
} } } }
random_line_split
pipe.rs
(libc::HANDLE); impl Event { fn new(manual_reset: bool, initial_state: bool) -> IoResult<Event> { let event = unsafe { libc::CreateEventW(ptr::null_mut(), manual_reset as libc::BOOL, initial_state as libc::BOOL, ...
Event
identifier_name
pipe.rs
unsafe { let _ = libc::CloseHandle(self.handle()); } } } struct Inner { handle: libc::HANDLE, lock: mutex::NativeMutex, read_closed: atomic::AtomicBool, write_closed: atomic::AtomicBool, } impl Inner { fn new(handle: libc::HANDLE) -> Inner { Inner { handle: handle,...
// Issue a nonblocking requests, succeeding quickly if it happened to // succeed. let ret = unsafe { libc::ReadFile(self.handle(), buf.as_ptr() as libc::LPVOID, buf.len() as libc::DWORD, &mut bytes_rea...
{ return Err(eof()) }
conditional_block
fingerprint.rs
use std::fs::{self, File, OpenOptions}; use std::io::prelude::*; use std::io::{BufReader, SeekFrom}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use filetime::FileTime; use core::{Package, Target, Profile}; use util; use util::{CargoResult, Fresh, Dirty, Freshness, internal, profile, ChainError}; us...
/// Prepare work for when a package starts to build pub fn prepare_init(cx: &mut Context, pkg: &Package, kind: Kind) -> (Work, Work) { let new1 = dir(cx, pkg, kind); let new2 = new1.clone(); let work1 = Work::new(move |_| { if fs::metadata(&new1).is_err() { try!(fs...
{ let _p = profile::start(format!("fingerprint build cmd: {}", pkg.package_id())); let new = dir(cx, pkg, kind); let loc = new.join("build"); info!("fingerprint at: {}", loc.display()); let new_fingerprint = try!(calculate_build_cmd_fingerprint(cx, pkg)); le...
identifier_body
fingerprint.rs
use std::fs::{self, File, OpenOptions}; use std::io::prelude::*; use std::io::{BufReader, SeekFrom}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use filetime::FileTime; use core::{Package, Target, Profile}; use util; use util::{CargoResult, Fresh, Dirty, Freshness, internal, profile, ChainError}; us...
<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, pkg: &'a Package, target: &'a Target, profile: &'a Profile, kind: Kind) -> CargoResult<Fingerprint> { let key = (pkg.package_id(), target, profile, kind); mat...
calculate
identifier_name
fingerprint.rs
use std::fs::{self, File, OpenOptions}; use std::io::prelude::*; use std::io::{BufReader, SeekFrom}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use filetime::FileTime; use core::{Package, Target, Profile}; use util; use util::{CargoResult, Fresh, Dirty, Freshness, internal, profile, ChainError}; us...
let flavor = if target.is_test() || profile.test { "test-" } else if profile.doc { "doc-" } else { "" }; format!("{}{}-{}", flavor, kind, target.name()) } // The dep-info files emitted by the compiler all have their listed paths // relative to whatever the current directory ...
source.fingerprint(pkg) } fn filename(target: &Target, profile: &Profile) -> String { let kind = if target.is_lib() {"lib"} else {"bin"};
random_line_split
build.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use protoc_grpcio; use std::path::{Path, PathBuf}; use build_utils::BuildRoot; use std::collections::HashSet; fn main() { let build_root = BuildRoot::find().unwrap(); let thirdpar...
} dirs_needing_mod_rs.remove(&dst); dst = dst.join("mod.rs"); std::fs::copy(f.path(), dst).unwrap(); } disable_clippy_in_generated_code(out_dir).expect("Failed to strip clippy from generated code"); for dir in &dirs_needing_mod_rs { generate_mod_rs(dir).expect("Failed to write mod.rs"); ...
{ std::fs::create_dir_all(&dst).unwrap(); }
conditional_block
build.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use protoc_grpcio; use std::path::{Path, PathBuf}; use build_utils::BuildRoot; use std::collections::HashSet; fn main() { let build_root = BuildRoot::find().unwrap(); let thirdpar...
.into_iter() .filter_map(|f| f.ok()) .filter(|f| f.path().extension() == Some("rs".as_ref())) { let mut parts: Vec<_> = f .path() .file_name() .unwrap() .to_str() .unwrap() .split('.') .collect(); // pop.rs parts.pop(); let mut dst = out_dir.to_owned(); ...
{ tower_grpc_build::Config::new() .enable_server(true) .enable_client(true) .build( &[PathBuf::from( "build/bazel/remote/execution/v2/remote_execution.proto", )], &std::fs::read_dir(&thirdpartyprotobuf) .unwrap() .into_iter() .map(|d| d.unwrap().path()) ...
identifier_body
build.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use protoc_grpcio; use std::path::{Path, PathBuf}; use build_utils::BuildRoot; use std::collections::HashSet; fn main() { let build_root = BuildRoot::find().unwrap(); let thirdpar...
<F: FnOnce(&Path)>(path: &Path, f: F) { let tempdir = tempfile::TempDir::new().unwrap(); f(tempdir.path()); if!dir_diff::is_different(path, tempdir.path()).unwrap() { return; } if path.exists() { std::fs::remove_dir_all(path).unwrap(); } std::fs::create_dir_all(path.parent().unwrap()).unwrap(); ...
replace_if_changed
identifier_name
build.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use protoc_grpcio; use std::path::{Path, PathBuf}; use build_utils::BuildRoot; use std::collections::HashSet; fn main() { let build_root = BuildRoot::find().unwrap(); let thirdpar...
format(path); }); let tower_output_dir = PathBuf::from("src/gen_for_tower"); replace_if_changed(&tower_output_dir, |path| { generate_for_tower(&thirdpartyprotobuf, path); format(path); }); // Re-gen if, say, someone does a git clean on the gen dir but not the target dir. This ensures // genera...
mark_dir_as_rerun_trigger(&thirdpartyprotobuf); let grpcio_output_dir = PathBuf::from("src/gen"); replace_if_changed(&grpcio_output_dir, |path| { generate_for_grpcio(&thirdpartyprotobuf, path);
random_line_split
simple.rs
use stb_truetype::FontInfo; use std::borrow::Cow; fn main()
{ let file = include_bytes!("../fonts/Gudea-Regular.ttf") as &[u8]; let font = FontInfo::new(Cow::Borrowed(file), 0).unwrap(); let vmetrics = font.get_v_metrics(); println!("{:?}", vmetrics); let c = '\\'; let cp = c as u32; let g = font.find_glyph_index(cp); println!("{:?} -> {:?}", cp,...
identifier_body
simple.rs
use stb_truetype::FontInfo; use std::borrow::Cow; fn
() { let file = include_bytes!("../fonts/Gudea-Regular.ttf") as &[u8]; let font = FontInfo::new(Cow::Borrowed(file), 0).unwrap(); let vmetrics = font.get_v_metrics(); println!("{:?}", vmetrics); let c = '\\'; let cp = c as u32; let g = font.find_glyph_index(cp); println!("{:?} -> {:?}", ...
main
identifier_name